Skip to content

Instantly share code, notes, and snippets.

@codemartial
Created April 17, 2018 05:53
Show Gist options
  • Save codemartial/625f1cbfe030f39451bb5785ccbf335e to your computer and use it in GitHub Desktop.
Save codemartial/625f1cbfe030f39451bb5785ccbf335e to your computer and use it in GitHub Desktop.
A worker pool for executing Redis commands using redigo
package main
import (
"fmt"
"github.com/gomodule/redigo/redis"
"sync"
"time"
)
var rconns *redis.Pool
func init() {
// SET UP REDIS POOL
rconns = &redis.Pool{
MaxIdle: 3,
MaxActive: 10,
IdleTimeout: time.Second,
Dial: func() (redis.Conn, error) {
c, err := redis.Dial("tcp", "localhost:6379")
if err != nil {
return nil, err
}
return c, err
},
TestOnBorrow: func(c redis.Conn, t time.Time) error {
_, err := c.Do("PING")
return err
},
}
}
var WorkersUnavailable error = fmt.Errorf("Workers Unavailable")
type WorkPool struct {
label string
queue chan Work
qtimeout time.Duration
workers []*Worker
rpool *redis.Pool
}
type Worker struct {
rpool *redis.Pool
queue chan Work
quit chan struct{}
}
type Work struct {
cmd Command
response chan Response
}
type Command struct {
cmd string
args []interface{}
}
type Response struct {
v interface{}
e error
}
// DoWork accepts a Redis command along with arguments and returns a Response
func (p *WorkPool) DoWork(cmd string, args ...interface{}) Response {
r := make(chan Response, 1)
if err := p.submit(Work{Command{cmd, args}, r}); err != nil {
return Response{nil, err}
}
return <-r
}
func (p *WorkPool) submit(w Work) error {
select {
case p.queue <- w:
return nil
case <-time.After(p.qtimeout):
return WorkersUnavailable
}
}
// Shutdown terminates all workers in the pool
func (p *WorkPool) Shutdown() {
for i, w := range p.workers {
fmt.Println("Shutting down worker", i)
w.quit <- struct{}{}
}
}
// NewWorkPool initialises and launches a new worker pool\
// label is a string identifier for the pool
// maxBacklog is the avg. number of outstanding requests per worker allowed in queue
// workers is the number of redis worker routines available
// rpool is the Redis Connection pool shared between all workers.
// Number of active connections in rpool should not be more than number of workers
func NewWorkPool(label string, maxBacklog, workers int, rpool *redis.Pool) *WorkPool {
wq := make(chan Work, maxBacklog*workers)
wlist := make([]*Worker, 0, workers)
for i := 0; i < workers; i++ {
quit := make(chan struct{}, 1)
w := Worker{rpool, wq, quit}
go w.Start()
wlist = append(wlist, &w)
//wlist[i] = &w
}
return &WorkPool{
label: label,
queue: wq,
qtimeout: time.Millisecond * 20,
workers: wlist,
rpool: rpool}
}
func (w Worker) Start() {
defer func() {
if p := recover(); p != nil {
w.Start() // Restart worker on panic
}
}()
for {
select {
case <-w.quit:
return
case work := <-w.queue:
w.process(work)
}
}
}
func (w Worker) process(work Work) {
conn := w.rpool.Get()
defer conn.Close()
r, e := conn.Do(work.cmd.cmd, work.cmd.args...)
work.response <- Response{r, e}
}
func main() {
wp := NewWorkPool("demo", 2, 10, rconns)
var wg sync.WaitGroup
wg.Add(200)
for i := 0; i < 100; i++ {
go func(i int) {
defer wg.Done()
resp := wp.DoWork("SET", i, i)
if resp.e != nil {
fmt.Println("Error in SET", i, resp.e)
}
}(i)
go func(i int) {
defer wg.Done()
resp := wp.DoWork("GET", i)
val, err := redis.String(resp.v, resp.e)
if err == nil {
fmt.Println("GET", i, "=", val)
} else {
fmt.Println("GET", i, "error:", err)
}
}(i)
}
wg.Wait()
wp.Shutdown()
}
/*
The MIT License
Copyright (c) 2018 Tahir Hashmi
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment