天天看点

spring boot2.0使用redis做缓存

1.添加依赖

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

     <dependency>           <groupId>org.springframework.boot</groupId>           <artifactId>spring-boot-starter-data-redis</artifactId>      </dependency>      <dependency>           <groupId>org.apache.commons</groupId>           <artifactId>commons-pool2</artifactId>           <version>2.4.2</version>      </dependency>

     <dependency>           <groupId>redis.clients</groupId>           <artifactId>jedis</artifactId>           <version>2.9.0</version>      </dependency>

2.新建配置类

import org.springframework.cache.CacheManager; import org.springframework.cache.annotation.CachingConfigurerSupport; import org.springframework.cache.annotation.EnableCaching; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.cache.RedisCacheManager; import org.springframework.data.redis.connection.RedisConnectionFactory;

@Configuration @EnableCaching //开启缓存支持 public class RedisCacheConfig extends CachingConfigurerSupport{      @Bean      public CacheManager cacheManager(RedisConnectionFactory connectionFactory) {           RedisCacheManager redisCacheManager = RedisCacheManager.create(connectionFactory);           return  redisCacheManager;      } }

3.在application.properties中添加redis的配置

# Redis数据库索引(默认为0) spring.redis.database=0 # Redis服务器地址 spring.redis.host=localhost # Redis服务器连接端口 spring.redis.port=6379 # Redis服务器连接密码(默认为空) spring.redis.password=123456 # 连接池中的最大空闲连接 spring.redis.jedis.pool.max-idle=8 # 连接池中的最小空闲连接 spring.redis.jedis.pool.min-idle=0 # 连接池最大阻塞等待时间(使用负值表示没有限制) spring.redis.jedis.pool.max-wait=-1 # 连接超时时间(毫秒) spring.redis.timeout=0

4.使用 在service方法上使用注解来声明缓存规则:

注解 解释
@Cacheable 在方法执行前先查看缓存中是否有数据,如果有数据,则直接返回缓存数据,若没有数据,调用方法并将方法返回值进行缓存
@CachePut 将方法的返回值放到缓存中
@CacheEvict 删除缓存数据
@Caching 可以通过@Caching注解组合多个注解策略在一个方法上

使用举例:      @Cacheable(value="appInfo",key="#appId")      public AppInfo findByAppId(String appId) {           AppInfo appInfo = appInfoRepository.findByAppId(appId);           return appInfo;      }

继续阅读