go语言使用redis(redigo)

Posted Golang语言社区

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了go语言使用redis(redigo)相关的知识,希望对你有一定的参考价值。

原文作者:laijh
来源:简书

go的redis client用的比较多两个包是redix和redigo,因为beego cache模块里redis使用的是redigo,所以我也就使用这个包了。因为代码内容偏多,结构不清晰,不方便阅读,最后整理成一份思维导图,便于学习。当把整体分析,会发现提供给开发者使用的内容非常巧妙。


go语言使用redis(redigo)


点击下载


Demo:

 1package main
2
3import (
4    "fmt"
5    "github.com/gomodule/redigo/redis"
6    "log"
7)
8
9func main() {
10    c1, err := redis.Dial("tcp""127.0.0.1:6379")
11    if err != nil {
12        log.Fatalln(err)
13    }
14    defer c1.Close()
15    c2, err := redis.DialURL("redis://127.0.0.1:6379")
16    if err != nil {
17        log.Fatalln(err)
18    }
19    defer c2.Close()
20
21
22    rec1, err := c1.Do("Get""name")
23    fmt.Println(string(rec1.([]byte)))
24
25    c2.Send("Get""name")
26    c2.Flush()
27    rec2, err := c2.Receive()
28    fmt.Println(string(rec2.([]byte)))
29}

下面内容是更加详细的源码分析

提供给开发者使用的内容
(1)变量
(2)常量
(3)新类型
(4)接口
(5)结构体
(6)函数

1、变量
var ErrNil = errors.New("redigo: nil returned")
2、常量
3、新类型
(1)type Args []interface{}
(2)type Error string
4、接口
(1)Conn
(2)ConnWithTimeout
(3)Scanner
(4)Argument
5、结构体
(1)DialOption
(2)Pool
(3)PoolStats
(4)Subscription
(5)PubSubConn
(6)Message
(7)Script
(8)Pong
6、函数
(1)func NewPool(newFn func() (Conn, error), maxIdle int) *Pool
(2)func NewScript(keyCount int, src string) *Script
(3)func NewLoggingConn(conn Conn, logger *log.Logger, prefix string) Conn
(4)func NewLoggingConnFilter(conn Conn, logger log.Logger, prefix string, skip func(cmdName string) bool) Conn
(5)func DoWithTimeout(c Conn, timeout time.Duration, cmd string, args ...interface{}) (interface{}, error)
(6)func DoWithTimeout(c Conn, timeout time.Duration, cmd string, args ...interface{}) (interface{}, error)
(7)func Int(reply interface{}, err error) (int, error)
(8)func Int64(reply interface{}, err error) (int64, error)
(9)func Uint64(reply interface{}, err error) (uint64, error)
(10)func Float64(reply interface{}, err error) (float64, error)
(11)func String(reply interface{}, err error) (string, error)
(12)func Bytes(reply interface{}, err error) ([]byte, error)
(13)func Bool(reply interface{}, err error) (bool, error)
(14)func MultiBulk(reply interface{}, err error) ([]interface{}, error)
(15)func Values(reply interface{}, err error) ([]interface{}, error)
(16)func Float64s(reply interface{}, err error) ([]float64, error)
(17)func Strings(reply interface{}, err error) ([]string, error)
(18)func ByteSlices(reply interface{}, err error) ([][]byte, error)
(19)func Int64s(reply interface{}, err error) ([]int64, error)
(20)func Ints(reply interface{}, err error) ([]int, error)
(21)func StringMap(result interface{}, err error) (map[string]string, error)
(22)func IntMap(result interface{}, err error) (map[string]int, error)
(23)func Int64Map(result interface{}, err error) (map[string]int64, error)
(24)func Positions(result interface{}, err error) ([]
[2]float64, error)
(25)func DialTimeout(network, address string, connectTimeout, readTimeout, writeTimeout time.Duration) (Conn, error)
(26)func DialReadTimeout(d time.Duration) DialOption
(27)func DialWriteTimeout(d time.Duration) DialOption
(28)func DialConnectTimeout(d time.Duration) DialOption
(29)func DialKeepAlive(d time.Duration) DialOption
(30)func DialNetDial(dial func(network, addr string) (net.Conn, error)) DialOption
(31)func DialDatabase(db int) DialOption
(32)func DialPassword(password string) DialOption
(33)func DialTLSConfig(c *tls.Config) DialOption
(34)func DialTLSSkipVerify(skip bool) DialOption

