Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

blog-dev-012-redis-cache #192

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions springBootBlog/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,27 @@
<scope>test</scope>
</dependency>

<!-- redis dep for cache -->

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

<!-- https://mvnrepository.com/artifact/org.springframework.data/spring-data-redis -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<!-- <version></version>-->
</dependency>

<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-pool2 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
<!-- <version>2.11.1</version>-->
</dependency>

</dependencies>

<build>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;

@EnableCaching
@SpringBootApplication
public class BlogApplication {
public static void main(String[] args) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package com.yen.mdblog.config;

import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
//import org.springframework.cache.redis.RedisCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;

@Configuration
@EnableCaching
public class RedisCacheConfig {

@Bean
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
RedisTemplate<Object, Object> template = new RedisTemplate<>();
template.setConnectionFactory(connectionFactory);
return template;
}

@Bean
public CacheManager cacheManager(RedisConnectionFactory connectionFactory) {
return RedisCacheManager.builder(connectionFactory).build();
}
}
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,10 +3,12 @@
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;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

@Service
Expand All @@ -15,11 +17,28 @@ public class PostServiceImpl implements PostService {

@Autowired PostMapper postMapper;

@Override
public List<Post> getPostsById(Integer authorId) {
@Autowired private CacheService cacheService;

return postMapper.findById(authorId);
}
@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 Expand Up @@ -51,4 +70,13 @@ public void updatePost(Post post) {
// log.info(">>> updatePost : post = {}", post);
postMapper.updatePost(post);
}

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

}
8 changes: 7 additions & 1 deletion springBootBlog/src/main/resources/application.properties
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,10 @@ spring.security.oauth2.client.registration.github.clientId=8c3b3cfa5ba107d7ad25
spring.security.oauth2.client.registration.github.clientSecret=
# google login
# custom error html
server.error.path=/error
server.error.path=/error

# redis
spring.cache.type=redis
spring.redis.host=localhost
spring.redis.port=6379
spring.redis.timeout=60000
Loading