This is the 28th day of my participation in the August Challenge
An overview of the
Springboot usually integrates redis in the form of a RedisTemplate, but there is another form of integration that uses Spring-supported annotations to access the cache.
The preparatory work
pom.xml
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.7.3</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.7.2. RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-redis</artifactId>
<version>RELEASE</version>
</dependency>
Copy the code
application.properties
# REDIS (RedisProperties) # REDIS database index (default 0) spring.redis.database=0 # REDIS server address spring.redis.host=127.0.0.1 # Port =6379 # Connection pool maximum number of connections (negative value indicates no limit) Spring.redis.pool. max-active=8 # Connection pool maximum block wait time (negative value indicates no limit) Spring-redis.pool. max-wait=-1 # Spring-redis.pool. max-idle=8 # Spring-redis.pool. min-idle=0 # Connection timeout (ms) Spring.redis. timeout=0Copy the code
Redis configuration class
package cn.chenlove.config; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Value; 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 redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig; @Configuration @EnableCaching public class RedisConfig extends CachingConfigurerSupport{ @Value("${spring.redis.host}") private String host; @Value("${spring.redis.port}") private int port; @Value("${spring.redis.timeout}") private int timeout; @Value("${spring.redis.pool.max-idle}") private int maxIdle; @Value("${spring.redis.pool.max-wait}") private long maxWaitMillis; @bean public JedisPool redisPoolFactory() {logger.getLogger (getClass()).info("JedisPool added successfully!!" ); Logger.getlogger (getClass()).info("redis address :" + host + ":" + port); JedisPoolConfig jedisPoolConfig = new JedisPoolConfig(); jedisPoolConfig.setMaxIdle(maxIdle); jedisPoolConfig.setMaxWaitMillis(maxWaitMillis); JedisPool jedisPool = new JedisPool(jedisPoolConfig, host, port, timeout); return jedisPool; }}Copy the code
As you can see, there are two main things that are configured here, the cacheManager method is configured with a cache name called ThisRedis, and when we use it in the method annotations, we need to distinguish between caches by name. RedisTemplate is more common, we set redisTemplate, so in code, we can also inject redisTemplate to manipulate Redis via @autoWired.
use
The next step is how to use annotations, which is the easiest. There are actually only two annotations, @cacheable and @cacheevict. The first annotation represents that the specified key is queried from the cache and, if so, fetched from the cache without executing the method. If not, the method is executed and the return value of the method is associated with the specified key and placed in the cache. @cacheevict clears the data for the specified key from the cache. The code used is as follows:
/ / a parameter
@Cacheable(value="thisredis", key="'users_'+#id")
public User findUser(Integer id) {
User user = new User();
user.setUsername("hlhdidi");
user.setPassword("123");
user.setUid(id.longValue());
System.out.println("Log4j2 bad?");
logger.info("Enter user, username :{}, password :{}",user.getUsername(),user.getPassword());
return user;
}
@CacheEvict(value="thisredis", key="'users_'+#id",condition="#id! = 1 ")
public void delUser(Integer id) {
/ / delete the user
System.out.println("The user to delete");
}
/ / no parameters
@RequestMapping("/get")
@Cacheable(value="thisredis")
@ResponseBody
public List<User> xx(a){
return userMapper.selectAll();
}
@RequestMapping("/get3")
@CacheEvict(value="thisredis")
@ResponseBody
public String xx3(a){
return "ok";
}
Copy the code
As you can see, we use the value attribute of @cacheable to specify the specific cache and place it in the cache by key. The key is very flexible here, supporting Spring’s EL expression, which can be used to produce variable keys from method arguments (see the findUser method) as well as to specify when to use/not to use caching (see the delUser method).