一、話不多說
package main
import (
"fmt"
"github.com/go-redis/redis"
"os"
"strings"
)
var DbRedis *redis.Client
var RedisPassword string
func getNonBlankStrFromEnv(key string) string {
v := strings.TrimSpace(os.Getenv(key))
if len(v) == 0 {
panic(fmt.Sprintf("missing env[%s]", key))
}
return v
}
// 1, 鏈接數(shù)據(jù)庫
func OpenDbRedis(){
var err error
DbRedis = redis.NewClient(
&redis.Options{
Addr: "localhost:6379",
Password: RedisPassword,
DB: 0,
})
pong,err := DbRedis.Ping().Result()
if err!=nil {
fmt.Printf("ping error[%s]\n", err.Error())
_ = fmt.Errorf(err.Error())
}
fmt.Printf("ping result: %s\n", pong) // 期待:PONG
}
func CloseDbRedis(){
_ = DbRedis.Close()
}
// 2派昧,發(fā)布訂閱
func Subscribe(channel string) *redis.PubSub {
var err error
fmt.Printf("Will subscribe channel [%v]\n", channel)
pubSub := DbRedis.Subscribe(channel)
_, err = pubSub.Receive()
if err != nil {
fmt.Printf("try subscribe channel[test_channel] error[%s]\n",
err.Error())
return nil
}
return pubSub
}
func CloseSubscribe(pubSub *redis.PubSub){
_ = pubSub.Close()
}
func Publish(channel string, msg string) error {
var err error
fmt.Printf("Will publish message [%v] to channel [%v]\n", msg, channel)
err = DbRedis.Publish(channel, msg).Err()
if err != nil {
fmt.Printf("try publish message to channel[test_channel] error[%s]\n",
err.Error())
return err
}
return nil
}
func HandlerSubscribeMessage(pubSub *redis.PubSub) {
ch := pubSub.Channel()
for {
msg, ok := <- ch
if !ok{
fmt.Printf("通道接收消息出錯!")
break
}
fmt.Printf("Recv message[%v] from channel[%v]\n", msg.Payload, msg.Channel)
}
}
func main() {
RedisPassword = getNonBlankStrFromEnv("DOCKER_REDIS_PASS")
OpenDbRedis()
defer CloseDbRedis()
// 消費消息
// 1.1, 訂閱 sanhuoRedis
sanhuoSub := Subscribe("sanhuoRedis")
defer CloseSubscribe(sanhuoSub)
// 1.2, 訂閱 消息接收處理
go HandlerSubscribeMessage(sanhuoSub)
// 生產(chǎn)消息
// 2.1 發(fā)布 toSanhuoRedis
toSanhuoReids := "toSanhuoRedis"
// 2.2 發(fā)布 消息 從命令行讀入消息
var msg string
for{
_, _ = fmt.Scanln(&msg)
_ = Publish(toSanhuoReids, msg)
}
}
二、運行redis
參考我上一篇文章《20年第45周:docker安裝/部署/使用redis (Redis 配置)》