1.linux开启单机redis或者redis集群
命令省略……
2.引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
3.properties的配置:
spring.redis.host:192.168.159.11
spring.redis.port:6379
4.需要缓存的对象要序列化
5.RedisTemplate 使用
@autowired
RedisTemplate redisTemplate;
@autowired
AService aService;
@getmapping("/redis")
public list<A> getAllAById(@requestparam id){
list<A> list1=null;
hashOperations hash=redisTemplate.opsForHash();
list1=hash.get("ads","big");
if(list1!=null&&list1.size()>0){
//表示当前缓存内有key=ads的数据
return list1;
}
//否则就进入数据库查询
list<A> list= aService.getAllAById(id);
list<B> bs=new arrayList<>();
//写相关的业务
for(A a:list){
//业务
B b=new B();
//业务
bs.add(b);
}
hash.set("ads","big",bs);
return bs;
}
6.RedisTemplate 主要API
redisTemplate.opsForValue();//操作字符串
redisTemplate.opsForHash();//操作hash
redisTemplate.opsForList();//操作list
redisTemplate.opsForSet();//操作set
redisTemplate.opsForZSet();//操作有序set