菜鳥學Spring Cloud——建立註冊中心(Eureka)
阿新 • • 發佈:2018-12-19
文章目錄
扯一扯
以下內容將引起極度舒適,請在女朋友的陪同下觀看。什麼?你沒有女朋友?哦,不好意思,我忘了,程式設計師是沒有女朋友的。那就好好學習吧,女朋友總會有的。
軟體環境
- Windows 10
- JDK 1.8
- IDEA 2018.2
- Spring Boot 2.1.0.RELEASE
- Spring Cloud Greenwich.M1
步驟
建立工程
跟建立一個普通的Spring Boot工程沒有什麼區別,選擇Spring Initializr
:
填寫專案資訊:
左側選擇Cloud Discovery
,右側勾選Eureka Server
:
pom檔案
pom檔案的核心引用:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.0.RELEASE</version>
<relativePath/>
</parent>
<properties>
<project.build.sourceEncoding >UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<spring-cloud.version>Greenwich.M1</spring-cloud.version>
</properties>
< dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
配置
宣告為註冊中心
新增@EnableEurekaServer註解:
@SpringBootApplication
@EnableEurekaServer
public class EurekaApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaApplication.class, args);
}
}
屬性配置
yaml
eureka:
client:
register-with-eureka: false
fetch-registry: false
properties
eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false
坑
如果不加上面的配置,工程啟動會出現如下錯誤:
com.sun.jersey.api.client.ClientHandlerException: java.net.ConnectException: Connection refused: connect
com.netflix.discovery.shared.transport.TransportException: Cannot execute request on any known server
原因是工程啟動後,預設是會尋找註冊中心的,然而它本身就是註冊中心,所以我們要告訴它:你已經長大了,不能依賴別人了,你要承擔更多,做別人可以依靠的肩膀,這就是長大的代價。
效果
啟動後,訪問localhost:8080
,看到如下頁面代表我們已經成功了,我們可以在配置檔案中將埠改成Eureka官方的預設埠8761
下集預告
OK,到此我們的註冊中心就建好了,太簡單太清爽了有沒有?下集我們將播出什麼內容呢?我想聰明的你已經猜到了,下集我們會一起學習一下如何建立一個客戶端。OK,下集見!