redis創建緩存的示例:
@Autowired
private JedisClient jedisClient;
/**
* 根據內容分類id查詢內容列表
cn.e3mall.content.service.ContentService#getContentListByCid(long)
*/
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;
}