服务端配置
pom.xml文件如下:
复制代码 4.0.0 com.neo spring-cloud-eureka-two 0.0.1-SNAPSHOT jar spring-cloud-eureka-two Demo project for Spring cloud eureka org.springframework.boot spring-boot-starter-parent 1.5.3.RELEASE UTF-8 UTF-8 1.8 Dalston.RELEASE org.springframework.cloud spring-cloud-starter-eureka-server org.springframework.boot spring-boot-starter-test test org.springframework.cloud spring-cloud-dependencies ${spring-cloud.version} pom import org.springframework.boot spring-boot-maven-plugin
application.properties如下:
spring.application.name=spring-cloud-eureka
application-peer1.properties如下:
server.port=8000eureka.instance.hostname=server1eureka.client.register-with-eureka=trueeureka.client.fetch-registry=trueeureka.client.serviceUrl.defaultZone=http://server2:8001/eureka/复制代码
application-peer2.properties如下:
server.port=8001eureka.instance.hostname=server2eureka.client.register-with-eureka=trueeureka.client.fetch-registry=trueeureka.client.serviceUrl.defaultZone=http://server1:8000/eureka/复制代码
启动类增加@EnableEurekaServer注解即可
import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;@SpringBootApplication@EnableEurekaServerpublic class SpringCloudEurekaApplication { public static void main(String[] args) { SpringApplication.run(SpringCloudEurekaApplication.class, args); }}复制代码
客户端配置
pom文件如下:
复制代码 4.0.0 com.didispace eureka-client 1.0.0 jar eureka-client Spring Cloud In Action org.springframework.boot spring-boot-starter-parent 1.5.4.RELEASE UTF-8 1.8 org.springframework.cloud spring-cloud-starter-eureka org.springframework.boot spring-boot-starter-web org.springframework.cloud spring-cloud-dependencies Dalston.SR1 pom import org.springframework.boot spring-boot-maven-plugin
application.properties配置如下:
spring.application.name=eureka-clientserver.port=2001eureka.client.serviceUrl.defaultZone=http://localhost:8000/eureka/,http://localhost:8001/eureka复制代码
启动类增加@EnableDiscoveryClient注解即可。
import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.boot.builder.SpringApplicationBuilder;import org.springframework.cloud.client.discovery.EnableDiscoveryClient;@EnableDiscoveryClient@SpringBootApplicationpublic class EurekaClientApplication { public static void main(String[] args) { new SpringApplicationBuilder(EurekaClientApplication.class).web(true).run(args); }}复制代码
Controller层
@RestControllerpublic class DcController { @Autowired DiscoveryClient discoveryClient; @GetMapping("/dc") public String dc() { String services = "Services: " + discoveryClient.getServices(); System.out.println(services); return services; }}复制代码
本机模拟运行2个Server,需要在hosts文件增加:
127.0.0.1 server1
127.0.0.1 server2
通过设置Program arguments参数启动2个Server端
启动后server1注册结果如下:
server2类似,通过Client端能够正常访问。
停止server1后,server2控制台报错Connect to server1:8000 timed out
,但依然能够提供服务,是由于注册信息已经同步server2.