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 use @ Cacheable in the Integration of springboot and redis

2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly explains "how to use @ Cacheable in the integration of springboot and redis". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to use @ Cacheable in the integration of springboot and redis".

First we need to configure a cache manager before we can use cache annotations to manage the cache

Package com.cherish.servicebase.handler;import com.fasterxml.jackson.annotation.JsonAutoDetect;import com.fasterxml.jackson.annotation.PropertyAccessor;import com.fasterxml.jackson.databind.ObjectMapper;import org.springframework.cache.CacheManager;import org.springframework.cache.annotation.CachingConfigurerSupport;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.connection.RedisConnectionFactory;import org.springframework.data.redis.core.RedisTemplate;import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;import org.springframework.data.redis.serializer.RedisSerializationContext;import org.springframework.data.redis.serializer.RedisSerializer;import org.springframework.data.redis.serializer.StringRedisSerializer;import java.time.Duration;@Configuration@EnableCachingpublic class RedisConfig extends CachingConfigurerSupport {@ Bean public RedisTemplate redisTemplate (RedisConnectionFactory factory) {RedisTemplate template = new RedisTemplate (); RedisSerializer redisSerializer = new StringRedisSerializer () Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer (Object.class); ObjectMapper om = new ObjectMapper (); om.setVisibility (PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); om.enableDefaultTyping (ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper (om); template.setConnectionFactory (factory); / / key serialization mode template.setKeySerializer (redisSerializer); / / value serialization template.setValueSerializer (jackson2JsonRedisSerializer) / / value hashmap serialize template.setHashValueSerializer (jackson2JsonRedisSerializer); return template;} @ Bean public CacheManager cacheManager (RedisConnectionFactory factory) {RedisSerializer redisSerializer = new StringRedisSerializer (); Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer (Object.class); / / resolve query cache conversion exception ObjectMapper om = new ObjectMapper (); om.setVisibility (PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY) Om.enableDefaultTyping (ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper (om) / / configure serialization (solve garbled problem). Expiration time: RedisCacheConfiguration config = RedisCacheConfiguration .defaultCacheConfig () .entryTtl (Duration.ofSeconds) .serializeKeysWith (RedisSerializationContext.SerializationPair.fromSerializer (redisSerializer)) .serializeValuesWith (RedisSerializationContext.SerializationPair.fromSerializer (jackson2JsonRedisSerializer)) .serialCachingNullValues () RedisCacheManager cacheManager = RedisCacheManager.builder (factory) .cacheDefaults (config) / / you can set different expiration times for different RedisCacheConfiguration of each cacheName / .withCacheConfiguration ("Users", config.entryTtl (Duration.ofSeconds (100) .transactionAware () .build (); return cacheManager;}} 1, @ Cacheable

Mark on a method or class to identify that the method or class supports caching. After calling the annotation identification method, Spring caches the return value to redis to ensure that the next time the method is called under the same condition, the return value is directly obtained from the cache. In this way, there is no need to re-execute the business process of the method and improve efficiency.

The three parameters commonly used in @ Cacheable are as follows:

CacheNames cache name

For key cached by key, you need to pay attention to how to write key.

Condition cache execution condition, which is executed when true is returned.

Example

/ / query all users and cache @ GetMapping ("/ selectFromRedis") @ Cacheable (cacheNames = "Users", key = "'user'") public ResultData getUserRedis () {List list = userService.list (null); return ResultData.ok () .data ("User", list);}

The first query is queried from the database and then cached to redis using the redis visualization tool to view the cached information

The second query is gone and the cache console has no output, so the redis cache is to get the result in redis and return it directly.

@ CacheEvict

Mark on the method, and delete the corresponding cache according to the condition or key after the method is executed. Commonly used attributes:

AllEntries boolean type, indicating whether all elements in the cache need to be cleared

Cached key that needs to be deleted by key

/ / after calling this API, delete the specified Redis cache @ PostMapping ("updateUser") @ CacheEvict (cacheNames = "Users", key = "user'") public ResultData updateUser (@ RequestBody User user) {String id = user.getId (); QueryWrapper wrapper=new QueryWrapper (); wrapper.eq ("id", id); boolean b = userService.update (user, wrapper) Return ResultData.ok () .data ("flag", b);} / do not delete the redis cache @ PostMapping ("updateUser2") public ResultData updateUser2 (@ RequestBody User user) {String id = user.getId (); QueryWrapper wrapper=new QueryWrapper (); wrapper.eq ("id", id); boolean b = userService.update (user, wrapper); return ResultData.ok () .data ("flag", b);}

When we update the data in the database, we need to empty the redis cache. Otherwise, the data we query is the data in the redis cache, which will lead to the inconsistency between the database and the cached data.

The example calls the interface without the @ CacheEvict annotation to modify the data before the data obtained by the query is unmodified.

So we need to clear the cache when we call the interface that modifies the data.

Add the @ CacheEvict annotation to clear the corresponding cache when querying the data to find that the data is up-to-date and consistent with the database.

Expiration time

We have implemented the basic functions of Spring Cache, integrating Redis as a RedisCacheManger, but it is well known that we cannot cache it when we use the @ Cacheable annotation. But sometimes in some scenarios we do need to give the cache an expiration time! This is the default expiration time

Data validity time

Custom expiration time

Use the new redis configuration to query the cached data again to see the validity period of the data.

Thank you for your reading. the above is the content of "how to use @ Cacheable in the integration of springboot and redis". After the study of this article, I believe you have a deeper understanding of how to use @ Cacheable in the integration of springboot and redis. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

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