Last active
December 12, 2018 12:36
-
-
Save AmirSoleimani/0296d677464f80c6722f6fb022f14b1d to your computer and use it in GitHub Desktop.
Redis Pub/Sub
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"github.com/go-redis/redis" | |
"github.com/sirupsen/logrus" | |
) | |
func main() { | |
// create redis connection | |
logrus.Infoln("Redis connection init...") | |
client := redis.NewClient(&redis.Options{ | |
Addr: "localhost:6379", | |
Password: "", // no password set | |
DB: 0, // use default DB | |
}) | |
_, err := client.Ping().Result() | |
if err != nil { | |
panic(err) // ;) | |
} | |
// subscribe `delivery` channel | |
pubsub := client.Subscribe("foodDelivery") | |
_, err = pubsub.Receive() | |
if err != nil { | |
panic(err) | |
} | |
// Go channel which receives messages. | |
ch := pubsub.Channel() | |
// Consume messages. | |
select { | |
case msg := <-ch: | |
fmt.Println(msg.Channel, "-> Heyy,", msg.Payload) | |
pubsub.Close() | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"time" | |
"github.com/go-redis/redis" | |
"github.com/sirupsen/logrus" | |
) | |
func main() { | |
// create redis connection | |
logrus.Infoln("Redis connection init...") | |
client := redis.NewClient(&redis.Options{ | |
Addr: "localhost:6379", | |
Password: "", // no password set | |
DB: 0, // use default DB | |
}) | |
_, err := client.Ping().Result() | |
if err != nil { | |
panic(err) // ;) | |
} | |
// Publish a message after 2 Seconds -> `delivery` channel (demo) | |
time.AfterFunc(2*time.Second, func() { | |
err = client.Publish("foodDelivery", "food is ready").Err() | |
if err != nil { | |
panic(err) | |
} | |
}) | |
// demo... | |
time.Sleep(3 * time.Second) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment