Ask Your Question
3

Can Java Spring achieve distributed locking with Redis while allowing different timeout values for each lock?

asked 2023-05-01 20:55:55 +0000

david gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2023-05-01 21:23:01 +0000

bukephalos gravatar image

Yes, Java Spring can achieve distributed locking with Redis while allowing different timeout values for each lock. The Redisson library provides a distributed locking mechanism for Java that can be used with Spring applications. Redisson supports multiple lock types, including supports with different timeout values.

Here's an example of how to create a lock with a custom timeout using Redisson:

// Create Redisson client and RedissonLock instance
Config config = new Config();
config.useSingleServer().setAddress("redis://localhost:6379");
RedissonClient redissonClient = Redisson.create(config);
RedissonLock lock = redissonClient.getLock("myLock");

// Acquire lock with custom timeout
boolean locked = lock.tryLock(10, TimeUnit.SECONDS);
if (locked) {
    try {
        // Code that requires exclusive access to the resource
    } finally {
        lock.unlock();
    }
}

In this example, the tryLock method is used to acquire the lock with a timeout of 10 seconds. If the lock cannot be acquired within that time, the method returns false, allowing the code to handle the failure condition appropriately. By default, Redisson locks have a timeout of 30 seconds, but this can be customized as needed.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-05-01 20:55:55 +0000

Seen: 10 times

Last updated: May 01 '23