自學spring-cloud系列,越來越感覺spring-cloud很強大!
主要分爲以下幾篇:
介紹
spring-cloud-eureka,被動式的服務發現,統一監控和管理你的服務列表。
什麼是服務發現?
服務發現就像聊天室一個,每個用戶來的時候去服務器上註冊,這樣他的好友們就能看到你,你同時也將獲取好友的上線列表. 在微服務中,服務就相當於聊天室的用戶,而服務註冊中心就像聊天室服務器一樣,目前服務發現的解決方案有Eureka,Consul,Etcd,Zookeeper,SmartStack,等等.
如何使用
- 創建server端
創建client端
1. 創建server端
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環境下運行,直接新配置一個運行環境就好了,如下圖:
然後在 dashboard 裏查看,可以看到:
這裏有好多坑,只有你踩過了才能發現真理。其中最主要的是不能用一樣的hostname,註冊時間有點慢和剔除時間有點慢。
2. 創建client端
當然了,也很簡單。
pom.xml:
<!--監控-->
<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,直接增加就行了,如上所示。
示例源碼
所有源碼在我的github倉庫裏,傳送門:https://github.com/xjtushilei/spring-cloud-simples.git
支持
如果你喜歡~ 給個星