[GO Language Fundamentals] Golang Operation Redis (16)

Redis

REmote DIctionary Server (Redis) is a key-value storage system written by Salvatore Sanfilippo.

installation

  • Installing
    Redis under Window supports 32-bit and 64-bit. This needs to be selected according to the actual situation of your system platform
  1. Start the server side
    Open a cmd window and use the cd command to switch the directory to the redis root directory (such as C:\redis) to run
    //默认启动
    redis-server.exe

    //根据修改的配置文件启动
    redis-server.exe redis.conf
  1. Run the client
    switch to the redis directory to run:
    redis-cli.exe -h 127.0.0.1 -p 6379  //127.0.0.1 是本机 IP ,6379 是 redis 服务端口。

    //测试
    redis> set myKey abc
    OK
    redis> get myKey
    abc
  • Install under Linux
    Download link: http://redis.io/download, download the latest stable version.
    $ wget http://download.redis.io/releases/redis-5.0.5.tar.gz
    $ tar xzf redis-5.0.5.tar.gz
    $ cd redis-5.0.5
    $ make

After make, the compiled redis service program redis-server will appear in the redis-5.0.5 directory, as well as the client program redis-cli for testing. The two programs are located in the src directory of the installation directory:

  1. Start the redis service.
    //默认启动
    $ ./redis-server    //注意这种方式启动redis 使用的是默认配置。也可以通过启动参数告诉redis使用指定配置文件使用下面命令启动。

    //根据修改的配置文件启动
    $ cd src
    $ ./redis-server ../redis.conf      //redis.conf 是一个默认的配置文件。我们可以根据需要使用自己的配置文件。
  1. Run client tests
    $ cd src
    $ ./redis-cli
    //测试
    redis> set foo bar
    OK
    redis> get foo
    "bar"

Configuration

The Redis configuration file is located in the Redis installation directory, and the file name is redis.conf (Windows name is redis.windows.conf).

  • View configuration
    You can view or set configuration items through the CONFIG command.
    CONFIG GET 命令基本语法:
    redis 127.0.0.1:6379> CONFIG GET CONFIG_SETTING_NAME
    ......
    //使用 * 号获取所有配置项:
    redis 127.0.0.1:6379> CONFIG GET *
  • Edit configuration
    You can modify the configuration by modifying the redis.conf file or using the CONFIG set command.
    CONFIG SET 命令基本语法:
    redis 127.0.0.1:6379> CONFIG SET CONFIG_SETTING_NAME NEW_CONFIG_VALUE
    OK
  • Parameter Description

Redis configuration parameter description

type of data

Redis supports five data types: string (string), hash (hash), list (list), set (collection) and zset (sorted set: ordered set).

Redis data type

Redis command reference

Redis command reference

Golang 操作 Redis

  • Install third-party open source Redis library
  1. Use a third-party open source redis library: github.com/garyburd/redigo/redis
    其他golang可用的第三方开源库:
    1. https://github.com/go-redis/redis
    2. https://github.com/gomodule/redigo
  1. Before using Redis, install the third-party Redis library first, and execute the installation instructions under the GOPATH path:
    $GOPATH >go get github.com/garyburd/redigo/redis

    //特别说明: 在安装 Redis 库前,确保已经安装并配置了 Git, 因为 是从 github 下载安装 Redis 库的,需要使用到 Git。 如果没有安装配置过 Git,请参考: 如何安装配置 Git

  1. Import package "github.com/garyburd/redigo/redis"
    import "github.com/garyburd/redigo/redis" //引入redis包 

  • Basic operations of Golang on Redis
  1. Link to redis
    conn, err := redis.Dial("tcp", "127.0.0.1:6379")

  1. Write data to redis through go
  2. Read data to redis through go (because the return r is interface{}, we need to convert it to the corresponding value type)
    //写入字符串类型
	_, err = conn.Do("Set", "name", "tom")
    //读取String类型
    r, err := redis.String(conn.Do("Get", "name"))

    //列表类型
    _, err = conn.Do("LPUSH", "list1", "ele1","ele2","ele3")

    res, err := redis.String(conn.Do("LPOP", "list1"))

    //hash类型
    _, err = conn.Do("HSet", "user", "name", "john")
    r1, err := redis.String(conn.Do("HGet","user", "name"))

    _, err = conn.Do("HSet", "user", "age", 18)
    r2, err := redis.Int(conn.Do("HGet","user", "age"))

    //多个值
    _, err = conn.Do("HMSet", "user", "name", "john", "age", 19)
    //多个值
    r, err := redis.Strings(conn.Do("HMGet","user02", "name", "age"))
    for i, v := range r {
		fmt.Printf("r[%d]=%s\n", i, v)
	}

  1. Set the effective time for key-value through Go
    //给 name 数据设置有效时间为 10s
    _, err = c.Do("expire", "name", 10)


  1. Close link
    conn.Close()

  • Redis link pool
    Through Golang to operate Redis, you can also use Redis link pool, the process is as follows:
  1. Initialize a certain number of links in advance and put them into the link pool
  2. When Go needs to operate Redis, just take out the link directly from the Redis link pool.
  3. This can save the time of temporarily obtaining Redis links, thereby improving efficiency.
    //定义一个全局的pool
    var pool *redis.Pool

    //当启动程序时,就初始化连接池
    func init() {
        pool = &redis.Pool{
            MaxIdle: 8, //最大空闲链接数
            MaxActive: 0, // 表示和数据库的最大链接数, 0 表示没有限制
            IdleTimeout: 100, // 最大空闲时间
            Dial: func() (redis.Conn, error) { // 初始化链接的代码, 链接哪个ip的redis
                return redis.Dial("tcp", "localhost:6379")
            },
        }	
    }
    func main() {
        //先从pool 取出一个链接
        conn := pool.Get()
        defer conn.Close()
        ...
        //我们要从pool 取出链接,一定保证链接池是没有关闭
        //如果pool.Close(),则无法获取链接
    }

  • Pipelining
    Redis pipeline technology can continue to send requests to the server when the server does not respond, and finally read all server responses at once.

