简单从这几个方面描述一下如何使用Cache,对Cache的各种原理介绍此处不涉及.
1.使用场景
2.如何使用Cache
3.创建方式
4. 如何和Spring搭配使用
+------------------------------------------------------分割线-------------------------------------------------------+
1. Cache的使用场景
一般而言,对于那些频繁需要查询比对的热点数据,我们采用使用缓存,对于数据量较小的,几条,几十条数据,而且需要加缓存的接口较少,这时候我们会采用Cache,建议使用Google提供的guava Cache,它简单易用的同时,性能也好. 而且线程安全(原因看源码) .对于那些较大数据量的,或者需要加缓存的接口较多的项目,可以去考虑Redis,memcached等等
2. 如何使用Cache
和Map的使用方式差不多,也可以和Spring结合,使用@Cacheable注解使用.
3. 创建方式
1. Cache Callable
2. LoadingCache
方式一:
1 package info.sanaulla.cache; 2 3 import com.google.common.cache.Cache; 4 import com.google.common.cache.CacheBuilder; 5 import org.junit.Test; 6 7 import java.util.concurrent.Callable; 8 import java.util.concurrent.ExecutionException; 9 import java.util.concurrent.TimeUnit; 10 11 /** 12 * ********************************************************* 13 * <p/> 14 * Author: XiJun.Gong 15 * Date: 2016-08-17 16:59 16 * Version: default 1.0.0 17 * Class description: 18 * <p/> 19 * ********************************************************* 20 */ 21 public class CacheDemo { 22 private static Cache<Object, Object> cache = CacheBuilder.newBuilder() 23 .maximumSize(100).expireAfterWrite(24, TimeUnit.HOURS) 24 .recordStats() 25 .build(); 26 27 public static Object get(Object key) throws ExecutionException { 28 29 Object var = cache.get(key, new Callable<Object>() { 30 @Override 31 public Object call() throws Exception { 32 System.out.println("如果没有值,就执行其他方式去获取值"); 33 String var = "Google.com.sg"; 34 return var; 35 } 36 }); 37 return var; 38 } 39 40 public static void put(Object key, Object value) { 41 cache.put(key, value); 42 } 43 44 class Person { 45 private String name; 46 private Integer age; 47 48 public Person() { 49 } 50 51 public Person(String name, Integer age) { 52 this.name = name; 53 this.age = age; 54 } 55 56 public String getName() { 57 return name; 58 } 59 60 public void setName(String name) { 61 this.name = name; 62 } 63 64 public Integer getAge() { 65 return age; 66 } 67 68 public void setAge(Integer age) { 69 this.age = age; 70 } 71 72 @Override 73 public String toString() { 74 return "Person{" + 75 "名字='" + name + '\'' + 76 ", 年纪=" + age + 77 '}'; 78 } 79 } 80 81 @Test 82 public void CacheTest() throws ExecutionException { 83 84 Person person = new Person(); 85 person.setAge(11); 86 person.setName("tSun"); 87 System.out.println(CacheDemo.get("man")); 88 CacheDemo.put("man", new Person("hopg", 123)); 89 System.out.println(CacheDemo.get("man")); 90 System.out.println(CacheDemo.get("man")); 91 92 System.out.println(CacheDemo.get("person").toString()); 93 CacheDemo.put("person", person); 94 System.out.println(CacheDemo.get("person").toString()); 95 System.out.println(CacheDemo.get("person").toString()); 96 97 System.out.println(CacheDemo.get("woman")); 98 CacheDemo.put("women", new Person("google", 666)); 99 System.out.println(CacheDemo.get("woman")); 100 System.out.println(CacheDemo.get("woman")); 101 System.out.println(CacheDemo.get("man")); 102 } 103 }