google本地缓存LoadingCache使用

在项目中语使用本地缓存记录一下,具体代码如下:

@Service
public class StrategyLocal {
	private static final Logger LOG = LoggerFactory.getLogger(StrategyLocal.class);
	@Autowired
	private RouteInfoDAO routeInfoDAO;
	private StrategyInfoDAO strategyInfoDAO;
	// cache对象的创建和缓存策略的设置。
	private LoadingCache> cache = CacheBuilder.newBuilder().maximumSize(500)
			.refreshAfterWrite(ReassignConstant.REFRESH_AFTER_WRITE, TimeUnit.SECONDS)
			.build(new CacheLoader>() {
				// 在本地没有缓存的时候会调用该方法进行加载,将获取的值进行缓存并返回结果
				@Override
				public Optional load(Integer cityId) throws Exception {
					Integer strategyId = routeInfoDAO.getStrategyId(cityId);
					StrategyInfo strategyInfo = strategyInfoDAO.getStrategy(strategyId);
					return Optional.ofNullable(strategyInfo);
				}
			});

	// 调用方法从缓存中获取缓存对象,如果本地没有缓存则会调用load方法加载数据,加载数据后本地缓存并返回结果
	public StrategyInfo getStrategyInfo(int cityId) {
		try {
			Optional op = cache.get(cityId);
			return op.isPresent() ? op.get() : null;
		} catch (Exception e) {
			LOG.error("缓存获取改派规则错误!!! cityId={}", cityId, e);
		}
		return null;
	}
}


你可能感兴趣的:(java)