概述
springboot通常整合redis,采用的是RedisTemplate的形式,除了這種形式以外,還有另外一種形式去整合,即采用spring支持的注解進行訪問緩存.
准備工作
pom.xml
1 <dependency> 2 <groupId>redis.clients</groupId> 3 <artifactId>jedis</artifactId> 4 <version>2.7.3</version> 5 </dependency> 6 <dependency> 7 <groupId>org.springframework.data</groupId> 8 <artifactId>spring-data-redis</artifactId> 9 <version>1.7.2.RELEASE</version> 10 </dependency> 11 <dependency> 12 <groupId>org.springframework.boot</groupId> 13 <artifactId>spring-boot-starter-redis</artifactId> 14 <version>RELEASE</version> 15 </dependency> 16
application.properties
1 # REDIS (RedisProperties) 2 # Redis數據庫索引(默認為0) 3 spring.redis.database=0 4 # Redis服務器地址 5 spring.redis.host=127.0.0.1 6 # Redis服務器連接端口 7 spring.redis.port=6379 8 # 連接池最大連接數(使用負值表示沒有限制) 9 spring.redis.pool.max-active=8 10 # 連接池最大阻塞等待時間(使用負值表示沒有限制) 11 spring.redis.pool.max-wait=-1 12 # 連接池中的最大空閑連接 13 spring.redis.pool.max-idle=8 14 # 連接池中的最小空閑連接 15 spring.redis.pool.min-idle=0 16 # 連接超時時間(毫秒) 17 spring.redis.timeout=0
Redis配置類
1 package cn.chenlove.config; 2 3 import org.apache.log4j.Logger; 4 import org.springframework.beans.factory.annotation.Value; 5 import org.springframework.cache.annotation.CachingConfigurerSupport; 6 import org.springframework.cache.annotation.EnableCaching; 7 import org.springframework.context.annotation.Bean; 8 import org.springframework.context.annotation.Configuration; 9 10 import redis.clients.jedis.JedisPool; 11 import redis.clients.jedis.JedisPoolConfig; 12 13 @Configuration 14 @EnableCaching 15 public class RedisConfig extends CachingConfigurerSupport{ 16 @Value("${spring.redis.host}") 17 private String host; 18 19 @Value("${spring.redis.port}") 20 private int port; 21 22 @Value("${spring.redis.timeout}") 23 private int timeout; 24 25 @Value("${spring.redis.pool.max-idle}") 26 private int maxIdle; 27 28 @Value("${spring.redis.pool.max-wait}") 29 private long maxWaitMillis; 30 31 @Bean 32 public JedisPool redisPoolFactory() { 33 Logger.getLogger(getClass()).info("JedisPool注入成功!!"); 34 Logger.getLogger(getClass()).info("redis地址:" + host + ":" + port); 35 JedisPoolConfig jedisPoolConfig = new JedisPoolConfig(); 36 jedisPoolConfig.setMaxIdle(maxIdle); 37 jedisPoolConfig.setMaxWaitMillis(maxWaitMillis); 38 39 JedisPool jedisPool = new JedisPool(jedisPoolConfig, host, port, timeout); 40 41 return jedisPool; 42 } 43 }
可以看出,我們這里主要配置了兩個東西,cacheManager方法配置了一個緩存名稱,它的名字叫做thisredis,當我們要在方法注解里面使用到它的時候,就要根據名稱進行區分不同緩存.同時設置了緩
存的過期時間.redisTemplate則是比較常見的,我們設置了RedisTemplate,因此在代碼里面,我們也可以通過@Autowired注入RedisTemplate來操作redis.
使用
接下來就是如何使用注解啦,這一步反而是最簡單的.其實只用到了兩個注解,@Cacheable和@CacheEvict.第一個注解代表從緩存中查詢指定的key,如果有,從緩存中取,不再執行方法.如果沒有則執
行方法,並且將方法的返回值和指定的key關聯起來,放入到緩存中.而@CacheEvict則是從緩存中清除指定的key對應的數據.使用的代碼如下:
1 //有參數 2 @Cacheable(value="thisredis", key="'users_'+#id") 3 public User findUser(Integer id) { 4 User user = new User(); 5 user.setUsername("hlhdidi"); 6 user.setPassword("123"); 7 user.setUid(id.longValue()); 8 System.out.println("log4j2壞啦?"); 9 logger.info("輸入user,用戶名:{},密碼:{}",user.getUsername(),user.getPassword()); 10 return user; 11 } 12 13 @CacheEvict(value="thisredis", key="'users_'+#id",condition="#id!=1") 14 public void delUser(Integer id) { 15 // 刪除user 16 System.out.println("user刪除"); 17 } 18 19 //無參數 20 @RequestMapping("/get") 21 @Cacheable(value="thisredis") 22 @ResponseBody 23 public List<User> xx(){ 24 return userMapper.selectAll(); 25 } 26 @RequestMapping("/get3") 27 @CacheEvict(value="thisredis") 28 @ResponseBody 29 public String xx3(){ 30 return "ok"; 31 }
可以看出,我們用@Cacheable的value屬性指定具體緩存,並通過key將其放入緩存中.這里key非常靈活,支持spring的el表達式,可以通過方法參數產生可變的key(見findUser方法),也可以通過其指定在
什么情況下,使用/不使用緩存(見delUser方法).