Guava之controller中使用缓存cache

阅读更多

之前介绍过的Guava这个工具包中有很多方便的用法,下面要使用它封装的Cache来实现功能.

示例:

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/hello")
public class HelloController {
	
	private static Logger logger = LoggerFactory.getLogger(HelloController .class);

	public static LoadingCache cacheBuilder;

	@Autowired
	private OverviewService overviewService;

	static OverviewParameter op ;
	
	@RequestMapping(value="/hh",method=RequestMethod.GET)
	public Result sayHello(OverviewParameter overviewParameter){
		Result result = null;
		setOviewParameter(overviewParameter);
		ObjectResultEx resObj  = (ObjectResultEx) getDataInCache("summary", overviewParameter);
		...	
		return result;
	}

	/**
	 * 根据键值获取缓存中的数据
	 */
	private Object getDataInCache(final String key, OverviewParameter overviewParameter){
		logger.info("before refresh cache, key:{}, param:{}",key, JSONObject.toJSONString(overviewParameter));
		op = overviewParameter;
		try {
			if ((cacheBuilder != null) && ((ObjectResultEx) cacheBuilder.get(key)).isSuccess()){
				return cacheBuilder.get(key);
                        }else {
				return commonCache(new CacheLoader() {
					@Override
					public Object load(String key) throws Exception {
						logger.info("refresh cache, key:{}, param:{}",key, JSONObject.toJSONString(op));
						switch (key){
							case "summary":
								return overviewService.overviewSummary(op);
							case "grantNums":
								return overviewService.overviewGrantNums(op);
							case "creditNums":
								return overviewService.overviewCreditNums(op);
							case "riskNums":
								return overviewService.overviewRiskNums(op);
							default:
								return new ObjectResultEx<>().makeFailedResult();
						}
					}
				}).get(key);
			}
		} catch (Exception e) {
			logger.error("获取缓存中的数据出错", e);
		}
		return new ObjectResultEx<>().makeFailedResult();
	}

	/**
	 * 为缓存设置loader
	 */
	private LoadingCache commonCache(CacheLoader loader) {
		synchronized (logger){
			cacheBuilder =  CacheBuilder
					.newBuilder()
					.refreshAfterWrite(1, TimeUnit.MINUTES)
					.build(loader);
		}
		return cacheBuilder;
	}
}

 

你可能感兴趣的:(Guava,Cache)