溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Spring Cloud 入門(mén)教程 - Eureka服務(wù)注冊(cè)與發(fā)現(xiàn)

發(fā)布時(shí)間:2020-09-09 15:52:01 來(lái)源:網(wǎng)絡(luò) 閱讀:1463 作者:zxuqian 欄目:建站服務(wù)器

簡(jiǎn)介

在微服務(wù)中,服務(wù)注冊(cè)與發(fā)現(xiàn)對(duì)管理各個(gè)微服務(wù)子系統(tǒng)起著關(guān)鍵作用。隨著系統(tǒng)水平擴(kuò)展的越來(lái)越多,系統(tǒng)拆分為微服務(wù)的數(shù)量也會(huì)相應(yīng)增加,那么管理和獲取這些微服務(wù)的URL就會(huì)變得十分棘手,如果我們每新加一個(gè)微服務(wù),就要在其它用到此微服務(wù)的地方手動(dòng)加上它的URL地址或者其他通信協(xié)議的地址,這樣會(huì)經(jīng)常出錯(cuò),而且工作量巨大,一旦某個(gè)微服務(wù)的地址發(fā)生了變化,就要手動(dòng)修改所有引用它的微服務(wù)的配置文件。所以spring-cloud eureka server就是為了解決這樣的問(wèn)題而出現(xiàn),經(jīng)過(guò)簡(jiǎn)單的配置,即可自動(dòng)注冊(cè)和發(fā)現(xiàn)微服務(wù)。

基礎(chǔ)環(huán)境

  • JDK 1.8
  • Maven 3.3.9
  • IntelliJ 2018.1
  • Git

項(xiàng)目源碼

Gitee碼云

搭建Eureka Server

上篇博客我們介紹了如何搭建spring-cloud的配置中心,還有一個(gè)測(cè)試的web client去訪問(wèn)它,這次我們?cè)谥暗幕A(chǔ)上搭建一個(gè)eureka server,并且讀取配置中心的配置,然后把web client作為Discovery Client注冊(cè)到eureka服務(wù)。首先在IntelliJ下新建一個(gè)Maven項(xiàng)目:

  • groupId: cn.zxuqian
  • artifactId: registry

然后在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>cn.zxuqian</groupId>
    <artifactId>registry</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.1.RELEASE</version>
        <relativePath/>
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-config</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>Finchley.M9</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/libs-milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>

</project>

這里用到了spring-cloud-starter-netflix-eureka-server這個(gè)eureka-server核心依賴,還有訪問(wèn)配置中心服務(wù)的客戶端組件spring-cloud-starter-config
然后在src/main/resources下創(chuàng)建bootstrap.yml文件,添加如下配置:

spring:
  application:
    name: eureka-server
  cloud:
    config:
      uri: http://localhost:8888

此文件配置了用以讀取配置文件的應(yīng)用名,即spring.application.name,它的名字對(duì)應(yīng)于服務(wù)中心的文件名。另外Eureka的自動(dòng)注冊(cè)和發(fā)現(xiàn)也是基于這個(gè)參數(shù)的。然后配置了配置服務(wù)中心的uri。
新建一個(gè)Java類(lèi),cn.zxuqian.Application,使用如下代碼:

package cn.zxuqian;

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

@EnableEurekaServer
@SpringBootApplication
public class Application {

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

這里只用@EnableEurekaServer一條注解即把該應(yīng)用配置為Eureka Server。然后在配置中心的git倉(cāng)庫(kù)中創(chuàng)建eureka-server.yml文件,添加如下配置:

server:
  port: 8761

eureka: 
 client: 
  register-with-eureka: false
  fetch-registry: false

此文件配置了eureka-server的端口,以及關(guān)閉eureka自我注冊(cè)和發(fā)現(xiàn),因?yàn)槿绻魂P(guān)閉的話,eureka在啟動(dòng)過(guò)程中就會(huì)去嘗試注冊(cè)自己,然而發(fā)現(xiàn)服務(wù)并沒(méi)有啟動(dòng)就會(huì)報(bào)錯(cuò)。到此,eureka server就配置完了。

更新Web Client

現(xiàn)在我們要更新web client,使之可以被eureka自動(dòng)注冊(cè)和發(fā)現(xiàn)。首頁(yè)在pom.xml中添加eureka client的依賴:

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>

然后在Application類(lèi)中加上@EnableDiscoveryClient注解:

