为什么要用Jetcache
JetCache是一个基于Java的缓存系统封装,它提供统一的API和注解来简化缓存的使用。JetCache比SpringCache更强大的注解,可以原生的支持TTL、两级缓存、分布式自动刷新,还提供了Cache接口用于手工缓存操作。
以前使用红薯大佬的j2cache,用起来挺舒服。但是由于j2cache很久没更新了,jedis驱动也比较旧,且不支持TTL。故而转为使用jetcache。
Jetcache现状
目前使用的版本是最新版2.7.4,按照官方的说法,最新版本已经不支持json序列化。但是由于某些数据监控和测试的需要,需要开启json以便在redis客户端能够很方便的观察数据。
有文章说未支持一级缓存的同步。从当前的版本看来,已经是实现了本地缓存的同步了,如果是redis作为二级的话,默认会使用LettuceBroadcastManager进行监听和推送。
需要配置地方
jetcache:remote:default:type: redis.lettucekeyConvertor: fastjson2 #other choose:fastjson/jacksonbroadcastChannel: ccframevalueEncoder: fastjson2 #other choose:kryo/kryo5/javavalueDecoder: fastjson2 #other choose:kryo/kryo5/java
只要配置好broadcastChannel即可,然后在生成cache时,指定syncLocal来监听变化:
@PostConstructpublic void initCache(){QuickConfig qc = QuickConfig.newBuilder(entityClass.getSimpleName() + "Cache").expire(Duration.ofMinutes(30)).cacheType(CacheType.BOTH) // two level cache.syncLocal(true) // invalidate local cache in all jvm process after update.build();cache = cacheManager.getOrCreateCache(qc);}
此处配置了一个30分钟时长的缓存,发生变更时会广播。
扩展点
回到正题,讲一下如何进行扩展。github上有人扩展了jetcache-plus添加了jackson,需要的可以看看。这里只讲讲如何把jetcache自带的fastjson2给开启起来:
STEP1
按照官方的例子,继承DefaultEncoderParser添加一个新的EncoderParser
package org.ccframe.commons.helper;import com.alicp.jetcache.CacheConfigException;
import com.alicp.jetcache.anno.SerialPolicy;
import com.alicp.jetcache.anno.support.DefaultEncoderParser;
import com.alicp.jetcache.support.*;
import io.github.qy8502.jetcacheplus.JacksonValueDecoder;
import io.github.qy8502.jetcacheplus.JacksonValueEncoder;
import org.apache.lucene.search.highlight.DefaultEncoder;import java.net.URI;
import java.util.function.Function;public class JsonEncoderParser extends DefaultEncoderParser {public static final String SERIAL_POLICY_FASTJSON2 = "FASTJSON2";@Overridepublic Function<Object, byte[]> parseEncoder(String valueEncoder) {if (SERIAL_POLICY_FASTJSON2.equalsIgnoreCase(valueEncoder)) {return new Fastjson2ValueEncoder(true);} else {return super.parseEncoder(valueEncoder);}}@Overridepublic Function<byte[], Object> parseDecoder(String valueDecoder) {if (SERIAL_POLICY_FASTJSON2.equalsIgnoreCase(valueDecoder)) {Fastjson2ValueDecoder fastjson2ValueDecoder = new Fastjson2ValueDecoder(true);DecoderMap decoderMap = DecoderMap.defaultInstance();decoderMap.register(SerialPolicy.IDENTITY_NUMBER_FASTJSON2, Fastjson2ValueDecoder.INSTANCE);fastjson2ValueDecoder.setDecoderMap(decoderMap);return fastjson2ValueDecoder;} else {return super.parseDecoder(valueDecoder);}}}
至于为什么要用decoderMap.register,因为跟踪代码发现NPE了,翻了下源码参考下,做了个按ID缓存的cache,添加后正常了
STEP2
jetcache设计了一个扩展点,在生成ConfigProvider时,可以指定EncoderParser的bean
/*** Created on 2022/08/03.*/
package com.alicp.jetcache.anno.support;import com.alicp.jetcache.SimpleCacheManager;
import com.alicp.jetcache.support.StatInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;import java.util.function.Consumer;/*** used in non-spring-boot projects.** @author <a href="mailto:areyouok@gmail.com">huangli</a>*/
public class JetCacheBaseBeans {protected SpringConfigProvider createConfigProvider() {return new SpringConfigProvider();}@Bean(destroyMethod = "shutdown")public SpringConfigProvider springConfigProvider(@Autowired ApplicationContext applicationContext,@Autowired GlobalCacheConfig globalCacheConfig,@Autowired(required = false) EncoderParser encoderParser,@Autowired(required = false) KeyConvertorParser keyConvertorParser,@Autowired(required = false) Consumer<StatInfo> metricsCallback) {SpringConfigProvider cp = createConfigProvider();cp.setApplicationContext(applicationContext);cp.setGlobalCacheConfig(globalCacheConfig);if (encoderParser != null) {cp.setEncoderParser(encoderParser);}if (keyConvertorParser != null) {cp.setKeyConvertorParser(keyConvertorParser);}if (metricsCallback != null) {cp.setMetricsCallback(metricsCallback);}cp.init();return cp;}@Bean(name = "jcCacheManager",destroyMethod = "close")public SimpleCacheManager cacheManager(@Autowired ConfigProvider configProvider) {SimpleCacheManager cacheManager = new SimpleCacheManager();cacheManager.setCacheBuilderTemplate(configProvider.getCacheBuilderTemplate());return cacheManager;}
}
同理keyConvertorParser和metricsCallback也可以类似指定。
因此,只需在connfig类里添加一行代码即完成扩展
@EnableCreateCacheAnnotation //缓存基本数据据类型的注解
@Configuration
public class RedisConfig{@Beanpublic EncoderParser encoderParser(){return new JsonEncoderParser(); // 支持json序列化}}
看下redis,已经是json格式了
收工~