zookeeper分布式锁

 

 

 

package cn.zh.distributedlock.controller;

import cn.zh.distributedlock.service.OrderService;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {
     @Autowired
    private OrderService orderService;
     @Value("${server.port}")
     private String port;
     @Autowired
     private CuratorFramework curatorFramework;

     @PostMapping("/stock/deduct")
     public Object reduceStock(Integer id) throws Exception {
         InterProcessMutex  interProcessMutex=new InterProcessMutex(curatorFramework,"/product_"+id);
         try {
             interProcessMutex.acquire();
             orderService.reduceStock(id);
         } catch (Exception e) {
            if(e instanceof  RuntimeException){
                throw e;
            }
         }finally{
             interProcessMutex.release();
         }

         return "ok:" + port;

     }

}

 

posted on 2021-08-23 21:44  小破孩楼主  阅读(43)  评论(0编辑  收藏  举报