使用 java-db 整合 ehcache

Ehcache 是一个广泛使用的开源的缓存黄金,它可以提高应用程序的性能和扩展性。 java-db 对 ehcache 进行了支持,使其的 java-db 中更易使用

整合 ehcache

添加依赖

需要用到 java-db

<dependency>
  <groupId>com.litongjava</groupId>
  <artifactId>java-db</artifactId>
  <version>${java-db.version}</version>
</dependency>
<dependency>
  <groupId>net.sf.ehcache</groupId>
  <artifactId>ehcache-core</artifactId>
  <version>2.6.11</version>
</dependency>

添加配置文件 ehcache.xml

ehcache.xml 是 Ehcache 缓存的配置文件。EcachePlugin 启动时会自动加载这个配置,它定义了缓存的基本属性和行为。以下是文件中每个部分的详细解释:

  1. <diskStore>: 指定磁盘存储的路径,用于溢出或持久化缓存数据到磁盘。

  2. <defaultCache>: 设置默认缓存的属性。这些属性将应用于未单独配置的所有缓存。

    • eternal: 设置为 false 表示缓存不是永久的,可以过期。
    • maxElementsInMemory: 内存中可以存储的最大元素数量。
    • overflowToDisk: 当内存中的元素数量超过最大值时,是否溢出到磁盘。
    • diskPersistent: 是否在 JVM 重启之间持久化到磁盘。
    • timeToIdleSeconds: 元素最后一次被访问后多久会变成空闲状态。
    • timeToLiveSeconds: 元素从创建或最后一次更新后多久会过期。
    • memoryStoreEvictionPolicy: 当内存达到最大值时,移除元素的策略(例如,LRU 表示最近最少使用)。

ehcache.xml 配置文件内容如下

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd" updateCheck="false">

  <diskStore path="java.io.tmpdir/EhCache" />

  <defaultCache eternal="false" maxElementsInMemory="10000" overflowToDisk="false" diskPersistent="false"
    timeToIdleSeconds="1800" timeToLiveSeconds="259200" memoryStoreEvictionPolicy="LRU" />
</ehcache>

EhCachePluginConfig 配置类

这个类是一个配置类,用于初始化和配置 EhCache 插件。它通过 @AConfiguration 注解标记为配置类。类中的方法 ehCachePlugin 通过 @ABean 注解标记为 Bean 方法,框架启动时会执行该方法并将返回值放到 bean 容器中。在这个方法中,创建了一个 Plugin 实例并启动它。destroyMethod 指定在服务关闭时将会调用该方法,关闭该插件

import com.litongjava.ehcache.EhCachePlugin;
import com.litongjava.jfinal.aop.annotation.AConfiguration;
import com.litongjava.jfinal.aop.annotation.AInitialization;
import com.litongjava.tio.boot.server.TioBootServer;

@AConfiguration
public class EhCachePluginConfig {

  @ABean(destroyMethod = "stop")
  public EhCachePlugin ehCachePlugin() {
    EhCachePlugin ehCachePlugin = new EhCachePlugin();
    ehCachePlugin.start();
    return ehCachePlugin;
  }
}

如果不想将 EhCachePlugin 放入 Aop 容器,你可以使用下面的配置类,实际上也完全没有必要放到到 Aop 容器中

import com.litongjava.ehcache.EhCachePlugin;
import com.litongjava.jfinal.aop.annotation.AConfiguration;
import com.litongjava.jfinal.aop.annotation.AInitialization;
import com.litongjava.tio.boot.server.TioBootServer;

@AConfiguration
public class EhCacheConfig {

  @AInitialization
  public void ehCachePlugin() {
    EhCachePlugin ehCachePlugin = new EhCachePlugin();
    ehCachePlugin.start();
    TioBootServer.me().addDestroyMethod(ehCachePlugin::stop);
  }
}

