SpringCloud 实战七:服务发现Discovery

  作者:记性不好的阁主

1、编写服务发现代码


  • 引入服务发现包


import org.springframework.cloud.client.discovery.DiscoveryClient;


  • 编写服务发现控制器


@GetMapping("/payment/discovery")
public Object discovery(){
List<String> services = discoveryClient.getServices();
for (String service : services) {
log.info("******element: " + service);
}
List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
for (ServiceInstance instance : instances) {
log.info(instance.getInstanceId() + "\t" + instance.getHost() + "\t" + instance.getPort() + "\t" + instance.getUri());
}
return this.discoveryClient;
}



  • 在启动类上开启服务发现


package com.laoxu.springcloud;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;

@SpringBootApplication
@EnableEurekaClient
@EnableDiscoveryClient
public class PaymentMain8001 {
public static void main(String[] args) {
SpringApplication.run(PaymentMain8001.class, args);
}
}



2、启动服务




3、访问http://localhost:8001/payment/discovery



4、查看服务信息日志


2020-08-29 20:50:15.030  INFO 14536 --- [nio-8001-exec-4] c.l.s.controller.PaymentController       : ******element: cloud-payment-service

2020-08-29 20:50:15.031  INFO 14536 --- [nio-8001-exec-4] c.l.s.controller.PaymentController       : ******element: cloud-order-consumer

2020-08-29 20:50:15.031  INFO 14536 --- [nio-8001-exec-4] c.l.s.controller.PaymentController       : payment8001 192.168.190.1 8001 http://192.168.190.1:8001

2020-08-29 20:50:15.031  INFO 14536 --- [nio-8001-exec-4] c.l.s.controller.PaymentController       : payment8002 192.168.190.1 8002 http://192.168.190.1:8002


相关推荐

评论 抢沙发

表情

分类选择