Caffine

Caffeine 简介

Caffeine 是一个高性能的 Java 缓存库,提供了近乎最优的命中率。它是一个完全在内存中的缓存,可以用作本地缓存或与其他缓存解决方案结合使用。Caffeine 的主要特点包括:

  • 快速的读写操作
  • 基于大小、时间和引用的驱逐策略
  • 统计和监听功能
  • 易用的 API

tio-boot 整合 Caffeine

  1. 添加依赖:首先,需要在项目的pom.xml中添加 Caffeine 的依赖项。tio-boot 已经内置了 caffeine-2.9.3 依赖
<dependency>
 <groupId>com.github.ben-manes.caffeine</groupId>
 <artifactId>caffeine</artifactId>
 <version>2.9.3</version>
</dependency>
  1. 配置缓存:在你的 Java 配置类中,你可以创建一个 Caffeine 缓存实例。例如:
import java.util.concurrent.TimeUnit;

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.litongjava.annotation.ABean;
import com.litongjava.annotation.AConfiguration;

@AConfiguration
public class CaffeineCacheConfig {
  @ABean
  public Cache<String, Object> caffeineCache() {
    return Caffeine.newBuilder().maximumSize(10000).expireAfterWrite(5, TimeUnit.MINUTES).build();
  }
}
  1. 使用缓存:一旦缓存被配置,你就可以在应用中使用它来存储和检索数据。
import com.github.benmanes.caffeine.cache.Cache;
import com.litongjava.annotation.AController;
import com.litongjava.annotation.RequestPath;
import com.litongjava.jfinal.aop.Aop;
import com.litongjava.tio.http.common.HttpRequest;

import lombok.extern.slf4j.Slf4j;

@AController
@RequestPath("/caffeine")
@Slf4j
public class CaffeineTestController {
  @RequestPath("/test")
  public Object test(HttpRequest request) {
    Cache<String, Object> cache = Aop.get(Cache.class);
    Object value = cache.getIfPresent("key");
    if (value == null) {
      log.info("计算value");
      cache.put("key", "11111");
    }

    return value;
  }
}

访问测试: http://localhost//caffeine/test

CaffeineUtils

1. CaffeineUtils 简介

CaffeineUtils 是一个用于管理缓存的工具类,支持创建和获取 Caffeine 缓存实例。它提供了两种方式:

  • 手动创建缓存:允许用户自定义缓存的过期时间、容量等参数。
  • 自动获取缓存:当缓存不存在时,根据默认参数自动创建缓存。

2. CaffeineUtils 主要功能

  1. 创建缓存CaffeineUtils.createLoadingCache 提供了一个灵活的接口来创建缓存,用户可以自定义缓存的名称、容量、过期策略以及是否记录缓存命中率等。

    LoadingCache<K, V> cache = CaffeineUtils.createLoadingCache(
        "exampleCache",       // 缓存名称
        600L,                 // 写缓存后600秒过期
        600L,                 // 读缓存后600秒过期
        100,                  // 初始容量100
        1000,                 // 最大容量1000
        true                  // 是否记录缓存命中率
    );
    
  2. 自动获取缓存CaffeineUtils.getCache 提供了通过缓存名称直接获取缓存实例的方式。如果缓存不存在,将会根据默认配置自动创建。

    LoadingCache<String, Object> cache = CaffeineUtils.getCache("exampleCache");
    

    默认配置:

    • 写缓存后 10 分钟过期
    • 读缓存后 10 分钟过期
    • 初始容量 500
    • 最大容量 Integer.MAX_VALUE
    • 记录缓存命中率

3. CaffeineUtils 的用法

下面通过一个控制器示例,展示如何在实际应用中使用 CaffeineUtils

package com.litongjava.tio.web.hello.controller;

import com.github.benmanes.caffeine.cache.LoadingCache;
import com.litongjava.annotation.AController;
import com.litongjava.annotation.RequestPath;
import com.litongjava.tio.http.common.HttpRequest;
import com.litongjava.tio.utils.caffeine.CaffeineUtils;

import lombok.extern.slf4j.Slf4j;

@AController
@RequestPath("/caffeine")
@Slf4j
public class CaffeineTestController {

  @RequestPath("/test")
  public String test(HttpRequest request) {
    // 获取缓存实例,名称为 "example"
    LoadingCache<Object, String> cache = CaffeineUtils.getCache("example");

    // 尝试从缓存中获取 key 对应的值
    String value = cache.getIfPresent("key");

    // 如果缓存中不存在该值,进行计算并放入缓存
    if (value == null) {
      log.info("缓存中未找到值,开始计算");
      value = "11111";  // 模拟计算结果
      cache.put("key", value);  // 将计算的值放入缓存
    }

    return value;  // 返回缓存中的值
  }
}

在这个示例中,CaffeineTestController/caffeine/test 路径会执行以下步骤:

  1. 获取缓存:通过 CaffeineUtils.getCache("example") 获取或创建名为 "example" 的缓存。
  2. 查询缓存:使用 cache.getIfPresent("key") 查询缓存中是否有对应的值。
  3. 计算并缓存:如果缓存中没有找到值,则执行计算并将结果放入缓存。
  4. 返回值:返回缓存中的值。

4. 自定义缓存的创建

如果你想在创建缓存时使用自定义配置,可以调用 createLoadingCache 方法。例如:

LoadingCache<String, Object> customCache = CaffeineUtils.createLoadingCache(
    "customCache",  // 缓存名称
    300L,           // 写缓存后300秒过期
    600L,           // 读缓存后600秒过期
    100,            // 初始容量100
    500,            // 最大容量500
    true            // 记录缓存命中率
);

5. 缓存数据的管理

除了创建和获取缓存之外,LoadingCache 还提供了多种管理缓存数据的方法:

  • 获取数据

    String value = cache.getIfPresent("key");  // 获取缓存中 key 对应的值
    
  • 更新缓存

    cache.put("key", "newValue");  // 将新的值放入缓存
    
  • 手动失效缓存

    cache.invalidate("key");  // 失效指定 key 对应的缓存项
    cache.invalidateAll();    // 清空缓存
    

6. 总结

CaffeineUtils 提供了一个简单易用的工具类,帮助开发者方便地管理 Caffeine 缓存。通过它,你可以轻松实现缓存的自动创建、获取、和管理,提升应用的性能。