Skip to content

Commit

Permalink
add cache to post service
Browse files Browse the repository at this point in the history
  • Loading branch information
yennanliu committed Dec 20, 2024
1 parent 721d326 commit d4a74c0
Showing 1 changed file with 14 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

@Service
Expand All @@ -16,8 +17,11 @@ 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);
}

Expand Down Expand Up @@ -51,4 +55,13 @@ public void updatePost(Post post) {
// log.info(">>> updatePost : post = {}", post);
postMapper.updatePost(post);
}

private void simulateDelay() {
try {
Thread.sleep(3000); // 3 seconds
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}

}

0 comments on commit d4a74c0

Please sign in to comment.