Go语言实现Redis的发布订阅功能

之前学习了使用redigo连接操作redis,今天测试一下redigo的发布订阅功能.

本文github: https://github.com/zboyco/go-test/blob/master/redigo-sub/main.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
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
package main

import (
"fmt"
"log"

"github.com/gomodule/redigo/redis"
)

func main() {
log.Println("测试redis发布订阅")

conn, err := redis.Dial("tcp", "192.168.2.99:6379")
checkErr(err)
defer conn.Close()

// 开启三个goroutine订阅redis
go subScribe()
go subScribe()
go subScribe()

// 从控制台获取内容发布到redis
for {
var s string
fmt.Scanln(&s)
_, err := conn.Do("PUBLISH", "testRoom", s)
if err != nil {
fmt.Println("pub err: ", err)
return
}
}
}

// 订阅
func subScribe() {
conn, err := redis.Dial("tcp", "192.168.2.99:6379")
checkErr(err)
defer conn.Close()

psc := redis.PubSubConn{
Conn: conn,
}
psc.Subscribe("testRoom")
for {
switch v := psc.Receive().(type) {
case redis.Message:
log.Printf("%s: message: %s\n", v.Channel, v.Data)
case redis.Subscription:
log.Printf("%s: %s %d\n", v.Channel, v.Kind, v.Count)
case error:
log.Fatalln(v)
}
}
}

// checkErr 错误检查
func checkErr(err error) {
if err != nil {
log.Fatalln(err)
}
}

效果如下: