介紹
spring-cloud-eureka,被動式的服務發現,統一監控和管理你的服務清單。
什麼是服務發現?
服務發現就像聊天室一個,每個使用者來的時候去伺服器上注冊,這樣他的好友們就能看到你,你同時也将擷取好友的上線清單. 在微服務中,服務就相當于聊天室的使用者,而服務注冊中心就像聊天室伺服器一樣,目前服務發現的解決方案有Eureka,Consul,Etcd,Zookeeper,SmartStack,等等.
如何使用
建立server端
建立client端
1.1 單機版
pom.xml:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka-server</artifactId>
</dependency>
當然了,我已經在全局加入了一些其他配置檔案,因為我使用了子產品式的開發,是以這裡很簡單。
配置檔案:
server:
port: 8761
spring:
application:
name: eureka-server
eureka:
instance:
lease-expiration-duration-in-seconds: 6
lease-renewal-interval-in-seconds: 2
client:
service-url:
defaultZone: http://localhost:${server.port}/eureka/
一般端口都是8761,可以随意設定。
開發的時候,一般要設定以下兩點
lease-expiration-duration-in-seconds: 6 意思是6秒不發送心跳檢查,就删除該執行個體,預設90秒
lease-renewal-interval-in-seconds: 2 心跳檢查的時間,預設30秒
這裡報一個 bug :我設定6秒還是不管用,依然是90秒才能剔除。可能是我時間設定的太短嗎?大家可以留言告訴我為什麼。
啟動:
@SpringBootApplication
@EnableConfigServer
public class SpringCloudConfigServerApplication {
public static void main(String[] args) {
SpringApplication.run(SpringCloudConfigServerApplication.class, args);
}
}
在啟動檔案裡,加入這樣一句話就好啦。
1.2 多節點版本
在系統的hosts裡寫入:
127.0.0.1 peer1
127.0.0.1 peer2
節點1配置檔案 application-peer1.yml :
server:
port: 8761
spring:
application:
name: eureka-server
eureka:
instance:
hostname: peer1
# lease-expiration-duration-in-seconds: 6
# lease-renewal-interval-in-seconds: 2
client:
service-url:
defaultZone: http://peer2:8762/eureka/
節點2配置檔案 application-peer2.yml :
server:
port: 8762
spring:
application:
name: eureka-server
eureka:
instance:
# lease-expiration-duration-in-seconds: 6
# lease-renewal-interval-in-seconds: 2
hostname: peer2
client:
service-url:
defaultZone: http://peer1:8761/eureka/
如果有更多個節點,更改端口号即可,并在 defaultZone:後面用逗号隔開,增加更多的就好了。
啟動方法:
采用不同的配置檔案啟動:
java -jar eureka-server-1.0.0.jar --spring.profiles.active=peer1
java -jar eureka-server-1.0.0.jar --spring.profiles.active=peer2
如果是用IDEA環境下運作,直接新配置一個運作環境就好了,這裡有好多坑,隻有你踩過了才能發現真理。其中最主要的是不能用一樣的hostname,注冊時間有點慢和剔除時間有點慢。
當然了,也很簡單。
<!--監控-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!--服務注冊-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
pom需要監控和服務注冊,同樣,推薦使用子產品化開發,直接在頂層配置這兩個,所有的檔案都不需要額外配置。
配置檔案:
server.port=8083
spring.application.name=eureka-client-1
eureka.client.service-url.defaultZone= http://peer1:8761/eureka/,http://peer2:8761/eureka/
這裡配置也很簡單,告訴我在哪裡就好了。如果有多個service-url,直接增加就行了,如上所示。
java B2B2C Springcloud多租戶電子商城系統