SpringBoot uses the implementation of the Redis cache

  • 2021-01-22 05:07:34
  • OfStack

(1) pom.xml introduces the jar package as follows:


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

(2) Modify the project startup class and add annotation @EnableCaching to enable caching function, as follows:


package springboot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableScheduling
@EnableCaching
public class SpringbootApplication{
  public static void main(String[] args) {
    SpringApplication.run(SpringbootApplication.class, args);
  }
}

(3) Redis connection information is configured in application.properties as follows:


# Redis Database index (default is 0 ) 
spring.redis.database=0
# Redis Server address 
spring.redis.host=172.31.19.222
# Redis Server connection port 
spring.redis.port=6379
# Redis Server connection password (empty by default) 
spring.redis.password=
#  Maximum number of connection pool connections (use negative values to indicate no limit) 
spring.redis.pool.max-active=8
#  Connection pool maximum blocking wait time (use negative values to indicate no limit) 
spring.redis.pool.max-wait=-1
#  Maximum free connection in the connection pool 
spring.redis.pool.max-idle=8
#  The minimum free connection in the connection pool 
spring.redis.pool.min-idle=0
#  Connection timeout in milliseconds 
spring.redis.timeout=0

Create a new Redis cache configuration class RedisConfig as follows:


package springboot.config;
import org.springframework.beans.factory.annotation.Value;
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;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
 * Redis Cache configuration class 
 * @author szekinwin
 *
 */
@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;
  // Custom cache key Generation strategy 
//  @Bean
//  public KeyGenerator keyGenerator() {
//    return new KeyGenerator(){
//      @Override
//      public Object generate(Object target, java.lang.reflect.Method method, Object... params) {
//        StringBuffer sb = new StringBuffer();
//        sb.append(target.getClass().getName());
//        sb.append(method.getName());
//        for(Object obj:params){
//          sb.append(obj.toString());
//        }
//        return sb.toString();
//      }
//    };
//  }
  // Cache manager 
  @Bean 
  public CacheManager cacheManager(@SuppressWarnings("rawtypes") RedisTemplate redisTemplate) {
    RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
    // Set the cache expiration time  
    cacheManager.setDefaultExpiration(10000);
    return cacheManager;
  }
  @Bean
  public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory){
    StringRedisTemplate template = new StringRedisTemplate(factory);
    setSerializer(template);// Set up the serialization tool 
    template.afterPropertiesSet();
    return template;
  }
   private void setSerializer(StringRedisTemplate template){
      @SuppressWarnings({ "rawtypes", "unchecked" })
      Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
      ObjectMapper om = new ObjectMapper();
      om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
      om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
      jackson2JsonRedisSerializer.setObjectMapper(om);
      template.setValueSerializer(jackson2JsonRedisSerializer);
   }
}

(5) Create UserMapper as follows:


package springboot.dao;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import springboot.domain.User;
@Mapper
@CacheConfig(cacheNames = "users")
public interface UserMapper {
  @Insert("insert into user(name,age) values(#{name},#{age})")
  int addUser(@Param("name")String name,@Param("age")String age);
  @Select("select * from user where id =#{id}")
  @Cacheable(key ="#p0") 
  User findById(@Param("id") String id);
  @CachePut(key = "#p0")
  @Update("update user set name=#{name} where id=#{id}")
  void updataById(@Param("id")String id,@Param("name")String name);
  // If specified as  true , all caches will be cleared immediately after the method call 
  @CacheEvict(key ="#p0",allEntries=true)
  @Delete("delete from user where id=#{id}")
  void deleteById(@Param("id")String id);
}

@Cacheable caches the result of the query into redis, and (key="#p0") specifies the first parameter passed in as key for redis.

@CachePut, specify key to synchronize the updated results into redis

@CacheEvict, specify key, delete the cached data, allEntries=true, the cache will be cleared immediately after the method is called

(6) The service layer and controller layer are integrated in the same way as the previous article. Start redis server. The installation and startup of redis server can refer to the previous blog, the address is as follows:

http://www.cnblogs.com/gdpuzxs/p/6623171.html

Configure log4j log information as follows:


## LOG4J configuration 
log4j.rootCategory=DEBUG,stdout
##  Console output 
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} %5p %c{1}:%L - %m%n

(8) Verify the redis cache

INSERT TABLE user INTO TABLE user;

Now, we are under the query 1 user id = 24 data in the table, wipe the console output of information, as follows:

As you can see from the console output, this time the database query was executed and ES75en was enabled to cache the query results. Select * from table id where id=24; select * from table id where id=24;

From the console output, we can see that this time, instead of executing a database query, the query is retrieved from the Redis cache and the query results are returned. Let's look at the information in redis as follows:

The finduser method uses the annotation @Cacheable (key="#p0"), which refers to id as the key value in redis. When we update the data, we should use @CachePut (key="#p0") to update the cached data, otherwise we will query to dirty data.

conclusion

The above is the site to introduce SpringBoot using Redis cache implementation method, hope to be helpful to you, if you have any questions welcome to give me a message, this site will reply to you in time!


Related articles: