0 redis安裝請參考Redis備忘錄
1. golang操作redis
[root@master src]# pwd
/dongguangming/goworkspace/src
[root@master src]# mkdir redis
[root@master src]# cd redis/
[root@master redis]# touch redis-conn.go
編輯redis-conn.go檔案 ,即
[root@master redis]# vi redis-conn.go
鍵入以下程式碼
package main
import (
"fmt"
"github.com/go-redis/redis"
)
func main() {
fmt.Println("golang連線redis")
client := redis.NewClient(&redis.Options{
Addr: "192.168.8.200:6379",
Password: "123456",
DB: 0,
})
pong, err := client.Ping().Result()
fmt.Println(pong, err)
}
執行以上程式
[root@master redis]# go run redis-conn.go
golang連線redis
PONG <nil>
沒有報錯,表示連線redis成功!!!
1.1 新增鍵值
透過golang設定redis鍵值前,請先透過redis shell查詢下是否存在
[root@master ~]# redis-cli -h 192.168.8.200 -p 6379 -a 123456
Warning: Using a password with '-a' or '-u' option on the command line interface may not be safe.
192.168.8.200:6379> get golang
(nil)
很好鍵golang並不存在,返回nil
然後透過golang新增鍵值
package main
import (
"fmt"
"github.com/go-redis/redis"
)
func main() {
fmt.Println("golang連線redis")
client := redis.NewClient(&redis.Options{
Addr: "192.168.8.200:6379",
Password: "123456",
DB: 0,
})
pong, err := client.Ping().Result()
fmt.Println(pong, err)
//新增鍵值對
err = client.Set("golang", "yes", 0).Err()
if err != nil {
fmt.Println(err)
}
fmt.Println("鍵golang設定成功")
}
執行以上程式碼
[root@master redis]# go run redis-conn.go
golang連線redis
PONG <nil>
鍵golang設定成功
最後透過shell 檢視是否鍵是否設定成功
[root@master ~]# redis-cli -h 192.168.8.200 -p 6379 -a 123456
Warning: Using a password with '-a' or '-u' option on the command line interface may not be safe.
192.168.8.200:6379> get golang
(nil)
192.168.8.200:6379> get golang
"yes"
結果表明通golang設定的鍵golang的值為yes生效了!!!
1.2 獲取鍵值
獲取1.1設定的鍵值
import (
"fmt"
"github.com/go-redis/redis"
)
func main() {
fmt.Println("golang連線redis")
client := redis.NewClient(&redis.Options{
Addr: "192.168.8.200:6379",
Password: "123456",
DB: 0,
})
pong, err := client.Ping().Result()
fmt.Println(pong, err)
//新增鍵值對
err = client.Set("golang", "yes", 0).Err()
if err != nil {
fmt.Println(err)
}
fmt.Println("鍵golang設定成功")
//透過鍵查詢值
val, err := client.Get("golang").Result()
if err != nil {
fmt.Println(err)
}
fmt.Println("鍵golang的值為: ",val)
}
執行程式,輸出結果
[root@master redis]# go run redis-conn.go
golang連線redis
PONG <nil>
鍵golang設定成功
鍵golang的值為: yes
其他特性自行發揮!!!
後記: 已把我的電子書已上傳至github:github.com/dongguangming/dgm-colle...
後續會慢慢上傳其他資料。
參考:
A tour of the Redis stars www.compose.com/articles/a-tour-of...
Golang / Go Crash Course 08 | Using Redis as A Cache for our REST API m.youtube.com/watch?v=x5GGLrTuQCA
Go and Compose - Redis, RethinkDB, and RabbitMQ www.compose.com/articles/go-and-co...
本作品採用《CC 協議》,轉載必須註明作者和本文連結