Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Atomic Locks in Laravel?

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?

like image 858
M. Ivashchuk Avatar asked Aug 01 '19 19:08

M. Ivashchuk


People also ask

What are atomic locks in Laravel?

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.

How do I enable caching in Laravel?

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.

How does Laravel manage cache?

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.


1 Answers

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.

like image 100
Kirill Timofejev Avatar answered Oct 24 '22 12:10

Kirill Timofejev