springboot integrates redis (cache annotation)

1. Introducing dependencies

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

        <!-- spring2.X集成redis所需common-pool2 -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
            <version>2.6.0</version>
        </dependency>

2. Create a redis configuration class

@EnableCaching
@Configuration
public class RedisConfig extends CachingConfigurerSupport {
    
    

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
    
    
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        RedisSerializer<String> redisSerializer = new StringRedisSerializer();
        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.setConnectionFactory(factory);
        //key序列化方式
        template.setKeySerializer(redisSerializer);
        //value序列化
        template.setValueSerializer(jackson2JsonRedisSerializer);
        //value hashmap序列化
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        return template;
    }

    @Bean
    public CacheManager cacheManager(RedisConnectionFactory factory) {
    
    
        RedisSerializer<String> redisSerializer = new StringRedisSerializer();
        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);
        // 配置序列化(解决乱码的问题),过期时间600秒
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofSeconds(600))
              .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))
                .disableCachingNullValues();
        RedisCacheManager cacheManager = RedisCacheManager.builder(factory)
                .cacheDefaults(config)
                .build();
        return cacheManager;
    }
}

3. Add redis basic configuration information

#insert redis config
spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.database= 4
spring.redis.timeout=1800000

spring.redis.lettuce.pool.max-active=20
spring.redis.lettuce.pool.max-wait=-1
#最大阻塞等待时间(负数表示没限制)
spring.redis.lettuce.pool.max-idle=5
spring.redis.lettuce.pool.min-idle=0

4. Add redis cache to the interface

springboot cache annotation

(1) @Cacheable
caches the returned result according to the method. When the next request is made, if the cache exists, the cached data is directly read and returned; if the cache does not exist, the method is executed and the returned result is stored in the cache.Generally used in query methods.
insert image description here
(2) The @CachePut
method marked with this annotation will be executed every time and the result will be stored in the specified cache. Other methods can read cached data directly from the response cache without having to query the database.Generally used in the method of adding.
insert image description here
(3) @CacheEvict
uses this annotation to clear the specified cache. Generally used in update or delete methods.
insert image description here

Use of cache annotations

For example, query operation:
Here, for the convenience of testing the effect, write the business logic directly in the controller:

    @Autowired
    private CrmBannerService crmBannerService;

    @GetMapping("/getAllBanner")
    @Cacheable(value = "banner",key = "'listTwoBanner'")
    @ApiOperation("获取全部轮播图")
    public Result<List<CrmBanner>> listAllBanner(){
    
    
        QueryWrapper<CrmBanner> wrapper = new QueryWrapper<>();
        wrapper.last("limit 2");
        List<CrmBanner> list = crmBannerService.list(wrapper);
        return new ResultUtil<List<CrmBanner>>().setData(list);
    }

Run the program, and the front end initiates an interface request:
open the redis management tool, and you can see
insert image description here
that the redis cache key value is "banner::listTwoBanner", which is { {value}} splicing "::" splicing { {key}}

Guess you like

Origin blog.csdn.net/weixin_42194695/article/details/125586387