一、变量
var ErrNil = errors.New("redigo: nil returned")
暴露给开发者的目的是,因为从redis服务器获取数据的时候可能遇到值为空的情况。
二、常量
三、新类型
(1)type Args []interface{}


  1type Args []interface{}
 2
 3func (args Args) Add(value ...interface{}) Args
 4// Add是直接将值追加到args后面的结果返回,但是并不会修改到args
 5func (args Args) AddFlat(v interface{}) Args 
 6// AddFlat根据值的类型存储,分为以下五种情况:Struct、Slice、Map、Ptr、其他类型
 71)Struct:
 8package main
 9
10import (
11    "fmt"
12    "github.com/gomodule/redigo/redis"
13
)
14
15type Ints struct 
{
16    A int
17    b int
18    C float32
19}
20
21func (Ints)Add() {
22    fmt.Println(123)
23}
24
25func main() {
26    i := Ints{1,2,1.2}
27    args := redis.Args{1,2,3}
28    args1 := args.AddFlat(i)
29    fmt.Println(args, len(args))
30    fmt.Println(args1, len(args1))
31}
32输出:
33[1 2 33
34[1 2 3 A 1 C 1.27
352)Slice:
36package main
37
38import (
39    "fmt"
40    "github.com/gomodule/redigo/redis"
41
)
42
43func main() 
{
44    i := []int{1,2,12}
45    args := redis.Args{1,2,3}
46    args1 := args.AddFlat(i)
47    fmt.Println(args, len(args))
48    fmt.Println(args1, len(args1))
49}
50输出:
51[1 2 33
52[1 2 3 1 2 126
533)Map:
54package main
55
56import (
57    "fmt"
58    "github.com/gomodule/redigo/redis"
59
)
60
61func main() 
{
62    i := map[int]string{1:"你好",2:"测试"}
63    args := redis.Args{1,2,3}
64    args1 := args.AddFlat(i)
65    fmt.Println(args, len(args))
66    fmt.Println(args1, len(args1))
67}
68输出:
69[1 2 33
70[1 2 3 1 你好 2 测试7
714Prt
72package main
73
74import (
75    "fmt"
76    "github.com/gomodule/redigo/redis"
77
)
78
79func main() 
{
80    a := 123
81    i := &a
82    args := redis.Args{1,2,3}
83    args1 := args.AddFlat(i)
84    fmt.Println(args, len(args))
85    fmt.Println(args1, len(args1))
86}
87输出:
88[1 2 33
89[1 2 3 0xc00008a2d84
905)其他类型:
91package main
92
93import (
94    "fmt"
95    "github.com/gomodule/redigo/redis"
96
)
97
98type Int int8
99
100func main() 
{
101    a := 123
102    b := Int(8)
103    args := redis.Args{1,2,3}
104    args1 := args.AddFlat(a)
105    args1 = args1.AddFlat(b)
106    fmt.Println(args, len(args))
107    fmt.Println(args1, len(args1))
108}
109输出:
110[1 2 33
111[1 2 3 123 85


(2)type Error string


1type Error string
2func (err Error) Error() string { return string(err) }


四、接口
(1)Conn
(2)ConnWithTimeout
(3)Scanner
(4)Argument
五、结构体
(1)DialOption
源码:


1type DialOption struct {
2    f func(*dialOptions)
3}
4


作用:该结构体是被设计成 当创建与redis服务器连接时,进行参数设置。
与该结构体有关的函数:


 11func DialReadTimeout(d time.Duration) DialOption
2设置读超时时间
3(2)func DialWriteTimeout(d time.Duration) DialOption
4设置读超时时间
5(3)func DialConnectTimeout(d time.Duration) DialOption
6设置连接超时时间
7(4)func DialKeepAlive(d time.Duration) DialOption 
8(5)func DialNetDial(dial func(network, addr string) (net.Conn, error)DialOption
9(6)func DialDatabase(db int) DialOption
10设置连接数据库
11(7)func DialPassword(password string) DialOption
12设置连接redis密码
13(8)func DialTLSConfig(c *tls.Config) DialOption
14设置TLS配置信息
15(9)func DialTLSSkipVerify(skip bool) DialOption
16是否跳过TLS验证
17(10)func DialUseTLS(useTLS bool) DialOption
18是否使用TLS
19


(2)Pool
源码:


 1type Pool struct {
2    Dial func() (Conn, error)
3    TestOnBorrow func(c Conn, t time.Timeerror
4    MaxIdle int
5    MaxActive int
6    IdleTimeout time.Duration
7    Wait bool
8    MaxConnLifetime time.Duration
9    chInitialized uint32
10    mu     sync.Mutex 
11    closed bool 
12    active int 
13    ch     chan struct{} 
14    idle   idleList
15}


作用:用来管理redis连接池
相关函数:


 11func NewPool(newFn func() (Conn, error)maxIdle int) *Pool
2            创建一个连接池对象
3(2)func (p *Pool) Get() Conn
4            获取一个连接 
5(3)func (p *Pool) Stats() PoolStats
6            获取池的状态
7(4)func (p *Pool) ActiveCount() int
8            获取存活数量
9(5)func (p *Pool) IdleCount() int
10            获取空闲数量
11(6)func (p *Pool) Close() error
12            关闭
13


(3)PoolStats
源码:


1type PoolStats struct {
2    ActiveCount int 
3    IdleCount int
4}


作用:记录redis池中存活连接数量和空闲连接数
(4)Subscription
源码:


1type Subscription struct {
2    Kind string          
3    Channel string  
4    Count int
5}


作用:Subscription用于订阅或取消订阅通知。
相关函数:

Demo:


 1package main
2
3import (
4    "fmt"
5    "github.com/gomodule/redigo/redis"
6    "log"
7    "reflect"
8)
9
10func main() {
11    rc, err := redis.Dial("tcp""127.0.0.1:6379")
12    if err != nil {
13        log.Fatalln(err)
14    }
15    defer rc.Close()
16
17    rc.Send("SUBSCRIBE""example")
18    rc.Flush()
19    for {
20        reply, err := redis.Values(rc.Receive())
21        if err != nil {
22            fmt.Println(err)
23        }
24        if len(reply) == 3 {
25            if reflect.TypeOf(reply[2]).String() == "[]uint8" {
26                fmt.Println(string(reply[2].([]byte)))
27            }
28        }
29    }
30}

(5)PubSubConn
源码:


1type PubSubConn struct {
2    Conn Conn
3}


相关函数:


 11func (c PubSubConn) Subscribe(channel ...interface{}) error
2            订阅给定的一个或多个频道的信息。
3(2)func (c PubSubConn) PSubscribe(channel ...interface{}) error
4            订阅一个或多个符合给定模式的频道。
5(3)func (c PubSubConn) Unsubscribe(channel ...interface{}) error
6            指退订给定的频道。
7(4)func (c PubSubConn) PUnsubscribe(channel ...interface{}) error
8            退订所有给定模式的频道。
9(5)func (c PubSubConn) Ping(data string) error 
10            测试客户端是否能够继续连通
11(6)func (c PubSubConn) Receive() interface
{}
12             获取回复信息
137func (c PubSubConn) ReceiveWithTimeout(timeout time.Duration) interface{}
14             在指定时间内获取时间
158func (c PubSubConn) Close() error 
16              关闭
17


(6)Message
源码:


1type Message struct {
2    Channel string    // 频道名称
3    Pattern string      // 频道模式
4    Data []byte            // 数据
5}


(7)Script
源码:


1type Script struct {
2    keyCount int
3    src               string
4    hash           string
5}


相关函数:


11func NewScript(keyCount int, src string) *Script 
2(2)func (s *Script) Hash() string
3(3)func (s *Script) Do(c Conn, keysAndArgs ...interface{}) (interface{}, error) 
4(4)func (s *Script) SendHash(c Conn, keysAndArgs ...interface{}) error 
5(5)func (s *Script) Send(c Conn, keysAndArgs ...interface{}) error 
6(6)func (s *Script) Load(c Conn) error
7


(8)Pong
源码:


1type Pong struct {
2    Data string
3}


(6)函数


 11func NewPool(newFn func() (Conn, error)maxIdle int) *Pool
2(2)func NewScript(keyCount int, src string) *Script 
3(3)func NewLoggingConn(conn Conn, logger *log.Logger, prefix string) Conn
4(4)func NewLoggingConnFilter(conn Conn, logger *log.Logger, prefix string, skip func(cmdName string) boolConn
5(5)func DoWithTimeout(c Conn, timeout time.Duration, cmd string, args ...interface{}) (interface{}, error)
6(6)func DoWithTimeout(c Conn, timeout time.Duration, cmd string, args ...interface{}) (interface{}, error)
7(7)func Int(reply interface{}, err error) (int, error)
8(8)func Int64(reply interface{}, err error) (int64, error)
9(9)func Uint64(reply interface{}, err error) (uint64, error)
10(10)func Float64(reply interface{}, err error) (float64, error)
11(11)func String(reply interface{}, err error) (string, error)
12(12)func Bytes(reply interface{}, err error) ([]byte, error)
13(13)func Bool(reply interface{}, err error) (bool, error) 
14(14)func MultiBulk(reply interface{}, err error) ([]interface{}, error) 
15(15)func Values(reply interface{}, err error) ([]interface{}, error)
16(16)func Float64s(reply interface{}, err error) ([]float64, error)
17(17)func Strings(reply interface{}, err error) ([]string, error) 
18(18)func ByteSlices(reply interface{}, err error) ([][]byte, error)
19(19)func Int64s(reply interface{}, err error) ([]int64, error)
20(20)func Ints(reply interface{}, err error) ([]int, error)
21(21)func StringMap(result interface{}, err error) (map[string]string, error) 
22(22)func IntMap(result interface{}, err error) (map[string]int, error)
23(23)func Int64Map(result interface{}, err error) (map[string]int64, error)
24(24)func Positions(result interface{}, err error) ([]*[2]float64, error)
25(25)func DialTimeout(network, address string, connectTimeout, readTimeout, writeTimeout time.Duration) (Conn, error) 
26(26)func DialReadTimeout(d time.Duration) DialOption
27(27)func DialWriteTimeout(d time.Duration) DialOption
28(28)func DialConnectTimeout(d time.Duration) DialOption
29(29)func DialKeepAlive(d time.Duration) DialOption 
30(30)func DialNetDial(dial func(network, addr string) (net.Conn, error)DialOption
31(31)func DialDatabase(db int) DialOption
32(32)func DialPassword(password string) DialOption
33(33)func DialTLSConfig(c *tls.Config) DialOption
34(34)func DialTLSSkipVerify(skip bool) DialOption
35


经过学习源码发现,这些顶尖的设计者与我们普通开发者的区别在于,他们包设计非常巧妙,以及只把有必要的内容提供给开发者。


版权申明:内容来源网络,版权归原创者所有。除非无法确认,我们都会标明作者及出处,如有侵权烦请告知,我们会立即删除并表示歉意。谢谢。



Golang语言社区

ID:Golangweb

www.bytedancing.com

游戏服务器架构丨分布式技术丨大数据丨游戏算法学习


以上是关于go语言使用redis(redigo)的主要内容,如果未能解决你的问题,请参考以下文章

go redigo的简单操作

从java到Go搭建Go的Redis客户端框架redigo

从java到Go搭建Go的Redis客户端框架redigo

从java到Go搭建Go的Redis客户端框架redigo

从java到Go搭建Go的Redis客户端框架redigo

Go语言操作Redis