java-code-GuavaDemo

pom
1
2
3
4
5
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>27.0.1-jre</version>
</dependency>
User
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package redis;

import java.io.Serializable;

public class User implements Serializable {
/**
*
*/
private static final long serialVersionUID = 7710153170636593560L;
private String userName;
private String userId;

public User(String userName, String userId) {
this.userName = userName;
this.userId = userId;
}

public String getUserId() {
return userId;
}

public void setUserId(String userId) {
this.userId = userId;
}

public String getUserName() {
return userName;
}

@Override
public String toString() {
return "User [userName=" + userName + ", userId=" + userId + "]";
}
}
GuavaCacheDemo
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package redis;

import com.google.common.cache.*;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

public class GuavaCacheDemo {

public static void main(String[] args) throws ExecutionException {
//缓存接口这里是LoadingCache,LoadingCache在缓存项不存在时可以自动加载缓存
LoadingCache<String, User> userCache
//CacheBuilder的构造函数是私有的,只能通过其静态方法newBuilder()来获得CacheBuilder的实例
= CacheBuilder.newBuilder()
//设置并发级别为8,并发级别是指可以同时写缓存的线程数
.concurrencyLevel(8)
//设置写缓存后8秒钟过期
.expireAfterWrite(8, TimeUnit.SECONDS)
//设置写缓存后1秒钟刷新
.refreshAfterWrite(1, TimeUnit.SECONDS)
//设置缓存容器的初始容量为10
.initialCapacity(10)
//设置缓存最大容量为100,超过100之后就会按照LRU最近虽少使用算法来移除缓存项
.maximumSize(100)
//设置要统计缓存的命中率
.recordStats()
//设置缓存的移除通知
.removalListener(new RemovalListener<Object, Object>() {
@Override
public void onRemoval(RemovalNotification<Object, Object> notification) {
System.out.println(notification.getKey() + " 被移除了,原因: " + notification.getCause());
}
})
//build方法中可以指定CacheLoader,在缓存不存在时通过CacheLoader的实现自动加载缓存
.build(
new CacheLoader<String, User>() {
@Override
public User load(String key) throws Exception {
System.out.println("缓存没有时,从数据库加载" + key);
// TODO jdbc的代码~~忽略掉
return new User("cache" + key, key);
}
}
);

// 第一次读取
for (int i = 0; i < 20; i++) {
User user = userCache.get("uid" + i);
System.out.println(user);
}

// 第二次读取
for (int i = 0; i < 20; i++) {
User user = userCache.get("uid" + i);
System.out.println(user);
}

System.out.println("cache stats:");
//最后打印缓存的命中率等 情况
System.out.println(userCache.stats().toString());
}
}