import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.stereotype.Component;
import java.util.concurrent.TimeUnit;
@Component
public class RedisLockTest {
public static int count = 0;
public static void main(String[] args) {
Config config = new Config();
config.useSingleServer().setAddress("redis://xxx.xxx.x.xxx:6379").setDatabase(0);
RedissonClient redisson = Redisson.create(config);
for (int i = 0; i < 1000; i++) {
new Thread(new Runnable() {
@Override
public void run() {
// 1.获取锁对象实例
RLock rLock = redisson.getLock("lockKey:aaaaaaaaaaaaaaaaaaaaa");
try {
/**
* 2.尝试获取锁
* waitTimeout 尝试获取锁的最大等待时间,超过这个值,则认为获取锁失败
* leaseTime 锁的持有时间,超过这个时间锁会自动失效(值应设置为大于业务处理的时间,确保在锁有效期内业务能处理完)
*/
boolean res = rLock.tryLock(10, 10, TimeUnit.SECONDS);
if (res) {
try {
Thread.sleep(1);
} catch (Exception e) {
}
count++;
System.out.println("运行结果:count=" + count);
}
} catch (Exception e) {
throw new RuntimeException("aquire lock fail");
} finally {
//无论如何, 最后都要解锁
rLock.unlock();
}
}
}).start();
}
}
}
Redisson分布式锁简单使用
最新推荐文章于 2024-03-18 18:27:17 发布