springboot+Redis+ehcache(双缓存)配置

1)maven和yml配置

maven配置如下:

    org.hibernate
    hibernate-ehcache
    ${hibernate.version}


    org.springframework.boot
    spring-boot-starter-data-redis

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 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 implements RedisSerializer {
    private static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
    private Class clazz;
    public FastJsonRedisSerializer(Class 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


    
    
    
     -->

 

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 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);
    }
}

 

你可能感兴趣的:(java,缓存)