GoLang: Simple PUB/SUB implementation using REDIS
PUB/SUB is an important concept when we want to alert all the connected application(Subscriber) in case of any event where Publisher emits the message to them.
To test the pub/sub using REDIS use below command
Make sure that you have REDIS installed in our system/server where you want to connect. Enter below command to connect to REDIS command line interface on multiple terminal so that one can act as subscriber and other can act as publisher.
redis-cli
To Publish the message the on a Channel
PUBLISH example testExplanation:
example : it is a channel where we want to publish the message
test : is the message which we want to publish through the channel
To Subscribe the message from the Channel
SUBSCRIBE exampleExplanation:
example : it is a channel where we want to publish the message
Step 1: Importing the Library
import "github.com/gomodule/redigo/redis"
Step 2: Establishing the Connection
c, err := redis.Dial("tcp", "localhost:6379")
if err != nil {
log.Println(err)
}
Step 3: Publish the message
c.Do("PUBLISH", "example", "hello "+time.Now().String())
Step 4: Subscribe the message
psc := redis.PubSubConn{Conn: c}
psc.Subscribe("example")
for {
switch v := psc.Receive().(type) {
case redis.Message:
fmt.Printf("%s: message: %s\n", v.Channel, v.Data)
case redis.Subscription:
fmt.Printf("%s: %s %d\n", v.Channel, v.Kind, v.Count)
case error:
fmt.Println(v)
}
}
Working Code for PUB/SUB
https://gist.github.com/irshadhasmat/abdd99a0126c1971a6bbe3b68a9f37ef