收藏606
分享
阅读11915
更新时间2022-04-11
public static void main(String[] args) throws Exception {
YMP.get().init();
try {
// 操作默认缓存
Caches.get().put("key1", "value1");
System.out.println(Caches.get().get("key1"));
// 操作指定名称的缓存
Caches.get().put("default", "key2", "value2");
System.out.println(Caches.get().get("default", "key2"));
} finally {
YMP.get().destroy();
}
}注:当指定缓存名称时,请确认与名称对应的配置是否已存在;
执行结果:
value1 value2
这里用到了@Cacheable注解,作用是标识类中方法的执行结果是否进行缓存,需要注意的是:
首先@Cacheable注解必须在已注册到YMP类对象管理器的类上声明,表示该类支持缓存;
其次,在需要缓存执行结果的方法上添加@Cacheable注解;
@Cacheable注解参数说明:
cacheName:缓存名称, 默认值为default;
key:缓存Key, 若未设置则使用keyGenerator自动生成;
generator:Key生成器接口实现类,默认为DefaultKeyGenerator.class;
scope:缓存作用域,可选值为APPLICATION、SESSION和DEFAULT,默认为DEFAULT,非DEFAULT设置需要缓存作用域处理器(ICacheScopeProcessor)接口配合;
timeout:缓存数据超时时间, 可选参数,数值必须大于等于0,为0表示默认缓存300秒;
示例代码:
@Bean
@Cacheable
public class CacheDemo {
@Cacheable
public String sayHi(String name) {
System.out.println("No Cached");
return "Hi, " + name;
}
public static void main(String[] args) throws Exception {
YMP.get().init();
try {
CacheDemo _demo = YMP.get().getBean(CacheDemo.class);
System.out.println(_demo.sayHi("YMP"));
System.out.println(_demo.sayHi("YMP"));
//
System.out.println("--------");
//
System.out.println(_demo.sayHi("YMPer"));
System.out.println(_demo.sayHi("YMP"));
System.out.println(_demo.sayHi("YMPer"));
} finally {
YMP.get().destroy();
}
}
}执行结果:
No Cached Hi, YMP Hi, YMP -------- No Cached Hi, YMPer Hi, YMP Hi, YMPer
以上结果输出可以看出,sayHi方法相同参数首次被调用时将输出“No Cached”字符串,说明它没有使用缓存,再次调用时直接从缓存中返回值;
相关
视频
RELATED VIDEOS
科技资讯
1
2
3
4
5
6
7
8
9
精选课程
共5课时
17.2万人学习
共49课时
77万人学习
共29课时
61.7万人学习
共25课时
39.3万人学习
共43课时
71万人学习
共25课时
61.6万人学习
共22课时
23万人学习
共28课时
33.9万人学习
共89课时
125万人学习