1. Import the jar package and build the project with maven and springboot:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-redis</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> </dependency>
2. Configure the connection address of redis database, and add:
# REDIS (RedisProperties) # Redis database index (0 by default) spring.redis.database=0 # Redis server address spring.redis.host=192.168.118.111 # Redis server connection port spring.redis.port=6379 # Redis server connection password (empty by default) spring.redis.password= # Maximum number of connections in the connection pool (use a negative value to indicate no limit) spring.redis.pool.max-active=1000 # Connection pool maximum block wait time (use a negative value to indicate no limit) spring.redis.pool.max-wait=-1 # Maximum free connections in connection pool spring.redis.pool.max-idle=8 # Minimum free connections in connection pool spring.redis.pool.min-idle=0 # Connection timeout (MS) spring.redis.timeout=0
3.redis key generation policy configuration class
package com.winstar.redis; 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.cache.interceptor.KeyGenerator; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; 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.core.StringRedisTemplate; import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; import java.lang.reflect.Method; @Configuration @EnableCaching public class RedisConfig extends CachingConfigurerSupport{ private final static String redis_key_questions="ACTIVITY_QUESTION"; private final static String redis_key_annual="ACTIVITY_ANNUAL"; private final static String redis_key_action="ACTIVITY_ACTION"; @Bean public KeyGenerator ACTIVITY_QUESTION_KEY(){ return new KeyGenerator() { @Override public Object generate(Object target, Method method, Object... params) { return redis_key_questions; } }; } @Bean public KeyGenerator ACTIVITY_ACTION_KEY(){ return new KeyGenerator() { @Override public Object generate(Object target, Method method, Object... params) { return redis_key_action; } }; } @Bean public KeyGenerator ACTIVITY_ANNUAL_KEY(){ return new KeyGenerator() { @Override public Object generate(Object target, Method method, Object... params) { return redis_key_annual; } }; } @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(); } }; } @Bean public CacheManager cacheManager( @SuppressWarnings("rawtypes") RedisTemplate redisTemplate) { return new RedisCacheManager(redisTemplate); } @Bean public RedisTemplate<String, String> redisTemplate( RedisConnectionFactory factory) { StringRedisTemplate template = new StringRedisTemplate(factory); 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.setValueSerializer(jackson2JsonRedisSerializer); template.afterPropertiesSet(); return template; } }
4. Use cache
Note: the cached query method is best written in servicepackage com.winstar.service.annualReport; import com.winstar.entity.annualReport.District; import com.winstar.entity.annualReport.IllegalAction; import com.winstar.repository.annualReport.DistrictRepository; import com.winstar.repository.annualReport.IllegalActionRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; import java.util.List; /** * @author shoo on 2018/1/10 10:43. * -- */ @Service public class AnnualReportsService { Logger logger = LoggerFactory.getLogger(AnnualReportsService.class); @Autowired private DistrictRepository districtRepository; @Autowired private IllegalActionRepository illegalActionRepository; @Cacheable(cacheNames = "ACTIVITY_ANNUAL", keyGenerator = "ACTIVITY_ANNUAL_KEY") public List<District> getDistricts(){ logger.info("getDistricts"); return districtRepository.findAll(); } @Cacheable(cacheNames = "ACTIVITY_ACTION", keyGenerator = "ACTIVITY_ACTION_KEY") public List<IllegalAction> getIllegalActions(){ logger.info("getIllegalActions"); return illegalActionRepository.findAll(); } }
1. In fact, the Cacheable annotation is added to the original query method, so that when the method is called to query, the corresponding key (such as the activity ﹣ action) will be checked from the redis database cache first, If not, query from MySQL and put the result into redis cache in the form of key value pairs. Later, query or judge the cache first. If the cache exists, the result will be obtained directly, and will not be queried from mysql.
2. Note that cacheNames of Cacheable correspond to keys in redis configuration class, and keyGenerator corresponds to key generation strategy bean s in configuration class
5. Refresh cache
To refresh the cache is to remove the corresponding key (delete) in the redis cache. Here, code operation removal is used:
Call this method where you need to refresh the cache/** * Refresh redis cache * @return */ @PutMapping("/refresh") public String refresh(){ if(redisTemplate.hasKey("ACTIVITY_ANNUAL")){ redisTemplate.delete("ACTIVITY_ANNUAL"); } if(redisTemplate.hasKey("ACTIVITY_ACTION")){ redisTemplate.delete("ACTIVITY_ACTION"); } return "ok"; }
Of course, you can also use the redis client management tool, RedisDesktopManager, to connect to redis for manual removal
It can also be removed regularly through the expression in the configuration file