Spring Cloud學習筆記14——整合 Eureka Client
阿新 • • 發佈:2018-12-21
開發環境
JDK8+
Gradle4+
Spring Boot 2.0.0.M3
Spring Cloud Starter Netflix Eureka Client Finchley.M2
建立專案
新建專案資料夾:
將hello-world
專案中的原始碼檔案複製貼上到新專案資料夾中:
修改原始碼
修改build.gradle
配置,修改Spring Boot
版本、指定Spring Cloud
版本、新增Eureka Client
依賴、新增Spring Cloud
依賴管理:
//buildscript程式碼塊中指令碼優先執行
buildscript {
//ext用於定義動態屬性
ext {
springBootVersion = '2.0.0.M3'
}
//使用了Maven的中央倉庫及Spring自己的倉庫(也可以指定其他倉庫)
repositories {
//mavenCentral()
maven{ url "https://repo.spring.io/snapshot" }
maven{ url "https://repo.spring.io/milestone" }
maven{ url "http://maven.aliyun.com/nexus/content/groups/public/" }
}
//依賴關係
dependencies {
//classpath聲明瞭在執行其餘的指令碼時,ClassLoader可以使用這些依賴項
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}
//使用外掛
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
//指定了生成的編譯檔案的版本,預設是打成了jar包
group = 'com.study.spring.cloud'
version = '1.0.0'
//指定編譯.java檔案的JDK版本
sourceCompatibility = 1.8
//使用了Maven的中央倉庫及Spring自己的倉庫(也可以指定其他倉庫)
repositories {
//mavenCentral()
maven{ url "https://repo.spring.io/snapshot" }
maven{ url "https://repo.spring.io/milestone" }
maven{ url "http://maven.aliyun.com/nexus/content/groups/public/" }
}
ext {
springCloudVersion = 'Finchley.M2'
}
//依賴關係
dependencies {
//Eureka Client
compile('org.springframework.cloud:spring-cloud-starter-netflix-eureka-client')
//該依賴用於測試階段
testCompile('org.springframework.boot:spring-boot-starter-test')
}
//Spring Cloud依賴管理
dependencyManagement{
imports{
mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
}
}
修改com.study.spring.cloud.weather
包下的Application
類,加入@EnableDiscoveryClient
註解:
package com.study.spring.cloud.weather;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
/*
* @SpringBootApplication註解宣告Spring Boot應用
* 作用等同於@Configuration, @EnableAutoConfiguration, @ComponentScan,
* 簡化Spring配置
*/
@SpringBootApplication
//啟用可發現的客戶端
@EnableDiscoveryClient
//Application類一定要處於整個工程的根目錄下,這樣它才能根據配置去掃描子節點下的Spring的Bean
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
修改application.properties
配置檔案:
#應用名稱
spring.application.name=micro-weather-eureka-client
#註冊伺服器的URL
eureka.client.service-url.defaultZone=http://localhost:8761/eureka/
執行
注意一定要先執行micro-weather-eureka-server
執行micro-weather-eureka-client
應用:
執行結果如下:
訪問http://localhost:8761
頁面,可以看到Eureka
的管理頁面:
將客戶端關閉:
重新整理Eureka
的管理頁面(需要一定時間才能監控到客戶端的變化):
可以在application.properties
配置檔案中新增:
#關閉自我防護功能
eureka.server.enable-self-preservation=false
再進行關閉客戶端的實驗,Eureka
的管理頁面顯示: