Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to integrate Redis as cache from zero-built Spring Boot scaffolding

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

This article will explain in detail how to integrate Redis as a cache in zero-build Spring Boot scaffolding. The content of the article is of high quality, so the editor shares it for you as a reference. I hope you will have some understanding of the relevant knowledge after reading this article.

1. Preface

Caching is a necessary function for a system application, except in reducing the pressure on the database. It also plays an important role in storing some short-term data scenarios, such as storing user Token, SMS verification code, and so on. At present, there are still many cache options, such as EHCACHE, HAZELCAST, CAFFEINE, COUCHBASE and REDIS to be integrated in this article. Next we will integrate Spring Cache and Redis into the kono scaffolding project.

two。 Integration goal

Make the project have cache function, at the same time, modify the default JDK serialization to Jackson serialization to store some objects, and implement some specific personalized cache space to meet different cache TTL time requirements in different scenarios.

3. Dependency integration

For now, you only need to introduce the following dependencies:

Org.springframework.boot spring-boot-starter-data-redis org.springframework.boot spring-boot-starter-cache org.apache.commons commons-pool2

By default, spring-data-redis uses a high-performance lettuce client implementation, and of course you can replace it with the old jedis.

4. Cache and Redis configuration

The configuration items related to cache and Redis are those at the beginning of spring.cache and spring.redis, respectively. The simple configuration here is as follows:

Spring: redis: host: localhost port: 6379 cache:# type: REDIS redis: # Global expiration time time-to-live: 1205. RedisTemplate personalization

By default, two template classes will be injected into Spring IoC for our use, requiring personalized configuration to meet the actual development.

One is RedisTemplate, which is mainly used for object caching, which uses JDK serialization by default. We need to change its serialization method to solve some problems, such as Java 8 date problem and JSON serialization problem. We need to rewrite it.

/ * some custom configurations of Redis. * * @ author felord.cn * @ since 2020 / 8 author felord.cn 17 20:39 * / @ ConditionalOnClass (ObjectMapper.class) @ Configuration (proxyBeanMethods = false) public class RedisConfiguration {/ * Redis template redis template. * * @ param redisConnectionFactory the redis connection factory * @ return the redis template * / @ Bean ("redisTemplate") public RedisTemplate redisTemplate (RedisConnectionFactory redisConnectionFactory) {RedisTemplate template = new RedisTemplate (); template.setConnectionFactory (redisConnectionFactory); / / replace the default serialization Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = initJacksonSerializer () with Jackson2JsonRedisSerialize; / / set value's serialization rule and key's serialization rule template.setValueSerializer (jackson2JsonRedisSerializer) Template.setKeySerializer (new StringRedisSerializer ()); template.afterPropertiesSet (); return template;} / * * handle redis serialization issues * @ return Jackson2JsonRedisSerializer * / private Jackson2JsonRedisSerializer initJacksonSerializer () {Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer (Object.class); ObjectMapper om = new ObjectMapper (); om.setVisibility (PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY) / / replace the old version of om.enableDefaultTyping (ObjectMapper.DefaultTyping.NON_FINAL); om.activateDefaultTyping (om.getPolymorphicTypeValidator (), ObjectMapper.DefaultTyping.NON_FINAL); / / bugFix Jackson2 deserialization data processing LocalDateTime type error om.disable (SerializationFeature.WRITE_DATE_KEYS_AS_TIMESTAMPS); / / java8 time support om.registerModule (new JavaTimeModule ()); jackson2JsonRedisSerializer.setObjectMapper (om) Return jackson2JsonRedisSerializer;}}

The other is StringRedisTemplate, which mainly deals with the caching of strings with key values, which is fine by default.

6. Cache personalization

When using Spring Cache for caching, there are scenarios where different expiration times are set for different key. For example, I want to set Jwt Token to expire in one week, and CAPTCHA to expire in five minutes. How can this be achieved? We need to personalize the configuration of RedisCacheManager. First I define these caches and their TTL times through enumerations. For example:

