springboot Redis 缓存

可以使用内存作为缓存,也可以使用 Redis 作为缓存,内存的弊端是集群的多个实例不发同步

1,添加依赖

<dependency>
         <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

2,配置文件中配置 Redis 数据源

spring.cache.redis.time-to-live:3600s  # 默认不过期,设置一个时间表示过期时间
redis.host=localhost # ip
redis.port=6379 # 端口
redis.jedis.pool.max-active=5 # 连接池
redis.jedis.pool.max-idle=10
redis.jedis.pool.max-wait=10000

3,启动类添加 @EnableCaching 注解

4,在方法上添加 @Cacheable/@CacheEvict/@CachePut 注解或在类上添加 @CacheConfig 注解

@Cacheable 获取缓存(不运行方法),如果没有就运行方法取得并把值放入缓存
@CacheEvict 删除缓存(这个方法每次都会执行,然后去通过方法的返回值去查,有就删除)
@CachePut 更新缓存(这个方法也是每次都执行,通过方法返回值去查,如果有就更新,没有就添加)
@CacheConfig 这个是写在类上面的,用于简化上面3个注解

示例:

示例1:
@Cacheable(cacheNames="user", key="#id")
public User getUserById(int id){}
示例2:
@CachePut(cacheNames="user", key="#user.id")
public User updateUserById(User user){}
示例3:
@CacheEvict(cacheNames="user")
public User deleteUserById(int id){}
// 如果参数是基本类型,那么 key 默认就是他,比如 示例3 中没有写 key,其实和 示例1 是一样的
示例4:
@CacheConfig("user")
public class UserService{
  @Cacheable
  public User getUserById(int id){}
  @CachePut(key="#user.id")
   public User updateUserById(User user){}
}

注意:和异步执行类似,只能在外部调用才会生效

猜你喜欢

转载自www.cnblogs.com/huanggy/p/9473822.html