高性能缓存方案 —— Caffeine

一、简介

Caffeine是一个高性能的Java缓存库,它提供了本地缓存的功能。

Caffeine和Redis都是内存级别的缓存,为什么要使用在这两缓存作为二级缓存,它们两有什么区别呢?

虽然它们都是内存级别的缓存,但是Redis是需要单独部署的,其需要一个单独的进程,在tomcat访问Redis时需要网络通信的开销,而Caffeine跟我们项目代码是写在一起的,它是JVM级别的缓存,用的就是Java中的堆内存,无需网络的通信的开销,在Caffeine找不到数据后才会去redis中查找。

以下是一个使用Caffeine作为本地缓存的简单示例:

复制代码
// JVM Processes Cache, Import Caffeine dependency.
<dependency>
	<groupId>com.github.ben-manes.caffeine</groupId>
	<artifactId>caffeine</artifactId>
</dependency>

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.stats.CacheStats;

import java.util.concurrent.TimeUnit;

public class CaffeineDemo {
    public static void main(String[] args) {
        // Create a local cache with a maximum size of 100
        Cache<String, String> cache = Caffeine.newBuilder()
                .maximumSize(100)
                .expireAfterWrite(5, TimeUnit.MINUTES)
                .build();

        // Put the data in the cache
        cache.put("key", "val");

        // Get data from the cache by the key, if no data, return null.
        String value = cache.getIfPresent("key");
        System.out.println(value);
        String value2 = cache.getIfPresent("key2");
        System.out.println(value2);

        // Get caching statistics
        CacheStats stats = cache.stats();
        System.out.println("Cache hits: " + stats.hitCount());
        System.out.println("Cache misses: " + stats.missCount());

        // Delete element from the cache
        cache.invalidate(("key"));
        System.out.println(cache.getIfPresent(("key")));
    }
}

运行结果:

二、驱逐策略

使用Caffeine为了防止内存溢出,提供了以下几种驱逐策略。

为了防止一直往内存里装数值导致占用内存,所以Caffeine给我们提供了驱逐策略。

1、基于容量(设置缓存的上限)

复制代码
   @Test
    public void test() {
        Cache<Object, Object> cache = Caffeine.newBuilder()
                .initialCapacity(100) //设置缓存的初始化容量
                .maximumSize(1000) //设置最大的容量
                .build();
    }

通过设置最大的容量来控制内存,当内存达到最大时,会将最早存入的数据删除,当缓存超出这个容量的时候,会使用Window TinyLfu策略来删除缓存。

2、基于时间(设置有效期)

复制代码
@Test
public void test1() {
    Cache<Object, Object> cache = Caffeine.newBuilder()
            .initialCapacity(100)
            .expireAfterWrite(Duration.ofSeconds(10)) //设置缓存的有效期,此时就是设置为10s
            .build();
}

3、基于引用

设置数据的强引用和弱引用,在内存不足的时候jvm会进行垃圾回收,会将弱引用的数据进行回收,性能差,不建议使用。

相关推荐
Boilermaker19925 小时前
[Redis] 分布式缓存与分布式锁
redis·分布式·缓存
Q的世界9 小时前
redis源码编译安装
数据库·redis·缓存
C_心欲无痕10 小时前
vue3 - 内置组件KeepAlive优化组件状态缓存
前端·vue.js·缓存
大布布将军12 小时前
⚡️ 性能加速器:利用 Redis 实现接口高性能缓存
前端·数据库·经验分享·redis·程序人生·缓存·node.js
_OP_CHEN12 小时前
【C++数据结构进阶】吃透 LRU Cache缓存算法:O (1) 效率缓存设计全解析
数据结构·数据库·c++·缓存·线程安全·内存优化·lru
消失的旧时光-194312 小时前
Repository 层如何无缝接入本地缓存 / 数据库
数据库·flutter·缓存
stand_forever13 小时前
redis秒杀实现
redis·缓存·php
消失的旧时光-194313 小时前
用 Drift 实现 Repository 无缝接入本地缓存/数据库(SWR:先快后准)
数据库·flutter·缓存
Tony Bai13 小时前
【API 设计之道】08 流量与配额:构建基于 Redis 的分布式限流器
数据库·redis·分布式·缓存
想学后端的前端工程师13 小时前
【Redis实战与高可用架构设计:从缓存到分布式锁的完整解决方案】
redis·分布式·缓存