go-redis use (redis link, data writing, data query, storage structure, automatic parsing and anti-parsing, MarshalBinary(), UnmarshalBinary())

Reference package: "github.com/go-redis/redis/v8"

1. redis link

1.1 Related structures

type Options struct {
    
    
    Network            string
    Addr               string
    Dialer             func(ctx context.Context, network string, addr string) (net.Conn, error)
    OnConnect          func(ctx context.Context, cn *Conn) error
    Username           string
    Password           string
    DB                 int
    MaxRetries         int
    MinRetryBackoff    time.Duration
    MaxRetryBackoff    time.Duration
    DialTimeout        time.Duration
    ReadTimeout        time.Duration
    WriteTimeout       time.Duration
    PoolFIFO           bool
    PoolSize           int
    MinIdleConns       int
    MaxConnAge         time.Duration
    PoolTimeout        time.Duration
    IdleTimeout        time.Duration
    IdleCheckFrequency time.Duration
    readOnly           bool
    TLSConfig          *tls.Config
    Limiter            Limiter
}

1.2 Grammar

func NewClient(opt *Options) *Client
  • syntax example
	rdb := redis.NewClient(&redis.Options{
    
    
		Addr:     "10.10.239.136:6379",
		Password: "",
		DB:       1,
	})

1.3 Complete example

  • full code
package main

import (
	"context"
	"fmt"
	"github.com/go-redis/redis/v8"
)

var ctx = context.Background()

func main() {
    
    
	rdb := RedisConnect()
	fmt.Printf("rdb : %+v", rdb)
}

func RedisConnect() (rdb *redis.Client) {
    
    
	var myRedis redis.Options
	myRedis.Addr = "10.10.239.136:6379"
	myRedis.Password = ""
	myRedis.DB = 1
	rdb = redis.NewClient(&myRedis)
	return rdb
}
  • print result
API server listening at: 127.0.0.1:62059
rdb : Redis<10.10.239.136:6379 db:1>
Debugger finished with the exit code 0

2. Save data

2.1 Grammar

  • grammar
func (c cmdable) Set(ctx context.Context, key string, value interface{
    
    }, expiration time.Duration) *StatusCmd
  • simple example
err := rdb.Set(ctx, "project:users:{user_name}:string", "GuanYu", time.Minute*2).Err()

expiration is 0 means there is no expiration limit

2.2 Simple example

  • full code
package main

import (
	"context"
	"fmt"
	"github.com/go-redis/redis/v8"
	"time"
)

var ctx = context.Background()

func main() {
    
    
	rdb := RedisConnect()
	fmt.Printf("rdb : %+v", rdb)
	
	err := rdb.Set(ctx, "project:users:{user_name}:string", "GuanYu", time.Minute*2).Err()
	if err != nil {
    
    
		fmt.Println("err: ", err)
	} else {
    
    
		fmt.Println("保存成功")
	}
}

func RedisConnect() (rdb *redis.Client) {
    
    
    //以下这些值在实际应用中,可以从环境变量或配置文件中读取
	var myRedis redis.Options
	myRedis.Addr = "10.10.239.136:6371"
	myRedis.Password = ""
	myRedis.DB = 1
	
	rdb = redis.NewClient(&myRedis)
	return rdb
}

  • view redis
    insert image description here

3. Data query

3.1 Grammar

  • grammar
func (c cmdable) Get(ctx context.Context, key string) *StringCmd
  • syntax example
esult := rdb.Get(ctx, "project:users:{user_name}:string")

3.2 Complete example

  • the code
package main

import (
	"context"
	"fmt"
	"github.com/go-redis/redis/v8"
	"time"
)

var ctx = context.Background()

func main() {
    
    
	rdb := RedisConnect()
	fmt.Printf("rdb : %+v", rdb)

	//写入
	err := rdb.Set(ctx, "project:users:{user_name}:string", "GuanYu", time.Minute*2).Err()
	if err != nil {
    
    
		fmt.Println("err: ", err)
	} else {
    
    
		fmt.Println("保存成功")
	}

	//查询
	result := rdb.Get(ctx, "project:users:{user_name}:string")
	err = result.Err()
	if err != nil {
    
    
		fmt.Println("err :", err)
		return
	}
	fmt.Printf("以string完整输出:%s\n", result.String())
	fmt.Printf("仅输出值:%s\n", result.Val())

}

func RedisConnect() (rdb *redis.Client) {
    
    
	var myRedis redis.Options
	myRedis.Addr = "10.10.239.136:6379"
	myRedis.Password = ""
	myRedis.DB = 1
	rdb = redis.NewClient(&myRedis)
	return rdb
}
  • output
string完整输出:get project:users:{
    
    user_name}:string: GuanYu
仅输出值:GuanYu

4. Other examples

4.1 Using the structure

  • use structure
package main

import (
	"context"
	"encoding/json"
	"fmt"
	"github.com/go-redis/redis/v8"
	"time"
)

var ctx = context.Background()

type UserName struct {
    
    
	UserId   int64  `json:"user_id"`
	UserName string `json:"user_name"`
	Age      int64  `json:"age"`
}

func main() {
    
    
	rdb := RedisConnect()

	data := &UserName{
    
    
		UserId:   1,
		UserName: "LiuBei",
		Age:      28,
	}

	//结构体转为json字串的[]byte
	b, err := json.Marshal(data)
	if err != nil {
    
    
		fmt.Println(err)
	}

	//写入
	err = rdb.Set(ctx, "project:users:{user_name}:struct", string(b), time.Minute*2).Err()
	if err != nil {
    
    
		fmt.Println("err: ", err)
	}

	//查找
	result := rdb.Get(ctx, "project:users:{user_name}:struct")
	fmt.Println(result.Val())
}

func RedisConnect() (rdb *redis.Client) {
    
    
	var myRedis redis.Options
	myRedis.Addr = "10.10.239.136:6379"
	myRedis.Password = ""
	myRedis.DB = 1
	rdb = redis.NewClient(&myRedis)
	return rdb
}
  • output
{
    
    "user_id":1,"user_name":"LiuBei","age":28}

4.2 MarshalBinary()和UnmarshalBinary()

  • MarshalBinary()

    • As in the above example, when writing, we need to analyze the structure instance. In fact, go-redisan analysis method has been provided for us to use.
    • When using the Set() method, it automatically calls MarshalBinary()the method of the structure
    • So we only need to define this method of the structure to parse the structure (the name of the structure is defined by go-redis, we cannot change it. See the complete code)
  • UnmarshalBinary()

    • As in the above example, when reading data, you need to use an instance of *redis.StringCmd to receive it. In fact, go-redisa method has been provided for our custom structure to receive it.
    • When using the Get method, it will automatically call MarshalBinary()the method of the structure
    • So we only need to define this method of the structure to parse the structure (see full code)
  • full code

import (
	"context"
	"encoding/json"
	"fmt"
	"github.com/go-redis/redis/v8"
)

type myStruct struct {
    
    
	UserId   string `json:"user_id"`
	UserName string `json:"user_name"`
	Age      int64  `json:"age"`
}

//var _ encoding.BinaryMarshaler = new(myStruct)
//var _ encoding.BinaryUnmarshaler = new(myStruct)

func (m *myStruct) MarshalBinary() (data []byte, err error) {
    
    
	return json.Marshal(m) //解析
}

func (m *myStruct) UnmarshalBinary(data []byte) error {
    
    
	return json.Unmarshal(data, m)  //反解析
}

func main() {
    
    
	var ctx = context.Background()
	rdb := RedisConnect()

	data := &myStruct{
    
    
		UserId:   "123",
		UserName: "GuanYu",
		Age:      25,
	}
	//写入
	err := rdb.Set(ctx, "project:users:{user_name}:struct", data, 0).Err()
	if err != nil {
    
    
		fmt.Println(err)
	}

	//读出
	result := &myStruct{
    
    }
	err = rdb.Get(ctx, "project:users:{user_name}:struct").Scan(result)
	if err != nil {
    
    
		fmt.Println(err)
	}
	//fmt.Printf("get success: %+v\n", result)
	fmt.Println(data)

}

func RedisConnect() (rdb *redis.Client) {
    
    
	var myRedis redis.Options
	myRedis.Addr = "10.10.239.136:6379"
	myRedis.Password = ""
	myRedis.DB = 1
	rdb = redis.NewClient(&myRedis)
	return rdb
}

  • output
&{
    
    UserId:123 UserName:GuanYu Age:25}

Guess you like

Origin blog.csdn.net/xingzuo_1840/article/details/129277351