https://github.com/go-redis/redis
https://github.com/gomodule/redigo
https://segmentfault.com/a/1190000017879129
go get github.com/alphazero/Go-Redis
go get github.com/simonz05/godis
go get github.com/garyburd/redigo
go get github.com/gosexy/redis
go get cgl.tideland.biz/redis
https://my.oschina.net/mickelfeng/blog/1580960
go-redis客户端对sentinel模式下(非集群cluster)redis-server主从切换的支持
https://blog.csdn.net/pengpengzhou/article/details/109363155
package app
import (
“fmt”
“git.qutoutiao.net/framework/autumn-lib-cache”
“github.com/go-redis/redis”
“strings”
)
var redisSentinelManager = cache.CreateRedisClientManager()
type Sentinel struct {
masterName string
masterIp string
masterPort string
masterManager *cache.RedisClientManager
slaveManager *cache.RedisClientManager
}
var sentinelClient *redis.SentinelClient
var masterClient *redis.Client
func init() {
fmt.Println(“ddddd”)
RedisSentinel()
}
/*
获取sentienl 客户端
/
func RedisSentinel() *redis.SentinelClient {
/rdb := redis.NewFailoverClient(&redis.FailoverOptions{
MasterName: “mymaster”,
SentinelAddrs: []string{“127.0.0.1:26379”,”127.0.0.1:26480”,”127.0.0.1:26481”},
})*/
if sentinelClient != nil {
return sentinelClient
}
/**
连接26379端口的sentinel;多个sentinel应循环获取可用的sentinel;
这里简单实现
*/
sentinelClient = redis.NewSentinelClient(&redis.Options{
Network: “tcp”,
Addr: “127.0.0.1:26379”,
})
//订阅切换主消息
go subScribe(sentinelClient)
return sentinelClient }
//处理 切主操作
/**
这里随便 订阅一个sentinel的 +switch-master
切换master会 sentinel 会向+switch-master发布一个消息
*/
func subScribe(sentinelClient *redis.SentinelClient) {
fmt.Println(“ccc”)
pubsub := sentinelClient.Subscribe(“+switch-master”)
fmt.Println(“ddd”)
_, err := pubsub.Receive()
if err != nil {
return
}
ch := pubsub.Channel()
for msg := range ch {
fmt.Println(“newMaster”,msg.Channel, msg.Payload, “\r\n”)
master := strings.Split(msg.Payload, “ “)
fmt.Println(master)
masterClient = redis.NewClient(&redis.Options{
Network: “tcp”,
Addr: master[1]+”:”+master[2],
})
}
}
/**
获取主节点信息
/
func GetMasterClient(sentinelClient *redis.SentinelClient) *redis.Client {
/if masterClient !=nil {
return masterClient
}*/
masterInfo, _ := sentinelClient.GetMasterAddrByName("mymaster").Result()
fmt.Println("masterInfo",masterInfo )
masterClient = redis.NewClient(&redis.Options{
Network: "tcp",
Addr: masterInfo[0]+":"+masterInfo[1],
})
fmt.Println("master", masterInfo[0]+masterInfo[1])
return masterClient }
func Subscribe(){
client := redis.NewClient(&redis.Options{
Network: “tcp”,
Addr: “127.0.0.1:26379”,
})
//参数1 频道名 字符串类型
pubsub := client.Subscribe("+switch-master")
_, err := pubsub.Receive()
if err != nil {
return
}
ch := pubsub.Channel()
for msg := range ch {
fmt.Println( msg.Channel, msg.Payload, "\r\n")
} }
go redis 常用客户端列表
godis:使用golang实现的redis客户端,灵感来源于jedis
redigo:是一个Redis数据库实现的go语言客户端
redis: 用Golang实现的Redis客户端
xredis:是一个类型安全、可定制化、干净易用的客户端Redis工具
上述中,个人比较推荐godis和redigo,也是redis官网上推荐。因为go-redis封装了redis的大部分命令,不用关心redis的命令的细节,直接调用相应接口就行;redigo是基于命令的,发送一个命令,然后在解析reply;所以相对而言,笔者觉得go-redis接口更友好
https://blog.csdn.net/enjoy_sun_moon/article/details/103614313
https://github.com/gistao/RedisGo-Async
https://www.jianshu.com/p/aeb27a6aa42d
https://www.cnblogs.com/zhangxiaoj/p/11291251.html
开源库redigo的使用 github地址: https://github.com/garyburd/redigo
文档地址:
http://godoc.org/github.com/garyburd/redigo/redis
获取:
go get github.com/garyburd/redigo/redis
连接redis
package main
import (
“fmt”
“github.com/garyburd/redigo/redis”
)
func main() {
c, err := redis.Dial(“tcp”, “127.0.0.1:6379”)
if err != nil {
fmt.Println(“Connect to redis error”, err)
return
}
defer c.Close()
}
读写
这里写入的值永远不会过期
package main
import (
“fmt”
"github.com/garyburd/redigo/redis" )
func main() {
c, err := redis.Dial(“tcp”, “127.0.0.1:6379”)
if err != nil {
fmt.Println(“Connect to redis error”, err)
return
}
defer c.Close()
_, err = c.Do("SET", "mykey", "superWang")
if err != nil {
fmt.Println("redis set failed:", err)
}
username, err := redis.String(c.Do("GET", "mykey"))
if err != nil {
fmt.Println("redis get failed:", err)
} else {
fmt.Printf("Get mykey: %v \n", username)
} }
如何设置过期呢,可以使用SET的附加参数:
package main
import (
“fmt”
“time”
"github.com/garyburd/redigo/redis" )
func main() {
c, err := redis.Dial(“tcp”, “127.0.0.1:6379”)
if err != nil {
fmt.Println(“Connect to redis error”, err)
return
}
defer c.Close()
_, err = c.Do("SET", "mykey", "superWang", "EX", "5")
if err != nil {
fmt.Println("redis set failed:", err)
}
username, err := redis.String(c.Do("GET", "mykey"))
if err != nil {
fmt.Println("redis get failed:", err)
} else {
fmt.Printf("Get mykey: %v \n", username)
}
time.Sleep(8 * time.Second)
username, err = redis.String(c.Do("GET", "mykey"))
if err != nil {
fmt.Println("redis get failed:", err)
} else {
fmt.Printf("Get mykey: %v \n", username)
} }
输出:
Get mykey: superWang
redis get failed: redigo: nil returned
批量写入读取
MGET key [key …]
MSET key value [key value …]
批量写入读取对象(Hashtable)
HMSET key field value [field value …]
HMGET key field [field …]
检测值是否存在
EXISTS key
package main
import (
“fmt”
"github.com/garyburd/redigo/redis" )
func main() {
c, err := redis.Dial(“tcp”, “127.0.0.1:6379”)
if err != nil {
fmt.Println(“Connect to redis error”, err)
return
}
defer c.Close()
_, err = c.Do("SET", "mykey", "superWang")
if err != nil {
fmt.Println("redis set failed:", err)
}
is_key_exit, err := redis.Bool(c.Do("EXISTS", "mykey1"))
if err != nil {
fmt.Println("error:", err)
} else {
fmt.Printf("exists or not: %v \n", is_key_exit)
}
}
输出:
exists or not: false
删除
DEL key [key …]
package main
import (
“fmt”
"github.com/garyburd/redigo/redis" )
func main() {
c, err := redis.Dial(“tcp”, “127.0.0.1:6379”)
if err != nil {
fmt.Println(“Connect to redis error”, err)
return
}
defer c.Close()
_, err = c.Do("SET", "mykey", "superWang")
if err != nil {
fmt.Println("redis set failed:", err)
}
username, err := redis.String(c.Do("GET", "mykey"))
if err != nil {
fmt.Println("redis get failed:", err)
} else {
fmt.Printf("Get mykey: %v \n", username)
}
_, err = c.Do("DEL", "mykey")
if err != nil {
fmt.Println("redis delelte failed:", err)
}
username, err = redis.String(c.Do("GET", "mykey"))
if err != nil {
fmt.Println("redis get failed:", err)
} else {
fmt.Printf("Get mykey: %v \n", username)
} } 输出: Get mykey: superWang redis get failed: redigo: nil returned
读写json到redis
package main
import (
“encoding/json”
“fmt”
"github.com/garyburd/redigo/redis" )
func main() {
c, err := redis.Dial(“tcp”, “127.0.0.1:6379”)
if err != nil {
fmt.Println(“Connect to redis error”, err)
return
}
defer c.Close()
key := "profile"
imap := map[string]string{"username": "666", "phonenumber": "888"}
value, _ := json.Marshal(imap)
n, err := c.Do("SETNX", key, value)
if err != nil {
fmt.Println(err)
}
if n == int64(1) {
fmt.Println("success")
}
var imapGet map[string]string
valueGet, err := redis.Bytes(c.Do("GET", key))
if err != nil {
fmt.Println(err)
}
errShal := json.Unmarshal(valueGet, &imapGet)
if errShal != nil {
fmt.Println(err)
}
fmt.Println(imapGet["username"])
fmt.Println(imapGet["phonenumber"]) } 设置过期时间 EXPIRE key seconds
// 设置过期时间为24小时
n, _ := rs.Do(“EXPIRE”, key, 24*3600)
if n == int64(1) {
fmt.Println(“success”)
}
列表操作
命令:
redis 127.0.0.1:6379> LPUSH runoobkey redis
(integer) 1
redis 127.0.0.1:6379> LPUSH runoobkey mongodb
(integer) 2
redis 127.0.0.1:6379> LPUSH runoobkey mysql
(integer) 3
redis 127.0.0.1:6379> LRANGE runoobkey 0 10
1) “mysql”
2) “mongodb”
3) “redis”
代码实现:
package main
import (
“fmt”
"github.com/garyburd/redigo/redis" )
func main() {
c, err := redis.Dial(“tcp”, “127.0.0.1:6379”)
if err != nil {
fmt.Println(“Connect to redis error”, err)
return
}
defer c.Close()
_, err = c.Do("lpush", "runoobkey", "redis")
if err != nil {
fmt.Println("redis set failed:", err)
}
_, err = c.Do("lpush", "runoobkey", "mongodb")
if err != nil {
fmt.Println("redis set failed:", err)
}
_, err = c.Do("lpush", "runoobkey", "mysql")
if err != nil {
fmt.Println("redis set failed:", err)
}
values, _ := redis.Values(c.Do("lrange", "runoobkey", "0", "100"))
for _, v := range values {
fmt.Println(string(v.([]byte)))
} } 输出: mysql mongodb redis
管道
请求/响应服务可以实现持续处理新请求,即使客户端没有准备好读取旧响应。这样客户端可以发送多个命令到服务器而无需等待响应,最后在一次读取多个响应。这就是管道化(pipelining),这个技术在多年就被广泛使用了。距离,很多POP3协议实现已经支持此特性,显著加速了从服务器下载新邮件的过程。
Redis很早就支持管道化,所以无论你使用任何版本,你都可以使用管道化技术
连接支持使用Send(),Flush(),Receive()方法支持管道化操作
Send(commandName string, args …interface{}) error
Flush() error
Receive() (reply interface{}, err error)
Send向连接的输出缓冲中写入命令。Flush将连接的输出缓冲清空并写入服务器端。Recevie按照FIFO顺序依次读取服务器的响应。下例展示了一个简单的管道:
c.Send(“SET”, “foo”, “bar”)
c.Send(“GET”, “foo”)
c.Flush()
c.Receive() // reply from SET
v, err = c.Receive() // reply from GET
Do方法组合了Send,Flush和 Receive方法。Do方法先写入命令,然后清空输出buffer,最后接收全部挂起响应包括Do方发出的命令的结果。如果任何响应中包含一个错误,Do返回错误。如果没有错误,Do方法返回最后一个响应。
开源库go-redis/redis的使用
github地址:
https://github.com/go-redis/redis
文档地址:
https://godoc.org/github.com/go-redis/redis
获取:
go get -u github.com/go-redis/redis
应用:
package main
import (
“fmt”
"github.com/go-redis/redis" )
func main() {
client := redis.NewClient(&redis.Options{
Addr: “127.0.0.1:6379”,
Password: “”, // no password set
DB: 0, // use default DB
})
pong, err := client.Ping().Result()
fmt.Println(pong, err)
err = client.Set("key", "value", 0).Err()
if err != nil {
panic(err)
}
val, err := client.Get("key").Result()
if err != nil {
panic(err)
}
fmt.Println("key", val)
val2, err := client.Get("key2").Result()
if err == redis.Nil {
fmt.Println("key2 does not exists")
} else if err != nil {
panic(err)
} else {
fmt.Println("key2", val2)
} }
输出:
PONG
key value
key2 does not exists
http://www.manongjc.com/detail/9-nkutfxsmwxfvwni.html