forked from reugn/go-streams
/
redis.go
110 lines (93 loc) · 2.22 KB
/
redis.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
package redis
import (
"context"
"log"
"github.com/go-redis/redis"
"github.com/wangjuelong/go-streams"
"github.com/wangjuelong/go-streams/flow"
)
// RedisSource is a Redis Pub/Sub Source
type RedisSource struct {
ctx context.Context
redisdb *redis.Client
channel string
out chan interface{}
}
// NewRedisSource returns a new RedisSource instance
func NewRedisSource(ctx context.Context, config *redis.Options, channel string) (*RedisSource, error) {
redisdb := redis.NewClient(config)
pubsub := redisdb.Subscribe(channel)
// Wait for a confirmation that subscription is created before publishing anything
_, err := pubsub.Receive()
if err != nil {
return nil, err
}
source := &RedisSource{
ctx: ctx,
redisdb: redisdb,
channel: channel,
out: make(chan interface{}),
}
go source.init(pubsub.Channel())
return source, nil
}
// init starts the main loop
func (rs *RedisSource) init(ch <-chan *redis.Message) {
loop:
for {
select {
case <-rs.ctx.Done():
break loop
case msg := <-ch:
rs.out <- msg
}
}
log.Printf("Closing redis consumer")
close(rs.out)
rs.redisdb.Close()
}
// Via streams data through the given flow
func (rs *RedisSource) Via(_flow streams.Flow) streams.Flow {
flow.DoStream(rs, _flow)
return _flow
}
// Out returns an output channel for sending data
func (rs *RedisSource) Out() <-chan interface{} {
return rs.out
}
// RedisSink is a Redis Pub/Sub Sink
type RedisSink struct {
redisdb *redis.Client
channel string
in chan interface{}
}
// NewRedisSink returns a new RedisSink instance
func NewRedisSink(config *redis.Options, channel string) *RedisSink {
sink := &RedisSink{
redis.NewClient(config),
channel,
make(chan interface{}),
}
go sink.init()
return sink
}
// init starts the main loop
func (rs *RedisSink) init() {
for msg := range rs.in {
switch m := msg.(type) {
case string:
err := rs.redisdb.Publish(rs.channel, m).Err()
if err != nil {
log.Printf("redisdb.Publish failed with: %s", err)
}
default:
log.Printf("Unsupported message type %v", m)
}
}
log.Printf("Closing redis producer")
rs.redisdb.Close()
}
// In returns an input channel for receiving data
func (rs *RedisSink) In() chan<- interface{} {
return rs.in
}