分布式锁2-Zookeeper分布式锁实战

Zookeeper分布式锁实战

使用curator操作Zookeeper进行实战;
curator是什么:Apache Curator包含一套高级API框架和工具类,它 是Apache ZooKeeper 的Java 客户端库。

准备

  1. pom文件引入curtor依赖和zookeeper依赖
<!--curator-->
<dependency>
    <groupId>org.apache.curator</groupId>
    <artifactId>curator-recipes</artifactId>
    <version>5.6.0</version>
</dependency>

<dependency>
    <groupId>org.apache.curator</groupId>
    <artifactId>curator-framework</artifactId>
    <version>5.6.0</version>
    </dependency>
<!--zookeeper-->
<dependency>
    <groupId>org.apache.zookeeper</groupId>
    <artifactId>zookeeper</artifactId>
    <version>3.9.2</version>
</dependency>
  1. yml配置
#zookeeper
curator:
  connectString: localhost:2181
  retryCount: 5
  elapsedTimeMs: 5000
  sessionTimeOutMs: 60000
  connectionTimeOutMs: 5000
		
	
  1. 配置类
/**
 * @Author 
 * @Date 2024/5/19 19:45
 */
@Data
@Component
@ConfigurationProperties(prefix = "curator")
public class WrapperZK {

    /** 重试次数*/
    private int retryCount;

    /** 重试间隔时间*/
    private int elapsedTimeMs;

    /** 连接地址*/
    private String connectString;

    /** session超时时间*/
    private int sessionTimeOutMs;

    /** 连接超时时间*/
    private int connectionTimeOutMs;
}
@Configuration
public class ZookeeperConfig {

    @Autowired
    private WrapperZK wrapperZK;

    @Bean
    public CuratorFramework curatorFramework(){
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(wrapperZK.getElapsedTimeMs(),wrapperZK.getRetryCount());
        CuratorFramework client = CuratorFrameworkFactory.newClient(wrapperZK.getConnectString(), wrapperZK.getSessionTimeOutMs(), wrapperZK.getConnectionTimeOutMs(), retryPolicy);
        client.start();
        return client;
    }
}
  1. 使用
  @Autowired
    private CuratorFramework curatorFramework;
    static InterProcessLock zkLock;
        /** 使用zookeeper分布式锁 */
    @Transactional
    public void updateByZookeeperLock(Long id,int count){
        if(zkLock == null){
            zkLock = new InterProcessMutex(curatorFramework, "/locks");
        }
        try {
            boolean acquire = zkLock.acquire(10000, TimeUnit.MILLISECONDS);
            /** 加锁*/
            if(acquire){
                Product product = mapper.selectById(id);
                int newCont = product.getProductCount() - count;
                product.setProductCount(newCont);
                if(mapper.updateProduct(product) >0 ){
                    System.out.println("扣减成功!");
                }else {
                    throw new RuntimeException("扣减失败");
                }
            }else {
                System.out.println("拿不到分布式锁!");
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                /** 释放锁*/
                zkLock.release();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }
@RestController
@RequestMapping("/product")
public class ProductController {

    @Autowired
    private ProductService service;

    @GetMapping("buy/{id}/{count}")
    public void buy(@PathVariable long id,@PathVariable int count){
        service.updateByZookeeperLock(id,count);
    }
}

  1. 测试
    压测前:

在这里插入图片描述
压测:
在这里插入图片描述
压测后:

在这里插入图片描述
成功!

  • 10
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值