微服务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

调用完成!

猜你喜欢

转载自www.cnblogs.com/dongbo/p/12207141.html