guava试水一篇

@Controller
@RequestMapping("/")
@SuppressWarnings("unchecked")
public class NavController extends GenericController {


	@Autowired
	private RevitNewEntityService revitNewEntityService ;


	LoadingCache> revitQueryCache
	// CacheBuilder的构造函数是私有的,只能通过其静态方法newBuilder()来获得CacheBuilder的实例
	= CacheBuilder.newBuilder()
	// 设置并发级别为8,并发级别是指可以同时写缓存的线程数
			.concurrencyLevel(8)
			// 设置写缓存后600秒钟过期
			.expireAfterWrite(600, TimeUnit.SECONDS)
			// 设置缓存容器的初始容量为10
			.initialCapacity(10)
			// 设置缓存最大容量为100,超过100之后就会按照LRU最近虽少使用算法来移除缓存项
			.maximumSize(100)
			// 设置要统计缓存的命中率
			.recordStats()
			// 设置缓存的移除通知
			.removalListener(new RemovalListener() {
				@Override
				public void onRemoval(RemovalNotification notification) {
					System.out.println(notification.getKey() + " was removed, cause is " + notification.getCause());
				}
			})
			// build方法中可以指定CacheLoader,在缓存不存在时通过CacheLoader的实现自动加载缓存
			.build(new CacheLoader>() {
				@Override
				public List load(String arg0) throws Exception {
					System.out.println("load from db");
					if(arg0.equals("hot")){
						return revitNewEntityService.getHotRevit();
					}else if(arg0.equals("popular")){
						return revitNewEntityService.getPopularRevit();
					}
					return null;
				}
			});
		@RequestMapping(value = "welcome", method = RequestMethod.GET)
	public String welcomeNew(HttpServletRequest request, HttpServletResponse response) throws ExecutionException {
/*		原来写法
        List hotRevitList = revitNewEntityService.getHotRevit();
		request.setAttribute("hotRevitList", hotRevitList);
		List popularRevit = revitNewEntityService.getPopularRevit();
		request.setAttribute("popularRevit", popularRevit);
*/
        //使用guaua写法
		request.setAttribute("hotRevitList", revitQueryCache.get("hot"));
		request.setAttribute("popularRevit", revitQueryCache.get("popular"));

		return "/index";
	}


总体看 非常灵活 使用本地缓存,单机服务器有时候比较方便 (不用redis的情况下)


输出结果

load from db
load from db
600s 内再次查询 不再提示,说明走了缓存

600s后

再次查询 输出过期缓存

hot was removed, cause is EXPIRED
load from db
popular was removed, cause is EXPIRED
load from db


然后查了一次数据库 继续查都走缓存了。。真的很方便

你可能感兴趣的:(j2se)