Spring Cloud構建微服務架構 | 第一篇: 服務的註冊與發現(Eureka)

目錄

後面的文章都是基於spring-boot 2.0.4版本進行編寫的

一、Spring Cloud簡介

Spring Cloud是一個基於Spring Boot實現的雲應用開發工具,它爲基於JVM的雲應用開發中的配置管理、服務發現、斷路器、智能路由、微代理、控制總線、全局鎖、決策競選、分佈式會話和集羣狀態管理等操作提供了一種簡單的開發方式。

Spring Cloud包含了多個子項目(針對分佈式系統中涉及的多個不同開源產品),比如:Spring Cloud Config、Spring Cloud Netflix、Spring Cloud CloudFoundry、Spring Cloud AWS、Spring Cloud Security、Spring Cloud Commons、Spring Cloud Zookeeper、Spring Cloud CLI等項目。

二、微服務架構

“微服務架構”在這幾年非常的火熱,以至於關於微服務架構相關的產品社區也變得越來越活躍(比如:netflix、dubbo),Spring Cloud也因Spring社區的強大知名度和影響力也被廣大架構師與開發者備受關注。

那麼什麼是“微服務架構”呢?簡單的說,微服務架構就是將一個完整的應用從數據存儲開始垂直拆分成多個不同的服務,每個服務都能獨立部署、獨立維護、獨立擴展,服務與服務間通過諸如RESTful API的方式互相調用。

對於“微服務架構”,大家在互聯網可以搜索到很多相關的介紹和研究文章來進行學習和了解。也可以閱讀始祖Martin Fowler的《Microservices》,本文不做更多的介紹和描述。

三、服務註冊與發現

在簡單介紹了Spring Cloud和微服務架構之後,下面迴歸本文的主旨內容,如何使用Spring Cloud搭建服務註冊與發現模塊。

這裏我們會用到Spring Cloud Netflix,該項目是Spring Cloud的子項目之一,主要內容是對Netflix公司一系列開源產品的包裝,它爲Spring Boot應用提供了自配置的Netflix OSS整合。通過一些簡單的註解,開發者就可以快速的在應用中配置一下常用模塊並構建龐大的分佈式系統。它主要提供的模塊包括:服務發現(Eureka),斷路器(Hystrix),智能路有(Zuul),客戶端負載均衡(Ribbon)等。

所以,我們這裏的核心內容就是服務發現模塊:Eureka。下面我們動手來做一些嘗試。

四、創建“服務註冊中心”

在這裏,我們需要用的的組件上Spring Cloud Netflix的Eureka ,eureka是一個服務註冊和發現模塊。

4.1 首先創建一個maven主工程。

在pom.xml中引入需要的依賴內容:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.springcloud</groupId>
    <artifactId>eurekaserver</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>eurekaserver</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.4.RELEASE</version>
        <relativePath /> <!-- lookup parent from repository -->
    </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>Finchley.SR1</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>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

    <repositories>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>
</project>
4.2、啓動一個服務註冊中心

只需要一個註解@EnableEurekaServer,這個註解需要在springboot工程的啓動application類上加:

package com.springcloud.eureka;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;


@EnableEurekaServer
@SpringBootApplication
public class EurekaserverApplication {

    public static void main(String[] args) {
        SpringApplication.run(EurekaserverApplication.class, args);
    }
}
4.3、配置application.properties或者application.yml文件

eureka是一個高可用的組件,它沒有後端緩存,每一個實例註冊之後需要向註冊中心發送心跳(因此可以在內存中完成),在默認情況下erureka server也是一個eureka client ,必須要指定一個 server。eureka server的配置文件application.yml:

server:
  port: 8761 #服務註冊中心端口號

eureka:
  instance:
     hostname: localhost #服務註冊中心實例的主機名
  client:
     registerWithEureka: false #是否向服務註冊中心註冊自己
     fetchRegistry: false #是否檢索服務
     serviceUrl:
       defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/ #服務註冊中心的配置內容,指定服務註冊中心的位置

eureka server的配置文件application.properties:

server.port=8761 
eureka.instance.hostname=localhost
eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false
eureka.client.serviceUrl.defaultZone=http://${eureka.instance.hostname}:${server.port}/eureka/

通過eureka.client.registerWithEureka:false和fetchRegistry:false來表明自己是一個eureka server.

4.4、啓動eureka server服務

啓動工程後,打開瀏覽器訪問:http://localhost:8761 ,
可以看到下面的頁面,其中還沒有發現任何服務
這裏寫圖片描述

No application available 沒有服務被發現 ……^_^
因爲沒有註冊服務當然不可能有服務被發現了。

五、創建一個服務提供者 (eureka client)

當client向server註冊時,它會提供一些元數據,例如主機和端口,URL,主頁等。Eureka server 從每個client實例接收心跳消息。 如果心跳超時,則通常將該實例從註冊server中刪除。

5.1、首先創建一個maven主工程。

創建過程同server類似,創建完pom.xml如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.springcloud</groupId>
    <artifactId>eurekaclient</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>eurekaclient</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </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>Finchley.SR1</spring-cloud.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</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>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
    <repositories>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>

</project>
5.2、設置一個eurekaclient

過註解@EnableEurekaClient 表明自己是一個eurekaclient.

package com.springcloud.eurekaclient;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@Configuration
@ComponentScan
@EnableAutoConfiguration
@EnableEurekaClient
@RestController
public class EurekaclicentApplication {

    public static void main(String[] args) {
        SpringApplication.run(EurekaclicentApplication.class, args);
    }

    @Value("${server.port}")
    String port;
    @RequestMapping("/hi")
    public String home(@RequestParam String name) {
        return "hi "+name+",i am from port:" +port;
    }

}
5.2、配置application.properties或者application.yml文件

僅僅@EnableEurekaClient是不夠的,還需要在配置文件中註明自己的服務註冊中心的地址,application.yml配置文件如下:

eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/ #在此指定服務註冊中心地址
server:
  port: 8762
spring:
  application:
    name: eurekaclient

eureka client的配置文件application.properties:

eureka.client.serviceUrl.defaultZone=http://localhost:8761/eureka/ #在此指定服務註冊中心地址
server.port=8762
spring.application.name=eurekaclient

需要指明spring.application.name,這個很重要,這在以後的服務與服務之間相互調用一般都是根據這個name 。
啓動工程,打開http://localhost:8761 ,即eureka server 的網址:
這裏寫圖片描述

你會發現一個服務已經註冊在服務中了,服務名爲EUREKACLIENT ,端口爲8762

這時打開 http://localhost:8762/hi?name=Eureka,你會在瀏覽器上看到 :

hi Eureka,i am from port:8762

這裏寫圖片描述

六、參考文檔

spring-cloud官方文檔

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章