Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

spring cache 세팅 및 테스트 #10

Merged
merged 1 commit into from
Mar 30, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,11 @@ dependencies {
// redis
implementation 'org.springframework.boot:spring-boot-starter-data-redis:3.2.3'

// spring cache
implementation 'org.springframework.boot:spring-boot-starter-cache'

testCompileOnly 'org.projectlombok:lombok'
testAnnotationProcessor 'org.projectlombok:lombok'

}

Expand Down
44 changes: 44 additions & 0 deletions src/main/java/com/LetMeDoWith/LetMeDoWith/config/CacheConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package com.LetMeDoWith.LetMeDoWith.config;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

import org.springframework.cache.CacheManager;
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.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import com.LetMeDoWith.LetMeDoWith.enums.SocialProvider;

@EnableCaching
@Configuration
public class CacheConfig {

@Bean
public CacheManager socialProviderPublicKeyCacheManager(RedisConnectionFactory cf) {
RedisCacheConfiguration defaultConfig = RedisCacheConfiguration.defaultCacheConfig()
.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
.serializeValuesWith(
RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()))
.entryTtl(Duration.ofMinutes(1L));// TODO - default TTL

Map<String, RedisCacheConfiguration> individualConfiguration = new HashMap<>();
// TODO - 각 Social Provider 마다 API Refresh Time 고려하여 TTL 설정 변경 필요
individualConfiguration.put(SocialProvider.APPLE.getCode(), defaultConfig.entryTtl(Duration.ofMinutes(1L)));
individualConfiguration.put(SocialProvider.GOOGLE.getCode(), defaultConfig.entryTtl(Duration.ofMinutes(1L)));
individualConfiguration.put(SocialProvider.KAKAO.getCode(), defaultConfig.entryTtl(Duration.ofMinutes(1L)));

return RedisCacheManager.RedisCacheManagerBuilder
.fromConnectionFactory(cf)
.cacheDefaults(defaultConfig)
.withInitialCacheConfigurations(individualConfiguration)
.build();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
package com.LetMeDoWith.LetMeDoWith.common;

import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import com.LetMeDoWith.LetMeDoWith.common.code.TestRepository;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@SpringBootTest
public class RedisCacheTest {

@Autowired
private TestRepository testRepository;

@Test
void objectTypeCacheSuccessTest() throws InterruptedException {

//given

//when
TestRepository.TestDto result1 = testRepository.testObject();
log.debug(result1.toString());
Thread.sleep(2000);
TestRepository.TestDto result2 = testRepository.testObject();
log.debug(result1.toString());

//then
Assertions.assertThat(result2.val1()).isEqualTo(result1.val1());
Assertions.assertThat(result2.val2()).isEqualTo(result1.val2());

}

@Test
void monoTypeNonBlockCacheSuccessTest() throws InterruptedException {

//given

//when
testRepository.testMono().subscribe(body -> log.debug(body.toString()));
Thread.sleep(2000);
testRepository.testMono().subscribe(body -> log.debug(body.toString()));

//then
// Assertions.assertThat(result2.val1()).isEqualTo(result1.val1());
// Assertions.assertThat(result2.val2()).isEqualTo(result1.val2());

}

@Test
void monoTypeBlockCacheSuccessTest() throws InterruptedException {

//given

//when
TestRepository.TestResponseDto result1 = testRepository.testMono().block();
Thread.sleep(2000);
TestRepository.TestResponseDto result2 = testRepository.testMono().block();

//then
Assertions.assertThat(result2.toString()).isEqualTo(result1.toString());

}

}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package com.LetMeDoWith.LetMeDoWith.client;
package com.LetMeDoWith.LetMeDoWith.common;

import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.DisplayName;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
package com.LetMeDoWith.LetMeDoWith.common.code;

import java.util.HashMap;
import java.util.Map;

import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Repository;
import org.springframework.web.reactive.function.client.WebClient;

import lombok.Builder;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import reactor.core.publisher.Mono;

@Slf4j
@Repository
@RequiredArgsConstructor
@CacheConfig(cacheNames = "APPLE", cacheManager = "socialProviderPublicKeyCacheManager")
public class TestRepository {

private final WebClient webClient;

private static String testUrl = "https://jsonplaceholder.typicode.com/todos/1";

private Map<String, Object> store = new HashMap<>();

@Cacheable(key = "'publicKey-String'")
public TestDto testObject() {
log.debug(">>>Test Method executed");
TestDto testDto = TestDto.builder().val1("value1").val2("value2").build();
store.put("testData", testDto);
return testDto;
}

@Cacheable(key = "'publicKey-Mono'")
public Mono<TestResponseDto> testMono() {
log.debug(">>>TestMono Method executed");
return webClient.get()
.uri(testUrl)
.accept(MediaType.APPLICATION_JSON)
.retrieve()
.onStatus(HttpStatusCode::isError, clientResponse ->
clientResponse.bodyToMono(String.class).map(body -> new Exception()))
.bodyToMono(TestResponseDto.class);
}


@Builder
public static record TestDto(String val1, String val2) {}

public record TestResponseDto(Long userId, Long id, String title, Boolean completed) {}
}