How to store array of hashes in redis

后端 未结 2 798
遇见更好的自我
遇见更好的自我 2021-02-18 23:24

I want to store array of hashes in redis , what is best way to code it ?

2条回答
  •  死守一世寂寞
    2021-02-19 00:26

    If you are using a language which supports to/from json conversion, you can convert your hash to json and append it in a list. You can do the following in Ruby:

    require 'rubygems'
    require 'redis'
    require 'json'
    require 'pp'
    
    redis = Redis.new(:host => '127.0.0.1', :port => 6379)
    
    h1 = { :k1 => 'v1', :k2 => 'v2' }
    redis.rpush('arr', h1.to_json)
    
    h2 = { :k3 => 'v3', :k4 => 'v4' }
    redis.rpush('arr', h2.to_json)
    
    hashes = redis.lrange('arr', 0, -1)
    hashes.map! { |x| JSON.parse(x) }
    pp hashes
    

提交回复
热议问题