Google Guava -緩存cache簡單使用


package guavacache;
import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import com.google.common.cache.RemovalListener; import com.google.common.cache.RemovalNotification; public class cachetest { public static class Student { private int id; public String name; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return id + "| " + name; } } 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(18, TimeUnit.SECONDS) // 設置緩存容器的初始容量為10 .initialCapacity(2) // 設置緩存最大容量為100,超過100之后就會按照LRU最近雖少使用算法來移除緩存項 .maximumSize(2) // 設置要統計緩存的命中率 .recordStats() // 設置緩存的移除通知 .removalListener(new RemovalListener<Object, Object>() { 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(i); // System.out.println(student); // // 休眠1秒 // TimeUnit.SECONDS.sleep(1); // } System.out.println("cache stats:"); // 最后打印緩存的命中率等 情況 System.out.println(studentCache.stats().toString()); } }

  測試最大容量LRU算法, 感覺更像是把使用時間最近的保留

		Student student = studentCache.get(1);
		System.out.println(student);
		student = studentCache.get(1);
		System.out.println(student);
		student = studentCache.get(1);
		System.out.println(student);
		
		student = studentCache.get(2);
		System.out.println(student);

		student = studentCache.get(3);
		System.out.println(student);

  結果為 1 was removed, cause is SIZE

maven 

    <dependency>
    	<groupId>com.google.guava</groupId>
    	<artifactId>guava</artifactId>
    	<version>18.0</version>
	</dependency>

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM