给service1, service2添加依赖
com.alibaba.cloud
spring-cloud-starter-alibaba-nacos-discovery
给service1, service2添加配置项
nacos:
discovery:
server-addr: 127.0.0.1:8848
namespace: c22e5019-0bee-43b1-b80b-fc0b9d847501
二,实现service1, service2
分别编写基础的controller,向外提供restapi
启动service1,service2,就会自动的向nacos注册这两个服务,服务名为spring.application.name
三,测试,编写调用service1, service2的demo模块,
1,new -> module -> Maven -> 填写xx -> finish
2,添加依赖
org.springframework.boot
spring-boot-starter-web
com.alibaba.cloud
spring-cloud-starter-alibaba-nacos-discovery
org.springframework.cloud
spring-cloud-starter-openfeign
3,添加配置bootstrap.yml
spring:
cloud:
nacos:
discovery:
server-addr: 127.0.0.1:8848
namespace: c22e5019-0bee-43b1-b80b-fc0b9d847501
4,编写启动程序,编写controller,编写接口调用service1, service2
启动类:
@SpringBootApplication
@EnableFeignClients
@EnableDiscoveryClientpublic classDemoApplication {public static voidmain(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
接口调用:
@FeignClient(value = "service1")public interfaceUserClient {
@GetMapping("/user/name")publicString getName();
@GetMapping("/user/address")publicString getAddress();
}
@FeignClient(value = "service2")public interfaceOrderClient {
@GetMapping("/order/id")publicString getId();
@GetMapping("/order/price")public doublegetPrice();
}
controller:
@RestController
@RequestMapping("/demo")public classDemoController {
@AutowiredprivateUserClient userClient;
@AutowiredprivateOrderClient orderClient;
@GetMapping("/test")publicString test(){return "test, name:"
+userClient.getName()+ ", address:" +userClient.getAddress()+ "order_id:" +orderClient.getId()+ "order_price:" +orderClient.getPrice();
}
}
输出:test, name:天涯, address:中国order_id:10000111##order_price:100.5
调用完成!
原文:https://www.cnblogs.com/dongbo/p/12207141.html