diff --git a/springBootBlog/src/main/java/com/yen/mdblog/service/CacheService.java b/springBootBlog/src/main/java/com/yen/mdblog/service/CacheService.java new file mode 100644 index 000000000..66d11f9fb --- /dev/null +++ b/springBootBlog/src/main/java/com/yen/mdblog/service/CacheService.java @@ -0,0 +1,28 @@ +package com.yen.mdblog.service; + +import org.springframework.cache.annotation.Cacheable; +import org.springframework.stereotype.Service; + +/** Cache service created by gpt */ +@Service +public class CacheService { + + /** + * Generic method to cache a result. + * + * @param cacheName the name of the cache + * @param key the cache key + * @param operation the operation to cache + * @param the type of the cached result + * @return the cached result + */ + @Cacheable(value = "#{cacheName}", key = "#{key}") + public T cacheResult(String cacheName, String key, CacheableOperation operation) { + return operation.execute(); + } + + @FunctionalInterface + public interface CacheableOperation { + T execute(); + } +} \ No newline at end of file diff --git a/springBootBlog/src/main/java/com/yen/mdblog/service/impl/PostServiceImpl.java b/springBootBlog/src/main/java/com/yen/mdblog/service/impl/PostServiceImpl.java index bfa504153..c4256d03f 100644 --- a/springBootBlog/src/main/java/com/yen/mdblog/service/impl/PostServiceImpl.java +++ b/springBootBlog/src/main/java/com/yen/mdblog/service/impl/PostServiceImpl.java @@ -3,6 +3,7 @@ import com.yen.mdblog.entity.Dto.SearchRequest; import com.yen.mdblog.entity.Po.Post; import com.yen.mdblog.mapper.PostMapper; +import com.yen.mdblog.service.CacheService; import com.yen.mdblog.service.PostService; import java.util.List; import lombok.extern.slf4j.Slf4j; @@ -16,14 +17,28 @@ public class PostServiceImpl implements PostService { @Autowired PostMapper postMapper; - @Override - @Cacheable(value = "authorId", key = "#authorId") - public List getPostsById(Integer authorId) { - // Simulate a time-consuming database operation - simulateDelay(); - System.out.println(">>> Query slow DB get post by userId"); - return postMapper.findById(authorId); - } + @Autowired private CacheService cacheService; + + @Override + @Cacheable(value = "authorId", key = "#authorId") + public List getPostsById(Integer authorId) { + // Simulate a time-consuming database operation + simulateDelay(); + System.out.println(">>> Query slow DB get post by userId"); + return postMapper.findById(authorId); + } +// +// @Override +// public List getPostsById(Integer authorId) { +// return cacheService.cacheResult( +// "authorId", +// "#authorId", +// () -> { +// simulateDelay(); +// System.out.println(">>> Query slow DB get post by userId"); +// return postMapper.findById(authorId); +// }); +// } @Override public List getAllPost() {