Golang 的 Redis 数据库链接及使用

go-redis

推荐使用 go-redis 进行链接管理.

参考文档: https://godoc.org/github.com/go-redis/redis

Demo 代码

Makefile

1
2
3
4
5
6
7
8
Proj=github.com/NICKNAME/redis-demo

all:
go build ${PROJ}
./redis-demo

test:
go test

chain/block.go

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package chain

import (
"fmt"
"reflect"
"github.com/goinggo/mapstructure"
)

type Block struct {
TxHash string `json:"txhash"`
Id string `json:"id"`
Phone string `json:"phone"`
}

func (block *Block) GetTxHash() (txHash string){
fmt.Println("block chain: ", block.TxHash)

return block.TxHash
}

func (block Block) ToMap() map[string]interface{} {
t := reflect.TypeOf(block)
v := reflect.ValueOf(block)

var data = make(map[string]interface{})
for i := 0; i < t.NumField(); i++ {
data[t.Field(i).Name] = v.Field(i).Interface()
}
return data
}

func (block *Block) FromMap(mapIns map[string]string) {
if err := mapstructure.Decode(mapIns, block); err != nil {
fmt.Println("Block From Map Failed", err)
}
}

connect.go 链接 demo

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package main

import (
"fmt"
"github.com/NICKNAME/redis-demo/chain"
"github.com/go-redis/redis"
)

func errPanic(err error) {
if err != nil {
fmt.Println("Error:", err)
panic(err)
}
}

func errRecover() {
if r := recover(); r != nil {
fmt.Println("Recover From Error", r)
}
}

func stringHandler(client *redis.Client) {
// write
err := client.Set("s_u:123", "ono", 0).Err()
errPanic(err)

// read existing string
name, err := client.Get("s_u:123").Result()
fmt.Println("Get Name:", name, err)
if err == redis.Nil {
fmt.Println("Key Doesn't Exist")
} else if err != nil {
errPanic(err)
}
fmt.Println("Name:", name)

// read empty string
age, err := client.Get("s_a:123").Result()
fmt.Println("Get Age:", age, err)
if err == redis.Nil {
fmt.Println("Key Doesn't Exist")
} else if err != nil {
errPanic(err)
}
fmt.Println("Age:", age)
}

func hashHandler(client *redis.Client) {
block := &chain.Block{"0x123", "123", "10086"}
cmd := client.HMSet("h_b:123", block.ToMap())
fmt.Println("HSet Ret Status:", cmd)

item := client.HGetAll("h_b:123")
fmt.Println("HGet Ret Data:", item)
fmt.Println("SSMC: ", item.Args(), item.Err(), item.Name(), item.String(), item.Val())
block.FromMap(item.Val())
fmt.Println("After Type Cast:", block)

}

func main() {
client := redis.NewClient(&redis.Options{
Addr : "localhost:6379",
Password : "",
DB : 1,
})

ping, err := client.Ping().Result()
errPanic(err)
fmt.Println("Connection Ping Status:", ping)

//stringHandler(client)
hashHandler(client)
}
Donate - Support to make this site better.
捐助 - 支持我让我做得更好.