forked from gosexy/redis
-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
92 lines (60 loc) · 1.58 KB
/
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package main
import (
"log"
"menteslibres.net/gosexy/redis"
"strings"
"time"
)
var host = "127.0.0.1"
var port = uint(6379)
func spawnPublisher() error {
var err error
var publisher *redis.Client
publisher = redis.New()
err = publisher.Connect(host, port)
if err != nil {
log.Fatalf("Publisher failed to connect: %s\n", err.Error())
return err
}
log.Println("Publisher connected to redis-server.")
log.Println("Publishing some messages...")
publisher.Publish("channel", "Hello world!")
publisher.Publish("channel", "Do you know how to count?")
for i := 0; i < 3; i++ {
publisher.Publish("channel", i)
}
log.Printf("Closing publisher...\n")
publisher.Quit()
return nil
}
func spawnConsumer() error {
var err error
var consumer *redis.Client
consumer = redis.New()
err = consumer.ConnectNonBlock(host, port)
if err != nil {
log.Fatalf("Consumer failed to connect: %s\n", err.Error())
return err
}
log.Println("Consumer connected to redis-server.")
rec := make(chan []string)
log.Printf("Consumer will read exactly 6 messages before quitting.\n")
go consumer.Subscribe(rec, "channel")
var ls []string
for j := 0; j < 6; j++ {
ls = <-rec
log.Printf("Consumer received message[%d]: %v\n", j, strings.Join(ls, ", "))
}
log.Printf("Closing consumer...\n")
consumer.Quit()
return nil
}
func main() {
log.Printf("Spawning consumer into a go-routine...\n")
go spawnConsumer()
time.Sleep(time.Second * 2)
log.Printf("Spawning publisher into a go-routine...\n")
go spawnPublisher()
log.Printf("Waiting 3 secs...\n")
time.Sleep(time.Second * 3)
}