• Stars
    star
    396
  • Rank 108,787 (Top 3 %)
  • Language
    Ruby
  • License
    MIT License
  • Created almost 13 years ago
  • Updated over 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Write Through and Read Through caching library inspired by CacheMoney and cache_fu, support ActiveRecord 4, 5 and 6.

SecondLevelCache

Gem Version build Code Climate

SecondLevelCache is a write-through and read-through caching library inspired by Cache Money and cache_fu, support ActiveRecord 4, ActiveRecord 5 and ActiveRecord 6.

Read-Through: Queries by ID, like current_user.articles.find(params[:id]), will first look in cache store and then look in the database for the results of that query. If there is a cache miss, it will populate the cache.

Write-Through: As objects are created, updated, and deleted, all of the caches are automatically kept up-to-date and coherent.

Install

In your gem file:

ActiveRecord 7

gem 'second_level_cache', '~> 2.7'

ActiveRecord 5.2 and 6.0:

gem 'second_level_cache', '~> 2.6.3'

ActiveRecord 5.0.x, 5.1.x:

gem 'second_level_cache', '~> 2.3.0'

For ActiveRecord 4:

gem "second_level_cache", "~> 2.1.9"

For ActiveRecord 3:

gem "second_level_cache", "~> 1.6"

Usage

For example, cache User objects:

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

Then it will fetch cached object in this situations:

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

Cache key:

user = User.find(1)
user.second_level_cache_key  # We will get the key looks like "slc/user/1/0"

Expires cache:

user = User.find(1)
user.expire_second_level_cache

or expires cache using class method:

User.expire_second_level_cache(1)

Disable SecondLevelCache:

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

Only SELECT * query will be cached:

# this query will NOT be cached
User.select("id, name").find(1)

Notice

  • SecondLevelCache cache by model name and id, so only find_one query will work.
  • Only equal conditions query WILL get cache; and SQL string query like User.where("name = 'Hooopo'").find(1) WILL NOT work.
  • SecondLevelCache sync cache after transaction commit:
# user and account's write_second_level_cache operation will invoke after the logger.
ActiveRecord::Base.transaction do
  user.save
  account.save
  Rails.logger.info "info"
end # <- Cache write

# if you want to do something after user and account's write_second_level_cache operation, do this way:
ActiveRecord::Base.transaction do
  user.save
  account.save
end # <- Cache write
Rails.logger.info "info"
  • If you are using SecondLevelCache with database_cleaner, you should set cleaning strategy to :truncation:
DatabaseCleaner.strategy = :truncation

Configure

In production env, we recommend to use Dalli as Rails cache store.

config.cache_store = [:dalli_store, APP_CONFIG["memcached_host"], { namespace: "ns", compress: true }]

Tips:

  • When you want to clear only second level cache apart from other cache for example fragment cache in cache store, you can only change the cache_key_prefix (default: slc):
SecondLevelCache.configure.cache_key_prefix = "slc1"
  • SecondLevelCache was added model schema digest as cache version, this means when you add/remove/change columns, the caches of this Model will expires.
  • When your want change the model cache version by manualy, just add the version option like this:
class User < ActiveRecord::Base
  second_level_cache version: 2, expires_in: 1.week
end
  • It provides a great feature, not hits db when fetching record via unique key (not primary key).
# this will fetch from cache
user = User.fetch_by_uniq_keys(nick_name: "hooopo")
post = Post.fetch_by_uniq_keys(user_id: 2, slug: "foo")

# this also fetch from cache
user = User.fetch_by_uniq_keys!(nick_name: "hooopo") # this will raise `ActiveRecord::RecordNotFound` Exception when nick name not exists.
  • You can use Rails's Eager Loading feature as normal. Even better, second_level_cache will transform the IN query into a Rails.cache.multi_read operation. For example:
Answer.includes(:question).limit(10).order("id DESC").each{|answer| answer.question.title}
Answer Load (0.2ms)  SELECT `answers`.* FROM `answers` ORDER BY id DESC LIMIT 10 # Only one SQL query and one Rails.cache.read_multi fetching operation.

Details for read_multi feature.

Original design by:

Contributors

Contributor List

License

MIT License

More Repositories

1

oauth_china

OAuth gem for rails,支持新浪,腾讯,网易,搜狐微博和豆瓣。
Ruby
185
star
2

petri_flow

Petri Net Workflow Engine for Ruby.
Ruby
166
star
3

direct_web_spider

A direct web spider framworks for Ruby
Ruby
140
star
4

pgmq

📮🐘 💎 pgmq. Message Queue with Postgres.
PLpgSQL
57
star
5

oh-my-github-circles

GitHub User Circle Generator Using GitHub Actions
JavaScript
47
star
6

schemaless-pg

使用Postgres实现一个Leancloud clone
Ruby
44
star
7

hackernews-insight

Hackernews Insight using TiDB Cloud
21
star
8

pg-fuzzywuzzy

postgresql fuzzywuzzy extension
PLpgSQL
12
star
9

shadow

shadow table.
PLpgSQL
12
star
10

txt2img

txt2img
Ruby
12
star
11

remote_session_demo

Remote Session Demo
Ruby
11
star
12

kiba-plus

Kiba enhancement for Ruby ETL.
Ruby
9
star
13

oh-my-github-dashboard

This repository provides a data pipeline that syncs GitHub repositories with a free MySQL-compatible cloud database, TiDB Cloud. It can be used as a standalone data pipeline or as a personal dashboard.
TypeScript
8
star
14

si9n

语录推荐系统
JavaScript
7
star
15

oh-my-github-pipeline

🔄 A flexible open-source data pipeline for seamlessly syncing data from any github user to your database.
Ruby
6
star
16

repo-track-pipeline

🔄 A flexible open-source data pipeline for seamlessly syncing data from any repository to your database.
Ruby
6
star
17

redundant_column

redundant_column
Ruby
6
star
18

hooopo.github.com

octopress
JavaScript
5
star
19

nolist

Simple Maillist with Mailgun and Sinatra
Ruby
4
star
20

rails-tidb

Ruby
4
star
21

pgmq_worker_ruby_demo

pgmq worker
Ruby
3
star
22

chatgpt-xiaoai

小爱音箱集成LLM,SaaS 服务
Ruby
3
star
23

learn_erlang

learn erlang
Erlang
3
star
24

activerecord-tidb-adapter-demo

Ruby
2
star
25

websocket_sinatra_demo

websocket sinatra demo
Ruby
2
star
26

kiba-plus-demo

Kiba Plus demo.
Ruby
2
star
27

dash-reshape

This is a GitHub tool that provides a comprehensive repository dashboard for analyzing and visualizing GitHub events in a powerful and intuitive way
Ruby
2
star
28

dlt

Data Lake Toolkit for Ruby.
1
star
29

drawerd-server

starter
JavaScript
1
star
30

repo-contributor-circles

GitHub repo contributor circles generator.
JavaScript
1
star
31

mi-service

XiaoMi Cloud Service for mi.com
Ruby
1
star
32

ossinsight-x

Automatically post trending repos to Twitter every day.
Ruby
1
star
33

tidb-serverless-ruby-connect-example

TiDB serverless ruby connect example
Ruby
1
star