Springboot 集成了 cache ,它可以说是一种规范,主要作用用于数据缓存,提升查询的效率。
下面主要配置了使用redis 来进行缓存操作。
首先选择springboot 项目,选择要引入的依赖
developer tool 中 lombok
Nosql 中 spring data redis
i/o 中 spring cache abstraction
接着 docker 启动一个 redis
docker run -d --name myredis -p 6379:6379 redis --requirepass “密码”
springboot 配置文件中配置 redis
spring.redis.port=6379(和上面启动的容器的端口号一致)
spring.redis.password=你的redis密码
spring.redis.host=linux机器的ip
接着就是测试
首先在启动类上面加上开启缓存的注解
@SpringBootApplication
@EnableCaching//开启缓存功能
public class RediscacheApplication {
public static void main(String[] args) {
SpringApplication.run(RediscacheApplication.class, args);
}
}
定义User类
因为要使用redis 序列化 ,所以要实现序列化接口
定义一个UserService,主要测试三个注解。
@Cacheable :缓存数据
@CachePut : 更新缓存的数据
@CacheEvict : 删除缓存的数据
@Cacheable(cacheNames = "sc", key = "#id")
//多个参数可以使用#标识哪一个是key,否则就会把所有的参数都当成key
public User getUser(int id){
System.out.println("调用了一次");
User user = new User();
user.setId(id);
user.setName("hhh");
return user;
}
cacheNames我在测试的时候必须要添加,作为缓存到redis 的键值对的 key 的前缀,否则会报错。
key 则是表示使用id 作为key ,只有一个参数其实可以不用使用key 参数。但是如果是多个参数则是必须要添加。通过多次调用此方法,最终输出结果打印一次“调用了一次”,多次输出user。
如果数据库的数据发生了更新,此时需要进行更新缓存。
@CachePut(cacheNames = "sc", key = "#user.id")
public User updateUser(User user) {
return user;
}
同样需要配置cacheNames 以及 配置key 是根据该对象的哪一个属性来进行更新的,一般都是唯一的主键 id。
最后如果是要删除缓存,如下。
@CacheEvict(cacheNames = "sc")
public void deleteUser(int id){
System.out.println("id delete");
}
通过该注解指定cacheNames 即可,并传入id 通过 id 来删除缓存。
该缓存只要实现了注解,就会自动向redis 中存储数据。其他的缓存原理大致是一致的。