您现在的位置是:首页 > 文章详情

SpringBoot2 项目缓存从 Redis 切换到 j2cache

日期:2018-09-28点击:1101

首先添加依赖,此处有坑。刚开始添加的是 <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 
原文链接:https://my.oschina.net/desert/blog/2218535
关注公众号

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。

持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。

转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。

文章评论

共有0条评论来说两句吧...

文章二维码

扫描即可查看该文章

点击排行

推荐阅读

最新文章