一.添加redis依赖(分布式)
<!--springboot整合redis依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>springboot-start-data-redis</artifactId>
</dependency>
二.在springboot配置文件中添加Redis的配置
#添加整合redis的配置
## Redis数据库索引(默认为0)
spring.redis.database=0
## Redis服务器地址
spring.redis.host=127.0.0.1
## Redis服务器连接端口
spring.redis.port=6379
## Redis服务器连接密码(默认为空)
spring.redis.password=
## 连接池最大连接数(使用负值表示没有限制)
spring.redis.jedis.pool.max-active=8
## 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.jedis.pool.max-wait=1ms
## 连接池中的最大空闲连接
spring.redis.jedis.pool.max-idle=8
## 连接池中的最小空闲连接
spring.redis.jedis.pool.min-idle=0
## 连接超时时间(毫秒)
spring.redis.timeout=1200ms
三 service controller 层
package com.ddbuy.ddbuycommonservice.service.impl;
import com.alibaba.dubbo.config.annotation.Service;
import com.team.ddbuy.entity.TbContent;
import com.team.ddbuy.entity.TbContentExample;
import com.team.ddbuy.mapper.TbContentMapper;
import com.team.ddbuy.service.TbContentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.concurrent.TimeUnit;
@Service(interfaceClass = TbContentService.class )
@Component
public class TbContentServiceImpl implements TbContentService {
@Autowired
private RedisTemplate redisTemplate;//底层对jedis封装
@Autowired(required = false)
private TbContentMapper tbContentMapper;
@Override
public List<TbContent> getTbContent() {
//实现缓存的思路:
//第一次查询数据库得到结果,并将结果保存到缓存服务器
//第二次获取数据时,从缓存中获取数据
//判断缓存服务器中有没有数据
//判断有没有键
List<TbContent>list=null;
ValueOperations<String,List<TbContent>> options = this.redisTemplate.opsForValue();
if (!this.redisTemplate.hasKey("ContentData")){
TbContentExample tbContentExample=new TbContentExample();
list = tbContentMapper.selectByExample(tbContentExample);
options.set("contentData",list,2, TimeUnit.MINUTES);//存数据
System.out.println("查询数据库,缓存中不存在");
}else{
list=options.get("contentData");
System.out.println("从缓存中拿的");
}
return list;
}
}
package com.ddbuy.ddbuyprotocalweb.controller;
import com.alibaba.dubbo.config.annotation.Reference;
import com.team.ddbuy.entity.TbContent;
import com.team.ddbuy.service.TbContentService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.List;
import java.util.Map;
@Controller
public class TbContentController {
@Reference(interfaceClass = TbContentService.class)
TbContentService tbContentService;
@RequestMapping("/goindex")
public String goindex(Model model){
List<TbContent> list = tbContentService.getTbContent();
model.addAttribute("contents",list);
return "Index";
}
}
四
五
六
七
八