Skip to content

Commit bd7a469

Browse files
committed
add cacheService
1 parent 71eb258 commit bd7a469

2 files changed

Lines changed: 51 additions & 8 deletions

File tree

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package com.yen.mdblog.service;
2+
3+
import org.springframework.cache.annotation.Cacheable;
4+
import org.springframework.stereotype.Service;
5+
6+
/** Cache service created by gpt */
7+
@Service
8+
public class CacheService {
9+
10+
/**
11+
* Generic method to cache a result.
12+
*
13+
* @param cacheName the name of the cache
14+
* @param key the cache key
15+
* @param operation the operation to cache
16+
* @param <T> the type of the cached result
17+
* @return the cached result
18+
*/
19+
@Cacheable(value = "#{cacheName}", key = "#{key}")
20+
public <T> T cacheResult(String cacheName, String key, CacheableOperation<T> operation) {
21+
return operation.execute();
22+
}
23+
24+
@FunctionalInterface
25+
public interface CacheableOperation<T> {
26+
T execute();
27+
}
28+
}

springBootBlog/src/main/java/com/yen/mdblog/service/impl/PostServiceImpl.java

Lines changed: 23 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import com.yen.mdblog.entity.Dto.SearchRequest;
44
import com.yen.mdblog.entity.Po.Post;
55
import com.yen.mdblog.mapper.PostMapper;
6+
import com.yen.mdblog.service.CacheService;
67
import com.yen.mdblog.service.PostService;
78
import java.util.List;
89
import lombok.extern.slf4j.Slf4j;
@@ -16,14 +17,28 @@ public class PostServiceImpl implements PostService {
1617

1718
@Autowired PostMapper postMapper;
1819

19-
@Override
20-
@Cacheable(value = "authorId", key = "#authorId")
21-
public List<Post> getPostsById(Integer authorId) {
22-
// Simulate a time-consuming database operation
23-
simulateDelay();
24-
System.out.println(">>> Query slow DB get post by userId");
25-
return postMapper.findById(authorId);
26-
}
20+
@Autowired private CacheService cacheService;
21+
22+
@Override
23+
@Cacheable(value = "authorId", key = "#authorId")
24+
public List<Post> getPostsById(Integer authorId) {
25+
// Simulate a time-consuming database operation
26+
simulateDelay();
27+
System.out.println(">>> Query slow DB get post by userId");
28+
return postMapper.findById(authorId);
29+
}
30+
//
31+
// @Override
32+
// public List<Post> getPostsById(Integer authorId) {
33+
// return cacheService.cacheResult(
34+
// "authorId",
35+
// "#authorId",
36+
// () -> {
37+
// simulateDelay();
38+
// System.out.println(">>> Query slow DB get post by userId");
39+
// return postMapper.findById(authorId);
40+
// });
41+
// }
2742

2843
@Override
2944
public List<Post> getAllPost() {

0 commit comments

Comments
 (0)