12345678910111213141516171819202122232425262728293031323334353637383940414243 |
- package controller;
- import org.apache.curator.RetryPolicy;
- import org.apache.curator.framework.CuratorFramework;
- import org.apache.curator.framework.CuratorFrameworkFactory;
- import org.apache.curator.framework.recipes.locks.InterProcessMutex;
- import org.apache.curator.retry.ExponentialBackoffRetry;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.GetMapping;
- import org.springframework.web.bind.annotation.ResponseBody;
- import service.ProductService;
- @Controller
- public class ProductAction {
- @Autowired
- private ProductService productService;
- private static String connectString = "192.168.48.128:2181,192.168.48.129:2181,192.168.48.130:2181";
- @GetMapping("/product/reduce")
- @ResponseBody
- public Object reduce(int id) throws Exception {
- RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000,3);
- CuratorFramework client = CuratorFrameworkFactory.newClient(connectString, retryPolicy);
- client.start();
- InterProcessMutex lock = new InterProcessMutex(client, "/product_"+id);
- try {
- lock.acquire();
- productService.reduceStock(id);
- } catch (Exception e) {
- if (e instanceof RuntimeException) {
- throw e;
- }
- } finally {
- lock.release();
- }
- return "ok";
- }
- }
|