Spring-Cloud-Eureka注冊中心和調用實例


 

Eureka是Netflix開發的服務發現框架,本身是一個基於REST的服務,主要用於定位運行在AWS域中的中間層服務,以達到負載均衡和中間層服務故障轉移的目的。 
SpringCloud將它集成在其子項目spring-cloud-netflix中,以實現SpringCloud的服務發現功能。

Eureka概述

Eureka包含兩個組件:Eureka Server(服務器,或服務注冊中心)和Eureka Client(客戶端)。

Eureka Server提供服務注冊服務,各個節點啟動后,會在Eureka Server中進行注冊,這樣EurekaServer中的服務注冊表中將會存儲所有可用服務節點的信息,服務節點的信息可以在界面中直觀的看到。
Eureka Client是一個java客戶端,用於簡化與Eureka Server的交互,客戶端同時也就是一個內置的、使用輪詢(round-robin)負載算法的負載均衡器。
在應用啟動后,將會向Eureka Server發送心跳,默認周期為30秒,如果Eureka Server在多個心跳周期內沒有接收到某個節點的心跳,Eureka Server將會從服務注冊表中把這個服務節點移除(默認90秒)。

Eureka Server之間通過復制的方式完成數據的同步,Eureka還提供了客戶端緩存機制,即使所有的Eureka Server都掛掉,客戶端依然可以利用緩存中的信息消費其他服務的API。
綜上,Eureka通過心跳檢查、客戶端緩存等機制,確保了系統的高可用性、靈活性和可伸縮性。

 

Eureka的服務發布與調用簡單例子

 

 

 

一、構建服務器(服務注冊中心)

注冊中心這么關鍵的服務,如果是單點話,遇到故障就是毀滅性的。在一個分布式系統中,服務注冊中心是最重要的基礎部分,理應隨時處於可以提供服務的狀態。為了維持其可用性,使用集群是很好的解決方案。Eureka通過互相注冊的方式來實現高可用的部署,所以我們只需要將Eureke Server配置其他可用的serviceUrl就能實現高可用部署。

實例結構如下圖所示,服務中心雙機部署(模仿集群)。

 

配置雙節點注冊中心

1.所有項目的父pom

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>2.3.4.RELEASE</version>
      <relativePath/> <!-- lookup parent from repository -->
  </parent>
  
  <groupId>com.cc8w</groupId>
  <artifactId>springcloud_eureka_demo</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>pom</packaging>
  <name>springcloud_eureka_demo</name>
  <url>http://maven.apache.org</url>

    <properties>
        <java.version>1.8</java.version>
        <spring.cloud-version>Hoxton.SR8</spring.cloud-version>
    </properties>
    <!-- 版本控制 -->
    <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>
    <dependencies>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
    
  <modules>
    <module>eureka_service</module>
    <module>cureka_provider</module>
    <module>eureka_consumer</module>
  </modules>
</project>

 

2.創建注冊中心的子maven工程

創建完成后的pom.xml配置文件,自動集成父項目SpringBoot2.3.4版本,對應SpringCould版本Hoxton.SR8。
加入的spring-cloud-starter-eureka-server會自動引入spring-boot-starter-web,因此可以不加web依賴,項目就具有Web容器的功能。
pom.xml完整內容如下:

<?xml version="1.0"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>com.cc8w</groupId>
    <artifactId>springcloud_eureka_demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
  </parent>

  <artifactId>eureka_service</artifactId>
  <name>eureka_service</name>
  <url>http://maven.apache.org</url>
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </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-config</artifactId>
        </dependency>
        <!--注冊中心-->
        <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>
</project>

 

3、創建application-peer1.properties,作為peer1服務中心的配置,並將serviceUrl指向peer2

 

# 服務名
spring.application.name=cloud-eureka-service
# 服務端口
server.port=8000

eureka.instance.hostname=peer1
# 指示此實例是否應將其信息注冊到eureka服務器以供其他人發現。在某些情況下,您不希望發現實例,而您只想發現其他實例。
eureka.client.register-with-eureka=true
# 指示該客戶端是否應從eureka服務器獲取eureka注冊表信息。
eureka.client.fetch-registry=false

eureka.client.service-url.defaultZone=http://peer2:8001/eureka/


# 關閉服務保護機制
eureka.server.enable-self-preservation=false
# 清理無效節點時間間隔(單位毫秒,默認是60*1000)
eureka.server.eviction-interval-timer-in-ms=30000

#每30S給其他服務發次請求,監測心跳
eureka.instance.lease-renewal-interval-in-seconds: 30
#如果其他服務沒心跳,90S后剔除該服務
eureka.instance.lease-expiration-duration-in-seconds: 90

 

4、創建application-peer2.properties,作為peer2服務中心的配置,並將serviceUrl指向peer1

# 服務名
spring.application.name=cloud-eureka-service
# 服務端口
server.port=8001

eureka.instance.hostname=peer2
# 指示此實例是否應將其信息注冊到eureka服務器以供其他人發現。在某些情況下,您不希望發現實例,而您只想發現其他實例。
eureka.client.register-with-eureka=true
# 指示該客戶端是否應從eureka服務器獲取eureka注冊表信息。
eureka.client.fetch-registry=false

eureka.client.service-url.defaultZone=http://peer1:8000/eureka/


# 關閉服務保護機制
eureka.server.enable-self-preservation=false
# 清理無效節點時間間隔(單位毫秒,默認是60*1000)
eureka.server.eviction-interval-timer-in-ms=30000

#每30S給其他服務發次請求,監測心跳
eureka.instance.lease-renewal-interval-in-seconds: 30
#如果其他服務沒心跳,90S后剔除該服務
eureka.instance.lease-expiration-duration-in-seconds: 90

 