/ * @ author felord.cn * @ see cn.felord.kono.configuration.CacheConfiguration * @ since 21:40 on 2020-8-17 * / public enum CacheEnum {/ * user jwt token cache space ttl 7 days * / JWT_TOKEN_CACHE ("usrTkn", 7 * 24 * 60 * 60) / * CAPTCHA cache 5 minutes ttl * / SMS_CAPTCHA_CACHE ("smsCode", 5 * 60) / * cache name * / private final String cacheName; / * seconds of cache expiration * / private final int ttlSecond; CacheEnum (String cacheName, int ttlSecond) {this.cacheName = cacheName; this.ttlSecond = ttlSecond;} public String cacheName () {return this.cacheName;} public int ttlSecond () {return this.ttlSecond }}

In this way, personalized caching can be clearly described.

Then we personalize the configuration by injecting RedisCacheConfiguration and RedisCacheManagerBuilderCustomizer into Spring IoC, respectively, and you can notice how CacheEnum works. If you have other personalized needs, you can also customize these two configuration classes.

Import cn.felord.kono.enumeration.CacheEnum;import org.springframework.boot.autoconfigure.cache.CacheProperties;import org.springframework.boot.autoconfigure.cache.RedisCacheManagerBuilderCustomizer;import org.springframework.cache.annotation.EnableCaching;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.data.redis.cache.RedisCacheConfiguration;import org.springframework.data.redis.cache.RedisCacheManager;import org.springframework.data.redis.core.RedisTemplate;import org.springframework.data.redis.serializer.RedisSerializationContext;import java.time.Duration Import java.util.EnumSet;import java.util.stream.Collectors;/** * redis cache configuration. * * @ author felord.cn * @ since 2020 / 8 author felord.cn 17 20:14 * / @ EnableCaching@Configurationpublic class CacheConfiguration {/ * Redis cache configuration. * * @ param redisTemplate the redis template * @ return the redis cache configuration * / @ Bean public RedisCacheConfiguration redisCacheConfiguration (RedisTemplate redisTemplate, CacheProperties cacheProperties) {/ / see spring.cache.redis CacheProperties.Redis redisProperties = cacheProperties.getRedis () RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig () / / serialization of the cache. SerializeValuesWith (RedisSerializationContext.SerializationPair .fromSerializer (redisTemplate.getValueSerializer (); if (redisProperties.getTimeToLive ()! = null) {/ / Global TTL time redisCacheConfiguration = redisCacheConfiguration.entryTtl (redisProperties.getTimeToLive ()) } if (redisProperties.getKeyPrefix ()! = null) {/ / key prefix value redisCacheConfiguration = redisCacheConfiguration.prefixCacheNameWith (redisProperties.getKeyPrefix ());} if (! redisProperties.isCacheNullValues ()) {/ / default cache null value can prevent cache penetration redisCacheConfiguration = redisCacheConfiguration.disableCachingNullValues () } if (! redisProperties.isUseKeyPrefix ()) {/ / do not use the key prefix redisCacheConfiguration = redisCacheConfiguration.disableKeyPrefix ();} return redisCacheConfiguration;} / * Redis cache manager personalized configuration cache expiration time. * @ see RedisCacheManager CacheEnum * @ return the redis cache manager builder customizer * / @ Bean public RedisCacheManagerBuilderCustomizer redisCacheManagerBuilderCustomizer (RedisCacheConfiguration redisCacheConfiguration) {return builder-> builder.cacheDefaults (redisCacheConfiguration) / / some custom cache configuration initializations are mainly specific caches and their ttl times. WithInitialCacheConfigurations (EnumSet.allOf (CacheEnum.class). Cache () .cache (Collectors.toMap (CacheEnum::cacheName) CacheEnum-> redisCacheConfiguration.entryTtl (Duration.ofSeconds (cacheEnum.ttlSecond () }}

At the same time, we can enable Spring Cache cache support by annotating @ EnableCaching. The details of Spring Cache can be found in the article Spring Cache.

> Please note that only caching through Spring Cache operations can achieve the effect shown in the above figure. Command line operations require explicit declaration instructions.

So much for sharing about how to integrate Redis as a cache in zero-build Spring Boot scaffolding. I hope the above content can be helpful to you and learn more. If you think the article is good, you can share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report