java redis 数组吗,Redis如何存储关联数组?设置还是散列还是列表?

I'm a bit confused with all the available storing options of Redis.

I want to do something simple and I don't want to over engineer it.

I'm working with phpredis and Redis v2.8.6.

I have this simple associative array that I need to store. I also need to be able to retrieve an item by its key and loop over all the items.

$a = array(

'12345' => array(

'name' => 'Post A',

'val2' => 'blah blah',

'val3' => 'blah blah blah',

),

'54321' => array(

'name' => 'Post B',

'val2' => 'blah blah',

'val3' => 'blah blah blah',

),

'998877' => array(

'name' => 'Post C',

'val2' => 'blah blah',

'val3' => 'blah blah blah',

)

);

So what I was doing till now was using hash type. storing my array like this:

foreach ($a as $key => $value) {

$this->redis->hSet('posts', $key, json_encode($value));

}

Like that I could access the key easily like this:

public function getPost($postId)

{

return json_decode($this->redis->hGet('posts', $postId), true);

}

// This is returning the information of Post A

$post = getPost(12345);

But now I need to loop over all the posts I don't know how to do it and if I can do it with my current structure. I don't know if I need to store all the post_id in another list to be able to loop over all the posts?

So my question is which data type(s) should I use to store my list of posts, allowing me to fetch a single post by its id and looping over all the posts?

Thanks,

Maxime

解决方案

You can use SET and Hash and SORT in combination

redis 127.0.0.1:6379> HMSET TEST_12345 name "Post A" val2 "Blah Blah" val3 "Blah Blah Blah"

OK

redis 127.0.0.1:6379> HMSET TEST_54321 name "Post B" val2 "Blah Blah" val3 "Blah Blah Blah"

OK

redis 127.0.0.1:6379> HMSET TEST_998877 name "Post C" val2 "Blah Blah" val3 "Blah Blah Blah"

OK

redis 127.0.0.1:6379> SADD All_keys TEST_12345 TEST_54321 TEST_998877

(integer) 3

redis 127.0.0.1:6379> HGETALL TEST_12345

To GET one HASH:

redis 127.0.0.1:6379> HGETALL TEST_12345

1) "name"

2) "Post A"

3) "val2"

4) "Blah Blah"

5) "val3"

6) "Blah Blah Blah"

TO GET All HASH

redis 127.0.0.1:6379> SORT All_keys BY nosort GET *->name GET *->val2 GET *->val3

1) "Post A"

2) "Blah Blah"

3) "Blah Blah Blah"

4) "Post B"

5) "Blah Blah"

6) "Blah Blah Blah"

7) "Post C"

8) "Blah Blah"

9) "Blah Blah Blah"

If you don't want to use sort you can use Fetch All the key names from SET using SMEMBERS and then use Redis Pipeline to fetch all the keys

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值