Pipeline operations can be understood as concurrent operations, and are implemented through three methods: Send(), Flush(), and Receive().

The client can use the send() method to send one or more commands to the server at one time. When the command is sent, use the flush() method to send the command input in the buffer to the server at one time, and then the client uses the Receive() method to follow Read all command operation results in first-in first-out order.

The most significant advantage of pipeline technology is to improve the performance of redis services.

    Send(commandName string, args ...interface{}) error
    Flush() error
    Receive() (reply interface{}, err error)

  1. Send: Send the command to the buffer
  2. Flush: clear the buffer and send the command to the server at one time
  3. Recevie: Read the server response results in sequence. When the read command does not respond, the operation will be blocked.
    package main

    import (
    "github.com/garyburd/redigo/redis"
    "fmt"
    )
    func main()  {
        conn,err := redis.Dial("tcp","10.1.210.69:6379")
        if err != nil {
            fmt.Println("connect redis error :",err)
            return
        }
        defer conn.Close()
        conn.Send("HSET", "student","name", "wd","age","22")
        conn.Send("HSET", "student","Score","100")
        conn.Send("HGET", "student","age")
        conn.Flush()

        res1, err := conn.Receive()
        fmt.Printf("Receive res1:%v \n", res1)
        res2, err := conn.Receive()
        fmt.Printf("Receive res2:%v\n",res2)
        res3, err := conn.Receive()
        fmt.Printf("Receive res3:%s\n",res3)
    }

    控制台打印结果:
    Receive res1:0 
    Receive res2:0
    Receive res3:22

  • Publish/subscribe
    redis itself has the function of publish and subscribe. Its publish and subscribe function is realized by the command SUBSCRIBE (subscription)/PUBLISH (publish), and the publish and subscribe mode can be many-to-many mode and support regular expressions. Or multiple channels send messages, and subscribers can subscribe to one or more channels to receive messages.
    package main

    import (
        "github.com/garyburd/redigo/redis"
        "fmt"
        "time"
    )

    func Subs() {  //订阅者
        conn, err := redis.Dial("tcp", "10.1.210.69:6379")
        if err != nil {
            fmt.Println("connect redis error :", err)
            return
        }
        defer conn.Close()
        psc := redis.PubSubConn{conn}
        psc.Subscribe("channel1") //订阅channel1频道
        for {
            switch v := psc.Receive().(type) {
            case redis.Message:
                fmt.Printf("%s: message: %s\n", v.Channel, v.Data)
            case redis.Subscription:
                fmt.Printf("%s: %s %d\n", v.Channel, v.Kind, v.Count)
            case error:
                fmt.Println(v)
                return
            }
        }
    }

    func Push(message string)  { //发布者
        conn, _ := redis.Dial("tcp", "10.1.210.69:6379")
        _,err1 := conn.Do("PUBLISH", "channel1", message)
        if err1 != nil {
                fmt.Println("pub err: ", err1)
                    return
                }

    }

    func main()  {
        go Subs()
        go Push("this is wd")
        time.Sleep(time.Second*3)
    }

    控制台打印结果:
    channel1: subscribe 1
    channel1: message: this is wd

  • Transaction operation
  1. MULTI, EXEC, DISCARD and WATCH form the basis of Redis transactions. Of course, when we use the go language to perform transaction operations on redis, we essentially use these commands.
  2. MULTI: Open transaction
  3. EXEC: execute transaction
  4. DISCARD: Cancel transaction
  5. WATCH: Monitor the key changes in the transaction, and cancel the transaction once there is a change.
    package main

    import (
    "github.com/garyburd/redigo/redis"
    "fmt"
    )


    func main()  {
        conn,err := redis.Dial("tcp","10.1.210.69:6379")
        if err != nil {
            fmt.Println("connect redis error :",err)
            return
        }
        defer conn.Close()
        conn.Send("MULTI")
        conn.Send("INCR", "foo")
        conn.Send("INCR", "bar")
        r, err := conn.Do("EXEC")
        fmt.Println(r)
    }

    控制台打印结果:
    [1, 1]

Guess you like

Origin blog.csdn.net/weixin_54707168/article/details/114006155