springboot3 CachingConfigurer如何配置
时间: 2023-06-22 17:37:17 浏览: 418
在Spring Boot 3中,可以使用CachingConfigurer来配置缓存的相关属性。以下是配置缓存的步骤:
1. 添加Spring Boot缓存依赖
在pom.xml文件中添加以下依赖:
```
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
```
2. 配置缓存
在Spring Boot的配置文件中,配置缓存相关属性:
```
spring.cache.type=redis # 设置缓存类型为Redis
spring.redis.host=localhost # 设置Redis的主机地址
spring.redis.port=6379 # 设置Redis的端口号
```
3. 实现CachingConfigurer接口
在实现类上添加@EnableCaching注解,并实现CachingConfigurer接口:
```
@Configuration
@EnableCaching
public class CacheConfig implements CachingConfigurer {
@Bean
public RedisCacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofSeconds(60)) // 设置缓存时间为60秒
.disableCachingNullValues() // 禁止缓存null值
.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer())) // 设置key序列化方式为String
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer())); // 设置value序列化方式为Json
return RedisCacheManager.builder(redisConnectionFactory)
.cacheDefaults(redisCacheConfiguration)
.build();
}
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(redisConnectionFactory);
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
return redisTemplate;
}
@Override
public CacheManager cacheManager() {
return cacheManager(redisConnectionFactory());
}
@Override
public KeyGenerator keyGenerator() {
return new SimpleKeyGenerator();
}
@Override
public CacheResolver cacheResolver() {
return new SimpleCacheResolver(cacheManager());
}
@Override
public CacheErrorHandler errorHandler() {
return new SimpleCacheErrorHandler();
}
@Bean
public RedisConnectionFactory redisConnectionFactory() {
return new JedisConnectionFactory();
}
}
```
这样就完成了Spring Boot 3中缓存的配置。在代码中使用缓存时,可以使用Spring提供的@Cacheable、@CachePut、@CacheEvict等注解实现对缓存的操作。
阅读全文