比Spring Cache 更好用 更简单的缓存工具 jscache 取名意义为 java simple cache ,基于AOP实现,支持注解到接口 自定义单个缓存过期时间配置 ttl,轻松扩展缓存实现,默认实现了jedis,spring-data- redis,还有一个基于本地内存的map。
jscache
AOP
ttl
jedis
spring-data- redis
map
源码仓库 https://github.com/peachyy/jscache.git
设置/获取缓存 如果当前KEY对应的缓存存在就直接返回,不存在则调用服务后 再对结果进行缓存。
配置项
el
prefix+key
redis
true
@Cacheable(prefix = "user:",key = "#p0",ttl = 60,returnCondition = "#result!=null") public User getUserById(Integer userId) { User user=new User(); user.setId(userId); user.setName("xxx"); log.info("GET getUserById"); return user; }
只是设置(put)缓存 无论缓存是否存在 这里支持设置(put)多个缓存
配置项 与 cacheable类似
@CachePut(prefix = "user:",key = "#p0") @CachePut(prefix = "members:",key = "#p0") public User getUserById(Integer userId) { User user=new User(); user.setId(userId); user.setName("xxx"); log.info("GET getUserById"); return user; }
删除缓存 支持删除多个缓存
@CacheEvict(prefix = "members:",key = "#p0") @CacheEvict(prefix = "user:",key = "#p0",argCondition = "#p0==100") public User getUserById(Integer userId) { User user=new User(); user.setId(userId); user.setName("xxx"); log.info("GET getUserById"); return user; }
如springboot中 标注@EnableCache注解 表示缓存功能启用 只要标注了注解的就会生效。
@EnableCache
引入jar
<dependency> <groupId>com.peachyy</groupId> <artifactId>jscache-core</artifactId> <version>${last.jscache.version}</version> </dependency>
启用缓存 并配置一个缓存实现。
@SpringBootApplication @EnableCache() public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } @Bean public JedisCache cache(){ Properties properties=new Properties(); properties.put("hosts","192.168.0.2:6379"); properties.put("password","bac123"); properties.put("database","0"); return new JedisCache(properties,null); }
这里有一个基于springboot的例子 https://github.com/peachyy/jscache/tree/master/jscache- springmvc-example
主要是用于针对部分rpc 如dubbo 当使用@Reference注解 实例没有被spring ioc管理到 就不能到框架AOP 所以提供一些简单的支持 目前仅实现了dubbo的这种情况
dubbo
@Reference
spring ioc
dubbo service
filter
序列化
序列化只针对值 key默认为String字符,方便监控查看。自定义序列化需要实现 com.peachyy.jscache.core.serialize.Serializer接口。默认的实现有fastJson,jackson,java 自定义的直接传自定义的全类名就行。
String
com.peachyy.jscache.core.serialize.Serializer
fastJson
jackson
java
如 扩展了一个com.xxx.myJacksonSerializer序列化方式 设置的方式大概就是这样
com.xxx.myJacksonSerializer
@EnableCache(serializer="com.xxx.myJacksonSerializer")
扩展缓存实现 扩展缓存需要实现com.peachyy.jscache.core.Cache接口,加入spring容器就完事了。不需要复杂的实现
com.peachyy.jscache.core.Cache
@Bean public JedisCache cache(){ Properties properties=new Properties(); properties.put("hosts","192.168.0.2:6379"); properties.put("password","bac123"); properties.put("database","0"); return new JedisCache(properties,null); }
和springcache比起来使用上的功能大部分有,一些设计也参考了它,使用上明显的差别就是支持了ttl过期时间,去掉了cacheManager设计,但是仅不止如此 开发者更易驾驭,一个系统中一般保持一套缓存规范就够了。总之适合就是最好的。
原文链接:https://www.cnblogs.com/peachyy/p/13542113.html