使用示例

  1. EhCacheTestController:

    • 这个控制器包含一个方法 test01,用于测试将数据添加到 EhCache 缓存中并从中检索数据。
    • 在这个方法中,首先尝试从缓存中获取一个键值。如果不存在,它将计算一个新值并将其存储在缓存中。
    • 这个控制器演示了如何使用 Ehcache 存储和检索简单的键值对。
  2. EhCacheController:

    • 这个控制器包含多个方法,用于与 Ehcache 进行更复杂的交互。
    • 方法如 getCacheNamesgetAllCacheValue 用于检索缓存中的信息,例如缓存名称或所有缓存的值。
    • 其他方法允许按名称检索特定缓存的值,或者根据缓存名称和键检索特定的值。
    • 这个控制器提供了更深入的视图,展示了如何管理和检查 Ehcache 中的数据。
import com.litongjava.ehcache.EhCache;
import com.litongjava.tio.http.server.annotation.RequestPath;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@RequestPath("/ecache/test")
public class EhCacheTestController {

  public String test01() {
    String cacheName = "student";
    String cacheKey = "litong";

    String cacheData = EhCache.get(cacheName, cacheKey);

    if (cacheData == null) {
      String result = "001";
      log.info("计算新的值");
      EhCache.put(cacheName, cacheKey, result);
    }
    return cacheData;
  }
}

访问测试 http://localhost/ecache/test/test01

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.litongjava.ehcache.EhCache;
import com.litongjava.tio.http.server.annotation.RequestPath;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

@RequestPath("/ecache")
public class EhCacheController {
  public String[] getCacheNames() {
    String[] cacheNames = EhCache.getCacheManager().getCacheNames();
    return cacheNames;
  }

  public Map<String, Map<String, Object>> getAllCacheValue() {
    CacheManager cacheManager = EhCache.getCacheManager();
    String[] cacheNames = cacheManager.getCacheNames();
    Map<String, Map<String, Object>> retval = new HashMap<>(cacheNames.length);
    for (String name : cacheNames) {
      Map<String, Object> map = cacheToMap(cacheManager, name);
      retval.put(name, map);
    }
    return retval;

  }

  public Map<String, Object> getCacheValueByCacheName(String cacheName) {
    CacheManager cacheManager = EhCache.getCacheManager();
    Map<String, Object> retval = cacheToMap(cacheManager, cacheName);
    return retval;
  }

  public Object getCacheValueByCacheNameAndCacheKey(String cacheName, String key) {
    Object object = EhCache.get(cacheName, key);
    return object;
  }

  private Map<String, Object> cacheToMap(CacheManager cacheManager, String name) {
    Cache cache = cacheManager.getCache(name);
    @SuppressWarnings("unchecked")
    List<String> keys = cache.getKeys();
    Map<String, Object> map = new HashMap<>(keys.size());
    for (String key : keys) {
      Element element = cache.get(key);
      Object value = element.getObjectValue();
      map.put(key, value);
    }
    return map;
  }
}

访问测试 http://localhost/ecache/getCacheNames
http://localhost/ecache/getAllCacheValue

EhCache 使用案例

用户注册数量计数

1. 思路

  • 创建用户表:创建一张用户注册记录表,每当有新用户注册时,将 userId 保存到此表中。
  • 统计用户数量:通过查询此表中的记录数量来统计用户注册总数,并将结果缓存。
  • 缓存机制:当有新用户注册时,清除缓存,然后更新表中的数据。

2. 数据库表设计

CREATE TABLE sys_new_user (
  id BIGINT PRIMARY KEY,
  user_id VARCHAR,
  remark VARCHAR (256),
  creator VARCHAR (64) DEFAULT '',
  create_time TIMESTAMP WITHOUT TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
  updater VARCHAR (64) DEFAULT '',
  update_time TIMESTAMP WITHOUT TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
  deleted SMALLINT NOT NULL DEFAULT 0,
  tenant_id BIGINT NOT NULL DEFAULT 0
);
  • sys_new_user 表记录了新用户的 user_id 以及一些元数据,如 create_timeupdate_time 等。

3. 业务逻辑实现

