Google Guava -缓存cache简单使用

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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package guavacache;<br>
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
 
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.cache.RemovalListener;
import com.google.common.cache.RemovalNotification;
 
public class cachetest {
    public static class Student {
        private int id;
        public String name;
 
        public int getId() {
            return id;
        }
 
        public void setId(int id) {
            this.id = id;
        }
 
        public String getName() {
            return name;
        }
 
        public void setName(String name) {
            this.name = name;
        }
 
        @Override
        public String toString() {
            return id + "| " + name;
        }
    }
 
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // 缓存接口这里是LoadingCache,LoadingCache在缓存项不存在时可以自动加载缓存
        LoadingCache<Integer, Student> studentCache
        // CacheBuilder的构造函数是私有的,只能通过其静态方法newBuilder()来获得CacheBuilder的实例
                = CacheBuilder.newBuilder()
                        // 设置并发级别为8,并发级别是指可以同时写缓存的线程数
                        .concurrencyLevel(8)
                        // 设置写缓存后8秒钟过期
                        .expireAfterWrite(18, TimeUnit.SECONDS)
                        // 设置缓存容器的初始容量为10
                        .initialCapacity(2)
                        // 设置缓存最大容量为100,超过100之后就会按照LRU最近虽少使用算法来移除缓存项
                        .maximumSize(2)
                        // 设置要统计缓存的命中率
                        .recordStats()
                        // 设置缓存的移除通知
                        .removalListener(new RemovalListener<Object, Object>() {
                            public void onRemoval(RemovalNotification<Object, Object> notification) {
                                System.out.println(
                                        notification.getKey() + " was removed, cause is " + notification.getCause());
                            }
                        })
                         
                        // build方法中可以指定CacheLoader,在缓存不存在时通过CacheLoader的实现自动加载缓存
                        .build(new CacheLoader<Integer, Student>() {
                            @Override
                            public Student load(Integer key) throws Exception {
                                System.out.println("load student " + key);
                                Student student = new Student();
                                student.setId(key);
                                student.setName("name " + key);
                                return student;
                            }
                        });
 
//      for (int i = 0; i < 20; i++) {
//          // 从缓存中得到数据,由于我们没有设置过缓存,所以需要通过CacheLoader加载缓存数据
//          Student student = studentCache.get(i);
//          System.out.println(student);
//          // 休眠1秒
//          TimeUnit.SECONDS.sleep(1);
//      }
                 
 
        System.out.println("cache stats:");
        // 最后打印缓存的命中率等 情况
        System.out.println(studentCache.stats().toString());
    }
 
}

  测试最大容量LRU算法, 感觉更像是把使用时间最近的保留

1
2
3
4
5
6
7
8
9
10
11
12
Student student = studentCache.get(1);
System.out.println(student);
student = studentCache.get(1);
System.out.println(student);
student = studentCache.get(1);
System.out.println(student);
 
student = studentCache.get(2);
System.out.println(student);
 
student = studentCache.get(3);
System.out.println(student);

  结果为 1 was removed, cause is SIZE

maven 

1
2
3
4
5
<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>18.0</version>
</dependency>

  

 

posted @   谭志宇  阅读(21004)  评论(1编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示