使用Template实现分布式架构之间通信的demo
首先创建一个 springboot 父项目
<?xml version="1.0" encoding="UTF-8"?>xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 order stock org.springframework.boot spring-boot-starter-parent 2.6.1 com.example springcloudalibaba 0.0.1-SNAPSHOT springcloudalibaba pom springcloudalibaba 1.8 org.springframework.boot spring-boot-starter org.springframework.boot spring-boot-starter-test test org.springframework.boot spring-boot-maven-plugin
在这个项目下创建子 maven 项目
<?xml version="1.0" encoding="UTF-8"?>xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> springcloudalibaba com.example 0.0.1-SNAPSHOT 4.0.0 order 商品订单模块 8 8 org.springframework.boot spring-boot-starter-web
<?xml version="1.0" encoding="UTF-8"?>xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 order stock org.springframework.boot spring-boot-starter-parent 2.6.1 com.example springcloudalibaba 0.0.1-SNAPSHOT springcloudalibaba pom springcloudalibaba 1.8 org.springframework.boot spring-boot-starter org.springframework.boot spring-boot-starter-test test org.springframework.boot spring-boot-maven-plugin
业务代码
order服务
/** * @Description: * @Author: LH * @Date: 2021/12/04/4:30 下午 */ @SpringBootApplication public class OrderApplication { public static void main(String[] args) { SpringApplication.run(OrderApplication.class,args); } // 用于远程调用的template,使用建造者模式 @Bean public RestTemplate restTemplate(RestTemplateBuilder builder) { RestTemplate restTemplate = builder.build(); return restTemplate; } }
/** * @Description: * @Author: LH * @Date: 2021/12/04/4:18 下午 */ @RestController @RequestMapping("/order") public class OrderController { @Autowired RestTemplate restTemplate; @RequestMapping("/add") public String add() { System.out.println("下单成功!"); String msg = restTemplate.getForObject("http://localhost:8082/stock/reduct", String.class); return "Hello World!" + msg; } }
stock服务
/** * @Description: * @Author: LH * @Date: 2021/12/04/4:32 下午 */ @SpringBootApplication public class StockApplication { public static void main(String[] args) { SpringApplication.run(StockApplication.class,args); } }
/** * @Description: * @Author: LH * @Date: 2021/12/04/4:21 下午 */ @RestController @RequestMapping("/stock") public class StockController { @RequestMapping("/reduct") public String reduct() { System.out.println("扣减库存"); return "扣减库存"; } }
起两个服务
在浏览器输入localhot:/8081/order/add进行访问