消费端添加依赖:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
注册到注册中心
eureka:
instance:
prefer-ip-address: true #显示IP地址
instance-id: provider8001 #修改别名
client:
service-url:
defaultZone: http://localhost:7001/eureka
启动类添加注解
增加@EnableEurekaClient注解
@SpringBootApplication
@EnableEurekaClient
public class ProviderApp {
public static void main(String[] args) {
SpringApplication.run(Provider8001_APP.class,args);
}
}
服务发现
介绍
系统中的微服务可以通过Eureka的服务发现去获得在Eureka中注册的服务的信息,这是一个对外暴露的接口。
使用方法(provider中)
注入DiscoveryClient 对象(spring包下的),在controller方法中获取
@Autowired
private DiscoveryClient discoveryClient;
@ResponseBody
@GetMapping("/provider/discovery")
public Object discovery(){
List<String> list = discoveryClient.getServices();
System.out.println(list);
List<ServiceInstance> insList = discoveryClient.getInstances("MICROSERVICECLOUD-DEPT");
for (ServiceInstance si:insList) {
System.out.println(si.getHost() +"," + si.getServiceId() +"," +si.getPort() +"," +si.getUri() +"," +si.getMetadata());
}
return this.discoveryClient;
}
启动类
在主启动类中加入@EnableDiscoveryClient注解