SpringCloud之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的服務發布與調用簡單例子

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

1、創建項目

開發工具:IntelliJ IDEA 2019.2.2
IDEA中創建一個新的SpringBoot項目,名稱為“first-ek-server”,SpringBoot版本選擇2.1.9,在選擇Dependencies(依賴)的界面勾選Spring Cloud Discovery -> Eureka Server。

 

創建完成后的pom.xml配置文件自動添加SpringCloud最新穩定版本依賴,當前為Greenwich.SR3
加入的spring-cloud-starter-eureka-server會自動引入spring-boot-starter-web,因此只需加入該依賴,項目就具有Web容器的功能。
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 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.1.9.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>first-ek-server</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>first-ek-server</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
        <spring-cloud.version>Greenwich.SR3</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>

</project>

2、修改配置application.yml

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

server:
  port: 8761
eureka:
  client:
    register-with-eureka: false
    fetch-registry: false

3、修改啟動類代碼FirstEkServerApplication.java

增加注解@EnableEurekaServer,聲明這是一個Eureka服務器。

package com.example.firstekserver;

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

@SpringBootApplication
@EnableEurekaServer
public class FirstEkServerApplication {

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

}

啟動服務,瀏覽器訪問http://localhost:8761,頁面顯示Eureka服務器控制台,里面有服務實例列表,當前是空的。

  

二、編寫服務提供者(生產者)

1、創建項目

IDEA中創建一個新的SpringBoot項目,除了名稱為“first-ek-service-provider”,其它步驟和上面一樣,pom.xml的依賴項也一樣。

2、修改配置application.yml

配置應用名稱為 first-service-provider,該服務將會被注冊到服務器 http://localhost:8761/eureka/

server:
  port: 8762
spring:
  application:
    name: first-service-provider
eureka:
  instance:
    hostname: localhost
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/

3、添加類 User.java

package com.example.firstekserviceprovider;

public class User {
    private Integer id;
    private String name;

    public User(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、添加控制器 UserController.java

提供一個簡單的REST服務。

package com.example.firstekserviceprovider;

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;

@RestController
public class UserController {

    @RequestMapping(value = "/user/{userId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public User findUser(@PathVariable("userId") Integer userId){
        User user = new User(userId, "gdjlc");
        return user;
    }
}

5、修改啟動類代碼FirstEkServerApplication.java

添加注解@EnableEurekaClient,聲明這是一個Eureka客戶端。

package com.example.firstekserviceprovider;

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

@SpringBootApplication
@EnableEurekaClient
public class FirstEkServiceProviderApplication {

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

}

啟動服務,瀏覽器訪問http://localhost:8761,服務實例列表已經增加了FIRST-SERVICE-PROVIDER。

  

三、編寫服務調用者(消費者)

調用者是指同樣注冊到 Eureka的客戶端,來調用其它客戶端發布的服務。

1、創建項目

IDEA中創建一個新的SpringBoot項目,除了名稱為“first-ek-service-invoker”,其它步驟和依賴項和上面都一樣。

2、修改配置application.yml

配置應用名稱為 first-service-invoker,該服務將會被注冊到服務器 http://localhost:8761/eureka/

server:
  port: 8763
spring:
  application:
    name: first-service-invoker
eureka:
  instance:
    hostname: localhost
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/

3、添加控制器 InvokerController.java

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

package com.example.firstekserviceinvoker;

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;

@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://first-service-provider/user/1", String.class);
        return json;
    }
}

4、修改啟動類代碼FirstEkServiceInvokerApplication.java

添加注解@EnableDiscoveryClient,使得服務調用者可以去Eureka中發現服務。
說明:@EnableDiscoveryClient注解已經包含了@EnableEurekaClient的功能。

package com.example.firstekserviceinvoker;

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

@SpringBootApplication
@EnableDiscoveryClient
public class FirstEkServiceInvokerApplication {

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

}

啟動服務,瀏覽器訪問http://localhost:8761,服務實例列表又增加了FIRST-SERVICE-INVOKER。

 

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

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

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

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

總結,本例子的結構圖:

 


免責聲明!

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



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