前提是redis配置好并启动服务:
一、引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
二、redis.properties配置

#Matser的ip地址
redis.hostName=192.168.1.100
#redis.hostName=127.0.0.1
#端口号
redis.port=6379
#如果有密码
redis.password=123456
#redis.password=xxx
#最大空闲数
redis.maxIdle=100
#最大连接数
redis.maxTotal=200
#最大建立连接等待时间。如果超过此时间将接到异常。设为-1表示无限制。
redis.maxWaitMillis=1000
#是否在从池中取出连接前进行检验,如果检验失败,则从池中去除连接并尝试取出另一个
redis.testOnBorrow=true
三、RedisConfig文件和RedisUtil文件
在我的资源里面
四、实体序列化

序列化,就是为了在不同时间或不同平台的JVM之间共享实例对象
Java的序列化机制是通过在运行时判断类的serialVersionUID来验证版本一致性的。
在进行反序列化时,JVM会把传来的字节流中的serialVersionUID与本地相应实体(类)的serialVersionUID进行比较,
如果相同就认为是一致的,可以进行反序列化,否则就会出现序列化版本不一致的异常
五、存储和获取缓存中的值
/**
* 根据id查询帖子详细信息
* @Author tony
* @Date 8:37 2019/12/27
**/
@RequestMapping("/{id}")
public ModelAndView view(@PathVariable("id")Integer id)throws Exception{
ModelAndView mav=new ModelAndView();
Article article=null;
String key="article_"+id;
if(redisUtil.hasKey(key)){
article=(Article) redisUtil.get(key);
}else{
article=articleService.get(id);
redisUtil.set(key, article, 60*60);
}
mav.addObject("article",article);
mav.addObject("title",article.getName());
List<Article> hotArticleList=null;
String hKey="hotArticleList_type_"+article.getArcType().getId();
if(redisUtil.hasKey(hKey)){
hotArticleList=redisUtil.lGet(hKey, 0, -1); //lGet获取集合
}else{
Article s_article=new Article();
s_article.setHot(true);
s_article.setArcType(article.getArcType());
hotArticleList = articleService.list(s_article, 1, 43, Sort.Direction.DESC,"publishDate");
redisUtil.lSet(hKey, hotArticleList, 60*60);
}
mav.addObject("hotArticleList", hotArticleList);
//查询条件
Comment s_comment = new Comment();
s_comment.setArticle(article);
s_comment.setState(1);//审核通过的
mav.addObject("commentCount", commentService.getTotal(s_comment));
mav.setViewName("article");
return mav;
}
2404

被折叠的 条评论
为什么被折叠?



