第一步,创建一个Maven工程
第二步,在Maven工程创建springcloud-eureka-server
添加pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
添加application.yml
server:
port: 8761
eureka:
instance:
hostname: localhost
client:
registerWithEureka: false
fetchRegistry: false
serviceUrl:
defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
在项目启动加上@EnableEurekaServer注解
@EnableEurekaServer
@SpringBootApplication
public class SpringcloudEurekaServerApplication {
public static void main(String[] args) {
SpringApplication.run(SpringcloudEurekaServerApplication.class, args);
}
}
启动SpringcloudEurekaServerApplication
在浏览器地址栏输入http:localhost:8761,显示如下结果
第三步,在Maven工程创建springcloud-eureka-client
添加pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.1.5.RELEASE</version>
<scope>compile</scope>
</dependency>
</dependencies>
添加application.yml
eureka:
client:
service-url:
#向三个服务端分别注册
defaultZone: http://localhost:8761/eureka/
server:
port: 8762
spring:
application:
name: service-hi
在项目启动加上@EnableDiscoveryClient注解
@EnableDiscoveryClient
@SpringBootApplication
public class SpringcloudEurekaClientApplication {
public static void main(String[] args) {
SpringApplication.run(SpringcloudEurekaClientApplication.class, args);
}
}
添加Controller
@Controller
public class DcController {
@Autowired
DiscoveryClient discoveryClient;
@GetMapping("/dc")
public String dc() {
String services = "Services: " + discoveryClient.getServices();
System.out.println(services);
return services;
}
}
启动SpringcloudEurekaClientApplication
访问http://localhost:8762/dc,在控制台会显示
在http://localhost:8761,Instances currently registered with Eureka中会发现一个Eureka客户端