一、启动redis服务:单机版即可(命令./redis-server),并在spring中进行配置
二、缓存代码(服务层和业务层分离)
1、Controller:调用service层的服务实现数据缓存
@Controller
public class ContentController {
@Autowired
private ContentService contentService;
/**
* 首页轮播图
*
* @param cid
* @return
*/
@RequestMapping("/content/{cid}")
@ResponseBody
public TaotaoResult getContentList(@PathVariable Long cid) {
try {
List<TbContent> list = contentService.getContentList(cid);
return TaotaoResult.ok(list);
} catch (Exception e) {
e.printStackTrace();
return TaotaoResult.build(500, ExceptionUtil.getStackTrace(e));
}
}
}
2、Service层:在查询数据库之前先查询缓存,若缓存中有,则直接返回;若缓存中没有,则查询数据库并将结果添加到缓存,其中 REDIS_CONTENT_KEY 是缓存的关键字,在配置文件resource.properties中定义
@Service
public class ContentServiceImpl implements ContentService {
@Autowired
private TbContentMapper tbContentMapper;
@Autowired
private JedisClient jedisClient;
@Value("${REDIS_CONTENT_KEY}")
private String REDIS_CONTENT_KEY;
@Override
public List<TbContent> getContentList(Long cid) {
//添加缓存
//在查询数据库之前先查询缓存,如果有直接返回
try {
//从redis中取缓存数据
String json = jedisClient.hget(REDIS_CONTENT_KEY, cid+"");
if(!StringUtils.isBlank(json)) {
//把json转换成list
List<TbContent> list = JsonUtils.jsonToList(json, TbContent.class);
return list;
}
} catch (Exception e) {
e.printStackTrace();
}
//创造查询条件
TbContentExample example = new TbContentExample();
Criteria criteria = example.createCriteria();
criteria.andCategoryIdEqualTo(cid);
//执行查询
List<TbContent> list = tbContentMapper.selectByExampleWithBLOBs(example );
//返回结果之前,添加到缓存
try {
//为了规范key可以使用hash
//定义一个保存内容的key,hash中的每一项就是cid
//value是list,需要把list转化成json数据
jedisClient.hset(REDIS_CONTENT_KEY, cid+"", JsonUtils.objectToJson(list));
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
}
3、调用缓存服务
三、缓存同步
当后台修改内容信息后,只需要把redis中缓存的数据删除即可。后台系统不直接操作redis数据库。
可以在taotao-rest中发布一个服务,当后台对内容信息修改后,调用服务即可。服务的功能就是根据cid删除redis中缓存数据。
1、Controller
2、Service
3、调用缓存同步服务