Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

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.