1.redis服务:
String get(String key);
String set(String key,String value);
String hget(String hkey,String key);
long hset(String hkey,String key,String value);
long incr(String key);
long expire(String key,int second);
long ttl(String key);
long del(String key);
long hdel(String hkey,String key);
2.缓存服务的调用
@Autowired
private TbContentMapper contentMapper;
@Autowired
private JedisClient jedisClient;
@Value("${INDEX_CONTENT_REDIS_KEY}")
private String INDEX_CONTENT_REDIS_KEY;
@Override
public List<TbContent> getContentList(long contentCid) {
//从缓存中取内容
try{
String result = jedisClient.hget(INDEX_CONTENT_REDIS_KEY, contentCid+ "");
if(!StringUtils.isBlank(result)){
//把字符串转换成list
List<TbContent> resultList = JsonUtils.jsonToList(result, TbContent.class);
return resultList;
}
}catch(Exception e){
e.printStackTrace();
}
//根据内容分类id查询内容列表
TbContentExample example = new TbContentExample();
Criteria criteria = example.createCriteria();
criteria.andCategoryIdEqualTo(contentCid);
//执行查询
List<TbContent> list = contentMapper.selectByExample(example);
//向缓存中添加内容
try{
//把list转换成字符串
String cacheString=JsonUtils.objectToJson(list);
jedisClient.hset(INDEX_CONTENT_REDIS_KEY, contentCid +"", cacheString);
}catch(Exception e){
e.printStackTrace();
}
return list;
}
3.编写同步缓存的服务
@Autowired
private JedisClient jedisClient;
@Value("${INDEX_CONTENT_REDIS_KEY}")
private String INDEX_CONTENT_REDIS_KEY;
@Override
public TaotaoResult syncContent(long contentCid) {
try{
jedisClient.hdel(INDEX_CONTENT_REDIS_KEY,contentCid+"");
}catch(Exception e){
e.printStackTrace();
return TaotaoResult.build(500, ExceptionUtil.getStackTrace(e));
}
return TaotaoResult.ok();
}
4、httpClient远程调用同步缓存的服务
@Autowired
private TbContentMapper contentMapper;
@Value("${REST_BASE_URL}")
private String REST_BASE_URL;
@Value("${REST_CONTENT_SYNC_URL}")
private String REST_CONTENT_SYNC_URL;
@Override
public TaotaoResult insertContent(TbContent content) {
//不全pojo内容
content.setCreated(new Date());
content.setUpdated(new Date());
contentMapper.insert(content);
//添加缓存同步逻辑
try{
HttpClientUtil.doGet(REST_BASE_URL+REST_CONTENT_SYNC_URL+content.getCategoryId());
}catch(Exception e){
e.printStackTrace();
}
return TaotaoResult.ok();
}
redis集群的搭建过程不在这里赘述!