Caching is sometimes used to speed up queries, but not all data is suitable for caching.

Things like infrequently modified data, fixed data, frequently queried data, etc., are suitable for caching.

So now I’m going to put the data from the dictionary function that I implemented earlier into the cache.

Spring Cache + Redis

Spring Cache is an excellent caching component.

Since Spring 3.1, annotated Cache support similar to @Transactional annotated transactions has been provided, as well as Cache abstraction to switch between various underlying caches (such as Redis).

Advantages of using Spring Cache:

  • Provides a basic Cache abstraction for switching between low-level caches
  • Annotating the Cache makes it possible to apply the Cache logic transparently to our business code in much less code, similar to transactions
  • The cache is also automatically rolled back when a transaction rollback is provided
  • Supports complex cache logic

Second, integration in the project

1. Introduce dependencies

<dependencies> <! -- redis --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <! Commonly-pool2 --> <dependency> <groupId>org.apache.commons</groupId> The < artifactId > Commons - pool2 < / artifactId > < version > server < / version > < / dependency > < / dependencies >Copy the code

2. Add the Redis configuration class

Configuration class is a more fixed way to write, need to understand the structure.

@enablecaching Public class RedisConfig {/** * Define the key rule ** @return */ @bean public KeyGenerator keyGenerator() { return new KeyGenerator() { @Override public Object generate(Object target, Method method, Object... params) { StringBuilder sb = new StringBuilder(); sb.append(target.getClass().getName()); sb.append(method.getName()); for (Object obj : params) { sb.append(obj.toString()); } return sb.toString(); }}; @param redisConnectionFactory * @return */ @bean public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) { RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>(); redisTemplate.setConnectionFactory(redisConnectionFactory); Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); ObjectMapper om = new ObjectMapper(); // Specify the fields to serialize, field,get, and set, and the modifier range, Have ANY is consist of private and public om. SetVisibility (PropertyAccessor. ALL, JsonAutoDetect. Visibility. ANY); // Specify the type of serialized input, class must be non-final, final modified class, Such as String, Integer later ran out of the abnormal om. EnableDefaultTyping (ObjectMapper. DefaultTyping. NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper(om); / / serial number key value redisTemplate. SetKeySerializer (new StringRedisSerializer ()); redisTemplate.setValueSerializer(jackson2JsonRedisSerializer); redisTemplate.setHashKeySerializer(new StringRedisSerializer()); redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer); redisTemplate.afterPropertiesSet(); return redisTemplate; } /** * Set the CacheManager cache rule. * @param Factory * @return */ @bean public CacheManager CacheManager (RedisConnectionFactory) factory) { RedisSerializer<String> 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); / / configuration serialization (solve the problem of noise), expiration time 600 seconds RedisCacheConfiguration config. = RedisCacheConfiguration defaultCacheConfig () .entryTtl(Duration.ofSeconds(600)) .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer)) .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer)) .disableCachingNullValues(); RedisCacheManager cacheManager = RedisCacheManager.builder(factory) .cacheDefaults(config) .build(); return cacheManager; }}Copy the code

There are three main methods:

  • Custom key rules: You can generate keys for our custom rules.
  • Set the RedisTemplate rule: The following operation redis, to access the content, need to use the RedisTemplate, here is the relevant Settings.
  • Set the CacheManager cache rules: Handles cache-related rules, such as cache duration and garbled handling.

3. Add redis configuration to the configuration file

spring.redis.host=XXX.XXX.XXX.XX spring.redis.port=6379 spring.redis.database= 0 spring.redis.timeout=1800000 Spring. Redis. Lettuce. Pool. Max - active = 20 spring. Redis. Lettuce. The pool. The Max - wait = 1 # biggest jam waiting time (negative said no limit) spring.redis.lettuce.pool.max-idle=5 spring.redis.lettuce.pool.min-idle=0Copy the code

4. Start the installed Redis

Please refer to my previous sharing about installation:

www.cnblogs.com/pingguo-sof…

I changed the cloud server and re-installed it, and it worked fine.

This is a stand-alone operation, if you need other hosts can also link to Redis, also need to change the configuration:

Spring Cache common annotations

Spring Cache provides annotations to make caching easy, but let’s take a look at some of the most common ones.

1. @Cacheable

The most commonly used annotations are also very powerful and are generally used in query methods.

The returned result can be cached according to the method. The next request, if the cache exists, will directly read the cache data and return; If the cache does not exist, the method is executed and the result returned is stored in the cache.

To put it bluntly, if I query the cache operation for the first time, if it doesn’t exist, I query the database, find the data, return it, and put it in the cache. When I query the cache for the second time, I can query the data in the cache.

View the source code, the property values are as follows:

  • valueThe cache name, mandatory, specifies which namespace to store your cache in
  • cacheNames: is similar to value
  • key: Optional property that allows you to customize the cache key using the SpEL tag

2. @CachePut

Generally used for adding methods.

Methods that use the annotation flag are executed each time and the results are stored in the specified cache. Other methods can read the cached data directly from the cache of the response without having to query the database.

View the source code, the property values are as follows:

  • valueThe cache name, mandatory, specifies which namespace to store your cache in
  • cacheNames: is similar to value
  • key: Optional property that allows you to customize the cache key using the SpEL tag

3. @CacheEvict

Typically used for update or delete methods, methods that use this annotation flag will clear the specified cache.

View the source code, the property values are as follows:

  • valueThe cache name, mandatory, specifies which namespace to store your cache in
  • cacheNames: is similar to value
  • key: Optional property that allows you to customize the cache key using the SpEL tag
  • allEntries: Indicates whether to clear all caches. The default value is false. If true, all caches will be cleared immediately after the method call
  • beforeInvocation: Whether to clear the method before execution. Default is false. If specified as true, the cache is cleared before the method executes

Four, the function of the cache operation

Update the dictionary function, add cache-related operations, add annotations to query and import (new) operations.

Query operation

Add annotation @cacheable (value = “dict”, keyGenerator = “keyGenerator”) to the corresponding implementation method of the service layer

Value = “dict”, keyGenerator = “keyGenerator”, which is used to construct the key. KeyGenerator is defined in the Redis configuration class:

Next, go to the front end to refresh the list page, make a query request, and then check redis:

This key is constructed according to the custom rules in the configuration class.

There’s data in the cache.

The import operation

Add a annotation @cacheevict (value = “dict”, allEntries=true) to the corresponding implementation of the service layer

To test this, I first delete the cache and then do an import operation on the front page:

After the import is successful, look at the cache again:

Description Added successfully.