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

Example Analysis of Custom configuration of SpringCache Cache

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article will explain in detail the example analysis of the custom configuration of SpringCache cache. The editor thinks it is very practical, so I share it with you for reference. I hope you can get something after reading this article.

Cacheable specifies custom properties

For more information, please refer to the spring official website to add a link description.

1.key 's name and TTL time

/ * * query all level 1 categories * @ Cacheable means that the result of the current method needs to be cached. If there is any in the cache, the method will not be called. If there is no one in the cache, the method will be called and the result will be placed in the cache. * default cache behavior: * a. If there is one in the cache, the method will not be called * b.key is automatically generated by default. The name of the cache:: SimpleKey [] (automatically generated key value) * c. The cached value, which uses the jdk serialization mechanism by default, saves the serialized data to redis * d. The default ttl time is-1 * @ return * / @ Cacheable (value = {"category"}, key = "'TopCategorys'") @ Overridepublic List getTopCategorys () {System.out.println (".getTopCategorys."); long startTime = System.currentTimeMillis (); List categoryEntityList = this.baseMapper.selectList (new QueryWrapper (). Eq ("parent_cid", 0)) System.out.println ("time consumed:" + (System.currentTimeMillis ()-startTime)); return categoryEntityList;}

/ * * query all level 1 categories * @ Cacheable means that the result of the current method needs to be cached. If there is any in the cache, the method will not be called. If there is no one in the cache, the method will be called and the result will be placed in the cache. * default cache behavior: * a. If there is one in the cache, the method will not be called * b.key is automatically generated by default. The name of the cache:: SimpleKey [] (automatically generated key value) * c. The cached value, which uses the jdk serialization mechanism by default, saves the serialized data to redis * d. The default ttl time is-1 * @ return * / / @ Cacheable (value = {"category"}, key = "'TopCategorys'") @ Cacheable (value = {"category"}, key = "# root.method.name") @ Override public List getTopCategorys () {System.out.println (".getTopCategorys."); long startTime = System.currentTimeMillis () List categoryEntityList = this.baseMapper.selectList (new QueryWrapper (). Eq ("parent_cid", 0); System.out.println ("elapsed time:" + (System.currentTimeMillis ()-startTime)); return categoryEntityList;}

two。 Cached data is saved in json format

* principle:

* CacheAutoConfiguration (selectImports method)-- > CacheConfigurations (MAPPINGS)

*-> RedisCacheConfiguration-- > cacheManager method-- > RedisCacheManager initializes all caches (determineConfiguration method

* each cache decides what configuration to use)-> createConfiguration method

Create a new MyCacheConfig configuration class under the config package

Package com.atguigu.gulimall.product.config;import org.springframework.boot.autoconfigure.cache.CacheProperties;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.serializer.GenericJackson2JsonRedisSerializer;import org.springframework.data.redis.serializer.RedisSerializationContext;import org.springframework.data.redis.serializer.StringRedisSerializer / * Cache configuration * @ author zfh * @ email hst1406959716@163.com * @ date 2021-12-25 09:40:46 * / @ EnableCaching@Configurationpublic class MyCacheConfig {@ Bean RedisCacheConfiguration redisCacheConfiguration () {RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig (); / / config = config.entryTtl (); config = config.serializeKeysWith (RedisSerializationContext.SerializationPair.fromSerializer (new StringRedisSerializer (); config = config.serializeValuesWith (RedisSerializationContext.SerializationPair.fromSerializer (new GenericJackson2JsonRedisSerializer () Return config;}}

We found that ttl became-1, and our application.properties didn't work.

Package com.atguigu.gulimall.product.config;import org.springframework.boot.autoconfigure.cache.CacheProperties;import org.springframework.boot.context.properties.EnableConfigurationProperties;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.serializer.GenericJackson2JsonRedisSerializer;import org.springframework.data.redis.serializer.RedisSerializationContext;import org.springframework.data.redis.serializer.StringRedisSerializer / * Cache configuration * @ author zfh * @ email hst1406959716@163.com * @ date 2021-12-25 09:40:46 * / @ EnableConfigurationProperties (CacheProperties.class) @ EnableCaching@Configurationpublic class MyCacheConfig {@ Bean RedisCacheConfiguration redisCacheConfiguration (CacheProperties cacheProperties) {RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig (); / / config = config.entryTtl (); config = config.serializeKeysWith (RedisSerializationContext.SerializationPair.fromSerializer (new StringRedisSerializer () Config = config.serializeValuesWith (RedisSerializationContext.SerializationPair.fromSerializer (new GenericJackson2JsonRedisSerializer (); CacheProperties.Redis redisProperties = cacheProperties.getRedis (); / / make all configurations in the configuration file effective if (redisProperties.getTimeToLive ()! = null) {config = config.entryTtl (redisProperties.getTimeToLive ()) } if (redisProperties.getKeyPrefix ()! = null) {config = config.prefixKeysWith (redisProperties.getKeyPrefix ());} if (! redisProperties.isCacheNullValues ()) {config = config.disableCachingNullValues ();} if (! redisProperties.isUseKeyPrefix ()) {config = config.disableKeyPrefix ();} return config;}}

3. Use cache prefix

In the application.properties file

Spring.cache.type=redis#spring.cache.cache-names=qq#TTL milliseconds spring.cache.redis.time-to-live=3600000#. If you specify a prefix, use the prefix we specify. If not, use the cached name as the prefix spring.cache.redis.key-prefix=CACHE_spring.cache.redis.use-key-prefix=true by default.

4. Cache null to prevent cache penetration

In the application.properties file

Spring.cache.type=redis#spring.cache.cache-names=qq#TTL millisecond spring.cache.redis.time-to-live=3600000# if you specify a prefix, use the prefix we specify. If not, use the cache name as the prefix by default. Whether spring.cache.redis.key-prefix=CACHE_spring.cache.redis.use-key-prefix=true# caches null values to prevent cache penetration through spring.cache.redis.cache-null-values=true.

Return null directly in the code

/ * * query all level 1 categories * @ Cacheable means that the result of the current method needs to be cached. If there is any in the cache, the method will not be called. If there is no one in the cache, the method will be called and the result will be placed in the cache. * default cache behavior: * a. If there is one in the cache, the method will not be called * b.key is automatically generated by default. The name of the cache:: SimpleKey [] (automatically generated key value) * c. The cached value, which uses the jdk serialization mechanism by default, saves the serialized data to redis * d. The default ttl time is-1 * * principle: * CacheAutoConfiguration (selectImports method)-- > CacheConfigurations (MAPPINGS) *-- > RedisCacheConfiguration-- > cacheManager method-- > RedisCacheManager initializes all caches (determineConfiguration method * each cache determines what configuration to use)-> createConfiguration method * @ return * / / @ Cacheable (value = {"category"}) Key = "'TopCategorys'") @ Cacheable (value = {"category"}, key = "# root.method.name") @ Override public List getTopCategorys () {System.out.println (".getTopCategorys.") Long startTime = System.currentTimeMillis (); List categoryEntityList = this.baseMapper.selectList (new QueryWrapper (). Eq ("parent_cid", 0)); System.out.println ("time consumed:" + (System.currentTimeMillis ()-startTime)); / / return categoryEntityList; return null;}

This is the end of this article on "sample Analysis of SpringCache Cache Custom configuration". I hope the above content can be helpful to you, so that you can learn more knowledge. if you think the article is good, please 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

Development

Wechat

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

12
Report