一:加入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);
}
}
}
本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。