一,以上一篇爲基礎 微服務從nacos配置中心得到配置信息html
給service1, service2添加依賴web
<dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId> </dependency>
給service1, service2添加配置項spring
nacos: discovery: server-addr: 127.0.0.1:8848 namespace: c22e5019-0bee-43b1-b80b-fc0b9d847501
二,實現service1, service2bootstrap
分別編寫基礎的controller,向外提供restapiapi
啓動service1,service2,就會自動的向nacos註冊這兩個服務,服務名爲spring.application.nameapp
三,測試,編寫調用service1, service2的demo模塊,spring-boot
1,new -> module -> Maven -> 填寫xx -> finish微服務
2,添加依賴測試
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency> </dependencies>
3,添加配置bootstrap.ymlspa
spring: cloud: nacos: discovery: server-addr: 127.0.0.1:8848 namespace: c22e5019-0bee-43b1-b80b-fc0b9d847501
4,編寫啓動程序,編寫controller,編寫接口調用service1, service2
啓動類:
@SpringBootApplication @EnableFeignClients @EnableDiscoveryClient public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } }
接口調用:
@FeignClient(value = "service1") public interface UserClient { @GetMapping("/user/name") public String getName(); @GetMapping("/user/address") public String getAddress(); }
@FeignClient(value = "service2") public interface OrderClient { @GetMapping("/order/id") public String getId(); @GetMapping("/order/price") public double getPrice(); }
controller:
@RestController @RequestMapping("/demo") public class DemoController { @Autowired private UserClient userClient; @Autowired private OrderClient orderClient; @GetMapping("/test") public String 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
調用完成!