Adding a Redis cache using Springboot needs to be introduced in the Pom file
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId></dependency><dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-redis</artifactId> <version>1.4.3.RELEASE</version></dependency>
Our support for adding the cache requires two dependencies, one for the Springboot internal cache configuration, and the other for our Redis cache.
Configuring the Redis Database
After the dependency addition is complete, we need to configure our local Redis database connection to the project, and we open the Application-local.properties configuration file to add the configuration as shown in 8:
#redisspring.redis.cluster.nodes=172.0.0.1:6379spring.redis.pool.max-active=20spring.redis.pool.max-idle=10spring.redis.pool.min-idle=5spring.redis.pool.max-wait=10spring.redis.timeout=5000
1. Easy Way
@Configuration @EnableCachingpublic class RedisConfig extends CachingConfigurerSupport {//生成key @Override@Beanpublic KeyGenerator keyGenerator() { return new KeyGenerator() { @Override public Object generate(Object target, Method method, Object... objects) { return UserConstant.REDIS_KEY; //常量key } };}
}
Take a look at Spring cache annotations @cacheable, @CacheEvict, @CachePut use reference
(https://www.cnblogs.com/fashflying/p/6908028.html)
Serviceimpl method @Cacheable ("Infos")
@Override@Cacheable("infos") public List<User> queryUser() { return this.UserMapper.queryUser();}
If you just need to add a note to the query can be called in the cache when the search, do not execute the method and then stored in the cache
In the implementation of the increase, deletion, change the need to delete the cache as follows:
@Override@CacheEvict("infos") public void editUserStatus(Map<String, Object> info) { UserMapper.editStatus(info);}
Add annotations to the corresponding method so that the cache is deleted
You can test it at the end.
Springboot Integrated Redis Cache