go redis 集合操作--sadd
程序员文章站
2024-03-24 11:55:04
...
redis的go语言包,我们使用官方推荐的redigo,https://github.com/garyburd/redigo
安装redigo
$ go get github.com/garyburd/redigo
redis set
set集合具有每个元素唯一性的特点。在redis中,可使用SADD命令操作:
SADD Example:
redis> SADD myset “Hello”
(integer) 1
redis> SADD myset “World”
(integer) 1
redis> SADD myset “World”
(integer) 0
redis> SMEMBERS myset
1) “World”
2) “Hello”redis>
在 go中redis简单举例如下。
simple SADD
package main
import (
"log"
"github.com/garyburd/redigo/redis"
)
func main() {
server := "127.0.0.1:6379"
option := redis.DialPassword("123456")
c, err := redis.Dial("tcp", server, option)
if err != nil {
log.Println("connect server failed:", err)
return
}
defer c.Close()
v, err := redis.Int64(c.Do("SADD", "myset", "10.8.37.98"))
if err != nil {
log.Println("SADD failed:", err)
return
}
log.Println("value:", v)
}
批量添加
package main
import (
"log"
"github.com/garyburd/redigo/redis"
)
func main() {
server := "127.0.0.1:6379"
option := redis.DialPassword("123456")
c, err := redis.Dial("tcp", server, option)
if err != nil {
log.Println("connect server failed:", err)
return
}
defer c.Close()
setKey := "myset"
args := []interface{}{setKey}
args = append(args, "10.1")
args = append(args, "10.2")
v, err := redis.Int64(c.Do("SADD", args...))
if err != nil {
log.Println("SADD failed:", err)
return
}
log.Println("value:", v)
}
查看:
$ ./src/redis-cli -a 123456
127.0.0.1:6379> SMEMBERS myset
1) “10.2”
2) “10.1”
3) “world”
4) “good”
5) “10.8.37.98”
6) “today”
7) “day”
8) “hello”
127.0.0.1:6379>
参考
redigo
https://github.com/garyburd/redigo
redigo API Reference
https://godoc.org/github.com/gomodule/redigo/redis
上一篇: 学习操作系统:自己动手写操作系统 ->chapter4_c
下一篇: 写更简洁的代码