使用Google Guava实现定时缓存功能


一:加入maven依赖

<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>19.0</version>
</dependency>

二:使用缓存

方法一:

package com.test.guava;

import java.util.concurrent.TimeUnit;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;

public class UserService
{
private final Cache<String, String> cache;

public UserService()
{
/**
* 5秒自动过期
*/
cache = CacheBuilder.newBuilder().expireAfterWrite(5, TimeUnit.SECONDS).build();
}

public String getUserName(String id) throws Exception
{
return cache.get(id, () -> {
System.out.println("method invoke2");
//这里执行查询数据库,等其他复杂的逻辑
return "User:" + id;
});
}
}

方法二:

package com.test.guava;

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 UserService
{
private final LoadingCache<String, String> cache;

public UserService()
{
/**
* 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 getUserName(String id) throws Exception
{
return cache.get(id);
}
}

三:测试代码:

package com.test.guava;

import java.util.concurrent.TimeUnit;

public class GuavaCacheTest
{
public static void main(String[] args)throws Exception
{
UserService us = new UserService();
for(int i=0;i<20;i++)
{
System.out.println(us.getUserName("1001"));
TimeUnit.SECONDS.sleep(1);
}
}
}

执行测试代码,输出如下:


智能推荐

注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
© 2014-2019 ITdaan.com 粤ICP备14056181号  

赞助商广告