一、創建eureka集羣
1.創建modul
另創建兩個與microservice-eureka2001一樣的模塊爲microservice-eureka2002、microservice-eureka2003
2.修改配置
(1)修改端口
把microservice-eureka2002的端口改爲2002
microservice-eureka2002端口改爲2003
(2)修改鏈接路徑
microservice-eureka2001的
defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
改爲:
defaultZone: http://localhost:2002/eureka/,http://localhost:2003/eureka/
同理2002:
defaultZone: http://localhost:2001/eureka/,http://localhost:2003/eureka/
2003:
defaultZone: http://localhost:2002/eureka/,http://localhost:2001/eureka/
3.測試
這裏測試發現沒有形成集羣,由於是本機一臺電腦啓動,三個eureka的ip都爲localhost。現修改方法:
修改host文件:
增加
127.0.0.1 eureka2001.com
127.0.0.1 eureka2002.com
127.0.0.1 eureka2003.com
分別修改3個eureka配置信息中的defaultZone屬性,把host改成對應的域名。例如eureka2001的defaultZone鏈接的應爲2002、2003:
defaultZone: http://eureka2002.com:2002/eureka/,http://eureka2003.com:2003/eureka/
最後測試成功
二、把服務註冊到eureka集羣中
1.添加依賴
要把服務microservice-provider1001註冊到eureka中,首先需要鏈接eureka的依賴:
<!-- 將微服務microservice-provider側註冊進eureka -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
2.配置鏈接
application.yml中,增加配置信息:
eureka:
client:
service-url:
defaultZone: http://eureka2001.com:2001/eureka/,http://eureka2002.com:2002/eureka/,http://eureka2003.com:2003/eureka/
3.啓動類開啓eureka
客戶端:
@SpringBootApplication
@EnableEurekaClient
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
4.修改註冊服務的主機名稱及顯示ip地址
修改配置如下:
eureka:
client:
service-url:
defaultZone: http://eureka2001.com:2001/eureka/,http://eureka2002.com:2002/eureka/,http://eureka2003.com:2003/eureka/
instance:
instance-id: microservicecloud-provider1001 #服務主機名稱
prefer-ip-address: true #訪問路徑可以顯示IP地址
5.定製當點擊鏈接時,顯示指定信息
(1)在父項目中增加build
<build>
<finalName>microservicecloud</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<configuration>
<delimiters>
<delimit>$</delimit>
</delimiters>
</configuration>
</plugin>
</plugins>
</build>
(2)microservice-provider1001的服務中增加如下依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
(3)microservice-provider1001中配置顯示的info信息
info:
app.name: microservicecloud-provider
company.name: www.syr.com
build.artifactId: $project.artifactId$
build.version: $project.version$
6.測試
測試成功