Spring Boot 开启异步方法注解
项目目录结构:
demo │ pom.xml │ └───src ├───main │ ├───java │ │ └───net │ │ └───wuxianjie │ │ └───demo │ │ │ DemoApplication.java │ │ │ │ │ └───product │ │ ProductController.java │ │ ProductService.java │ │ │ └───resources │ application.properties │ └───test
同步方法调用
DemoApplication.java
源码:
package net.wuxianjie.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } }
ProductController.java
源码:
package net.wuxianjie.demo.product; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/prods") public class ProductController { @Autowired ProductService productService; @GetMapping("{id:\\d}") public String getProduct(@PathVariable("id") String productId) { String productStr = productService.getProduct(productId); productService.updateProductMetadata(productId); return productStr; } }
ProductService.java
源码:
package net.wuxianjie.demo.product; import org.springframework.stereotype.Service; @Service public class ProductService { public String getProduct(String productId) { return "获取 ID 为 " + productId + " 的商品详情"; } public void updateProductMetadata(String productId) { mockLongTimeProcess(); System.out.println("商品 ID 为 " + productId + " 的点击数+1"); } private void mockLongTimeProcess() { try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } } }
异步方法调用
在 Spring Boot 的启动类上打上 @EnableAsync
注解。
DemoApplication.java
源码:
package net.wuxianjie.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.scheduling.annotation.EnableAsync; @SpringBootApplication @EnableAsync public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } }
ProductController.java
中的代码不用动。只需在想要异步调用的方法上打上 @Async
注解即可。
ProductService.java
源码:
package net.wuxianjie.demo.product; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; @Service public class ProductService { public String getProduct(String productId) { return "获取 ID 为 " + productId + " 的商品详情"; } @Async public void updateProductMetadata(String productId) { mockLongTimeProcess(); System.out.println("商品 ID 为 " + productId + " 的点击数+1"); } private void mockLongTimeProcess() { try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } } }
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论