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