SpringBoot2 项目缓存从 Redis 切换到 j2cache


声明:本文转载自https://my.oschina.net/desert/blog/2218535,转载目的在于传递更多信息,仅供学习交流之用。如有侵权行为,请联系我,我会及时删除。

首先添加依赖,此处有坑。刚开始添加的是 <artifactId>j2cache-spring-boot-starter</artifactId>,一直报错,后来发现springboot2工程需要使用 <artifactId>j2cache-spring-boot2-starter</artifactId>.

<dependency>
	<groupId>net.oschina.j2cache</groupId>
	<artifactId>j2cache-spring-boot2-starter</artifactId>
	<version>2.7.0-release</version>
	<exclusions>
		<exclusion>
			<groupId>com.alibaba</groupId>
			<artifactId>fastjson</artifactId>
		</exclusion>
	</exclusions>
</dependency>

之前配置的缓存管理器及缓存RedisTemplate等工具都是基于Redis、Jedis的,使用了j2cache的starter后,之前的缓存配置基本上已经没有用了,需要注释掉。

之前加的spring-session-data-redis,也需要去掉或者使用使用j2cache作为缓存,也可以切换到j2cache的session方案(暂时没有尝试)。

        <dependency>
            <groupId>org.springframework.session</groupId>
            <artifactId>spring-session-data-redis</artifactId>
        </dependency>

原cache工具类:

@Component("redisCacheUtil")
public class RedisCacheUtilImpl<T> implements RedisCacheUtil<T> {
    @Autowired
    CacheManager cacheManager;
}

修改后:

@Component("redisCacheUtil")
@ConditionalOnClass(J2CacheAutoConfiguration.class)
@AutoConfigureAfter(J2CacheCacheManger.class)
public class RedisCacheUtilImpl<T> implements RedisCacheUtil<T> {
    private static final Logger log = LoggerFactory.getLogger(RedisCacheUtilImpl.class);

    @Autowired
    J2CacheCacheManger cacheManager;
}

这里可能会报cacheManager Could not autowire,没关系,不影响。

springboot项目天生可以区分运行环境,我们可以使用j2cache-${spring.profiles.active}.properties来引用不同环境的配置。在application.yml中配置增加:

spring:
  cache:
    type: none // 原先使用redis,现在改为none
j2cache:
  config-location: /j2cache-${spring.profiles.active}.properties
  redis-client: lettuce
  open-spring-cache: true

我们使用的redis-client为lettuce,并开启spring cache。 在j2cache.properties中,我们重点针对性修改配置:

// 广播策略
j2cache.broadcast = net.oschina.j2cache.cache.support.redis.SpringRedisPubSubPolicy
// 一级缓存使用caffeine
j2cache.L1.provider_class = caffeine
// 二级缓存使用lettuce,和redis-client对应
j2cache.L2.provider_class = lettuce
// L2配置
j2cache.L2.config_section = redis
// redis缓存序列化方式,不建议配置为json,如果父类和子类有同样的属性(id),在序列化的json中会出现两个id属性,其中一个为空。使用fastjson没有此问题。另外,本人认为使用json序列化比类序列化更好,可以做到更好的反序列化兼容。
j2cache.serialization = fastjson
// caffeine的配置文件位置,缓存数量及超时时间可以在里面配置
caffeine.properties = /caffeine.properties

本文发表于2018年09月28日 11:00
(c)注:本文转载自https://my.oschina.net/desert/blog/2218535,转载目的在于传递更多信息,并不代表本网赞同其观点和对其真实性负责。如有侵权行为,请联系我们,我们会及时删除.

阅读 2750 讨论 0 喜欢 0

抢先体验

扫码体验
趣味小程序
文字表情生成器

闪念胶囊

你要过得好哇,这样我才能恨你啊,你要是过得不好,我都不知道该恨你还是拥抱你啊。

直抵黄龙府,与诸君痛饮尔。

那时陪伴我的人啊,你们如今在何方。

不出意外的话,我们再也不会见了,祝你前程似锦。

这世界真好,吃野东西也要留出这条命来看看

快捷链接
网站地图
提交友链
Copyright © 2016 - 2021 Cion.
All Rights Reserved.
京ICP备2021004668号-1