>  기사  >  데이터 베이스  >  springboot와 redis 통합에서 @Cacheable을 사용하는 방법

springboot와 redis 통합에서 @Cacheable을 사용하는 방법

王林
王林앞으로
2023-05-28 20:59:121448검색

먼저 캐시 관리자를 구성한 다음 캐시 주석을 사용하여 캐시를 관리할 수 있습니다

package com.cherish.servicebase.handler;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
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.RedisCacheConfiguration;
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.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;

@Configuration
@EnableCaching
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)
             // 可以给每个cacheName不同的RedisCacheConfiguration  设置不同的过期时间
            //.withCacheConfiguration("Users",config.entryTtl(Duration.ofSeconds(100)))
                .transactionAware()
                .build();
        return cacheManager;
    }
}

1. @Cacheable

은 메서드나 클래스에 표시되어 해당 메서드나 클래스가 캐싱을 지원함을 나타냅니다. Spring이 주석 식별 메소드를 호출한 후, 반환 값은 Redis에 캐시되어 다음에 동일한 조건으로 메소드가 호출될 때 반환 값이 캐시에서 직접 얻어질 수 있도록 보장합니다. 이렇게 하면 이 방법의 비즈니스 처리 프로세스를 다시 실행할 필요가 없어 효율성이 향상됩니다.

@Cacheable에서 일반적으로 사용되는 세 가지 매개 변수는 다음과 같습니다.

cacheNames 캐시 이름
캐시 키, 키 쓰기 방법에 주의해야 함
캐시 실행 조건, true가 반환될 때 실행

Example

    //查询所有用户,缓存到redis中
    @GetMapping("/selectFromRedis")
    @Cacheable(cacheNames = "Users",key = "&#39;user&#39;")
    public ResultData getUserRedis(){
        List<User> list = userService.list(null);
        return ResultData.ok().data("User",list);
    }

springboot와 redis 통합에서 @Cacheable을 사용하는 방법

첫 번째 쿼리는 데이터베이스에서 쿼리된 다음 Redis에 캐시됩니다. Redis 시각화 도구를 사용하여 캐시된 정보를 봅니다.

springboot와 redis 통합에서 @Cacheable을 사용하는 방법

두 번째 쿼리는 캐시 콘솔로 이동합니다. 출력이 없으므로 Redis 캐시는 Redis에서 결과를 가져와 직접 반환하는 것입니다. 메소드에

springboot와 redis 통합에서 @Cacheable을 사용하는 방법

@CacheEvict

표시가 되어 있으며, 메소드 실행 후 조건이나 키에 따라 해당 캐시가 삭제됩니다. 일반적으로 사용되는 속성:

  • allEntries 부울 유형, 캐시의 모든 요소를 ​​지워야 하는지 여부를 나타냄

  • key 삭제해야 하는 캐시된 키

 //调用这个接口结束后,删除指定的Redis缓存
    @PostMapping("updateUser")
    @CacheEvict(cacheNames ="Users",key = "&#39;user&#39;")
    public ResultData updateUser(@RequestBody User user){
        String id = user.getId();
        QueryWrapper<User> wrapper=new QueryWrapper<>();
        wrapper.eq("id",id);
        boolean b = userService.update(user, wrapper);
        return ResultData.ok().data("flag",b);
    }
 //不删除redis缓存
    @PostMapping("updateUser2")
    public ResultData updateUser2(@RequestBody User user){
        String id = user.getId();
        QueryWrapper<User> wrapper=new QueryWrapper<>();
        wrapper.eq("id",id);
        boolean b = userService.update(user, wrapper);
        return ResultData.ok().data("flag",b);
    }

데이터베이스의 데이터를 업데이트할 때, Redis 비어 있음을 캐시해야 합니다. 그렇지 않으면 우리가 쿼리하는 데이터는 Redis Cache의 데이터이므로 데이터베이스와 캐시된 데이터 간에 불일치가 발생합니다.

예: @CacheEvict 주석 없이 인터페이스를 호출하여 데이터를 수정합니다. 쿼리에서 얻은 데이터는 수정 전입니다.

springboot와 redis 통합에서 @Cacheable을 사용하는 방법

그래서 데이터를 수정하기 위해 인터페이스를 호출할 때 캐시를 지워야 합니다.

해당 캐시를 지우려면 @CacheEvict 주석을 추가하세요. 이때 데이터를 쿼리하면 데이터가 다음과 같습니다. 최신이고 데이터베이스와 일치합니다.

springboot와 redis 통합에서 @Cacheable을 사용하는 방법

Expiration time

Spring Cache의 기본 기능을 구현하고 Redis를 RedisCacheManger,但众所周知,我们在使用@Cacheableannotation으로 통합했습니다. 이는 캐시에 부여할 수 없는 만료 시간입니다. 그러나 때로는 일부 시나리오에서는 캐시에 만료 시간을 주어야 하는 경우도 있습니다. 이것은 기본 만료 시간입니다

springboot와 redis 통합에서 @Cacheable을 사용하는 방법

데이터 유효 시간

springboot와 redis 통합에서 @Cacheable을 사용하는 방법

사용자 지정 만료 시간

springboot와 redis 통합에서 @Cacheable을 사용하는 방법

새 Redis 구성을 사용하고 캐시를 다시 쿼리하여 데이터 유효 기간을 확인하세요

springboot와 redis 통합에서 @Cacheable을 사용하는 방법

위 내용은 springboot와 redis 통합에서 @Cacheable을 사용하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 yisu.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제