1. 在pom.xml中 引入redis依赖
<!-- 缓存依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<!-- redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis-reactive</artifactId>
</dependency>
<!--spring2.0集成redis所需common-pool2-->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
<version>2.8.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
2. yml 配置
server:
port: 16379
spring:
cache:
type: redis
redis:
cache-null-values: true # 表示是否缓存空值,一般情况下是允许的.如果设置false即不允许缓存空值,这样会导致很多请求数据库没有的数据时,不会缓存到redis导致每次都会请求到数据库。这种情况即:缓存穿透。
time-to-live: 30m # 缓存超时时间ms
# use-key-prefix: true #启用前缀
# key-prefix: key #前缀
redis:
##########redis 单例 ###########
host: 127.0.0.1
port: 6379
##########redis 单例 ###########
timeout: 60s # 数据库连接超时时间,springboot2.0 中该参数的类型为Duration,这里在配置的时候需要指明单位
database: 0
##########redis 集群###########
# cluster:
# nodes: 192.168.3.157:7000,192.168.3.158:7000,192.168.3.159:7000,192.168.3.157:7001,192.168.3.158:7001,192.168.3.159:7001
##########redis 集群###########
lettuce: # 连接池配置,springboot2.0中直接使用jedis或者lettuce配置连接池
pool:
max-active: -1 # 最大活跃连接数,负数为不限制
max-idle: 500 # 最大空闲连接数
min-idle: 50 # 等待可用连接的最大时间,负数为不限制
max-wait: -1s # 等待可用连接的最大时间,负数为不限制
logging:
pattern:
level: info
# dateformat: yyy-MM-dd HH:mm:ss
3. java启动类 须使用@EnableCaching
才可启用 注解缓存
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
@EnableCaching
@SpringBootApplication
public class OpenReidsApplication {
public static void main(String[] args) {
SpringApplication.run(OpenReidsApplication.class, args);
}
}
4. 自定义缓存管理器RedisCacheConfig
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.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;
@Configuration
@EnableCaching
public class RedisCacheConfig extends CachingConfigurerSupport {
@Bean(name = "redisTemplate")
public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, String> template = new RedisTemplate<>();
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
RedisSerializer stringSerializer = new StringRedisSerializer();
template.setKeySerializer(stringSerializer);
template.setValueSerializer(stringSerializer);
template.setHashKeySerializer(stringSerializer);
template.setHashValueSerializer(stringSerializer);
template.setConnectionFactory(factory);
return template;
}
@Bean
/** 自定义key生成器 */
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
/** redis-cache configuration */
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);
// 配置序列化(解决乱码的问题)
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
// 30分钟 缓存过期时间
.entryTtl(Duration.ofMillis(30))
.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))
.disableCachingNullValues();
RedisCacheManager cacheManager = RedisCacheManager.builder(factory)
.cacheDefaults(config)
.build();
return cacheManager;
}
}
5. 使用缓存 测试
@RestController
@CacheConfig(cacheNames = "test")
public class RedisTestCtl {
@RequestMapping(value = "/list")
@Cacheable(key = "#p0" )
public String list(int id,String name) {
return "list-"+name;
}
@RequestMapping(value = "/add")
@CachePut(key = "#id")
public String add(int id,String name) {
return "add-"+ name;
}
@RequestMapping(value = "/edit")
@CachePut( key = "#id")
public String edit(int id,String name) {
return "edit-"+ name;
}
@RequestMapping(value = "/del")
@CacheEvict(key = "#id")
public String del(String id) {
return "del-"+id;
}
}