@EnableDiscoveryClient
@SpringBootApplication
public class Application {

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

最后我們創(chuàng)建一個(gè)類(lèi)用以測(cè)試服務(wù)是不是已成功注冊(cè)和發(fā)現(xiàn)。新建一個(gè)Java類(lèi)cn.zxuqian.controllers.ServiceInstanceController,添加如下代碼:

package cn.zxuqian.controllers;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class ServiceInstanceController {

    @Autowired
    private DiscoveryClient discoveryClient;

    @RequestMapping("/service-instances/{applicationName}")
    public List<ServiceInstance> serviceInstancesByApplicationName(
            @PathVariable String applicationName) {
        return this.discoveryClient.getInstances(applicationName);
    }

}

這是一個(gè)普通的RestController, 定義了一個(gè)DiscoveryClient類(lèi)型的變量并添加了@Autowire注解。此注解是Spring框架提供的依賴注入功能,在Spring的context下,它會(huì)自動(dòng)尋找DiscoveryClient的實(shí)現(xiàn)類(lèi),此處是eureka client。關(guān)于Spring的一些特性和原理,將在以后的博文中講到。
此類(lèi)還定義了serviceInstancesByApplicationName方法,用以處理/service-instances/{applicationName}請(qǐng)求。這里的{applicationName}匹配url路徑中/service-instances/以后的部分,然后用@PathVariable注解賦值給方法的applicationName參數(shù)。例如訪問(wèn)http://localhost:8080/service-instances/web-client,那么applicationName的值就是web-client。方法的作用是從discoveryClient中根據(jù)spring.application.name的值來(lái)取出對(duì)應(yīng)的實(shí)例信息,返回的是一個(gè)list,會(huì)自動(dòng)轉(zhuǎn)換為json數(shù)組的形式返回給瀏覽器。

測(cè)試

因?yàn)閑ureka server和web client都需要從配置服務(wù)中讀取配置,所以先啟動(dòng)config-server,然后再啟動(dòng)eureka-server,最后啟動(dòng)web-client,在啟動(dòng)成功后可能需要稍等十幾秒讓eureka-server發(fā)現(xiàn)和注冊(cè)web-client。完成之后訪問(wèn)http://localhost:8080/service-instances/web-client,會(huì)得到如下結(jié)果:

[{"host":"xuqians-imac","port":8080,"instanceInfo":{"instanceId":"xuqians-imac:web-client","app":"WEB-CLIENT","appGroupName":null,"ipAddr":"192.168.72.31","sid":"na","homePageUrl":"http://xuqians-imac:8080/","statusPageUrl":"http://xuqians-imac:8080/actuator/info","healthCheckUrl":"http://xuqians-imac:8080/actuator/health","secureHealthCheckUrl":null,"vipAddress":"web-client","secureVipAddress":"web-client","countryId":1,"dataCenterInfo":{"@class":"com.netflix.appinfo.InstanceInfo$DefaultDataCenterInfo","name":"MyOwn"},"hostName":"xuqians-imac","status":"UP","leaseInfo":{"renewalIntervalInSecs":30,"durationInSecs":90,"registrationTimestamp":1525319124967,"lastRenewalTimestamp":1525319124967,"evictionTimestamp":0,"serviceUpTimestamp":1525319124363},"isCoordinatingDiscoveryServer":false,"metadata":{"management.port":"8080"},"lastUpdatedTimestamp":1525319124967,"lastDirtyTimestamp":1525319124297,"actionType":"ADDED","asgName":null,"overriddenStatus":"UNKNOWN"},"metadata":{"management.port":"8080"},"uri":"http://xuqians-imac:8080","serviceId":"WEB-CLIENT","secure":false,"scheme":null}]

注意一下,這里并沒(méi)有把配置中心服務(wù)設(shè)置為可以被eureka server注冊(cè)和發(fā)現(xiàn),因?yàn)檫@里把配置文件都放到了config-server中,它和eureka server有著雞生蛋,蛋生雞的問(wèn)題,所以如果要讓config-server被自動(dòng)注冊(cè)和發(fā)現(xiàn),那么就需要單獨(dú)配置eureka server,然后在config server中配置eureka的uri,以及設(shè)置spring.cloud.config.discovery.enabled為true。具體以后需要用的時(shí)候再詳細(xì)說(shuō)明。

總結(jié)

配置eureka server相當(dāng)簡(jiǎn)單,只需要加一條@EnableEurekaServer注解,并在配置中關(guān)閉自我注冊(cè)和發(fā)現(xiàn)即可。然后在客戶端應(yīng)用的Application類(lèi)中加上@EnableDiscoveryClient注解即可。

歡迎訪問(wèn)我的博客

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI