springboot+Redis+ehcache(双缓存)配置
1)maven和yml配置
maven配置如下:
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-ehcache</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
yml配置如下:
spring:
redis:
#redis数据库索引(默认为0)
database: 0
#redis服务器地址
host: localhost
#redis服务器连接端口
port: 6379
#redis连接密码
password:
#redis连接池设置
pool:
#最大空闲连接
max-idle: 100
#最小空闲连接
min-idle: 1
#最大连接数(负数表示没有限制)
max-active: 1000
#最大阻塞等待时间(负数表示没有限制)
max-wait: -1
#连接超时时间(毫秒)
timeout: 0
2)缓存配置类CacheConfig 和序列化类FastJsonRedisSerializer
@Configuration
public class CacheConfig {
private final String prefix = "algorithm";
public interface CacheManagerNames {
String REDIS_CACHE_MANAGER = "redisCacheManager";
String EHCACHE_CACHE_MANAGER = "ehCacheManager";
}
@Primary
@Bean(name = CacheManagerNames.REDIS_CACHE_MANAGER)
public RedisCacheManager redisCacheManager(RedisConnectionFactory factory) {
RedisSerializationContext.SerializationPair keySerializationPair = RedisSerializationContext.SerializationPair.fromSerializer(
new StringRedisSerializer());
FastJsonRedisSerializer<Object> fastJsonRedisSerializer = new FastJsonRedisSerializer<>(Object.class);
RedisSerializationContext.SerializationPair valueSerializationPair = RedisSerializationContext.SerializationPair.fromSerializer(
fastJsonRedisSerializer);
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
.computePrefixWith(cacheName -> prefix.concat(":").concat(cacheName).concat(":"))
.entryTtl(Duration.ofHours(12))
.serializeKeysWith(keySerializationPair)
.serializeValuesWith(valueSerializationPair);
return RedisCacheManager
.builder(RedisCacheWriter.nonLockingRedisCacheWriter(factory))
.cacheDefaults(config).build();
}
@Bean(name = CacheManagerNames.EHCACHE_CACHE_MANAGER)
public EhCacheCacheManager ehCacheCacheManager(EhCacheManagerFactoryBean bean){
//为了解决序列化报错:com.alibaba.fastjson.JSONException: autoType is not support. com.model.request.entity.User
ParserConfig.getGlobalInstance().setAutoTypeSupport(true);
return new EhCacheCacheManager(bean.getObject());
}
@Bean
public EhCacheManagerFactoryBean cacheManagerFactoryBean(){
EhCacheManagerFactoryBean bean = new EhCacheManagerFactoryBean();
bean.setConfigLocation(new ClassPathResource("ehcache.xml"));
bean.setShared(true);
return bean;
}
}
public class FastJsonRedisSerializer<T> implements RedisSerializer<T> {
private static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
private Class<T> clazz;
public FastJsonRedisSerializer(Class<T> clazz) {
super();
this.clazz = clazz;
}
@Override
public byte[] serialize(T t) throws SerializationException {
if (null == t) {
return new byte[0];
}
return JSON.toJSONString(t, SerializerFeature.WriteClassName).getBytes(DEFAULT_CHARSET);
}
@Override
public T deserialize(byte[] bytes) throws SerializationException {
if (null == bytes || bytes.length <= 0) {
return null;
}
String str = new String(bytes, DEFAULT_CHARSET);
return (T) JSON.parseObject(str, clazz);
}
}
3)配置ehcache.xml
<ehcache>
<diskStore path="java.io.tmpdir"/>
<defaultCache
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="true"
/>
<cache name="sampleCache1"
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="300"
timeToLiveSeconds="600"
overflowToDisk="true"
/>
<cache name="sampleCache2"
maxElementsInMemory="1000"
eternal="true"
timeToIdleSeconds="0"
timeToLiveSeconds="0"
overflowToDisk="false"
/> -->
</ehcache>
4)代码应用
//使用Redis缓存,cacheNames灵活可变
@org.springframework.cache.annotation.CacheConfig(cacheNames = {"user"},cacheManager = CacheConfig.CacheManagerNames.REDIS_CACHE_MANAGER)
public interface UserService {
public int save(User user);
@Cacheable(key = "#a0")
public User getUser(String name);
}
//使用ehcache缓存,cacheNames必须与ehcache.xml对应
@org.springframework.cache.annotation.CacheConfig(cacheNames = {"sampleCache1"},cacheManager = CacheConfig.CacheManagerNames.EHCACHE_CACHE_MANAGER)
public interface UserRepository extends PagingAndSortingRepository<User,Long> {
User findByName(@Param("name") String name);
@Cacheable(key = "#a0")
User findOneByName(@Param("name") String name);
}
5)启动类添加@EnableCaching
@SpringBootApplication
@EnableCaching
public class AlgorithmApp {
public static void main(String[] args) {
SpringApplication.run(AlgorithmApp.class);
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· winform 绘制太阳,地球,月球 运作规律
· 上周热点回顾(3.3-3.9)
2022-07-28 vue store用法