首页
/ SecondLevelCache 技术文档

SecondLevelCache 技术文档

2024-12-26 18:02:10作者:庞眉杨Will

本文档旨在帮助用户安装、使用及深入了解 SecondLevelCache 项目,以下是项目的安装指南、使用说明以及 API 使用文档。

1. 安装指南

首先,您需要在项目的 Gemfile 文件中添加相应的依赖。根据所使用的 ActiveRecord 版本,添加如下配置:

  • 对于 ActiveRecord 7:
gem 'second_level_cache', '~> 2.7'
  • 对于 ActiveRecord 5.2 和 6.0:
gem 'second_level_cache', '~> 2.6.3'
  • 对于 ActiveRecord 5.0.x 和 5.1.x:
gem 'second_level_cache', '~> 2.3.0'
  • 对于 ActiveRecord 4:
gem "second_level_cache", "~> 2.1.9"
  • 对于 ActiveRecord 3:
gem "second_level_cache", "~> 1.6"

完成 Gemfile 的修改后,运行以下命令安装依赖:

bundle install

2. 项目的使用说明

以下是如何在项目中使用 SecondLevelCache 的示例:

缓存 User 对象

class User < ActiveRecord::Base
  second_level_cache expires_in: 1.week
end

在此配置下,以下场景将会获取缓存的对象:

User.find(1)
user.articles.find(1)
User.where(status: 1).find(1)
User.where(id: 1).first # 或 .last
article.user

获取缓存键

user = User.find(1)
user.second_level_cache_key  # 将得到形如 "slc/user/1/0" 的键

过期缓存

user = User.find(1)
user.expire_second_level_cache

或者使用类方法过期缓存:

User.expire_second_level_cache(1)

禁用 SecondLevelCache

User.without_second_level_cache do
  user = User.find(1)
  # ...
end

请注意,只有 SELECT * 查询会被缓存:

# 这个查询不会被缓存
User.select("id, name").find(1)

3. 项目 API 使用文档

SecondLevelCache 提供了以下 API:

  • second_level_cache: 在模型中启用缓存功能,可以设置缓存过期时间。
  • second_level_cache_key: 获取模型的缓存键。
  • expire_second_level_cache: 过期单个模型的缓存。
  • without_second_level_cache: 在块内禁用缓存。
  • fetch_by_uniq_keys: 通过唯一键从缓存中获取记录。
  • fetch_by_uniq_keys!: 通过唯一键从缓存中获取记录,如果记录不存在则抛出异常。

更多 API 和用法请参考项目文档。

4. 项目安装方式

SecondLevelCache 的安装方式已在安装指南中详细说明,请参照安装指南完成安装。

登录后查看全文
热门项目推荐