Not long ago, the business implementation needed to use the local cache to solve some of the relatively small data volume but frequently accessed data, by looking for various materials, found a possible solution-the use of Google's cachebuilder. Here is the code implementation process:
1. First introduce the following package in Maven;
- <dependency>
- <groupId>com.google.guava</groupId>
- <artifactid>guava</artifactid>
- <version>19.0</version>
- </Dependency>
2. The following paragraph is the cache code, the use of anonymous internal class way;
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 Seconds Automatic Expiration
*/
cache = Cachebuilder.newbuilder (). Expireafterwrite (5, Timeunit.seconds). Build (new cacheloader<string, Strin G> () {
Public string Load (string id) throws Exception
{
System.out.println ("Method Inovke");
//The query database is executed here, and other complex logic
return "User:" + ID;
}
});
}
Public string Getandyname (String id) throws Exception
{
return Cache.get (ID);
}
}
3. Here is the test case
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. The following is the code entry in the console:
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
For reasons why you should use a local cache instead of using a different approach, see the summary of predecessors:
Http://www.cnblogs.com/fengli9998/p/7875027.html
Java Local cache solution one (using Google's Cachebuilder)