Successfully reported this slideshow.
Your SlideShare is downloading. ×

Redis速習会@Wantedly

Ad
Ad
Ad
Ad
Ad
Ad
Ad
Ad
Ad
Ad
Ad
Loading in …3
×

Check these out next

1 of 31 Ad

Redis速習会@Wantedly

Download to read offline

社内のエンジニア向け速習会の資料です。

- Redisの基本的な使い方
- Ruby on RailsからのRedisの使い方

We are hiring! → https://www.wantedly.com/companies/wantedly/projects

社内のエンジニア向け速習会の資料です。

- Redisの基本的な使い方
- Ruby on RailsからのRedisの使い方

We are hiring! → https://www.wantedly.com/companies/wantedly/projects

Advertisement
Advertisement

More Related Content

Slideshows for you (20)

Similar to Redis速習会@Wantedly (20)

Advertisement

More from Yoshinori Kawasaki (11)

Recently uploaded (20)

Advertisement

Redis速習会@Wantedly

  1. 1. Redis速習会@Wantedly 川崎禎紀 / Yoshinori Kawasaki
  2. 2. シゴトでココロオドル • Redisの基本的な使い方 • Ruby on RailsからのRedisの使い方 今日速習する内容
  3. 3. シゴトでココロオドル REmote DIctionary Server
  4. 4. シゴトでココロオドル In-memory http://www.eecs.berkeley.edu/~rcs/research/interactive_latency.html
  5. 5. シゴトでココロオドル • 高速なKVS – メモリに全てのデータを保存 • 様々なデータ型 – 後述 • ディスクに非同期で永続化 – 後述 • 用途 – データベース – キャシュ – message broker Redis
  6. 6. シゴトでココロオドル • シングルスレッド • 普通はCPU律速にならず、メモリまたはネッ トワーク律速になる • 最新バージョンは 3.0.5 – https://raw.githubusercontent.com/antirez/redi s/3.0/00-RELEASENOTES • ドキュメントがしっかりしている Redis (contd)
  7. 7. シゴトでココロオドル $ brew install redis $ redis-server /usr/local/etc/redis.conf $ redis-cli 127.0.0.1:6379> PING PONG 課題 PING
  8. 8. シゴトでココロオドル 127.0.0.1:6379> GET foo (nil) 127.0.0.1:6379> SET foo bar OK 127.0.0.1:6379> GET foo "bar" 127.0.0.1:6379> GETSET foo baz "bar" 127.0.0.1:6379> GET foo "baz" 課題 GET, SET
  9. 9. シゴトでココロオドル • String – 数値もString • List – 双方向リンクリスト – LPOP, LPUSH, RPOP, RPUSH, RPOPLPUSH… – ブロッキング版BLPOP, BRPOP, BRPOPLPUSH • Set – 集合 • Sorted set – スコアつき集合 – range queryが使える – スコアボードとかにつかう Data Types
  10. 10. シゴトでココロオドル • Hash – Key-Value set • Bitmap (bit array) – bit列 • HyperLogLog – 集合のcardinarity • Geospatial item – 緯度経度。まだ安定版にはない。 • http://redis.io/topics/data-types • http://redis.io/topics/data-types-intro Data Types (contd)
  11. 11. シゴトでココロオドル 127.0.0.1:6379> GET baz (nil) 127.0.0.1:6379> INCR baz (integer) 1 127.0.0.1:6379> GET baz "1" 127.0.0.1:6379> INCRBY baz 1000 (integer) 1001 127.0.0.1:6379> GET baz "1001" 課題 INCR, DECR
  12. 12. シゴトでココロオドル 127.0.0.1:6379> SET foo hello OK 127.0.0.1:6379> EXPIRE foo 10 (integer) 1 127.0.0.1:6379> GET foo "hello" 127.0.0.1:6379> TTL foo (integer) 1 127.0.0.1:6379> GET foo (nil) 127.0.0.1:6379> TTL foo (integer) -2 課題 EXPIRE
  13. 13. シゴトでココロオドル • http://redis.io/commands コマンド一覧
  14. 14. シゴトでココロオドル • RDB – デフォルト – 非同期スナップショット • forkして書き込むので親processでdisk I/O発生しない – 履歴バックアップしやすい – リスタート時の読み込みがはやい – 数分のデータロスの可能性 • AOF – 追記型 • disk seekが発生しない – RDBのログ相当(PostgreSQLのWAL) • 再生可能 – スナップショットよりサイズが大きい – 単独で使わない方がいい • 作者は将来統合したいと思っている – “we'll likely end up unifying AOF and RDB into a single persistence model in the future (long term plan).” ディスク永続化 http://redis.io/topics/persistence
  15. 15. シゴトでココロオドル • Hash, List, Set(整数のみ), Sorted Setはデー タ数とデータ長が設定値より少ない場合、エン コードされて保存される • CPUとメモリのトレードオフ メモリ最適化されたデータ型 http://redis.io/topics/memory-optimization
  16. 16. シゴトでココロオドル • noeviction – don't expire at all, just return an error on write operations – デフォルト。キャッシュとして使わない場合 • volatile-lru – remove the key with an expire set using an LRU algorithm – キャッシュとデータ永続化を両方使いたい場合 • allkeys-lru – remove any key according to the LRU algorithm – 冪乗則のアクセスパターンの場合 – まよったらこれ • volatile-random – remove a random key with an expire set – キャッシュとデータ永続化を両方使いたい場合 • allkeys-random – remove a random key, any key – 均等にアクセスがある場合 • volatile-ttl – remove the key with the nearest expire time (minor TTL) – キャッシュ生成時によいTTLを設定できるならこれ • EXPIRE使うとメモリを余計にとる • キャッシュとデータ永続化は別々のRedisインスタンスにするのがオススメ maxmemoryに達した場合の挙動 http://redis.io/topics/lru-cache
  17. 17. シゴトでココロオドル $ redis-cli FLUSHALL $ redis-benchmark -t SET -r 100000 -n 1000000 $ redis-cli INFO | grep used_memory used_memory:11745408 used_memory_human:11.20M used_memory_rss:20680704 used_memory_peak:20696752 used_memory_peak_human:19.74M 課題 メモリ使用量
  18. 18. シゴトでココロオドル • コメントが充実している • 一度ざっと目を通すのがオススメ • 場所 – Homebrewでインストールした人 • /usr/local/etc/redis.conf – GitHub 3.0 branch • https://github.com/antirez/redis/blob/3.0/redis.conf 課題 設定ファイル
  19. 19. シゴトでココロオドル $ redis-cli -h 130.211.253.154 130.211.253.154:6379> SUBSCRIBE channels:1 Reading messages... (press Ctrl-C to quit) 1) "subscribe" 2) "channels:1" 3) (integer) 1 1) "message" 2) "channels:1" 3) "wantedly!" $ redis-cli -h 130.211.253.154 127.0.0.1:6379> PUBLISH channels:1 wantedly! (integer) 1 課題 Pub/Sub
  20. 20. シゴトでココロオドル • Pipelining – 複数コマンドを同時リクエスト – RTTを削減 • Transaction – MULTI / EXECコマンド – Rollbackはしない • Luaスクリプト – EVALコマンド – RDBのstored procedureのようなことも出来る • Master-Slave replication • Redis Sentinel • Redis Cluster その他の機能
  21. 21. シゴトでココロオドル ここからRubyの話になります
  22. 22. シゴトでココロオドル • redis • redis-rails • redis-rack • redis-activesupport • redis-actionpack • redis-namespace • redis-objects • hiredis • sidekiq, resque Gem
  23. 23. シゴトでココロオドル Railsと使う場合 # For Rails.cache # config/application.rb config.cache_store = :redis_store, 'redis://localhost:6379/0/cache', { expires_in: 90.minutes } # For session store # config/initializers/session_store.rb MyApplication::Application.config.session_store :redis_store, servers: ‘redis://localhost:6379/0/cache’ 実体は別のgem require 'redis-store' require 'redis-activesupport' require 'redis-actionpack' redis-rails gem
  24. 24. シゴトでココロオドル redis-rails で使えないコマンドが使える コマンドがそのままメソッド名になっている # Remove the last element in a list, append it to another list and return it. # # @param [String] source source key # @param [String] destination destination key # @return [nil, String] the element, or nil when the source key does not exist def rpoplpush(source, destination) synchronize do |client| client.call([:rpoplpush, source, destination]) end end redis gem
  25. 25. シゴトでココロオドル • redis gemはpure ruby • hiredis gemはCで書かれたconnectionと reply parserのhiredisを使えるようにする • benchmark – https://github.com/redis/hiredis- rb#benchmarks hiredis gem
  26. 26. シゴトでココロオドル Redisのdata typeをRuby的なdata typeにマップしてくれる class Team < ActiveRecord::Base include Redis::Objects lock :trade_players, :expiration => 15 # sec value :at_bat counter :hits counter :runs counter :outs counter :inning, :start => 1 list :on_base list :coaches, :marshal => true set :outfielders hash_key :pitchers_faced # "hash" is taken by Ruby sorted_set :rank, :global => true end redis-objects gem
  27. 27. シゴトでココロオドル @team = Team.first @team.on_base << 'player1' @team.on_base << 'player2' @team.on_base << 'player3' @team.on_base # ['player1', 'player2', 'player3'] @team.on_base.pop @team.on_base.shift @team.on_base.length # 1 @team.on_base.delete('player2') redis-objects gem (contd)
  28. 28. シゴトでココロオドル keyにデフォルトのnamespaceをつける redis = Redis.new namespaced_redis = Redis::Namespace.new(:foo, redis: redis) namespaced_redis.set(‘bar’, ‘baz’) # equivalent to redis.set('ns:foo', 'bar')) redis.get('foo:bar') # => 'baz' redis-namespace gem
  29. 29. シゴトでココロオドル • ソースコード – git@github.com:wantedly/instant-learn-redis.git • SNS的なやつ – User: id, name, email, avatar_url – Relation: user_id, friend_id • プロフィールページ – 共通の友人一覧が遅い – http://localhost:3000/users/2 課題 mutual friends
  30. 30. シゴトでココロオドル $ git clone git@github.com:antirez/redis.git オプショナル課題
  31. 31. シゴトでココロオドル • 速習したこと – Redisの基本的な使い方 – Ruby on RailsからのRedisの使い方 • 速習しなかったこと – Luaスクリプト – Master-Slave replication – Cluster – Sentinel – 実運用にむけた注意点 • ドキュメント読もう! • ソースも読もう!! まとめ

×