goRedisDLM/worker/rpc.go

57 lines
1.1 KiB
Go

package worker
import (
"context"
"errors"
"fmt"
"goRedisDLM/engine"
"goRedisDLM/redisLock"
"log"
"math/rand"
"strconv"
"time"
"github.com/go-redis/redis/v8"
"github.com/google/uuid"
)
type Inventory struct {
Client *redis.Client
}
func (i *Inventory) Work(request engine.Request, response *engine.Response) error {
value := uuid.New()
log.Printf("uuid: %s, lock key: %s\n", value.String(), request.Dlock)
lock := redisLock.CreateRedisLock(i.Client, context.Background(), request.Dlock, value.String(), 300)
lock.Lock()
time.Sleep(time.Duration(rand.Int31n(100)) * time.Millisecond)
get := i.Client.Get(context.Background(), "inventory")
log.Printf("%s\n", get)
inventory, err := strconv.Atoi(get.Val())
if err != nil {
goto Error
}
inventory = inventory - 1
if inventory >= 0 {
i.Client.Set(context.Background(), "inventory", fmt.Sprintf("%d", inventory), redis.KeepTTL)
} else {
log.Printf("error DLock error :%d\n", inventory)
err = errors.New("inventory err")
goto Error
}
lock.Unlock()
response.Id = request.Id
return nil
Error:
lock.Unlock()
return err
}