SpringBoot2 項目緩存從 Redis 切換到 j2cache

首先添加依賴,此處有坑。剛開始添加的是 <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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章