目录
创建spring_clou_api_commons module
引入Maven (spring_cloud_api_common)
构建订单微服务模块
项目搭建
与支付微服务模块相似流程建立module
- 建Module
- 改POM,引入依赖
- 写yml
- 主启动类
- 业务类
RestTemplate远程访问
因为这里是消费者类,主要是消费,那么就没有service和dao,需要调用pay模块的方法, 并且这里还没有微服务的远程调用,那么如果要调用另外一个模块,则需要使用基本的api调用,使用RestTemplate调用pay模块,RestTemplate提供了多种便捷访问远程Http服务的方法,是一种简单便捷的访问restful服务模版类,是Spring提供的用于访问Rest服务的客户端模版工具类。
使用RestTemplate访问restful接口非常简单粗暴无脑。(url,requestMap,ResponseBean.class)这三个参数分别代表REST请求地址/请求参数/HTTP响应转换被转换成的对象类型。
将restTemplate注入到容器
package com.tudeen.learn.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
@Configuration
public class ApplicationContextConfig {
@Bean //applicationContext.xml <bean id="" class="">
//@LoadBalanced 暂时注解掉,使用自定义负载
public RestTemplate getRestTemplate(){
return new RestTemplate();
}
}
订单controller
package com.tudeen.learn.controller;
import com.tudeen.learn.common.CommonResult;
import com.tudeen.learn.entity.Payment;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import javax.annotation.Resource;
@Slf4j
@RestController
public class OrderController {
//远程调用支付模块8001端口
private static final String PAYMENT_URL="http://localhost:8001";
@Resource
private RestTemplate restTemplate;
@GetMapping("/consumer/payment/create")
public CommonResult<Payment> create(Payment payment) {
return restTemplate.postForObject(PAYMENT_URL + "/payment/create", payment, CommonResult.class);
}
@GetMapping("/consumer/payment/getId/{id}")
public CommonResult<Payment> getId(@PathVariable("id") String id) {
return restTemplate.getForObject(PAYMENT_URL + "/payment/getPaymentByid/" + id, CommonResult.class);
}
}
启动运行
同时运行支付与订单模块项目
点击运行
http://localhost/consumer/payment/getId/31 可以远程调用支付模块的接口
工程重构
创建spring_clou_api_commons module
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools
</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true
</optional>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.1.0</version>
</dependency>
</dependencies>
entity和实体类放入common中
迁移支付模块与订单模块相同的entity类
使用maven,将common模块打包(install)
修改其他模块对应的代码
删除重复
删除原先支付与订单模块的重复的Payment与CommentResult实体类
引入Maven (spring_cloud_api_common)
<dependency>
<groupId>com.tudeen.learn</groupId>
<artifactId>spring_cloud_api_commons</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>