master #19
@ -1,11 +1,9 @@
|
||||
package routers
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
tasks "queues-go/app/storage/mongo/collections"
|
||||
"queues-go/app/storage/redis"
|
||||
"time"
|
||||
"sync"
|
||||
)
|
||||
|
||||
type TaskResponse struct {
|
||||
@ -18,17 +16,16 @@ type TakeResponse struct {
|
||||
Task *TaskResponse `json:"task"`
|
||||
}
|
||||
|
||||
var MutexMap map[string]*sync.Mutex
|
||||
|
||||
func Take(r *http.Request) (interface{}, int) {
|
||||
queue := r.Header.Get("queue")
|
||||
mutex := redis.Sync.NewMutex(fmt.Sprintf("lock_queues_%s", queue))
|
||||
for {
|
||||
err := mutex.Lock()
|
||||
if err != nil {
|
||||
time.Sleep(time.Millisecond * 5)
|
||||
} else {
|
||||
break
|
||||
}
|
||||
mutex, ok := MutexMap[queue]
|
||||
if !ok {
|
||||
mutex = &sync.Mutex{}
|
||||
MutexMap[queue] = mutex
|
||||
}
|
||||
mutex.Lock()
|
||||
task, err := tasks.Take(queue)
|
||||
mutex.Unlock()
|
||||
if err != nil {
|
||||
|
4
main.go
4
main.go
@ -6,7 +6,7 @@ import (
|
||||
"net/http"
|
||||
"queues-go/app/routers"
|
||||
client "queues-go/app/storage/mongo"
|
||||
"queues-go/app/storage/redis"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
@ -31,7 +31,7 @@ func handlerWrapper(f func(*http.Request) (interface{}, int)) func(http.Response
|
||||
|
||||
func main() {
|
||||
client.Connect()
|
||||
redis.Connect()
|
||||
routers.MutexMap = make(map[string]*sync.Mutex)
|
||||
http.HandleFunc("/api/v1/take", handlerWrapper(routers.Take))
|
||||
http.HandleFunc("/api/v1/finish", handlerWrapper(routers.Finish))
|
||||
http.HandleFunc("/api/v1/put", handlerWrapper(routers.Put))
|
||||
|
Loading…
Reference in New Issue
Block a user