設置服務端口、服務器注冊開關。
默認情況下,服務器啟動時會把自己當做一個客戶端,去注冊Eureka服務器,並且會到Eureka服務器抓取注冊信息。
但這里只是作為一個服務器,而不是服務的提供者(客戶端),因此設置屬性值為flase,否則啟動時會在控制台看到異常信息。
Caused by: java.net.ConnectException: Connection refused: connect
com.netflix.discovery.shared.transport.TransportException: Cannot execute request on any known server

 

5.總的application.properties

#多配置文件
spring.profiles.active=peer1

 

6、host轉換 (system32下... host文件)

127.0.0.1 peer1 
127.0.0.1 peer2 

7.啟動類

package com.cc8w;

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


@SpringBootApplication
@EnableEurekaServer //啟用注冊中心,增加注解@EnableEurekaServer,聲明這是一個Eureka服務器。
public class EurekaServiceApplication 
{
    public static void main( String[] args )
    {
        SpringApplication.run(EurekaServiceApplication.class, args);
    }
}

 

8. 啟動(兩個注冊中心)

啟動第一個注冊中心后,修改application.properties文件改為peer2,再啟動.

 

 

服務方生產者 eureka_provider

 

 

 

 

 

 

 1.pom.xml文件

<?xml version="1.0"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>com.cc8w</groupId>
    <artifactId>springcloud_eureka_demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
  </parent>

  <artifactId>cureka_provider</artifactId>
  <name>cureka_provider</name>
  <url>http://maven.apache.org</url>
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </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-config</artifactId>
        </dependency>
        <!--注冊中心-->
        <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-netflix-eureka-client</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
  </dependencies>
</project>

2.修改配置文件application.properties

# 服務名
spring.application.name=cloud-eureka-provider
# 服務端口
server.port=8761

eureka.instance.hostname=localhost
eureka.client.service-url.defaultZone=http://localhost:8000/eureka/

3.添加實體類UserEntity(一般實體類最好序列化)

package com.cc8w.entity;

import java.io.Serializable;

public class UserEntity implements Serializable {
    
    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    private Integer id;
    private String name;
    public UserEntity() {
        
    }
    public UserEntity(Integer id, String name){
        this.id = id;
        this.name = name;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

4.添加控制器

package com.cc8w.controller;

import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.cc8w.entity.UserEntity;

@RestController
public class UserController {
    @RequestMapping(value = "/user/{userId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public UserEntity findUser(@PathVariable("userId") Integer userId){
        UserEntity user = new UserEntity(userId, "cc8w");
        return user;
    }
}

5.修改啟動類

package com.cc8w;

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

@SpringBootApplication
@EnableEurekaClient //添加注解@EnableEurekaClient,聲明這是一個Eureka客戶端。
public class EurekaProviderApplication 
{
    public static void main( String[] args )
    {
        SpringApplication.run(EurekaProviderApplication.class, args);
    }
}

啟動服務,瀏覽器訪問http://localhost:8000,服務實例列表已經增加了CLOUD-EUREKA-PROVIDER

 

 

 

調用方消費者 eureka_consumer

 

 

 

1.pom.xml文件(可和生產者一樣)

2.修改配置文件application.properties

# 服務名
spring.application.name=cloud-eureka-consumer
# 服務端口
server.port=8762

eureka.instance.hostname=localhost
eureka.client.service-url.defaultZone=http://localhost:8000/eureka/

3.添加控制器

package com.cc8w.controller;

import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * 在控制器中,配置了RestTemplate的Bean,RestTemplate是spring-web模塊下面的類,主要用來調用REST服務。
 * 本身不具有調用分布式服務的能力,但被@LoadBalanced注解修飾后,這個RestTemplate實例就具有訪問調用分布式服務的能力。
 * 另外,下面調用服務,通過服務名稱進行調用。
 */

@RestController
@Configuration
public class InvokerController {
    
    @Bean
    @LoadBalanced
    public RestTemplate getRestTemplate(){
        return new RestTemplate();
    }

    @RequestMapping(value = "/router", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public String router(){
        RestTemplate restTpl = getRestTemplate();
        //根據應用名稱調用服務
        String json = restTpl.getForObject("http://cloud-eureka-provider/user/1", String.class);
        return json;
    }

}

 

4.添加啟動器

package com.cc8w;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

/**
 * 添加注解@EnableDiscoveryClient,使得服務調用者可以去Eureka中發現服務。
 * 說明:@EnableDiscoveryClient注解已經包含了@EnableEurekaClient的功能。
 */
@SpringBootApplication
@EnableDiscoveryClient
public class EurekaConsumerApplication 
{
    public static void main( String[] args )
    {
        SpringApplication.run(EurekaConsumerApplication.class, args);
    }
}

啟動服務,瀏覽器訪問http://localhost:8000,服務實例列表又增加了CLOUD-EUREKA-CONSUMER

 

備注:上面的紅色粗體警告信息表示Eureka已經進入自我保護模式,暫時不用理會。

瀏覽器訪問http://localhost:8762/router,頁面輸出:

{"id":1,"name":"cc8w"}

 

 

可知,成功調用了服務提供者的服務。

總結,本例子的結構圖:

 

 

 代碼在: https://gitee.com/fps2tao/javaboot_study/tree/master/springcloud_eureka_demo

 

轉與參考:

https://www.cnblogs.com/gdjlc/p/11784681.html

https://www.cnblogs.com/e206842/p/11726734.html

https://www.cnblogs.com/xujie09/p/8469735.html

https://www.cnblogs.com/itgaofei/p/9334741.html

https://blog.csdn.net/weixin_42949808/article/details/108018471

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM