【分布式缓存】springboot整合jetcache使用详解
import com.alicp.jetcache.Cache;
import com.alicp.jetcache.CacheBuilder;
import com.alicp.jetcache.embedded.EmbeddedCacheBuilder;
import com.alicp.jetcache.anno.CacheConsts;
import com.alicp.jetcache.anno.config.EnableCreateCacheAnnotation;
import com.alicp.jetcache.anno.config.EnableMethodCache;
import com.alicp.jetcache.anno.support.SpringConfigProvider;
import com.alicp.jetcache.embedded.EmbeddedCacheConfig;
import com.alicp.jetcache.support.FastjsonKeyConvertor;
import com.alicp.jetcache.support.JavaValueDecoder;
import com.alicp.jetcache.support.JavaValueEncoder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@EnableMethodCache(basePackages = "com.yourpackage.service")
@EnableCreateCacheAnnotation
public class CacheConfig {
@Bean
public SpringConfigProvider springConfigProvider() {
return new SpringConfigProvider();
}
@Bean
public CacheBuilder<Object, Object> cacheBuilder() {
EmbeddedCacheBuilder embeddedCacheBuilder = EmbeddedCacheBuilder.createEmbeddedCacheBuilder()
.keyConvertor(FastjsonKeyConvertor.INSTANCE)
.valueEncoder(JavaValueEncoder.INSTANCE)
.valueDecoder(JavaValueDecoder.INSTANCE)
.config(config());
return embeddedCacheBuilder;
}
private EmbeddedCacheConfig config() {
EmbeddedCacheConfig cacheConfig = new EmbeddedCacheConfig();
cacheConfig.setName(CacheConsts.DEFAULT_CACHE_NAME);
// 设置其他配置参数
return cacheConfig;
}
@Bean
public Cache<Object, Object> defaultCache(CacheBuilder<Object, Object> cacheBuilder) {
return cacheBuilder.buildCache();
}
}
这个配置类定义了一个名为defaultCache
的缓存Bean,它使用了FastjsonKeyConvertor
进行序列化,JavaValueEncoder
和JavaValueDecoder
进行值的编码和解码。同时,它也启用了注解方式的缓存,这意味着在服务层的方法上使用@CreateCache
和@RefreshCache
注解可以创建和刷新缓存。这个配置类也展示了如何配置默认缓存的基本参数。
评论已关闭