使用go怎么對(duì)redis的有序集合進(jìn)行操作?針對(duì)這個(gè)問題,這篇文章詳細(xì)介紹了相對(duì)應(yīng)的分析和解答,希望可以幫助更多想解決這個(gè)問題的小伙伴找到更簡(jiǎn)單易行的方法。
package main import ( "fmt" "github.com/garyburd/redigo/redis" ) func main() { // 連接redis數(shù)據(jù)庫(kù),指定數(shù)據(jù)庫(kù)的IP和端口 conn, err := redis.Dial("tcp", "36.99.16.197:6379") if err != nil { fmt.Println("Connect to redis error", err) return } else { fmt.Println("Connect to redis ok.") } // 函數(shù)退出時(shí)關(guān)閉連接 defer conn.Close() // 執(zhí)行一個(gè)有序zset插入 _, err = conn.Do("ZADD", "mykey", "INCR", 1, "robot1") if err != nil { fmt.Println("redis set failed:", err) } // 再執(zhí)行一個(gè)有序zset插入 _, err = conn.Do("ZADD", "mykey", "INCR", 1, "robot2") if err != nil { fmt.Println("redis set failed:", err) } // 讀取指定zset user_map, err := redis.StringMap(conn.Do("ZRANGE", "mykey", 0, 10, "withscores")) if err != nil { fmt.Println("redis get failed:", err) } else { fmt.Printf("Get mykey: %v \n", user_map) } for user := range user_map { fmt.Printf("user name: %v %v\n", user, user_map[user]) } }
輸出:
Connect to redis ok. Get mykey: map[robot1:1 robot2:1] user name: robot1 1 user name: robot2 1
補(bǔ)充:Redis中zset的golang實(shí)現(xiàn)
初衷是在不用Redis的前提下實(shí)現(xiàn)排行榜
項(xiàng)目地址https://github.com/liyiheng/zset
go get -u github.com/liyiheng/zset
Removed RWLock in the SortedSet.
Just implement it yourself if you need.
s := zset.New() // add data s.Set(66, 1001, "test1") s.Set(77, 1002, "test2") s.Set(88, 1003, "test3") s.Set(100, 1004, "liyiheng") s.Set(99, 1005, "test4") s.Set(44, 1006, "test5") // update data s.Set(44, 1001, "test1") // get rank by id rank, score, extra := s.GetRank(1004, false) // get data by rank id, score, extra := s.GetDataByRank(0, true) // get data by id dat, ok := s.GetData(1001) // delete data by id s.Delete(1001)
go test -test.bench=".*" BenchmarkSortedSet_Add-4 1000000 4121 ns/op BenchmarkSortedSet_GetRank-4 500000 3592 ns/op BenchmarkSortedSet_GetDataByRank-4 2000000 667 ns/op PASS ok zset 11.365s
關(guān)于使用go怎么對(duì)redis的有序集合進(jìn)行操作問題的解答就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道了解更多相關(guān)知識(shí)。
本文標(biāo)題:使用go怎么對(duì)redis的有序集合進(jìn)行操作-創(chuàng)新互聯(lián)
轉(zhuǎn)載注明:http://chinadenli.net/article14/cdhpde.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供靜態(tài)網(wǎng)站、App開發(fā)、Google、商城網(wǎng)站、網(wǎng)頁(yè)設(shè)計(jì)公司、關(guān)鍵詞優(yōu)化
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容