微服務nacos服務注冊與發現


一,以上一篇為基礎 微服務從nacos配置中心獲得配置信息

  給service1, service2添加依賴

     <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>

  給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,添加依賴

<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.yml

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

調用完成!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM