关于 Spring Cache 注解请查看:Spring Cache 注解详解
Redis的安装教程:https://blog.csdn.net/LDY1016/article/details/76083162
下面进入正题。。。
1、在pom.xml中添加redis的依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
2、在application.properties文件中配置redis缓存
#redis
spring.redis.host=127.0.0.1
spring.redis.port = 6379
#spring.redis.password=
# 连接超时时间(毫秒)
spring.redis.timeout=10000
# Redis默认情况下有16个分片,这里配置具体使用的分片
spring.redis.database=0
# 连接池最大连接数(使用负值表示没有限制) 默认 8
spring.redis.lettuce.pool.max-active=8
# 连接池最大阻塞等待时间(使用负值表示没有限制) 默认 -1
spring.redis.lettuce.pool.max-wait=-1
# 连接池中的最大空闲连接 默认 8
spring.redis.lettuce.pool.max-idle=8
# 连接池中的最小空闲连接 默认 0
spring.redis.lettuce.pool.min-idle=0
#cache
# 一般来说是不用配置的,Spring Cache 会根据依赖的包自行装配
spring.cache.type=redis
3、配置RedisConfig
package com.ldy.bootv2.demo;
import java.time.Duration;
import org.springframework.cache.CacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(redisConnectionFactory);
redisTemplate.setKeySerializer(keySerializer());
redisTemplate.setHashKeySerializer(keySerializer());
redisTemplate.setValueSerializer(valueSerializer());
redisTemplate.setHashValueSerializer(valueSerializer());
return redisTemplate;
}
@Primary
@Bean
public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
// 缓存配置对象
RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig();
redisCacheConfiguration = redisCacheConfiguration.entryTtl(Duration.ofMinutes(30L)) // 设置缓存的默认超时时间:30分钟
.disableCachingNullValues() // 如果是空值,不缓存
.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(keySerializer())) // 设置key序列化器
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer((valueSerializer()))); // 设置value序列化器
return RedisCacheManager.builder(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory))
.cacheDefaults(redisCacheConfiguration).build();
}
private RedisSerializer<String> keySerializer() {
return new StringRedisSerializer();
}
private RedisSerializer<Object> valueSerializer() {
return new GenericJackson2JsonRedisSerializer();
}
}
4、在启动类上加上@EnableCaching注解开启缓存
package com.ldy.bootv2.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
@EnableCaching
@SpringBootApplication
public class BootV2App {
public static void main(String[] args) {
SpringApplication.run(BootV2App.class, args);
}
}
5、在service层加入缓存
package com.ldy.bootv2.demo.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;
import com.ldy.bootv2.demo.entity.UserEntity;
import com.ldy.bootv2.demo.mapper.UserMapper;
@Service
public class UserService {
@Autowired
UserMapper userMapper;
@Cacheable(value = "user", key = "'list'", unless = "#result == null") // unless="#result == null"表示返回结果为空时不缓存
public List<UserEntity> getAll() {
return userMapper.getAll();
}
@Cacheable(value = "user", key = "#id", unless = "#result == null") // unless="#result == null"表示返回结果为空时不缓存
public UserEntity getOne(Integer id) {
return userMapper.getOne(id);
}
@CachePut(value = "user", key = "#entity.id") // 将返回结果更新到缓存中
@CacheEvict(value = "user", key = "'list'") // list数据有变更,清空list缓存
public UserEntity insert(UserEntity entity) {
userMapper.insert(entity);
return entity;
}
@CachePut(value = "user", key = "#entity.id") // 将返回结果更新到缓存中
@CacheEvict(value = "user", key = "'list'") // list数据有变更,清空list缓存
public UserEntity update(UserEntity entity) {
userMapper.update(entity);
return entity;
}
@Caching(evict = { @CacheEvict(value = "user", key = "#id"), @CacheEvict(value = "user", key = "'list'") })
// @CacheEvict(value = "user", key = "#id")//清除指定id的缓存
// @CacheEvict(value="user", allEntries=true)//allEntries为true时,将忽略指定的key,清除全部user缓存
public void delete(Integer id) {
userMapper.delete(id);
}
}
上述代码亲测有效,有问题欢迎留言!!!