Cache module usage example
Example 1: Operate cached data directly through the cache module
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(); } }
Note: When specifying the cache name, please Confirm whether the configuration corresponding to the name already exists;
Execution result:
value1 value2
Example 2: Completed based on annotations Cache of class methods
The @Cacheable annotation is used here, which is used to identify whether the execution results of the methods in the class are cached. It should be noted that:
First, the @Cacheable annotation must be in Declared on a class that has been registered with the YMP class object manager, indicating that the class supports caching;
Secondly, add the @Cacheable annotation on the method that needs to cache the execution results;
@ Cacheable annotation parameter description:
cacheName: cache name, the default value is default;
key: cache Key, if not set, it will be automatically generated using keyGenerator;
generator: Key generator interface implementation class, the default is DefaultKeyGenerator.class;
scope: cache scope, optional values are APPLICATION, SESSION and DEFAULT, the default is DEFAULT, non-DEFAULT settings require a cache scope processor (ICacheScopeProcessor) interface coordination;
timeout: cache data timeout, optional parameter, the value must be greater than or equal to 0, 0 means the default cache is 300 seconds;
Sample code:
@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(); } } }
Execution result:
No Cached Hi, YMP Hi, YMP -------- No Cached Hi, YMPer Hi, YMP Hi, YMPer
It can be seen from the above result output that the sayHi method is the same When the parameter is called for the first time, the "No Cached" string will be output, indicating that it does not use the cache. When called again, the value will be returned directly from the cache;