Skip to content
This repository was archived by the owner on Jul 15, 2023. It is now read-only.

Commit 209c616

Browse files
committed
changer to reconnect to redis when disconnected
1 parent b7f3d53 commit 209c616

File tree

2 files changed

+39
-4
lines changed

2 files changed

+39
-4
lines changed

api.go

Lines changed: 30 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -111,11 +111,39 @@ func (s *RoomAPIServer) Start() error {
111111
return err
112112
}
113113

114-
go s.subscribe(psc)
115-
116114
ctx, cancel := context.WithCancel(context.Background())
117115
defer cancel()
118116

117+
go func(ctx context.Context, psc redis.PubSubConn) {
118+
if err := s.subscribe(ctx, psc); err != nil {
119+
s.Logger.Println(err)
120+
}
121+
122+
for {
123+
select {
124+
case <-ctx.Done():
125+
return
126+
default:
127+
}
128+
129+
redisConn, err := redis.Dial("tcp", s.RedisHost)
130+
if err != nil {
131+
s.Logger.Println(err)
132+
break
133+
}
134+
135+
psc = redis.PubSubConn{Conn: redisConn}
136+
if err := psc.Subscribe(channelServer, channelRoom); err != nil {
137+
s.Logger.Println(err)
138+
break
139+
}
140+
141+
if err := s.subscribe(ctx, psc); err != nil {
142+
s.Logger.Println(err)
143+
}
144+
}
145+
}(ctx, psc)
146+
119147
go s.serverManager.DeleteUnhealthServerAtPeriodic(ctx, s.ServerDeadLine)
120148
go s.roomManager.DeleteDeadRoomAtPeriodic(ctx, s.RoomDeadLine)
121149

redis.go

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package api
22

33
import (
4+
"context"
45
"github.com/golang/protobuf/proto"
56
"github.com/gomodule/redigo/redis"
67
pb "github.com/iguagile/iguagile-room-proto/room"
@@ -18,8 +19,14 @@ const (
1819
unregisterRoomMessage
1920
)
2021

21-
func (s *RoomAPIServer) subscribe(psc redis.PubSubConn) {
22+
func (s *RoomAPIServer) subscribe(ctx context.Context, psc redis.PubSubConn) error {
2223
for {
24+
select {
25+
case <-ctx.Done():
26+
return nil
27+
default:
28+
}
29+
2330
switch v := psc.Receive().(type) {
2431
case redis.Message:
2532
if len(v.Data) <= 1 {
@@ -61,7 +68,7 @@ func (s *RoomAPIServer) subscribe(psc redis.PubSubConn) {
6168
case redis.Subscription:
6269
s.Logger.Printf("Subscribe %v %v %v\n", v.Channel, v.Kind, v.Count)
6370
case error:
64-
s.Logger.Println(v)
71+
return v
6572
}
6673
}
6774
}

0 commit comments

Comments
 (0)