1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
| package redis;
import com.google.common.cache.*;
import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit;
public class GuavaCacheDemo {
public static void main(String[] args) throws ExecutionException { LoadingCache<String, User> userCache = CacheBuilder.newBuilder() .concurrencyLevel(8) .expireAfterWrite(8, TimeUnit.SECONDS) .refreshAfterWrite(1, TimeUnit.SECONDS) .initialCapacity(10) .maximumSize(100) .recordStats() .removalListener(new RemovalListener<Object, Object>() { @Override public void onRemoval(RemovalNotification<Object, Object> notification) { System.out.println(notification.getKey() + " 被移除了,原因: " + notification.getCause()); } }) .build( new CacheLoader<String, User>() { @Override public User load(String key) throws Exception { System.out.println("缓存没有时,从数据库加载" + key); return new User("cache" + key, key); } } );
for (int i = 0; i < 20; i++) { User user = userCache.get("uid" + i); System.out.println(user); }
for (int i = 0; i < 20; i++) { User user = userCache.get("uid" + i); System.out.println(user); } System.out.println("cache stats:"); System.out.println(userCache.stats().toString()); } }
|