A preface

Public account: Knowledge seeker

Inheriting the spirit of open Source, Spreading technology knowledge;

Pring provides us with caching annotations Spring Cache. Spring supports a variety of caching technologies: RedisCacheManager, EhCacheCacheManager, GuavaCacheManager, etc., today’s content is the integration of RedisCacheManager cache technology;

The second Spring Cache

Common spring Cache annotations are as follows

2.1 @ Cacheable

Add data to cache

The parameters are as follows:

  • CacheNames Cache name
  • Key Specifies the SPEL expression for the cache key
  • Condition Specifies the condition that the cache executes, executed when true is returned

2.2 @ CachePut

Effect: Modified the database data and updated the cache.

The parameters are as follows:

  • CacheNames Cache name
  • Key Specifies the SPEL expression for the cache key
  • Condition Specifies the condition that the cache executes, executed when true is returned

2.3 @ CacheEvict

Action: Delete data, delete cache

The parameters are as follows:

  • AllEntries Boolean type, indicating whether to clear all elements in the cache
  • Key Indicates the cache key to be deleted

Three Integration Configuration

3.1 depend on

Springboot 2.1.1

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

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

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

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.18</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.0</version>
        </dependency>
    </dependencies>
Copy the code

3.2 application. Yml

Mainly redis and database link configuration; If you use mysql itself better database link drivers and dependencies;

server:
  port: 9000

spring:
  redis:
    # Redis server address
    host: localhost
    #Redis server connection port
    port: 6379
    #password:
    # Redis database index (default 0)
    database: 2
    Connection timeout (ms)
    timeout: 5000
    jedis:
      pool:
        # maximum number of connections in the pool (use negative values to indicate no limit)
        max-active: 100
        Minimum free connection in connection pool
        max-idle: 10
        Maximum connection pool blocking wait time (negative value indicates no limit)
        max-wait: 100000
  # database configuration
  datasource:
    driverClassName: org.postgresql.Driver
    url: JDBC: postgresql: / / 127.0.0.1:5432 / springboot
    username: postgres
    password: 123456

logging:
  level:
    com.zszxz.cach.mapper : debug
Copy the code

3.3 redis configuration

The main thing is to set up CacheManager and redisTemplate; And support the default key expiration time, and garble problem solving;

/ * * *@AuthorLSC * <p> Redis configuration </p> */
@Configuration
@EnableCaching
public class RedisConfig  extends CachingConfigurerSupport {



