Implement Redis Multi-Database Caching with SpringBoot
Redis multi-database storage implements user behavior cache
In my system, in order to optimize the storage and access efficiency of user behavior data, I introduced Redis cache and distributed the data in different Redis databases. In this way, the load on a single database can be reduced and the overall performance of the system can be improved.
Main implementation steps
Redis configuration
- Configure two Redis connection factories to store token and user behavior data respectively.
- Create the corresponding RedisTemplate instance and specify different connection factories and serialization methods.
-
User behavior services
- pass
UserBehaviorService
Interface and implementation classesUserBehaviorServiceImpl
, realize the record of user likes, collections, comments, and browsing behaviors. - While operating the database, user behavior data is stored in Redis to improve read efficiency.
- pass
-
Token Interceptor
- use
TokenInterceptor
The class verifies the token before each request. - After verification is passed, store user information in
ThreadLocal
, for subsequent operations.
- use
Code implementation
Redis configuration class
@Configuration public class RedisConfig { @Value("${}") private String redisHost; @Value("${}") private int redisPort; @Value("${}") private String redisPassword; @Bean(name = "tokenRedisConnectionFactory") public RedisConnectionFactory tokenRedisConnectionFactory() { RedisStandaloneConfiguration config = new RedisStandaloneConfiguration(redisHost, redisPort); (redisPassword); (0); return new LettuceConnectionFactory(config); } @Bean(name = "userBehaviorRedisConnectionFactory") public RedisConnectionFactory userBehaviorRedisConnectionFactory() { RedisStandaloneConfiguration config = new RedisStandaloneConfiguration(redisHost, redisPort); (redisPassword); (1); return new LettuceConnectionFactory(config); } @Bean(name = "redisTemplate") public StringRedisTemplate redisTemplate(@Qualifier("tokenRedisConnectionFactory") RedisConnectionFactory redisConnectionFactory) { StringRedisTemplate template = new StringRedisTemplate(); (redisConnectionFactory); (new StringRedisSerializer()); (new StringRedisSerializer()); return template; } @Bean(name = "userBehaviorRedisTemplate") public RedisTemplate<String, Map<String, Integer>> userBehaviorRedisTemplate(@Qualifier("userBehaviorRedisConnectionFactory") RedisConnectionFactory redisConnectionFactory) { RedisTemplate<String, Map<String, Integer>> template = new RedisTemplate<>(); (redisConnectionFactory); (new StringRedisSerializer()); (new Jackson2JsonRedisSerializer<>()); return template; } }
User behavior service implementation class
@Service public class UserBehaviorServiceImpl implements UserBehaviorService { private static final long CACHE_EXPIRATION_DAYS = 1; private static final String CACHE_PREFIX = "articleCounts:"; @Autowired private UserBehaviorMapper userBehaviorMapper; @Autowired @Qualifier("userBehaviorRedisTemplate") private RedisTemplate<String, Map<String, Integer>> userBehaviorRedisTemplate; @Override public void setLikeArticle(Likes likes) { (()); Integer userId = ("id"); if (userId != null) { (userId); } (likes); } @Override public void setFavoriteArticle(Favorites favorites) { (()); Integer userId = ("id"); if (userId != null) { (userId); } (favorites); } @Override public void setCommentArticle(Comments comments) { (()); Integer userId = ("id"); if (userId != null) { (userId); } (comments); } @Override public void setViewArticle(Views views) { (()); Integer userId = ("id"); if (userId != null) { (userId); } (views); } @Override public Map<String, Integer> getArticleCounts(Integer articleId) { String key = CACHE_PREFIX + articleId; Map<String, Integer> counts = ().get(key); if (counts == null) { counts = fetchArticleCountsFromDB(articleId); cacheArticleCounts(articleId, counts); } return counts; } private Map<String, Integer> fetchArticleCountsFromDB(Integer articleId) { Map<String, Integer> counts = new HashMap<>(); ("likesCount", (articleId)); ("favoritesCount", (articleId)); ("commentsCount", (articleId)); ("viewsCount", (articleId)); return counts; } private void cacheArticleCounts(Integer articleId, Map<String, Integer> counts) { String key = CACHE_PREFIX + articleId; ().set(key, counts, CACHE_EXPIRATION_DAYS, ); } }
Token Interceptor
@Component public class TokenInterceptor implements HandlerInterceptor { @Autowired private StringRedisTemplate redisTemplate; @Override public boolean preHandle(HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler) throws Exception { String token = ("Authorization"); if (token == null || ()) { (()); return false; } try { ValueOperations<String, String> operations = (); String redisToken = (token); if (redisToken == null) { (()); return false; } Map<String, Object> claims = (token); (claims); return true; } catch (Exception e) { (()); return false; } } @Override public void postHandle(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler, ModelAndView modelAndView) throws Exception { } @Override public void afterCompletion(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler, Exception ex) throws Exception { (); } }
This is the end of this article about using SpringBoot to implement Redis multi-database cache. For more related SpringBoot Redis data cache content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!
Related Articles
Detailed explanation of common configurations for Maven command line packaging and
This article mainly introduces the detailed explanation of the commonly used configurations of Maven command line packaging and . The example code is introduced in the article very detailed, which has certain reference learning value for everyone's study or work. Friends who need it, please learn with the editor below.2020-11-11Example of Java using dichotomy for search and sorting
This article mainly introduces examples of Java using dichotomy for search and sorting. Bipartite insertion sorting and bipartite search are the basic algorithms. Friends who need it can refer to it.2016-04-04Interpret the general process of obtaining configuration files in nacos
This article mainly introduces the general process of obtaining configuration files in Nacos, which is of great reference value. I hope it will be helpful to everyone. If there are any errors or no complete considerations, I hope you will be very encouraged.2024-07-07Talk about how to upload files in Servlet
Many friends are not clear about how to upload files in Servlets. When talking about this issue, we first need to master the steps of developing servlets. This article introduces you very detailed through the example code, which has certain reference value for your study or work. If you need it, please refer to it.2021-05-05How is Java classes loaded in Tomcat (Process Analysis)
This article mainly introduces the analysis of how Java classes are loaded in Tomcat. This article introduces you in a very detailed way through pictures and texts, which has certain reference value for your study or work. Friends who need it can refer to it2020-07-07Java Search Replace the specified text in pdf
This article mainly introduces how Java can find and replace the specified text in pdf, helping everyone better understand and use Java. Interested friends can learn about it2020-12-12Resolve the cause of transaction failure from Spring source code
Today, I will learn about Spring's knowledge. The article revolves around the causes of Spring transaction failure and other related knowledge. There are very detailed introductions and graphic examples in the article. Friends who need it can refer to it.2021-06-06When the springboot project is started, the main method is running the error NoClassDefFoundError problem
This article mainly introduces the problem of NoClassDefFoundError when running the main method to report an error when the springboot project is started. It has good reference value. I hope it will be helpful to everyone. If there are any errors or no complete considerations, I hope you will be very encouraged.2024-01-01Interpretation of Strategy mode in Java design pattern
This article mainly introduces the interpretation of the Strategy pattern in Java design pattern. A certain behavior of an object has different implementation methods in different scenarios. The specific implementation of these behaviors can be defined as a set of strategies. Each implementation class implements a strategy. Different implementations are used in different scenarios, and strategies can be switched freely. Friends who need it can refer to it.2023-10-10Java spring boot Example code to implement Alipay payment function
This article mainly introduces Java spring boot to implement Alipay payment function. This article introduces it to you in detail through the combination of example code, graphics and text. It has certain reference value for your study or work. Friends who need it can refer to it.2020-06-06