如何將購物車信息存到Redis中?


存到Redis中,好處是速度快。畢竟寫到硬盤需要更多的時間。加入購物車的功能,操作很頻繁,可以通過Redis快速寫入,移除,修改。

用什么方式呢?

傳統的KEY,VALUE不太合適,每次增加修改,都要把VALUE取出,序列化成數組之后,再改變結構,然后序列化存入。

幸好,Redis中有一種哈希的方式。它的特點就是每個KEY下面,包含對應的子KEY,VALUE。這樣就方便操作每個用戶下的購物車信息了。

用戶的購物車標識為:

appid:openid:cart 作為大KEY

購物車中的存儲內容為:

pid:sku_id 作為小KEY  pnum 作為小VALUE

hset 存

127.0.0.1:6379> hset appid:openid:cart 3:1 10
(integer) 1

hgetall 取所有

127.0.0.1:6379> hgetall appid:openid:cart
1) "1:1"
2) "1"
3) "1:2"
4) "2"
5) "3:1"
6) "10"

hkeys 取KEY

127.0.0.1:6379> hkeys appid:openid:cart
1) "1:1"
2) "1:2"
3) "3:1"

hvals 取值

127.0.0.1:6379> hvals appid:openid:cart
1) "1"
2) "2"
3) "10"

hdel 刪除

127.0.0.1:6379> hdel appid:openid:cart 3:1
(integer) 1

hlen 獲取長度

127.0.0.1:6379> hgetall appid:openid:cart
1) "1:1"
2) "1"
3) "1:2"
4) "2"
127.0.0.1:6379> hlen appid:openid:cart
(integer) 2

hset 修改

127.0.0.1:6379> hset appid:openid:cart 3:1 100
(integer) 0
127.0.0.1:6379> hget appid:openid:cart 3:1
"100"

hincrby 增加,減少

127.0.0.1:6379> hget appid:openid:cart 3:1
"100"
127.0.0.1:6379> hincrby appid:openid:cart 3:1 1
(integer) 101
127.0.0.1:6379> hincrby appid:openid:cart 3:1 1
(integer) 102
127.0.0.1:6379> hincrby appid:openid:cart 3:1 -1
(integer) 101
127.0.0.1:6379> hincrby appid:openid:cart 3:1 -1
(integer) 100
127.0.0.1:6379> hincrby appid:openid:cart 3:1 -1
(integer) 99


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM