redisson实现redis分布式锁

ゝ一世哀愁。 2023-05-29 13:21 83阅读 0赞

1、概述

  1. 12306、京东、淘宝等电商,高并发的场景比较多;举几个栗子:春运抢票,秒杀,双十一等场景,都存在对核心资源争抢,比如商品库存的争夺,如若控制不当,库存量有可能被减少成负值,与现实不符。
  2. Web应用,都是集群或分布式部署,在单实例上假同步加锁,根本无法实现分布式锁;如果考虑给数据库加锁,但对于超过1000次/s的高并发,数据库可能由行锁变成表锁,性能极具下降,显然不可取。然而,使用Redis的分布式锁,是个较好的策略。Redis官方推荐使用的Redisson,提供了分布式锁和相关服务。

2、pom.xml,引入jar

  1. <!-- https://mvnrepository.com/artifact/org.redisson/redisson -->
  2. <dependency>
  3. <groupId>org.redisson</groupId>
  4. <artifactId>redisson</artifactId>
  5. <version>3.11.5</version>
  6. </dependency>

3、代码实现案例

  1. package com.redis;
  2. import org.redisson.Redisson;
  3. import org.redisson.api.RLock;
  4. import org.redisson.api.RedissonClient;
  5. import org.redisson.config.Config;
  6. import java.util.concurrent.ExecutorService;
  7. import java.util.concurrent.Executors;
  8. import java.util.concurrent.TimeUnit;
  9. public class TestRedissonLock {
  10. //最长等待时长
  11. private static final Integer WAIT_TIME = 20;
  12. //自动解锁时长
  13. private static final Integer TIME_OUT = 10;
  14. private static final String IP = "192.168.30.153";
  15. private static final String PORT = "6379";
  16. private static final RedissonClient redissonClient;
  17. static {
  18. Config config = new Config();
  19. config.useSingleServer().setAddress(IP + ":" + PORT);
  20. redissonClient = Redisson.create(config);
  21. }
  22. public static void main(String[] args) {
  23. //获取锁,场景:集群或分布式模式下可以使用前缀+订单号作为锁的key
  24. String lockKey = "cloudLock";
  25. RLock rLock = redissonClient.getLock(lockKey);
  26. //所有线程共用一把锁
  27. new TestRedissonLock().testExecuteThreads(rLock);
  28. }
  29. public void testExecuteThreads(RLock cloudLock) {
  30. ExecutorService pool = Executors.newFixedThreadPool(10);
  31. for (int i = 1; i <= 10; i++) {
  32. pool.execute(new IThread("【Thread_" + i+"】", cloudLock));
  33. }
  34. }
  35. class IThread implements Runnable {
  36. private String threadName;
  37. private RLock rLock;
  38. public IThread(String threadName, RLock rLock) {
  39. this.threadName = threadName;
  40. this.rLock = rLock;
  41. }
  42. @Override
  43. public void run() {
  44. boolean lockFlag = false;
  45. System.out.println(threadName + "开始执行");
  46. try {
  47. lockFlag = rLock.tryLock(WAIT_TIME, TIME_OUT, TimeUnit.SECONDS);
  48. if (lockFlag) {
  49. System.out.println(this.threadName + "任务开始执行...");
  50. //任务执行2秒钟
  51. TimeUnit.SECONDS.sleep(2);
  52. System.out.println(this.threadName + "任务完美结束!");
  53. } else {
  54. System.out.println(threadName + "等待超时,执行失败!!!");
  55. }
  56. } catch (InterruptedException e) {
  57. e.printStackTrace();
  58. } finally {
  59. if (lockFlag) {
  60. rLock.unlock();
  61. }
  62. }
  63. }
  64. }
  65. }

发表评论

表情:
评论列表 (有 0 条评论,83人围观)

还没有评论,来说两句吧...

相关阅读