Redis Cache annotation

This commit is contained in:
kimyonghwa
2019-08-08 01:52:39 +09:00
parent e729ff1504
commit 945b44fdc7
7 changed files with 150 additions and 10 deletions

View File

@@ -46,6 +46,4 @@ public class RedisConfig {
return RedisCacheManager.RedisCacheManagerBuilder.fromConnectionFactory(connectionFactory).cacheDefaults(configuration) return RedisCacheManager.RedisCacheManagerBuilder.fromConnectionFactory(connectionFactory).cacheDefaults(configuration)
.withInitialCacheConfigurations(cacheConfigurations).build(); .withInitialCacheConfigurations(cacheConfigurations).build();
} }
} }

View File

@@ -5,6 +5,7 @@ import com.rest.api.entity.User;
import com.rest.api.entity.common.CommonDateEntity; import com.rest.api.entity.common.CommonDateEntity;
import lombok.Getter; import lombok.Getter;
import lombok.NoArgsConstructor; import lombok.NoArgsConstructor;
import lombok.Setter;
import org.hibernate.annotations.Proxy; import org.hibernate.annotations.Proxy;
import javax.persistence.*; import javax.persistence.*;
@@ -12,6 +13,7 @@ import java.io.Serializable;
@Entity @Entity
@Getter @Getter
@Setter
@NoArgsConstructor @NoArgsConstructor
public class Post extends CommonDateEntity implements Serializable { public class Post extends CommonDateEntity implements Serializable {
@Id @Id

View File

@@ -1,10 +1,7 @@
package com.rest.api.repo.board; package com.rest.api.repo.board;
import com.rest.api.common.CacheKey;
import com.rest.api.entity.board.Board; import com.rest.api.entity.board.Board;
import com.rest.api.entity.board.Post; import com.rest.api.entity.board.Post;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List; import java.util.List;

View File

@@ -15,6 +15,7 @@ import com.rest.api.service.cache.CacheSevice;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable; import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@@ -39,19 +40,19 @@ public class BoardService {
return Optional.ofNullable(boardJpaRepo.findByName(boardName)).orElseThrow(CResourceNotExistException::new); return Optional.ofNullable(boardJpaRepo.findByName(boardName)).orElseThrow(CResourceNotExistException::new);
} }
// 게시판 이름으로 게시 리스트 조회. // 게시판 이름으로 게시 리스트 조회.
@Cacheable(value = CacheKey.POSTS, key = "#boardName", unless = "#result == null") @Cacheable(value = CacheKey.POSTS, key = "#boardName", unless = "#result == null")
public List<Post> findPosts(String boardName) { public List<Post> findPosts(String boardName) {
return postJpaRepo.findByBoard(findBoard(boardName)); return postJpaRepo.findByBoard(findBoard(boardName));
} }
// 게시ID로 게시 단건 조회. 없을경우 CResourceNotExistException 처리 // 게시ID로 게시 단건 조회. 없을경우 CResourceNotExistException 처리
@Cacheable(value = CacheKey.POST, key = "#postId", unless = "#result == null") @Cacheable(value = CacheKey.POST, key = "#postId", unless = "#result == null")
public Post getPost(long postId) { public Post getPost(long postId) {
return postJpaRepo.findById(postId).orElseThrow(CResourceNotExistException::new); return postJpaRepo.findById(postId).orElseThrow(CResourceNotExistException::new);
} }
// 게시을 등록합니다. 게시의 회원UID가 조회되지 않으면 CUserNotFoundException 처리합니다. // 게시을 등록합니다. 게시의 회원UID가 조회되지 않으면 CUserNotFoundException 처리합니다.
@CacheEvict(value = CacheKey.POSTS, key = "#boardName") @CacheEvict(value = CacheKey.POSTS, key = "#boardName")
public Post writePost(String uid, String boardName, ParamsPost paramsPost) { public Post writePost(String uid, String boardName, ParamsPost paramsPost) {
Board board = findBoard(boardName); Board board = findBoard(boardName);
@@ -59,7 +60,8 @@ public class BoardService {
return postJpaRepo.save(post); return postJpaRepo.save(post);
} }
// 게시을 수정합니다. 게시 등록자와 로그인 회원정보가 틀리면 CNotOwnerException 처리합니다. // 게시을 수정합니다. 게시 등록자와 로그인 회원정보가 틀리면 CNotOwnerException 처리합니다.
//@CachePut(value = CacheKey.POST, key = "#postId") 갱신된 정보만 캐시할경우에만 사용!
public Post updatePost(long postId, String uid, ParamsPost paramsPost) { public Post updatePost(long postId, String uid, ParamsPost paramsPost) {
Post post = getPost(postId); Post post = getPost(postId);
User user = post.getUser(); User user = post.getUser();
@@ -72,7 +74,7 @@ public class BoardService {
return post; return post;
} }
// 게시을 삭제합니다. 게시 등록자와 로그인 회원정보가 틀리면 CNotOwnerException 처리합니다. // 게시을 삭제합니다. 게시 등록자와 로그인 회원정보가 틀리면 CNotOwnerException 처리합니다.
public boolean deletePost(long postId, String uid) { public boolean deletePost(long postId, String uid) {
Post post = getPost(postId); Post post = getPost(postId);
User user = post.getUser(); User user = post.getUser();

View File

@@ -0,0 +1,67 @@
package com.rest.api.cache;
import com.rest.api.entity.board.Post;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
@Service
public class CacheRepo {
private static final String CACHE_KEY = "CACHE_TEST";
@Cacheable(value = CACHE_KEY, key = "#postId")
public Post getPost(long postId) {
Post post = new Post();
post.setPostId(postId);
post.setTitle("title_" + postId);
post.setAuthor("author_" + postId);
post.setContent("content_" + postId);
return post;
}
@CachePut(value = CACHE_KEY, key = "#post.postId")
public Post updatePost(Post post) {
return post;
}
@Cacheable(value = CACHE_KEY, key = "{#postId, #title}")
public Post getPostMultiKey(long postId, String title) {
Post post = new Post();
post.setPostId(postId);
post.setTitle("title_" + postId);
post.setAuthor("author_" + postId);
post.setContent("content_" + postId);
return post;
}
@CachePut(value = CACHE_KEY, key = "{#post.postId, #post.title}")
// @CachePut(value = CACHE_KEY, key = "{#post.postId, #post.getTitle()}")
public Post updatePostMultiKey(Post post) {
return post;
}
@CacheEvict(cacheNames = {CACHE_KEY}, allEntries = true)
public void clearCache(){}
@Cacheable(value = CACHE_KEY, key = "{#postId}", condition="#postId > 10")
public Post getPostCondition(long postId) {
Post post = new Post();
post.setPostId(postId);
post.setTitle("title_" + postId);
post.setAuthor("author_" + postId);
post.setContent("content_" + postId);
return post;
}
@Cacheable(value = CACHE_KEY, key = "T(com.rest.api.cache.CustomKeyGenerator).create(#postId, #title)")
public Post getPostKeyGenerator(long postId, String title) {
Post post = new Post();
post.setPostId(postId);
post.setTitle("title_" + postId);
post.setAuthor("author_" + postId);
post.setContent("content_" + postId);
return post;
}
}

View File

@@ -0,0 +1,67 @@
package com.rest.api.cache;
import com.rest.api.entity.board.Post;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import static org.junit.Assert.*;
@RunWith(SpringRunner.class)
@SpringBootTest
public class CacheTest {
@Autowired
private CacheRepo cacheRepo;
@Test
public void cacheTest() throws Exception {
// get cache
Post post = cacheRepo.getPost(1L);
assertSame(1L, post.getPostId());
assertEquals("title_1", post.getTitle());
// update cache
post.setTitle("title_modified");
post.setContent("content_modified");
cacheRepo.updatePost(post);
// get cache
Post postModified = cacheRepo.getPost(1L);
assertEquals("title_modified", postModified.getTitle());
assertEquals("content_modified", postModified.getContent());
}
@Test
public void cacheTestMultiKey() throws Exception {
// get cache
Post post = cacheRepo.getPostMultiKey(1L, "title_1");
assertSame(1L, post.getPostId());
assertEquals("title_1", post.getTitle());
// update cache
post.setTitle("title_modified");
post.setContent("content_modified");
cacheRepo.updatePostMultiKey(post);
// get cache
Post postModified = cacheRepo.getPostMultiKey(1L, "title_modified");
assertEquals("title_modified", postModified.getTitle());
assertEquals("content_modified", postModified.getContent());
}
@Test
public void cacheTestCustomKeyGenerator() throws Exception {
// get cache
Post post = cacheRepo.getPostKeyGenerator(1L, "title_1");
assertSame(1L, post.getPostId());
assertEquals("title_1", post.getTitle());
}
@Test
public void deleteAllCache() {
cacheRepo.getPost(1L);
cacheRepo.getPost(2L);
cacheRepo.getPost(3L);
cacheRepo.getPost(4L);
cacheRepo.clearCache();
}
}

View File

@@ -0,0 +1,7 @@
package com.rest.api.cache;
public class CustomKeyGenerator {
public static Object create(Object o1, Object o2) {
return "FRONT:" + o1 + ":" + o2;
}
}