Spring Cloud是最近比較流行的微服務(wù)架構(gòu)框架洪规,本文介紹如何使用Spring Cloud搭建服務(wù)注冊與發(fā)現(xiàn)模塊。
這里會用到Spring Cloud Netflix衷咽,Spring Cloud的子項目之一稼钩,主要內(nèi)容是對Netflix公司一系列開源產(chǎn)品的包裝谭网,它為Spring Boot應(yīng)用提供了自配置的Netflix OSS整合。通過一些簡單的注解低斋,開發(fā)者就可以快速的在應(yīng)用中配置一下常用模塊并構(gòu)建龐大的分布式系統(tǒng)蜂厅。它主要提供的模塊包括:服務(wù)發(fā)現(xiàn)(Eureka),斷路器(Hystrix)拔稳,智能路有(Zuul)葛峻,客戶端負(fù)載均衡(Ribbon/Feign)等等。
創(chuàng)建服務(wù)注冊中心
創(chuàng)建一個基礎(chǔ)的Spring Boot工程巴比,在pom.xml中引入需要的依賴內(nèi)容(亦可以通過boot工程向?qū)В?/p>
<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>Dalston.RELEASE</spring-cloud.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-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注解啟動一個服務(wù)注冊中心提供給其他應(yīng)用术奖。只需要在Spring Boot應(yīng)用中添加這個注解就能開啟此功能,比如:
package com.smart.cloud;
import org.springframework.boot.SpringApplication;
import org.springframework.cloud.client.SpringCloudApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
@EnableEurekaServer
@SpringCloudApplication
public class EurekaServerApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaServerApplication.class, args);
}
}
應(yīng)用配置application.properties:
server.port=1111
#eureka.instance.hostname=localhost
eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false
eureka.client.serviceUrl.defaultZone=http://localhost:${server.port}/eureka/
在默認(rèn)設(shè)置下轻绞,該服務(wù)注冊中心也會將自己作為客戶端來嘗試注冊它自己采记,如果我們需要禁用它的客戶端注冊行為,只需要在application.properties中問增加如下配置:
eureka.client.register-with-eureka=false
這里將服務(wù)注冊中心的端口通過server.port屬性設(shè)置為1111
啟動工程后政勃,訪問:http://localhost:1111/
可以看到下面的頁面唧龄,還沒有發(fā)現(xiàn)任何服務(wù)
該工程可參見:eureka-server