下面是核心的 NewUserService 服务类,用于保存用户注册信息和统计用户数量。

import com.litongjava.db.activerecord.Db;
import com.litongjava.db.activerecord.Record;
import com.litongjava.ehcache.CacheKit;
import com.litongjava.tio.utils.snowflake.SnowflakeIdUtils;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class NewUserService {

  public boolean save(String userId) {
    boolean exists = Db.existsBySql("select count(1) from sys_new_user where user_id=?", userId);
    if (exists) {
      return false;
    }
    Record record = Record.by("id", SnowflakeIdUtils.id()).set("user_id", userId);
    CacheKit.remove("sys_new_user", "count");

    return Db.save("sys_new_user", record);
  }

  public Long count() {
    Long count = CacheKit.get("sys_new_user", "count");

    if (count == null) {
      count = Db.countTable("sys_new_user");
      log.info("user count:{}", count);
      CacheKit.put("sys_new_user", "count", count);
    }

    return count;
  }
}
  • save 方法:接收 userId,生成唯一 id,保存到数据库,并清除缓存。
  • count 方法:首先尝试从缓存中获取用户数量,如果缓存不存在则查询数据库,并将结果放入缓存。

4. 测试代码

测试代码用于验证 NewUserService 的功能,包括用户注册和缓存机制。

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.junit.Test;

import com.litongjava.ehcache.CacheKit;
import com.litongjava.jfinal.aop.Aop;
import com.litongjava.open.chat.config.DbConfig;
import com.litongjava.open.chat.config.EhCacheConfig;
import com.litongjava.tio.utils.environment.EnvUtils;
import com.litongjava.tio.utils.json.JsonUtils;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

public class NewUserServiceTest {

  @Test
  public void test() {
    EnvUtils.load();
    new DbConfig().config();
    new EhCacheConfig().ehCachePlugin();

    NewUserService newUserService = Aop.get(NewUserService.class);
    newUserService.save("001");
    newUserService.save("002");

    newUserService.count();
    newUserService.count();
    newUserService.count();
    Long count = newUserService.count();
    System.out.println(count);

    CacheManager cacheManager = CacheKit.getCacheManager();
    String[] cacheNames = cacheManager.getCacheNames();
    Map<String, Map<String, Object>> allValue = new HashMap<>(cacheNames.length);
    for (String name : cacheNames) {
      Map<String, Object> map = cacheToMap(cacheManager, name);
      allValue.put(name, map);
    }

    System.out.println(JsonUtils.toJson(allValue));

  }

  private Map<String, Object> cacheToMap(CacheManager cacheManager, String name) {
    Cache cache = cacheManager.getCache(name);
    @SuppressWarnings("unchecked")
    List<String> keys = cache.getKeys();
    Map<String, Object> map = new HashMap<>(keys.size());
    for (String key : keys) {
      Element element = cache.get(key);
      Object value = element.getObjectValue();
      map.put(key, value);
    }
    return map;
  }

}
  • 测试流程
    1. 初始化环境和配置。
    2. 测试用户注册功能,并验证缓存机制是否生效。
    3. 打印缓存内容以确认数据存储是否正确。

5. 测试日志输出

以下是测试运行后的日志输出:

2024-08-12 16:55:19.632 [main] INFO  c.z.h.HikariDataSource.<init>:80 - HikariPool-1 - Starting...
2024-08-12 16:55:20.418 [main] INFO  c.z.h.HikariDataSource.<init>:82 - HikariPool-1 - Start completed.
2024-08-12 16:55:20.443 [main] INFO  c.l.o.c.c.DbConfig.config:75 - show sql:true
2024-08-12 16:55:20.549 [main] WARN  c.l.e.CacheKit.getOrAddCache:33 - Could not find cache config [sys_new_user], using default.
Sql: insert into "sys_new_user"("id", "user_id") values(?, ?)
Sql: insert into "sys_new_user"("id", "user_id") values(?, ?)
Sql: SELECT count(*) from sys_new_user;
2024-08-12 16:55:20.590 [main] INFO  c.l.o.c.s.NewUserService.count:25 - user count:4
4
{"sys_new_user":{"count":"4"}}
  • 日志解读
    • 数据源初始化成功。
    • 新用户注册时,向数据库中插入数据。
    • 执行 count 方法时,系统从数据库查询用户数量并缓存结果。
    • 缓存中的用户数量被正确打印出来。

