tile38/internal/endpoint/disque.go

83 lines
1.5 KiB
Go
Raw Permalink Normal View History

2016-09-12 05:01:24 +03:00
package endpoint
import (
"fmt"
"sync"
"time"
2018-08-14 03:05:30 +03:00
2018-10-29 15:00:54 +03:00
"github.com/gomodule/redigo/redis"
"github.com/tidwall/tile38/internal/log"
2016-09-12 05:01:24 +03:00
)
const disqueExpiresAfter = time.Second * 30
2016-09-12 05:01:24 +03:00
2018-04-19 19:25:39 +03:00
// DisqueConn is an endpoint connection
type DisqueConn struct {
2016-09-12 05:01:24 +03:00
mu sync.Mutex
ep Endpoint
ex bool
t time.Time
2018-08-14 03:05:30 +03:00
conn redis.Conn
2016-09-12 05:01:24 +03:00
}
2018-04-19 19:25:39 +03:00
func newDisqueConn(ep Endpoint) *DisqueConn {
return &DisqueConn{
2016-09-12 05:01:24 +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 *DisqueConn) Expired() bool {
2016-09-12 05:01:24 +03:00
conn.mu.Lock()
defer conn.mu.Unlock()
if !conn.ex {
if time.Since(conn.t) > disqueExpiresAfter {
2016-09-12 05:01:24 +03:00
if conn.conn != nil {
conn.close()
}
conn.ex = true
}
}
return conn.ex
}
2018-04-19 19:25:39 +03:00
func (conn *DisqueConn) close() {
2016-09-12 05:01:24 +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 *DisqueConn) Send(msg string) error {
2016-09-12 05:01:24 +03:00
conn.mu.Lock()
defer conn.mu.Unlock()
if conn.ex {
2017-02-10 15:27:02 +03:00
return errExpired
2016-09-12 05:01:24 +03:00
}
conn.t = time.Now()
if conn.conn == nil {
addr := fmt.Sprintf("%s:%d", conn.ep.Disque.Host, conn.ep.Disque.Port)
var err error
2018-08-14 03:05:30 +03:00
conn.conn, err = redis.Dial("tcp", addr)
2016-09-12 05:01:24 +03:00
if err != nil {
return err
}
}
2018-08-14 03:05:30 +03:00
var args []interface{}
args = append(args, conn.ep.Disque.QueueName, msg, 0)
2016-09-12 05:01:24 +03:00
if conn.ep.Disque.Options.Replicate > 0 {
2018-08-14 03:05:30 +03:00
args = append(args, "REPLICATE", conn.ep.Disque.Options.Replicate)
2016-09-12 05:01:24 +03:00
}
2018-08-14 03:05:30 +03:00
reply, err := redis.String(conn.conn.Do("ADDJOB", args...))
2016-09-12 05:01:24 +03:00
if err != nil {
conn.close()
return err
}
2018-08-14 03:05:30 +03:00
log.Debugf("Disque: ADDJOB '%s'", reply)
2016-09-12 05:01:24 +03:00
return nil
}