How SpringBoot customizes Redis to implement cache serialization
Jun 03, 2023 am 11:32 AM1. Customized RedisTemplate
1.1. Redis API default serialization mechanism
The API-based Redis cache implementation uses the RedisTemplate template for data caching operations. Open the RedisTemplate class here to view Source code information of this class
public class RedisTemplate<K, V> extends RedisAccessor implements RedisOperations<K, V>, BeanClassLoaderAware { // 聲明了key、value的各種序列化方式,初始值為空 @Nullable private RedisSerializer keySerializer = null; @Nullable private RedisSerializer valueSerializer = null; @Nullable private RedisSerializer hashKeySerializer = null; @Nullable private RedisSerializer hashValueSerializer = null; ... // 進行默認序列化方式設(shè)置,設(shè)置為JDK序列化方式 public void afterPropertiesSet() { super.afterPropertiesSet(); boolean defaultUsed = false; if (this.defaultSerializer == null) { this.defaultSerializer = new JdkSerializationRedisSerializer( this.classLoader != null ? this.classLoader : this.getClass().getClassLoader()); } ... } ... }
As can be seen from the above RedisTemplate core source code, various serialization methods for cached data key and value are declared inside RedisTemplate, and the initial values ????are empty; in the afterPropertiesSet() method , determine if the default serialization parameter defaultSerializer is empty, set the default serialization method of data to JdkSerializationRedisSerializer
According to the analysis of the above source code information, the following two important conclusions can be drawn:
(1) When using RedisTemplate for Redis data caching operations, the internal default serialization method is JdkSerializationRedisSerializer, so the entity class for data caching must implement the JDK's own serialization interface (such as Serializable);
( 2) When using RedisTemplate to perform Redis data caching operations, if the cache serialization method defaultSerializer is customized, the customized serialization method will be used.
In addition, in the RedisTemplate class source code, the various serialization types of cached data keys and values ??seen are RedisSerializer. Enter the RedisSerializer source code to view the serialization methods supported by RedisSerializer (after entering the class, use Ctrl Alt and left-click the class name to view)
It can be seen that RedisSerializer is a Redis The serialization interface has 6 implementation classes by default. These 6 implementation classes represent 6 different data serialization methods. Among them, JdkSerializationRedisSerializer comes with JDK and is also the default data serialization method used within RedisTemplate. Developers can choose other supported serialization methods (such as JSON method) as needed.
1.2. Customized RedisTemplate serialization Mechanism
After introducing Redis dependency into the project, the RedisAutoConfiguration automatic configuration provided by Spring Boot will take effect. Open the RedisAutoConfiguration class and view the definition of RedisTemplate in the internal source code
public class RedisAutoConfiguration { @Bean @ConditionalOnMissingBean( name = {"redisTemplate"} ) public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException { RedisTemplate<Object, Object> template = new RedisTemplate(); template.setConnectionFactory(redisConnectionFactory); return template; } ... }
As can be seen from the above RedisAutoConfiguration core source code, in the Redis automatic configuration class, a RedisTemplate is initialized through the Redis connection factory RedisConnectionFactory; above the class The @ConditionalOnMissingBean annotation (as the name suggests, takes effect when a Bean does not exist) is added to indicate that if the developer customizes a Bean named redisTemplate, the default initialized RedisTemplate will not take effect.
If you want to use RedisTemplate with a custom serialization method for data caching operations, you can refer to the above core code to create a Bean component named redisTemplate and set the corresponding serialization method in the component
Next, create a package named com.lagou.config in the project, create a Redis custom configuration class RedisConfig under the package, and customize the Bean component named redisTemplate according to the above ideas
@Configuration public class RedisConfig { // 自定義RedisTemplate @Bean public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) { RedisTemplate<Object, Object> template = new RedisTemplate<>(); template.setConnectionFactory(redisConnectionFactory); // 創(chuàng)建一個JSON格式序列化對象,對緩存數(shù)據(jù)的key和value進行轉(zhuǎn)換 Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); // 解決查詢緩存轉(zhuǎn)換異常的問題 ObjectMapper om = new ObjectMapper(); om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper(om); // 設(shè)置RedisTemplate模板api序列化方式為json template.setDefaultSerializer(jackson2JsonRedisSerializer); return template; } }
defines a RedisConfig configuration class through the @Configuration annotation, and uses the @Bean annotation to inject a redisTemplate component with the default name of the method name (note that the Bean component name must be redisTemplate). In the defined Bean component, a RedisTemplate is customized, using the customized Jackson2JsonRedisSerializer data serialization method; in the customized serialization method, an ObjectMapper is defined for data conversion settings
1.3, effect testing
It can be seen that executing the findById() method correctly queries the user comment information Comment, and repeats the same query operation. The database only executes the SQL statement once, which shows that the customization The Redis cache takes effect.
Use the Redis client visual management tool Redis Desktop Manager to view the cached data:
Execute the findById() method to query the user comment information and the Comment is correctly stored in Redis In the cache library, and the data cached to the Redis service has been stored and displayed in JSON format, it is also very convenient to view and manage, indicating that the customized Redis API template tool RedisTemplate takes effect
2. Customized RedisCacheManager
We have just improved the custom serialization method for the API-based RedisTemplate, thus realizing the JSON serialization method to cache data. However, this custom RedisTemplate has no effect on the annotation-based Redis cache. .
Next, we will explain the annotation-based Redis caching mechanism and custom serialization method
2.1. Redis annotation default serialization mechanism
Open Spring Boot to integrate Redis components The provided cache automatic configuration class RedisCacheConfiguration (under the org.springframework.boot.autoconfigure.cache package), view the source code information of this class, its core code is as follows
@Configuration class RedisCacheConfiguration { @Bean public RedisCacheManager cacheManager(RedisConnectionFactory redisConnectionFactory, ResourceLoader resourceLoader) { RedisCacheManagerBuilder builder = RedisCacheManager .builder(redisConnectionFactory) .cacheDefaults(this.determineConfiguration(resourceLoader.getClassLoader())); List<String> cacheNames = this.cacheProperties.getCacheNames(); if (!cacheNames.isEmpty()) { builder.initialCacheNames(new LinkedHashSet(cacheNames)); } return (RedisCacheManager) this.customizerInvoker.customize(builder.build()); } private org.springframework.data.redis.cache.RedisCacheConfiguration determineConfiguration(ClassLoader classLoader) { if (this.redisCacheConfiguration != null) { return this.redisCacheConfiguration; } else { Redis redisProperties = this.cacheProperties.getRedis(); org.springframework.data.redis.cache.RedisCacheConfiguration config = org.springframework.data.redis.cache.RedisCacheConfiguration.defaultCacheConfig(); config = config.serializeValuesWith(SerializationPair.fromSerializer( new JdkSerializationRedisSerializer(classLoader))); ... return config; } } }
從上述核心源碼中可以看出,同RedisTemplate核心源碼類似,RedisCacheConfiguration內(nèi)部同樣通過Redis連接工廠RedisConnectionFactory定義了一個緩存管理器RedisCacheManager;同時定制RedisCacheManager時,也默認使用了JdkSerializationRedisSerializer序列化方式。
如果想要使用自定義序列化方式的RedisCacheManager進行數(shù)據(jù)緩存操作,可以參考上述核心代碼創(chuàng)建一個名為cacheManager的Bean組件,并在該組件中設(shè)置對應(yīng)的序列化方式即可
在Spring Boot 2.X版本中,RedisCacheManager是獨立構(gòu)建的。因此,在SpringBoot 2.X版本中,對RedisTemplate進行自定義序列化機制構(gòu)建后,仍然無法對RedisCacheManager內(nèi)部默認序列化機制進行覆蓋(這也就解釋了基 于注解的Redis緩存實現(xiàn)仍然會使用JDK默認序列化機制的原因),想要基于注解的Redis緩存實現(xiàn)也使用自定義序列化機制,需要自定義RedisCacheManager
2.2、自定義RedisCacheManager
在項目的Redis配置類RedisConfig中,按照上一步分析的定制方法自定義名為cacheManager的Bean組件
@Bean public RedisCacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) { // 分別創(chuàng)建String和JSON格式序列化對象,對緩存數(shù)據(jù)key和value進行轉(zhuǎn)換 RedisSerializer<String> strSerializer = new StringRedisSerializer(); Jackson2JsonRedisSerializer jacksonSerial = new Jackson2JsonRedisSerializer(Object.class); // 解決查詢緩存轉(zhuǎn)換異常的問題 ObjectMapper om = new ObjectMapper(); om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); // om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); om.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY); // 上面注釋過時代碼的替代方法 jacksonSerial.setObjectMapper(om); // 定制緩存數(shù)據(jù)序列化方式及時效 RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig() .entryTtl(Duration.ofDays(1)) // 設(shè)置緩存數(shù)據(jù)的時效(設(shè)置為了1天) .serializeKeysWith(RedisSerializationContext.SerializationPair .fromSerializer(strSerializer)) // 對當(dāng)前對象的key使用strSerializer這個序列化對象,進行轉(zhuǎn)換 .serializeValuesWith(RedisSerializationContext.SerializationPair .fromSerializer(jacksonSerial)) // 對value使用jacksonSerial這個序列化對象,進行轉(zhuǎn)換 .disableCachingNullValues(); RedisCacheManager cacheManager = RedisCacheManager .builder(redisConnectionFactory).cacheDefaults(config).build(); return cacheManager; }
上述代碼中,在RedisConfig配置類中使用@Bean注解注入了一個默認名稱為方法名的cacheManager組件。在定義的Bean組件中,通過RedisCacheConfiguration對緩存數(shù)據(jù)的key和value分別進行了序列化方式的定制,其中緩存數(shù)據(jù)的key定制為StringRedisSerializer(即String格式),而value定制為了Jackson2JsonRedisSerializer(即JSON格式),同時還使用entryTtl(Duration.ofDays(1))方法將緩存數(shù)據(jù)有效期設(shè)置為1天
完成基于注解的Redis緩存管理器RedisCacheManager定制后,可以對該緩存管理器的效果進行測試(使用自定義序列化機制的RedisCacheManager測試時,實體類可以不用實現(xiàn)序列化接口)
The above is the detailed content of How SpringBoot customizes Redis to implement cache serialization. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

The essential Laravel extension packages for 2024 include: 1. LaravelDebugbar, used to monitor and debug code; 2. LaravelTelescope, providing detailed application monitoring; 3. LaravelHorizon, managing Redis queue tasks. These expansion packs can improve development efficiency and application performance.

The steps to build a Laravel environment on different operating systems are as follows: 1.Windows: Use XAMPP to install PHP and Composer, configure environment variables, and install Laravel. 2.Mac: Use Homebrew to install PHP and Composer and install Laravel. 3.Linux: Use Ubuntu to update the system, install PHP and Composer, and install Laravel. The specific commands and paths of each system are different, but the core steps are consistent to ensure the smooth construction of the Laravel development environment.

Redis is superior to traditional databases in high concurrency and low latency scenarios, but is not suitable for complex queries and transaction processing. 1.Redis uses memory storage, fast read and write speed, suitable for high concurrency and low latency requirements. 2. Traditional databases are based on disk, support complex queries and transaction processing, and have strong data consistency and persistence. 3. Redis is suitable as a supplement or substitute for traditional databases, but it needs to be selected according to specific business needs.

Linux system restricts user resources through the ulimit command to prevent excessive use of resources. 1.ulimit is a built-in shell command that can limit the number of file descriptors (-n), memory size (-v), thread count (-u), etc., which are divided into soft limit (current effective value) and hard limit (maximum upper limit). 2. Use the ulimit command directly for temporary modification, such as ulimit-n2048, but it is only valid for the current session. 3. For permanent effect, you need to modify /etc/security/limits.conf and PAM configuration files, and add sessionrequiredpam_limits.so. 4. The systemd service needs to set Lim in the unit file

Redis is primarily a database, but it is more than just a database. 1. As a database, Redis supports persistence and is suitable for high-performance needs. 2. As a cache, Redis improves application response speed. 3. As a message broker, Redis supports publish-subscribe mode, suitable for real-time communication.

Redis goes beyond SQL databases because of its high performance and flexibility. 1) Redis achieves extremely fast read and write speed through memory storage. 2) It supports a variety of data structures, such as lists and collections, suitable for complex data processing. 3) Single-threaded model simplifies development, but high concurrency may become a bottleneck.

The steps to build a dynamic PHP website using PhpStudy include: 1. Install PhpStudy and start the service; 2. Configure the website root directory and database connection; 3. Write PHP scripts to generate dynamic content; 4. Debug and optimize website performance. Through these steps, you can build a fully functional dynamic PHP website from scratch.

Redisisanopen-source,in-memorydatastructurestoreusedasadatabase,cache,andmessagebroker,excellinginspeedandversatility.Itiswidelyusedforcaching,real-timeanalytics,sessionmanagement,andleaderboardsduetoitssupportforvariousdatastructuresandfastdataacces
