ProductAction.java 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. package controller;
  2. import org.apache.curator.RetryPolicy;
  3. import org.apache.curator.framework.CuratorFramework;
  4. import org.apache.curator.framework.CuratorFrameworkFactory;
  5. import org.apache.curator.framework.recipes.locks.InterProcessMutex;
  6. import org.apache.curator.retry.ExponentialBackoffRetry;
  7. import org.springframework.beans.factory.annotation.Autowired;
  8. import org.springframework.stereotype.Controller;
  9. import org.springframework.web.bind.annotation.GetMapping;
  10. import org.springframework.web.bind.annotation.ResponseBody;
  11. import service.ProductService;
  12. @Controller
  13. public class ProductAction {
  14. @Autowired
  15. private ProductService productService;
  16. private static String connectString = "192.168.48.128:2181,192.168.48.129:2181,192.168.48.130:2181";
  17. @GetMapping("/product/reduce")
  18. @ResponseBody
  19. public Object reduce(int id) throws Exception {
  20. RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000,3);
  21. CuratorFramework client = CuratorFrameworkFactory.newClient(connectString, retryPolicy);
  22. client.start();
  23. InterProcessMutex lock = new InterProcessMutex(client, "/product_"+id);
  24. try {
  25. lock.acquire();
  26. productService.reduceStock(id);
  27. } catch (Exception e) {
  28. if (e instanceof RuntimeException) {
  29. throw e;
  30. }
  31. } finally {
  32. lock.release();
  33. }
  34. return "ok";
  35. }
  36. }