Spring Boot中使用阿里JetCache
背景
当系统在有缓存应用场景时,目前常见的是使用redis缓存框架完成,但redis只是二级缓存,而且调用代码不精简,常用的使用redisTemplate完成调用。
JetCache完美支持多级缓存使用,并且使用简单,支持分布式同步,简化代码,优雅实现。
官方地址:https://github.com/alibaba/jetcache
使用方式
介入我所用项目中用到的JetCache结合Redis使用场景,这里不包含redis的部分,项目先要完成redis的引用,以下介绍如何使用JetCache。
引用Pom
这里我所用的版本是2.7.0,具体可以根据官方Github去选择,但注意与Spring Boot间的版本关系。
<!-- jet cache -->
<dependency>
<groupId>com.alicp.jetcache</groupId>
<artifactId>jetcache-starter-redis-springdata</artifactId>
<version>2.7.0</version>
</dependency>
yml配置
这里配置jetcache的一二级缓存格式和存储,这里的redis使用参数配置,以便维护。
# jetcache
jetcache:
statIntervalMinutes: 1
areaInCacheName: false
local:
default:
type: linkedhashmap
keyConvertor: fastjson
remote:
default:
type: redis.springdata
keyConvertor: fastjson
expireAfterWriteInMillis: 7200000
host: ${spring.redis.host}
password: ${spring.redis.password}
port: ${spring.redis.port}
database: ${spring.redis.database}
启动注解
启动类需要增加@EnableMethodCache注解。
@EnableScheduling
@SpringBootApplication(scanBasePackages = {"dev.demo"})
@EnableMethodCache(basePackages = {"dev.demo"})
@EnableAsync
@Slf4j
public class DemoServerApplication {
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(DemoServerApplication.class, args);
Environment environment = context.getEnvironment();
Integer port = environment.getProperty("server.port", Integer.class);
log.info("Congratulations! service is running on port {}.", port);
}
}
使用方法
例如在获取系统配置方法中,在方法上增加@Cached注解,name代表缓存前缀,key代表缓存标识,例如在redis中,将创建name+key的缓存key。expire代表过期时间,单位为秒。
@Slf4j
@Service
public class ConfigServiceImpl implements ConfigService {
@Override
@Cached(name = "SYSTEM_CONFIG__KEY_", key="#key", expire = RedisKey.TWO_HOUR)
public Config getByKey(String key) {
return configMapper.getByKey(key);
}
}
高阶用法
JetCache的简单用法已经介绍,像cacheType可以配置缓存在内存中还是Redis中,类似可以参考JetCache官方文档。