Eureka
Eureka Server
创建项目命名为eureka-server
maven依赖:
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka-server</artifactId>
</dependency>
</dependencies>
配置Euraka:
spring.application.name=eureka-server
server.port=1001
eureka.instance.hostname=localhost
eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false
使用@EnableEurekaServer注解启用Eureka Server:
@EnableEurekaServer
@SpringBootApplication
public class EurekaServerApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaServerApplication.class, args);
}
}
启动程序:

Eureka Client
创建SpringBoot应用命名为eureka-client
maven依赖:
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
application.properties配置文件:
spring.application.name=eureka-client
server.port=2001
eureka.client.serviceUrl.defaultZone=http://localhost:1001/eureka/
注册微服务的基本配置。
Application类:
@EnableDiscoveryClient
@SpringBootApplication
public class EurekaClientApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaClientApplication.class, args);
}
}
@EnableDiscoveryClient能激活注册中心(Eureka、Consul)中的DiscoveryClient实现,可以让注册中心发现,扫描到该服务。这样才能够访问注册中心的信息。
实现测试接口:
@RestController
public class DcController {
@Autowired
DiscoveryClient discoveryClient;
@GetMapping("/ls")
public String listServices() {
String services = "Services: " + discoveryClient.getServices();
System.out.println(services);
return services;
}
@GetMapping("/instance/{serviceId}")
public ResponseEntity<Map<String, String>> getInstanceInfo(@PathVariable String serviceId) {
Map<String, String> resultMap = new HashMap<>();
List<ServiceInstance> servicesInstance = discoveryClient.getInstances(serviceId);
if(servicesInstance.size()==0) {
return new ResponseEntity<>(resultMap, HttpStatus.OK);
}
ServiceInstance serviceInstance = servicesInstance.get(0);
resultMap.put("host", serviceInstance.getHost());
resultMap.put("port", String.valueOf(serviceInstance.getPort()));
return new ResponseEntity<>(resultMap, HttpStatus.OK);
}
}
启动eureka-client访问eureka-server(http://localhost:1001)可以看到服务已经注册

测试接口:



浙公网安备 33010602011771号