2017-01-13 18:01:34 +03:00
|
|
|
package endpoint
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"sync"
|
|
|
|
"time"
|
2018-08-14 03:05:30 +03:00
|
|
|
|
|
|
|
"github.com/garyburd/redigo/redis"
|
2017-01-13 18:01:34 +03:00
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
|
|
|
redisExpiresAfter = time.Second * 30
|
|
|
|
)
|
|
|
|
|
2018-04-19 19:25:39 +03:00
|
|
|
// RedisConn is an endpoint connection
|
|
|
|
type RedisConn struct {
|
2017-01-13 18:01:34 +03:00
|
|
|
mu sync.Mutex
|
|
|
|
ep Endpoint
|
|
|
|
ex bool
|
|
|
|
t time.Time
|
2018-08-14 03:05:30 +03:00
|
|
|
conn redis.Conn
|
2017-01-13 18:01:34 +03:00
|
|
|
}
|
|
|
|
|
2018-04-19 19:25:39 +03:00
|
|
|
func newRedisConn(ep Endpoint) *RedisConn {
|
|
|
|
return &RedisConn{
|
2017-01-13 18:01:34 +03:00
|
|
|
ep: ep,
|
|
|
|
t: time.Now(),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-04-19 19:25:39 +03:00
|
|
|
// Expired returns true if the connection has expired
|
|
|
|
func (conn *RedisConn) Expired() bool {
|
2017-01-13 18:01:34 +03:00
|
|
|
conn.mu.Lock()
|
|
|
|
defer conn.mu.Unlock()
|
|
|
|
if !conn.ex {
|
|
|
|
if time.Now().Sub(conn.t) > redisExpiresAfter {
|
|
|
|
if conn.conn != nil {
|
|
|
|
conn.close()
|
|
|
|
}
|
|
|
|
conn.ex = true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return conn.ex
|
|
|
|
}
|
|
|
|
|
2018-04-19 19:25:39 +03:00
|
|
|
func (conn *RedisConn) close() {
|
2017-01-13 18:01:34 +03:00
|
|
|
if conn.conn != nil {
|
|
|
|
conn.conn.Close()
|
|
|
|
conn.conn = nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-04-19 19:25:39 +03:00
|
|
|
// Send sends a message
|
|
|
|
func (conn *RedisConn) Send(msg string) error {
|
2017-01-13 18:01:34 +03:00
|
|
|
conn.mu.Lock()
|
|
|
|
defer conn.mu.Unlock()
|
|
|
|
|
|
|
|
if conn.ex {
|
2017-02-10 15:27:02 +03:00
|
|
|
return errExpired
|
2017-01-13 18:01:34 +03:00
|
|
|
}
|
|
|
|
conn.t = time.Now()
|
|
|
|
if conn.conn == nil {
|
|
|
|
addr := fmt.Sprintf("%s:%d", conn.ep.Redis.Host, conn.ep.Redis.Port)
|
|
|
|
var err error
|
2018-08-14 03:05:30 +03:00
|
|
|
conn.conn, err = redis.Dial("tcp", addr)
|
2017-01-13 18:01:34 +03:00
|
|
|
if err != nil {
|
2018-08-14 03:05:30 +03:00
|
|
|
conn.close()
|
2017-01-13 18:01:34 +03:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
2018-08-14 03:05:30 +03:00
|
|
|
_, err := redis.Int(conn.conn.Do("PUBLISH", conn.ep.Redis.Channel, msg))
|
2017-01-13 18:01:34 +03:00
|
|
|
if err != nil {
|
|
|
|
conn.close()
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|