RedisKeyUtils
public class RedisKeyUtils {
//商品id自增key
public final static String ITEMS_ID = "ITEMS:ID";
//商品排行榜key
public static final String ITEMS_SELLSORT = "ITEMS:SELLSORT";
//商品信息key
public static String getItemKey(Long itemId){
<span style="white-space:pre"> </span> return "ITEMS:" + itemId;
}
//商品评论key
public static String getItemCommentKey(Long itemId){
return"ITEMS:COMMENT" + itemId;
}
}
po
public class Comment {
private long id;
//评论内容
private String name;
//评论时间
private Date date;
.....
public class Items {
private Integer id;
private String name;
private Float price;
private String pic;
private Date createtime;
private String detail;
JedisProTest
public class JedisProTest {
private ApplicationContext applicationContext;
// 使用jackson进行json转换
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
// redis集群
private JedisCluster jedisCluster;
@Before
public void init() {
applicationContext = new ClassPathXmlApplicationContext(
"classpath:");
jedisCluster = (JedisCluster) applicationContext
.getBean("jedisCluster");
}
// 获取商品自增id主键
@Test
public void testGetItemsId() {
Long item_id = (RedisKeyUtils.ITEMS_ID);
(item_id);
}
// 向hash中存储商品信息
@Test
public void testSaveItems() {
((1002l), "id", "3");
((1002l), "name", "苹果4");
((1002l), "price", "999.9");
}
// 根据商品id从hash获取商品信息
@Test
public void testGetItemsById() {
Map<String, String> map = (RedisKeyUtils
.getItemKey(1002l));
(map);
}
// 向list存储商品评论列表
@Test
public void testSaveItemsComment() throws JsonGenerationException,
JsonMappingException, IOException {
// 将商品评价信息转成json
Comment comment = new Comment();
(1l);
("商品不错,很好!!");
(new Date());
// 将商品评论转成json串
String comment_json = OBJECT_MAPPER.writeValueAsString(comment);
(comment_json);
// 将商品评论存储到redis
jedisCluster
.lpush((1001l), comment_json);
// 获取商品评论
List<String> lrange = (
(1001l), 0, -1);
for (String content : lrange) {
// 将json数据转成java对象
(content);
Comment comment_obj = OBJECT_MAPPER.readValue(content,
);
(comment_obj);
}
}
// 商品排行榜
// 向sortedSet存储商品评论列表
@Test
public void testItemsSellSort() {
//初始化商品销量
//商品1001
(RedisKeyUtils.ITEMS_SELLSORT, 100, "1001");
//商品1002
(RedisKeyUtils.ITEMS_SELLSORT, 200, "1002");
//商品销售出增加销量
//增加1001商品的销量
(RedisKeyUtils.ITEMS_SELLSORT, 1, "1001");
//商品销量前10名
Set<Tuple> zrevrangeWithScores = (RedisKeyUtils.ITEMS_SELLSORT, 0, 9);
for(Tuple content:zrevrangeWithScores){
(()+" "+());
}
}
//设置key的过期时间
@Test
public void testSetKeyExpire() throws InterruptedException{
//设置test的值为1
("test", "1");
(("test"));
//设置生成时间为5秒,单位为秒
("test", 5);
//设置生成时间为5秒,单位为毫秒
// ("test", 5000);
(5000);
(("test"));
}
}