系統中用到了了Guava Cache:
private DriverInfoServiceImpl(DriverClientProxy driverClientProxy) { this.driverClientProxy = driverClientProxy; this.driverCacheLoader = new DriverCacheLoader(driverClientProxy); loadingCache = CacheBuilder .newBuilder() .concurrencyLevel(5) .recordStats() .expireAfterWrite(1, TimeUnit.MINUTES) .build(driverCacheLoader); }
相應的參數解釋:
concurrencyLevel(5) ==並發度,可以同時寫緩存的線程數。
recordStats==設置要統計緩存的命中率;
expireAfterWrite(1, TimeUnit.MINUTES);設置寫緩存后,1分鍾過期
public static void main(String[] args) throws ExecutionException, InterruptedException{ //緩存接口這里是LoadingCache,LoadingCache在緩存項不存在時可以自動加載緩存 LoadingCache<Integer,Student> studentCache //CacheBuilder的構造函數是私有的,只能通過其靜態方法newBuilder()來獲得CacheBuilder的實例 = CacheBuilder.newBuilder() //設置並發級別為8,並發級別是指可以同時寫緩存的線程數 .concurrencyLevel(8) //設置寫緩存后8秒鍾過期 .expireAfterWrite(8, TimeUnit.SECONDS) //設置緩存容器的初始容量為10 .initialCapacity(10) //設置緩存最大容量為100,超過100之后就會按照LRU最近雖少使用算法來移除緩存項 .maximumSize(100) //設置要統計緩存的命中率 .recordStats() //設置緩存的移除通知 .removalListener(new RemovalListener<Object, Object>() { @Override public void onRemoval(RemovalNotification<Object, Object> notification) { System.out.println(notification.getKey() + " was removed, cause is " + notification.getCause()); } }) //build方法中可以指定CacheLoader,在緩存不存在時通過CacheLoader的實現自動加載緩存 .build( new CacheLoader<Integer, Student>() { @Override public Student load(Integer key) throws Exception { System.out.println("load student " + key); Student student = new Student(); student.setId(key); student.setName("name " + key); return student; } } ); for (int i=0;i<20;i++) { //從緩存中得到數據,由於我們沒有設置過緩存,所以需要通過CacheLoader加載緩存數據 Student student = studentCache.get(1); System.out.println(student); //休眠1秒 TimeUnit.SECONDS.sleep(1); } System.out.println("cache stats:"); //最后打印緩存的命中率等 情況 System.out.println(studentCache.stats().toString()); }