intra-mart Accel Platform / Script研制模式编程指南

«  Lock服务   ::   Contents   ::   执行旧版本中创建的程序  »

Cache 服务

Cache 的定义

Cache是通过应用程序服务器上的内存来保存对象的功能。
将数据库访问及文件访问等获取结果保存在缓存中,可以提高应用程序的性能。

式样

按标准,实现Cache要使用EHCache。
关于EHCache的详细内容,请参阅 http://ehcache.org

如果超出配置文件中指定的元素数或Size上限,则登记到Cache中的对象被毁弃。
另外,超出有效期限的对象也将被毁弃。
使用Cache时,Cache的设置必须配置在 <CONTEXT_PATH>/WEB-INF/conf/im-ehcache-config/ 文件夹下任意名字的 xml 文件中。
下述为配置文件示例。
<?xml version="1.0" encoding="UTF-8"?>
<im-ehcache-config xmlns="http://www.intra-mart.jp/cache/ehcache/config"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://www.intra-mart.jp/cache/ehcache/config im-ehcache-config.xsd ">

   <cache name="myCache"
         enable="true"
         max-bytes-memory="10m"
         max-elements-on-memory="100"
         overflow-to-disk="true"
         max-bytes-disk="50m"
         max-elements-on-disk="500"
         time-to-idle-seconds="600"
         time-to-live-seconds="3600" />

</im-ehcache-config>

警告

请将字符代码置为 UTF-8 并保存。
关于各种设置的详细内容如下所示。
属性名 说明
name 设置Cache名。
enable 指定true或false。指定为false时,相应的Cache无效。
max-btyes-memory 指定在内存中储存对象时的最大Size。 可以设置为1k, 10M, 50G等。
max-elements-on-memory 指定保存在内存中对象的最大数量。
overflow-to-disk 设置超过内存缓存空间上限时,是否写入磁盘。
max-bytes-disk 指定在磁盘上储存对象时的最大Size。 可以设置为1k, 10M, 50G等。
max-elements-on-disk 指定磁盘缓存对象的最大数量。
time-to-idle-seconds 指定空闲时间(秒),在指定时间内未浏览此对象时,毁弃该对象。
time-to-live-seconds 指定生存时间(秒),超过指定的生存时间时,毁弃该对象。

编程方法

function getUsers() {
  // 生成 cache 实例,参数 'myCache' 需要指定为定义在 im-ehcache-config 中的 Cache 名。
  var cache = new Cache('myCache');
  // 尝试从缓存中获取信息。获取信息成功时,返回该值。
  var users = cache.get('key');
  if(users != null){
    return users;
  }
  // 因为缓存中不存在信息,所以通过数据库获取信息。
  var database = new TenantDatabase();
  var result = database.select('SELECT user_cd FROM b_m_account_b');
  // 从数据库获取信息失败时,返回空数组。
  // 通常需要输出日志,返回错误信息。请根据不同目的进行实现。
  if(result.error){
    return [];
  }
  // 将获取的信息存入缓存中后,返回数值。
  users = [];
  for(var i = 0, length = result.data.length; i < length; i++){
    var record = result.data[i];
    users.push(record.user_cd);
  }
  // 存入缓存中并返回。
  cache.put('key', users);
  return users;
}
从数据库获取数据时的示例。

注解

缓存的生存时间等完全取决于配置文件。
明确需要删除缓存时,可以通过调用 Cache#remove 或者 Cache#removeAll 来实现删除操作。

«  Lock服务   ::   Contents   ::   执行旧版本中创建的程序  »