redis创建缓存的示例:
@Autowired
private JedisClient jedisClient;
public ListgetContentListByCid(long cid) {
//查询缓存
try {
//如果缓存中有直接响应结果
String json = jedisClient.hget("CONTENT_LIST", cid + "");
if (StringUtils.isNotBlank(json)) {
Listlist = JsonUtils.jsonToList(json, TbContent.class);
return list;
}
} catch (Exception e) {
e.printStackTrace();
}
//如果没有查询数据库
TbContentExample example = new TbContentExample();
Criteria criteria = example.createCriteria();
//设置查询条件
criteria.andCategoryIdEqualTo(cid);
//执行查询
Listlist = contentMapper.selectByExampleWithBLOBs(example);
//把结果添加到缓存
try {
jedisClient.hset("CONTENT_LIST", cid + "", JsonUtils.objectToJson(list));
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
}
缓存同步
当做增删改时需要更新缓存
@Override
public E3Result addContent(TbContent content) {
//插入到数据库
contentMapper.insert(content);
//当增删改操作时缓存同步,删除缓存中对应的数据,下次查询时从数据库中查
jedisClient.hdel(CONTENT_LIST, content.getCategoryId().toString());
return E3Result.ok();
}
public TbItem getItemById(long itemId) {
//查询缓存
try {
String json = jedisClient.get("REDIS_ITEM_PRE" + ":" + itemId + ":BASE");
if(StringUtils.isNotBlank(json)) {
TbItem tbItem = JsonUtils.jsonToPojo(json, TbItem.class);
return tbItem;
}
} catch (Exception e) {
e.printStackTrace();
}
//缓存中没有,查询数据库
TbItemExample example = new TbItemExample();
Criteria criteria = example.createCriteria();
//设置查询条件
criteria.andIdEqualTo(itemId);
//执行查询
Listlist = itemMapper.selectByExample(example);
if (list != null && list.size() > 0) {
//把结果添加到缓存
try {
jedisClient.set("REDIS_ITEM_PRE" + ":" + itemId + ":BASE", JsonUtils.objectToJson(list.get(0)));
//设置过期时间
jedisClient.expire("REDIS_ITEM_PRE" + ":" + itemId + ":BASE",3600);
} catch (Exception e) {
e.printStackTrace();
}
return list.get(0);
}
return null;
}