Skip to content

Commit

Permalink
add cacheService
Browse files Browse the repository at this point in the history
  • Loading branch information
yennanliu committed Dec 21, 2024
1 parent 71eb258 commit bd7a469
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 8 deletions.
Original file line number Diff line number Diff line change
@@ -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 <T> the type of the cached result
* @return the cached result
*/
@Cacheable(value = "#{cacheName}", key = "#{key}")
public <T> T cacheResult(String cacheName, String key, CacheableOperation<T> operation) {
return operation.execute();
}

@FunctionalInterface
public interface CacheableOperation<T> {
T execute();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -16,14 +17,28 @@ public class PostServiceImpl implements PostService {

@Autowired PostMapper postMapper;

@Override
@Cacheable(value = "authorId", key = "#authorId")
public List<Post> 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<Post> 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<Post> 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<Post> getAllPost() {
Expand Down

0 comments on commit bd7a469

Please sign in to comment.