Skip to content

Instantly share code, notes, and snippets.

@nidhi-ag
Last active January 15, 2018 12:15
Show Gist options
  • Save nidhi-ag/dffad78e2c581fc59f1a3eb3e4635e94 to your computer and use it in GitHub Desktop.
Save nidhi-ag/dffad78e2c581fc59f1a3eb3e4635e94 to your computer and use it in GitHub Desktop.
Use ssdb as priority queue in GO
import (
"github.com/ssdb/gossdb/ssdb"
"strconv"
"time"
)
var priorityQueue *ssdb.Client
func pushToQueue() {
key := "xyz" // Some unique key
value := "abc"
score := strconv.Itoa(time.Now().Unix()) // keep timestamp as score or any other param as per requirement
/* Set key score */
var zset_err error
_, zset_err = priorityQueue.Do("zset", "queue-name", key, score)
if zset_err != nil {
return
}
/* Set key value */
var set_err error
_, set_err = priorityQueue.Do("set", key, value)
if set_err != nil {
return
}
}
// Listen to Queue
func listenToQueue () {
for {
for {
zpop_resp, zpop_err := priorityQueue.Do("zpop_front", "queue-name", 1)
if (zpop_err != nil) {
continue
}
// Priority Queue is empty
if (len(zpop_resp) == 1 && zpop_resp[0] == "ok") {
break
}
// Priority Queue returned failed status
if (len(zpop_resp) > 0 && zpop_resp[0] != "ok") {
continue
}
key := zpop_resp[1]
score_str := zpop_resp[2]
score, _ := strconv.ParseInt(score_str, 10, 64)
pop_resp, pop_err := priorityQueue.Do("get", key)
if (pop_err != nil) {
continue
}
// key not found in priority queue
if (len(pop_resp) > 0 && pop_resp[0] != "ok") {
continue
}
// use your data
}
// comes here when queue is empty
time.Sleep(time.Second * 2)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment