SpringCloud 搭建服務註冊中心

SpringCloud 搭建服務註冊中心

原創 作者 | 於海東

在這裏插入圖片描述
之前在巧玩SpringBoot——SpringBoot的第一個“Hello World!”(https://blog.csdn.net/dongdong9223/article/details/82802137)中講述過SpringBoot的搭建,能夠看出SpringBoot搭建出一個Service還是非常簡單的。今天來講解一下使用SpringCloud搭建服務註冊與服務發現。

SpringCloud是什麼?

我們知道,SpringBoot是由Pivotal團隊提供的全新框架,其設計目的是用來簡化新Spring應用的初始搭建以及開發過程。也就是說SpringBoot其實不是什麼新的框架,它默認配置了很多框架的使用方式,使得搭建服務非常簡便,這使得它搭上了微服務的快車,被廣泛應用於微服務領域的服務開發。

俗話說,家不可一日無主!既然每個“微(小)”的“服務”工作已經有人做了,那麼這些服務之間的管理又由誰來管呢?答案就是SpringCloud!SpringCloud就是微服務之間的大管家,統一協調服務系統之間的諸多工作的,比如服務發現註冊、配置中心、消息總線、負載均衡、斷路器、數據監控等。

SpringBoot與SpringCloud本來是簡化Spring家族的系統操作的,不過自從搭上了微服務這個時下異常火熱的技術快車之後,已經蓬勃發展、圈粉無數,就如同周杰倫與方文山一樣組合成實力強悍、互爲御用的好夥(ji)伴(you)_,一躍成爲Spring家族的當家花旦!

創建服務註冊中心(Server)

這裏首先說明一點,雖然說SpringCloud與SpringBoot互爲御用,從概念上說它們有不同分工,但實現上它們之間卻並不是各自獨立的實體,而是一種寄生關係:SpringCloud也要基於SpringBoot這個服務體來實現其功能。

2.1 官網下載Maven工程

2.1.1 選擇配置

來到SPRING INITIALIZR,選擇配置爲:

Generate a:Maven Project

With:Java

Spring Boot:2.1.0

在Project Metadata中配置好Group和Artifact;在Dependencies中輸入Eureka Server並將其選擇;最後點擊Generate Project,生成一個Maven工程的模板並下載下來,使用Eclipse將其導入。

2.1.2 pom.xml的配置

自動生成的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.yhd</groupId>
    <artifactId>springcloudserver</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

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

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.0.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>Greenwich.M3</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>

2.1.3 修改SpringBoot的入口文件

這裏的入口文件爲:SpringcloudserverApplication.java,在其中加入註解:@EnableEurekaServer。

文件內容如下:

package com.yhd.springcloudserver;

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

@SpringBootApplication
@EnableEurekaServer
public class SpringcloudserverApplication {

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

2.1.4 編輯application.yml文件

這裏使用yml的編輯方式。先將application.properties文件名改爲:application.yml,在其中加入:

server:
  port: 7001

eureka:
  instance:
    hostname: localhost
  client:
    registerWithEureka: false
    fetchRegistry: false
    serviceUrl:
      defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/

spring:
  application:
    name: eureka-server

2.2 運行Server

啓動文件:SpringcloudserverApplication.java,在瀏覽器中輸入:http://localhost:8761/,這樣就進入了Eureka Server的界面。如圖所示:
在這裏插入圖片描述這裏面的:No instances available,表示還沒有發現註冊進來的服務。

創建服務提供者(Client)

OK,服務中心創建好了,我們來創建一個服務提供者,也就是Eureka Client。

3.1 官網下載Maven工程

3.1.1 選擇配置

這裏面的配置大部分都同2.1.1中配置的一樣,除了在Dependencies中,要輸入:

Web

Eureka Discovery

最後點擊Generate Project生成模板,下載下來並導入進Eclipse裏面。

3.1.2 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.yhd</groupId>
    <artifactId>springcloudclient</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

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

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.0.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>Greenwich.M3</spring-cloud.version>
    </properties>

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

3.1.3 修改SpringBoot的入口文件

這裏的入口文件爲:SpringcloudclientApplication.java,這裏要做2件事:添加註解,添加一個controller。

3.1.3.1 添加註解

在其中加入註解:

@EnableEurekaClient

@RestController

3.1.3.2 添加controller
@RequestMapping("/hello")
    public String home(@RequestParam(value = "name", defaultValue = "zhangsan") String name) {
        return "Hello " + name + " ,your port is:" + port;
    }

整體上文件內容如下:

package com.yhd.springcloudclient;

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

@SpringBootApplication
@EnableEurekaClient
@RestController
public class SpringcloudclientApplication {

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

    @Value("${server.port}")
    String port;

    @RequestMapping("/hello")
    public String home(@RequestParam(value = "name", defaultValue = "張三") String name) {
        return "Hello " + name + " ,your port is:" + port;
    }
}

3.1.4 編輯application.yml文件

編輯application.yml,在其中加入:


server:
  port: 7002

eureka:
  instance:
    hostname: service1
  client:
    registerWithEureka: true
    fetchRegistry: true
    serviceUrl:
      defaultZone: http://localhost:7001/eureka/

spring:
  application:
    name: eureka-service

這裏的設置,同2.1.4對比,去掉了:


eureka:
  client:
      #設置是否向註冊中心註冊,默認是true
    registerWithEureka: false
    #是否需要去檢索尋找服務,默認是true
    fetchRegistry: false

由於這兩個配置默認都爲true,對於client端就不需要設置了,這樣纔會將自己的服務暴露給註冊中心。

3.2 運行client

啓動client的入口文件:SpringcloudclientApplication.java

查看服務註冊中心

確保先運行Eureka Server,再運行Eureka Client,這樣將兩個服務都運行起來後,在瀏覽器中輸入:http://localhost:7001/,進入Eureka Server的界面。

在這裏插入圖片描述
能夠看到註冊中心已經成功查找到了服務並將其註冊了進來。
調用服務
再打開一個瀏覽器頁面,輸入:

http://localhost:7002/hello?name=zhangsan

會得到返回結果的響應:

Hello zhangsan ,your port is:7002

如圖所示:
在這裏插入圖片描述可見註冊成功的服務也被成功調用了!

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