JAVA日常優化---Guava緩存玩耍異步刷新

/**
 * v2支撐
 * @author chenzhen
 *         Created by chenzhen on 2018/11/20.
 */
public class TypeNumberCache {

	private static Logger logger = LoggerFactory.getLogger(TypeNumberCache.class);

	private static EntityInfoDaoImpl entityInfoDao = new EntityInfoDaoImpl();

	/**
	 * LRU算法
	 */
	private static LoadingCache<String, Integer> localCache = CacheBuilder.newBuilder().initialCapacity(1000).maximumSize(2000).refreshAfterWrite(2, TimeUnit.MINUTES)
			.build(new CacheLoader<String, Integer>() {
				//默認的數據加載實現,當調用get取值的時候,如果key沒有對應的值,就調用這個方法進行加載.
				@Override
				public Integer load(String s) throws Exception {
					Integer value = entityInfoDao.listEntityBy("_type",s).size();
					TypeNumberCache.setKey(s,value);
					return value;
				}

				@Override
				public ListenableFuture<Integer> reload(String key, Integer oldValue) throws Exception {

					//asynchronous,異步刷新
					ListenableFutureTask<Integer> task = ListenableFutureTask.create(new Callable<Integer>() {
						@Override
						public Integer call() throws Exception {
							return entityInfoDao.listEntityBy("_type",key).size();
						}
					});
					ExecutorService executorService = CacheExecutorServiceUtil.newExecutorService();
					executorService.execute(task);
					executorService.shutdown();
					return task;
				}
			});

	public static void setKey(String key, Integer value) {
		localCache.put(key, value);
	}

	public static Integer getKey(String key) {
		Integer value;
		try {
			value = localCache.get(key);
			if (value==null) {
				return -1;
			}
			return value;
		} catch (Exception e) {
			logger.error("TypeNumberCache get error", e);
		}
		return -1;
	}

	public static void cleanUp() {
		localCache.cleanUp();
	}
}

自定義線程池

/**
 * Guava緩存自定義線程池
 * @author chenzhen
 *         Created by chenzhen on 2018/11/27.
 */
public class CacheExecutorServiceUtil {

	private static final int CORE_POOL_SIZE = 10;
	private static final int MAXIMUM_POOL_SIZE = 30;
	private static final long KEEP_ALIVE_TIME = 10L;
	private static final TimeUnit TIME_UNIT = TimeUnit.SECONDS;

	private static final ThreadFactory THREAD_FACTORY = new ThreadFactory() {
		private final ThreadFactory defaultFactory = Executors.defaultThreadFactory();
		private final AtomicInteger threadNumber = new AtomicInteger(1);

		@Override
		public Thread newThread(Runnable r) {
			Thread thread = this.defaultFactory.newThread(r);
			if(!thread.isDaemon()) {
				thread.setDaemon(true);
			}

			thread.setName("Guava-Cache" + this.threadNumber.getAndIncrement());
			return thread;
		}
	};

	public static ExecutorService newExecutorService() {
		return new ThreadPoolExecutor(CORE_POOL_SIZE,MAXIMUM_POOL_SIZE, KEEP_ALIVE_TIME, TIME_UNIT, new ArrayBlockingQueue<>(200), THREAD_FACTORY);
	}

}

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章