I have some set of entities and users. The entity can be processed only by one user. So if the user did GET request on this entity it will be "connected" to him in some time.
I found that I can use cache for this thing, but the explanation about Atomic locks isn't clear for me, could someone help with a simple example that demonstrates using?
Atomic locks is a mechanism provided by Laravel to manage race conditions and concurrency. If your application uses the redis cache driver, you must be careful not to use the same cache connection for locks as you do for your caching.
To enable Laravel caching services, first use the Illuminate\Contracts\Cache\Factory and Illuminate\Contracts\Cache\Repository, as they provide access to the Laravel caching services. The Factory contract gives access to all the cache drivers of your application.
Your application's cache configuration file is located at config/cache.php . In this file, you may specify which cache driver you would like to be used by default throughout your application. Laravel supports popular caching backends like Memcached, Redis, DynamoDB, and relational databases out of the box.
This is what I have implemented recently:
try {
// Trying to acquiring lock.
// If lock is already acquired, waiting 5 seconds to try again.
Cache::lock($key)->block(5);
} catch (LockTimeoutException $e) {
// Unable to acquire lock, can't cache the token
return;
}
// Lock acquired, caching the token
Cache::put($key, $token, 1);
To test this we've used 2 devices logged in as the same user and making the same request at the same time. Hope this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With