Srping Boot使用redis缓存
0
引入依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
redis配置:
spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.database=0
然后配置缓存CacheManager
:
package com.api.core.config;
import java.time.Duration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.CacheManager;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.cache.interceptor.SimpleKeyGenerator;
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;
/**
* 缓存配置
*/
@Configuration
public class CacheConfig {
private static final Logger LOGGER = LoggerFactory.getLogger(CacheConfig.class);
@Bean
public CacheManager cacheManager(RedisConnectionFactory connectionFactory) {
LOGGER.info("初始化CacheManager");
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
config = config
// .serializeKeysWith(null) // key 序列化
// .serializeValuesWith(null) // value 序列化
.entryTtl(Duration.ofMinutes(30)) // 设置过期时间
.disableCachingNullValues(); // 不缓存空值,如果出现null会抛异常
// 初始化缓存配置
Set<String> caches = new HashSet<>();
caches.add("cache-key-1");
caches.add("cache-key-2");
// 缓存设置
Map<String, RedisCacheConfiguration> cacheConfigs = new HashMap<>();
cacheConfigs.put("cache-key-1", config);
cacheConfigs.put("cache-key-2", config);
// 创建缓存
RedisCacheManager cacheManager = RedisCacheManager.builder(connectionFactory)
.initialCacheNames(caches)
.withInitialCacheConfigurations(cacheConfigs)
.build();
return cacheManager;
}
@Bean
public KeyGenerator keyGenerator() {
LOGGER.info("初始化KeyGenerator");
return new SimpleKeyGenerator();
}
}
然后就可以使用@Cacheable
等注解了。