SpringCloud入門教程-Eureka服務注冊與發(fā)現(xiàn)

簡介

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

成都創(chuàng)新互聯(lián)公司長期為1000+客戶提供的網站建設服務,團隊從業(yè)經驗10年,關注不同地域、不同群體,并針對不同對象提供差異化的產品和服務;打造開放共贏平臺,與合作伙伴共同營造健康的互聯(lián)網生態(tài)環(huán)境。為襄陽企業(yè)提供專業(yè)的成都網站設計、成都網站制作,襄陽網站改版等技術服務。擁有10余年豐富建站經驗和眾多成功案例,為您定制開發(fā)。

基礎環(huán)境

  • JDK 1.8
  • Maven 3.3.9
  • IntelliJ 2018.1
  • Git

項目源碼

Gitee碼云

搭建Eureka Server

上篇博客我們介紹了如何搭建spring-cloud的配置中心,還有一個測試的web client去訪問它,這次我們在之前的基礎上搭建一個eureka server,并且讀取配置中心的配置,然后把web client作為Discovery Client注冊到eureka服務。首先在IntelliJ下新建一個Maven項目:

  • 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這個eureka-server核心依賴,還有訪問配置中心服務的客戶端組件spring-cloud-starter-config
然后在src/main/resources下創(chuàng)建bootstrap.yml文件,添加如下配置:

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

此文件配置了用以讀取配置文件的應用名,即spring.application.name,它的名字對應于服務中心的文件名。另外Eureka的自動注冊和發(fā)現(xiàn)也是基于這個參數(shù)的。然后配置了配置服務中心的uri。
新建一個Java類,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一條注解即把該應用配置為Eureka Server。然后在配置中心的git倉庫中創(chuàng)建eureka-server.yml文件,添加如下配置:

server:
  port: 8761

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

此文件配置了eureka-server的端口,以及關閉eureka自我注冊和發(fā)現(xiàn),因為如果不關閉的話,eureka在啟動過程中就會去嘗試注冊自己,然而發(fā)現(xiàn)服務并沒有啟動就會報錯。到此,eureka server就配置完了。

更新Web Client

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

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

然后在Application類中加上@EnableDiscoveryClient注解:

@EnableDiscoveryClient
@SpringBootApplication
public class Application {

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

最后我們創(chuàng)建一個類用以測試服務是不是已成功注冊和發(fā)現(xiàn)。新建一個Java類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);
    }

}

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

測試

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

[{"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}]

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

總結

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

歡迎訪問我的博客

本文名稱:SpringCloud入門教程-Eureka服務注冊與發(fā)現(xiàn)
標題鏈接:http://muchs.cn/article16/iepigg.html

成都網站建設公司_創(chuàng)新互聯(lián),為您提供標簽優(yōu)化、定制開發(fā)、網站設計公司、域名注冊、網站營銷做網站

廣告

聲明:本網站發(fā)布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創(chuàng)新互聯(lián)

h5響應式網站建設