1、建moudle:cloud-consumer-order80
2、改pom
在子工pom文件中添加
<dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-actuator</artifactId><version>2.2.2.RELEASE</version></dependency><!--热部署--><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>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><version>2.2.2.RELEASE</version><scope>test</scope></dependency></dependencies>
3、写yml
在resources目录下新建application.yml文件
4、主启动
5、业务类
1、复制cloud-provider-payment8001项目里的entities(里面2个实体类)到本项目(cloud-consumer-order80)的springcloud entities包下。(在后面的工程重构,阳哥会把实体类抽取出来)
2、在springcloud包下新建config.ApplicationContextConfig
@Configuration
public class ApplicationContextConfig {
//RestTemplate提供了多种便捷访问远程http访问的方法@Bean //用注解的方式依赖注入,即往容器中添加一个RestTemplatepublic RestTemplate getTestTemplate(){
return new RestTemplate();}
}
3、在springcloud包下新建controller.OrderController
@RestController
@Slf4j
public class OrderController {
public static final String PAYMENT_URL = "http://localhost:8001";//用注解注入并实例化@Resourceprivate RestTemplate restTemplate;@GetMapping("/consumer/payment/create")public CommonResult<Payment> create(Payment payment){
log.info("********插入的数据:" + payment);//postForObject分别有三个参数:请求地址,请求参数,返回的对象类型return restTemplate.postForObject(PAYMENT_URL + "/payment/create",payment,CommonResult.class);}@GetMapping("/consumer/payment/get/{id}")public CommonResult<Payment> getPayment(@PathVariable("id") Long id){
log.info("********查询的id:" + id);//getForObject两个参数:请求地址,返回的对象类型return restTemplate.getForObject(PAYMENT_URL + "/payment/get/" + id, CommonResult.class);}}
6、测试
启动两个项目进行测试,两个都启动后,右下角会弹出个services提示,点击show。
然后会把运行的项目合并在一起显示:
在浏览器中输入localhost/consumer/payment/get/1成功查询到数据:
在浏览器中输入” http://localhost/consumer/payment/create?serial=张来福 “插入一条数据。
但数据库中有主键却没有内容,要注意加上@RequestBody注解,才会产生真实记录