    /* * * @author LSC * 

Custom key generation rule

* @param [] * @return KeyGenerator */
@Override @Bean public KeyGenerator keyGenerator(a) { return new KeyGenerator() { @Override public Object generate(Object o, Method method, Object... objects) { // Formats the cache key string StringBuilder sb = new StringBuilder(); // Append the class name sb.append(o.getClass().getName()); // Append the method name sb.append(method.getName()); // Iterate over the parameters and append for (Object obj : objects) { sb.append(obj.toString()); } returnsb.toString(); }}; }@Bean public CacheManager cacheManager(RedisConnectionFactory factory) { RedisSerializer<String> redisSerializer = new StringRedisSerializer(); Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); // Resolve the query cache conversion exception ObjectMapper om = new ObjectMapper(); om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper(om); // Configure serialization (solve the problem of garbled characters), expiration time 120 seconds RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig() .entryTtl(Duration.ofSeconds(120)) .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer)) .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer)) .disableCachingNullValues(); RedisCacheManager cacheManager = RedisCacheManager.builder(factory) .cacheDefaults(config) .build(); return cacheManager; } @Bean public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) { / / create redisTemplate RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>(); redisTemplate.setConnectionFactory(connectionFactory); / / use Jackson2JsonRedisSerialize replace the default serialization Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); ObjectMapper objectMapper = new ObjectMapper(); objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper(objectMapper); //set value serializer redisTemplate.setDefaultSerializer(jackson2JsonRedisSerializer); // Key uses String serialization redisTemplate.setKeySerializer(new StringRedisSerializer()); // Value serialization uses Jackson redisTemplate.setValueSerializer(jackson2JsonRedisSerializer); // The hash key also uses String serialization redisTemplate.setHashKeySerializer(new StringRedisSerializer()); // The hash value serialization method uses Jackson redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer); redisTemplate.afterPropertiesSet(); returnredisTemplate; }}Copy the code

3.3 Integrate redis cache with annotations

/* * * @author LSC * 

If set,keyGenerator = "keyGenerator" cannot set key *

* @param [user_id] * @Return com.zszxz.cach.entity.UserEntity */
@Override @Cacheable(cacheNames = "UserEntity", key = "#user_id") public UserEntity getUser(Long user_id) { return userMapper.getUser(user_id); } /* * * @author LSC *

Call the target method first and then cache the result of the method

* @param [userEntity] * @return int */
@Override @CachePut(cacheNames = "UserEntity", key = "#result.user_id") public UserEntity updateUser(UserEntity userEntity) { userMapper.updateUser(userEntity); // Note that the cache will update the value of the non-parameter userEntity return userEntity; } /* * * @author LSC *

allEntries Whether to empty all cache contents. The default value is false.

* @param [user_id] * @return int */
@Override @CacheEvict(cacheNames = "UserEntity", key = "#user_id") public int delUser(Long user_id) { return userMapper.delUser(user_id); } Copy the code

Four test

4.1 Query Test

The test code

    @Test
    public void testGet(a){
        UserEntity user = userService.getUser(1L);
        System.out.println(user);
    }
Copy the code

The first query console prints SQL, and the second query does not print SQL and is fetched directly from Redis

4.2 Modifying the Cache Test

The result of modifying the cache is the return value of the method. Since this side parameter is directly used as the return value, the attribute of the parameter user entity must be full attribute. Otherwise, multiple parameters will be null when querying the cache, but there are values in the database. For example, the user_telephone field over here;

    @Test
    public void testPUT(a){
        UserEntity userEntity = new UserEntity();
        userEntity.setUser_id(1L);
        userEntity.setUser_name("Knowledge seekers");
        userEntity.setUser_gender("female");
        userService.updateUser(userEntity);
    }
Copy the code

4.3 Deleting a Cache Test

After the cache is deleted, the cache of the specified key is deleted.

    @Test
    public void testDel(a){
        userService.delUser(1L);
    }
Copy the code

See the link below for sping CAhe learning

Blog.csdn.net/u012240455/…

This set of tutorials

  • Springboot introduction (1)
  • Springboot Custom banner(2)
  • Springboot configuration file parsing (3)
  • Springboot integration mybatis (4)
  • JdbcTemplate springboot integration (5)
  • Spingboot Unit Test (6)
  • Springboot integration thymeleaf (7)
  • Springboot Multi-file upload (8)
  • Springboot file download (9)
  • Springboot Custom exception Class (10)
  • Springboot Multi-environment Configuration (11)
  • Springboot Automatic configuration principle (12)
  • Springboot integrated with restTemplate interface call (13)
  • Springboot Integrated Task Scheduling (14)
  • Springboot Cross-domain CORS Processing (15)
  • Springboot enables GIZP compression (16)
  • Springboot integration logback (17)
  • Springboot integration Swagger (18)
  • Springboot Integrated Actuator Monitoring (19)
  • Springboot integration mybatis + oracle + druid (20)
  • Springboot integration springsession (21)
  • JWT springboot integration (22)
  • Springboot integration with admin background Monitoring (23)
  • Springboot Integration redis Basics (24)
  • Redis Cache with SpringBoot
  • Springboot uses AOP log interception (26)
  • Springboot integration Validation (27)
  • Springboot integration mybatisPlus (28)
  • Springboot integration shiro (29)
  • Springboot implementation of interface parity check (30)
  • Springboot – integrated web sockets (31)
  • RestTemplate (32)
  • SpringBoot uses @async asynchronous calls with thread pools (33)
  • To be continued

Focus on knowledge seekers: