【Golang】go-redis 连接Redis

Posted by 西维蜀黍 on 2020-03-22, Last Modified on 2021-09-21

go-redis

client := redis.NewClient(&redis.Options{
	Addr:     "localhost:6379",
	Password: "", // password
	DB:       0,  // use default DB
})

pong, err := client.Ping().Result()
fmt.Println(pong, err)
var id uint64 = 64
rule := &Rule{
	Id: &id,
}
b, err := json.Marshal(rule)
if err != nil {
	panic(err)
}

fmt.Println(client.Set("cache1", b, 0).Result())

a, err := client.Get("cache1").Result()

var item myProto.CompositeLogisticPromotionRule
err = json.Unmarshal([]byte(a), &item)
if err != nil {
	panic(err)
}
fmt.Println(item.Id)

SADD的区别

package main

import (
	"github.com/go-redis/redis/v7"
)

func main() {
	client := redis.NewClient(&redis.Options{
		Addr:     "localhost:6379",
		Password: "", // password
		DB:       0,  // use default DB
	})

	client.SAdd("aaa", nil)
  
  var bbb []string 
  client.SAdd("bbb", bbb)
  
	client.SAdd("ccc", []string{})
  
	a := make([]string, 0)
	client.SAdd("ddd", a)
}

Output

127.0.0.1:6379> SMEMBERS aaa
1) ""
127.0.0.1:6379> SMEMBERS bbb
(empty array)
127.0.0.1:6379> SMEMBERS ccc
(empty array)
127.0.0.1:6379> SMEMBERS ddd
(empty array)

Reference