Java本地缓存解决方案其一(使用Google的CacheBuilder)

前不久,业务实现上需要用到本地缓存来解决一些数据量相对较小但是频繁访问的数据,通过查找各种资料,找到了一种可以实现的方案——采用的是Google的CacheBuilder。下面是代码实现过程:
1.首先在maven中引入下面的包;
  1. <dependency>  
  2.     <groupId>com.google.guava</groupId>  
  3.     <artifactId>guava</artifactId>  
  4.     <version>19.0</version>  
  5. </dependency>
2.下面这段是缓存代码,用到了匿名内部类的方式;
package com.jd.common.util;
import java.util.concurrent.TimeUnit;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;

public class AndyService

{
private final LoadingCache<String, String> cache;

public AndyService()
{
/**
* 5秒自动过期
*/
cache = CacheBuilder.newBuilder().expireAfterWrite(5, TimeUnit.SECONDS).build(new CacheLoader<String, String>() {
public String load(String id) throws Exception
{
System.out.println("method inovke");
//这里执行查询数据库,等其他复杂的逻辑
return "User:" + id;
}
});
}

public String getAndyName(String id) throws Exception
{
return cache.get(id);
}
}
3.下面是测试用例
class GuavaCacheTest
{
public static void main(String[] args)throws Exception
{
AndyService us = new AndyService();
for(int i=0;i<20;i++)
{
System.out.println(us.getAndyName("1001"));
TimeUnit.SECONDS.sleep(1);
}
}
}
4.下面的是控制台中代码输入内容:

method inovke
User:1001
User:1001
User:1001

method inovke
User:1001
User:1001
User:1001

method inovke
User:1001
User:1001
User:1001

method inovke
User:1001
User:1001
User:1001


关于为什么使用本地缓存而不使用别的方式的原因,详见前辈的总结:
http://www.cnblogs.com/fengli9998/p/7875027.html

转载于:https://www.cnblogs.com/andychou/p/8342007.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值