RubyのクラスをRedisに保存、復元してみる
2014年2月27日Redisを使い始めました。なかなか面白いですね。今回は単純な文字列のキー・バリューではなく、Rubyのクラス情報をRedisに保存し、再びクラスに復元する方法について記載します。 Redisのインストール方法については、この記事を参照ください。 まずは単純な文字列をRubyで保存、取得してみます。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
require "redis" redis = Redis.new p "------ test simple key & value ------ " #中身が空のほうが良いので、DB番号3を選択 redis.select(3) p redis.keys("*") #シンプルなキーとバリューを保存 redis.set("aaa","taro") redis.set("bbb","hanako") redis.keys("*").each do |key| p "key = #{key} value = #{redis.get(key)}" end |
実行結果
1 2 3 4 |
"------ test simple key & value ------ " [] "key = bbb value = hanako" "key = aaa value = taro" |
クラスを作ります。(Personクラス)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
class Person attr_accessor :id , :name , :age def initialize(id,name,age) @id = id @name = name @age = age end def to_json(*a) { :id => @id, :name => @name, :age => @age }.to_json end def self.from_json(json) obj = self.new(1,2,3) #適当な値を突っ込む obj.id = json["id"] obj.name = json["name"] obj.age = json["age"] return obj end end |
クラスデータをRedisに保存し、復元してみます…
Leave a comment