首先添加依賴,此處有坑。剛開始添加的是 <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
版權聲明:本文為CSDN部落客「weixin_34163741」的原創文章,遵循CC 4.0 BY-SA版權協定,轉載請附上原文出處連結及本聲明。
原文連結:https://blog.csdn.net/weixin_34163741/article/details/91762897