一、话不多说
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, 链接数据库
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,发布订阅
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)
// 生产消息
// 2.1 发布 toSanhuoRedis
toSanhuoReids := "toSanhuoRedis"
// 2.2 发布 消息 从命令行读入消息
var msg string
for{
_, _ = fmt.Scanln(&msg)
_ = Publish(toSanhuoReids, msg)
}
}
二、运行redis
参考我上一篇文章《20年第45周:docker安装/部署/使用redis (Redis 配置)》
有疑问加站长微信联系(非本文作者)