YMP Online Manual /缓存模块使用示例

缓存模块使用示例

示例一:直接通过缓存模块操作缓存数据
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”字符串,说明它没有使用缓存,再次调用时直接从缓存中返回值;