The purpose of caching is to improve query speed. Fixed and frequently queried data that is not frequently modified is suitable for caching
1, Spring Cache + Redis cache technologySpring Cache is an excellent caching component
From spring 3.1, annotation Cache support for * * @ Transactional annotation transactions is provided
Cache abstraction is provided to facilitate switching between various underlying caches (such as Redis)**
Benefits of Spring Cache
1. Provide basic Cache abstraction to facilitate switching between various underlying caches
2. Providing annotation Cache can realize the same as transaction. The Cache logic can be transparently applied to our code, requiring less code to complete
3. Automatically roll back the cache when providing transaction eunuch
4. Support complex cache logic
Install Redis under windows, linux and Ubuntu operating systems
3, Project integration Spring Cache + Redis 1. Add dependencyThe cache is for public use and can be used by all service modules. Add the dependency to the pom.xml file of the service util module under common
<dependencies> <dependency> <groupId>com.zhengyibao</groupId> <artifactId>common_util</artifactId> <version>0.0.1-SNAPSHOT</version> </dependency> <!--redis--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <!--spring2.x integrate redis Required common-pool2--> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-pool2</artifactId> <version>2.6.0</version> </dependency> </dependencies>2. Add redis configuration class
common/service_util/src/main/java/com/zhengyibao/yygh/common/config/RedisConfig
package com.zhengyibao.yygh.common.config; 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.EnableCaching; import org.springframework.cache.interceptor.KeyGenerator; 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.lang.reflect.Method; import java.time.Duration; /** * @author wenmiao * @create 2021-10-13 11:05 * @explain redis Configuration class for */ @Configuration //Represents a configuration class @EnableCaching //On behalf of opening cache processing public class RedisConfig { //redis is in the form of a key value //Custom key rules, including package name, class name, method name and multi parameter name @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(); } }; } //Set RedisTemplate rules @Bean public RedisTemplate<Object,Object> redisTemplate(RedisConnectionFactory redisConnectionFactory){ RedisTemplate<Object,Object> redisTemplate=new RedisTemplate<>(); redisTemplate.setConnectionFactory(redisConnectionFactory); Jackson2JsonRedisSerializer jackson2JsonRedisSerializer=new Jackson2JsonRedisSerializer(Object.class); //Solve the problem of query cache conversion exception ObjectMapper om=new ObjectMapper(); //Specify the field, field,get,set and modifier range to be sequenced. ANY includes private and public om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); //Specify the type of serialized input. The class must be non final modified. Final modified classes, such as String and Integer, will throw exceptions 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.setHashKeySerializer(jackson2JsonRedisSerializer); redisTemplate.afterPropertiesSet(); return redisTemplate; } //Setting CacheManager cache rules @Bean public CacheManager cacheManager(RedisConnectionFactory factory){ RedisSerializer<String> redisSerializer=new StringRedisSerializer(); Jackson2JsonRedisSerializer jackson2JsonRedisSerializer=new Jackson2JsonRedisSerializer(Object.class); //Solve the problem of 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 the problem of garbled code), and the expiration time is 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; } }3. Add redis configuration
common/service_cmn/resources/application.properties
spring.redis.host=192.168.44.165 spring.redis.port=6379 spring.redis.database=0 spring.redis.timeout=1800000 spring.redis.lettuce.pool.max-active=20 spring.redis.lettuce.pool.max-wait=-1 # Maximum blocking waiting time press (negative number disappears without limit) spring.redis.lettuce.pool.max-idle=5 spring.redis.lettuce.pool.min-idle=04. Understanding of common cache tags 4.1 Cacheable
Generally used in query methods
Direct query cache. The first time there is no result in the query cache, query the database according to the query method, and store the query result in the cache. The next request, if the query cache exists, directly read the cached data and return.
Generally used in addition methods
The method using this annotation flag will be executed every time, and the inserted content will be stored in the specified cache. Other methods can directly read the cached data from the response cache without querying the database
It is generally used in update or deletion methods
The method using this annotation flag will empty the specified cache
//Put the queried dictList into the cache. value defines the cache name as dict, and keyGenerator is the custom key generated by RedisConfig @Cacheable(value = "dict" , keyGenerator = "keyGenerator") //Note: @ Cacheabl annotation imports the package of spring framework: import org.springframework.cache.annotation.Cacheable;5.1 add comments in the addition method of DictServiceImpl
@CacheEvict(value="dict" ,allEntries = true) //When adding data, first empty the contents of the cache, and then add data again6. Test
dict::com.zhengyibao.yygh.cmn.service.impl.DictServiceImplfindDictList is the generated keyGenerator
Data in cache