I need the a number of requests of a identical API for a selected customers to be executed sequentially. If 3 requests of identical API for a customers comes collectively then the first request must be processed instantly and the 2nd and third request must be placed on wait. 2nd request ought to begin execution solely after the completion of 1st request. third request ought to begin execution solely after the completion of 2nd request and so forth.
For instance, person making 3 scan and pay again to again
Request R1 POST create-txn/user001 {quantity : 50}
Request R2 POST create-txn/user001 {quantity : 100}
Request R3 POST create-txn/user001 {quantity : 10}
In Laravel we deal with like:
use IlluminateSupportFacadesCache;
use IlluminateContractsCacheLockTimeoutException;
perform createTxn()
{
$lock = Cache::lock("create_txn_" . $postdata['user_id'] . '_lock', 30);
strive {
$lock->block(5); // Lock acquired after ready most of 5 seconds..
// code for creating txn
} catch (LockTimeoutException $e) {
throw new ServiceErrorException('create txn api LockTimeout Exception', 105);
} lastly {
optionally available($lock)->launch();
}
}
I need the Go equal code for the above logic. I attempted bsm/redislock and mutex however I didn’t get the anticipated end result. Want instance in Go.
I attempted under code however didnt work additionally
package deal fundamental
import (
"context"
"fmt"
"time"
"github.com/bsm/redislock"
"github.com/redis/go-redis/v9"
"github.com/gin-gonic/gin"
)
func fundamental() {
router := gin.Default()
router.GET("/take a look at/:id", getTestByID)
router.Run("localhost:8080")
}
func getTestByID(c *gin.Context) {
id := c.Param("id")
lockKey := "test_"+id;
fmt.Println("recieved", id, lockKey)
// Hook up with redis.
consumer := redis.NewClient(&redis.Choices{
Community: "tcp",
Addr: "127.0.0.1:6379",
DB: 9,
})
defer consumer.Shut()
// Create a brand new lock consumer.
locker := redislock.New(consumer)
ctx := context.Background()
// Attempt to get hold of lock.
lock, _ := locker.Acquire(ctx, lockKey, 5*time.Second, nil)
// Remember to defer Launch.
defer lock.Launch(ctx)
fmt.Println("I've a lock!")
// Sleep and examine the remaining TTL.
time.Sleep(4*time.Second)
fmt.Println(5*time.Second)
//lock.Launch(ctx)
}
When referred to as localhost:8080/take a look at/4 a number of occasions first print will be executed instantly for all of the calls however 2nd and third print statements must be delayed because of lock for the 2nd request onwards