设置过期时间

方法签名

public Record findFirstByCache(String cacheName, Object key, int ttl, String sql, Object... paras)

参数解释

  1. cacheName (String):

    • 作用: 指定缓存的名称。在应用程序中,通常会有多个缓存区域(或命名空间),cacheName 用于区分不同的缓存区域。
    • 使用场景: 当你想要在特定的缓存区域中存储或查找数据时,cacheName 用于标识该区域。
  2. key (Object):

    • 作用: 用于在缓存中查找具体的数据。key 是缓存数据的唯一标识符,在给定的 cacheName 中,每个 key 都对应特定的一条缓存数据。
    • 使用场景: 当你想要通过某个唯一标识符(例如用户 ID、查询参数等)从缓存中获取对应的数据时,key 用于标识该数据。
  3. ttl (int):

    • 作用: 指定缓存数据的存活时间(Time To Live),单位是秒。ttl 确定了数据在缓存中存活的时长,超过这个时间后,缓存的数据会被视为过期,并可能被移除或替换。
    • 使用场景: 你可以使用 ttl 来控制缓存数据的有效期,例如设置一个较短的 ttl 来确保缓存中的数据足够新鲜,或设置一个较长的 ttl 来减少对数据库的频繁访问。
  4. sql (String):

    • 作用: 表示要执行的 SQL 查询语句。sql 是用于从数据库中检索数据的原始 SQL 语句。
    • 使用场景: 当缓存中没有找到对应的数据,或缓存数据已过期时,方法会执行此 SQL 语句来从数据库中查询数据,并将查询结果缓存起来。
  5. paras (Object...):

    • 作用: 表示 SQL 查询语句中需要的参数。paras 是可变长度参数,允许你传入多个参数,这些参数会被依次替换到 SQL 语句中的占位符(通常是 ?)。
    • 使用场景: 当 SQL 查询需要带有条件参数(例如 WHERE 子句中的条件)时,你可以通过 paras 参数传入这些条件值。

方法返回值

  • 返回类型: Record:
    • 作用: 方法返回一个 Record 对象,这通常表示从数据库中查询到的单条记录。Record 是一种数据结构,用于存储和访问查询结果中的列值。
    • 使用场景: 调用此方法后,你可以直接使用返回的 Record 对象来访问查询结果的字段值。

总结

findFirstByCache 方法通过指定的缓存名称 cacheName 和键 key 从缓存中查找数据,如果数据过期或不存在,则执行 sql 查询,并使用 paras 作为查询参数。查询结果会被缓存起来,ttl 控制数据在缓存中的存活时间。

findFirstByCache 示例

import com.litongjava.db.activerecord.Db;
import com.litongjava.db.activerecord.Record;

public class SchoolDictDao {
  public Record getById(Long id) {
    String sql = "select * from rumi_school_dict where id=?";
    return Db.findFirstByCache("rumi_school_dict", id, 600, sql, id);
  }
}
import org.junit.Test;

import com.litongjava.db.activerecord.Record;
import com.litongjava.jfinal.aop.Aop;
import com.litongjava.open.chat.config.DbConfig;
import com.litongjava.open.chat.config.EhCacheConfig;
import com.litongjava.tio.utils.environment.EnvUtils;
import com.litongjava.tio.utils.json.JsonUtils;

public class SchoolDictDaoTest {

  @Test
  public void test() {
    EnvUtils.load();
    new DbConfig().config();
    new EhCacheConfig().ehCachePlugin();
    Record record = Aop.get(SchoolDictDao.class).getById(1L);
    System.out.println(JsonUtils.toJson(record.toMap()));
  }
}