Spring Boot Redis Entity 별로 TTL 지정하기

By | 2021년 1월 10일
Table of Content

Spring Boot Redis Entity 별로 TTL 지정하기

의존성 추가

아래 설정으로 설정이 끝납니다.

Redis Java Client 는 Lettuce 가 자동으로 추가됩니다.

build.gradle

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-data-redis'
}

EnableRedisRepositories 생성

RedisCacheManager 에서 Entity 마다의 TTL 을 설정할 수 있습니다.

@RequiredArgsConstructor
@Configuration
@Slf4j
@EnableRedisRepositories
public class RedisRepositoryConfig {

    private final RedisProperties redisProperties;

    private final int DEFAULT_EXPIRE_SECONDS = 1;

    private final String ApiAccessInfo = "ApiAccessInfo";
    private final int API_ACCESS_INFO_EXPIRE_SECONDS = 600;

    private final String Menus = "Menus";
    private final int MENUS_EXPIRE_SECONDS = 3600;

    @Bean(name = "cacheManager")
    public RedisCacheManager cacheManager(RedisConnectionFactory connectionFactory) {
        RedisCacheConfiguration configuration = RedisCacheConfiguration.defaultCacheConfig()
                .disableCachingNullValues()
                .entryTtl(Duration.ofSeconds(DEFAULT_EXPIRE_SECONDS))
                .computePrefixWith(CacheKeyPrefix.simple())
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()));

        Map<String, RedisCacheConfiguration> cacheConfigurations = new HashMap<>();

        // ApiAccessInfo
        cacheConfigurations.put(ApiAccessInfo, RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofSeconds(API_ACCESS_INFO_EXPIRE_SECONDS)));

        // Menus
        cacheConfigurations.put(Menus, RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofSeconds(MENUS_EXPIRE_SECONDS)));

        return RedisCacheManager.RedisCacheManagerBuilder.fromConnectionFactory(connectionFactory).cacheDefaults(configuration)
                .withInitialCacheConfigurations(cacheConfigurations).build();
    }

    @Bean
    public RedisConnectionFactory redisConnectionFactory() {
        return new LettuceConnectionFactory(redisProperties.getHost(), redisProperties.getPort());
    }

    @Bean
    public RedisTemplate<?, ?> redisTemplate() {
        RedisTemplate<byte[], byte[]> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory());
        return redisTemplate;
    }
}

Cacheable 추가

Cacheable 을 추가해 줌으로 해서 TTL 이 10분으로 지정됩니다.

@RequiredArgsConstructor
@Service
public class ApiAccessInfoService {

    private final ApiAccessInfoRepository apiAccessInfoRepository;

    @Transactional(readOnly = true)
    @Cacheable(value="ApiAccessInfo")
    public ApiAccessInfoResponseDto findByAccessIdAndAccessKeyAndAccessIp(String accessId, String accessKey, String accessIp) {

        ApiAccessInfo apiAccessInfo = apiAccessInfoRepository.findByAccessIdAndAccessKeyAndAccessIp(accessId, accessKey, accessIp);

        if (apiAccessInfo != null) {
            return new ApiAccessInfoResponseDto(apiAccessInfo);
        }

        return new ApiAccessInfoResponseDto();
    }
}

답글 남기기