跟我學SpringCloud | 第三篇:服務的提供與Feign調用

来源:https://www.cnblogs.com/babycomeon/archive/2019/07/03/11117763.html
-Advertisement-
Play Games

跟我學SpringCloud | 第三篇:服務的提供與Feign調用 上一篇,我們介紹了註冊中心的搭建,包括集群環境嚇註冊中心的搭建,這篇文章介紹一下如何使用註冊中心,創建一個服務的提供者,使用一個簡單的客戶端去調用服務端提供的服務。 本篇文章中需要三個角色,分別是服務的提供者,服務的消費者,還有一 ...


跟我學SpringCloud | 第三篇:服務的提供與Feign調用

上一篇,我們介紹了註冊中心的搭建,包括集群環境嚇註冊中心的搭建,這篇文章介紹一下如何使用註冊中心,創建一個服務的提供者,使用一個簡單的客戶端去調用服務端提供的服務。

本篇文章中需要三個角色,分別是服務的提供者,服務的消費者,還有一個是上一篇文章的主角——註冊中心Eureka(使用單機版本即可,本篇的示例也會使用單機版本的Eureka)。

整體流程為:

  1. 先啟動註冊中心Eureka
  2. 啟動服務的提供者將提供服務,並將服務註冊到註冊中心Eureka上
  3. 啟動服務的消費者,在註冊中心中找到服務並完成消費

1. 服務提供者

1. 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>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.6.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.springcloud</groupId>
    <artifactId>producer</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>producer</name>
    <description>Demo project for Spring Boot</description>

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

</project>

2. 配置文件application.yml

server:
  port: 8080
spring:
  application:
    name: spring-cloud-producer
eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka/

3. 啟動類ProducerApplication.java

增加@EnableEurekaClient,如果是其他註冊中心可以使用註解@EnableDiscoveryClient來進行服務的註冊

package com.springcloud.producer;

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

@SpringBootApplication
@EnableEurekaClient
public class ProducerApplication {

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

}

4. Controller

package com.springcloud.producer.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created with IntelliJ IDEA.
 *
 * @Date: 2019/7/2
 * @Time: 0:02
 * @email: [email protected]
 * Description:
 */
@RestController
public class HelloController {
    @RequestMapping("/hello")
    public String hello(@RequestParam String name) {
        return "hello "+name+",producer is ready";
    }
}

先在可以先啟動上一篇當中單機版的Eureka,再啟動我們剛寫好的producer服務提供者,啟動成功後,訪問鏈接http://localhost:8761/,可以看到我們的的服務提供者producer已經成功註冊在註冊中心上了。

至此,服務的提供者已經配置完成。

2. 服務消費者

1. 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>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.6.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.springcloud</groupId>
    <artifactId>consumers</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>consumers</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
        <spring-cloud.version>Greenwich.SR1</spring-cloud.version>
    </properties>

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

spring-boot-starter-web: 這個包是通用的web開發包,裡面包含了spring-web、spring-webmvc等包

spring-cloud-starter-openfeign: 這個包是springcloud對於Feign的封裝,Feign是一個聲明式的Web服務客戶端。它支持Feign本身的註解、JAX-RS註解以及SpringMVC的註解。Spring Cloud集成Ribbon和Eureka以在使用Feign時提供負載均衡的http客戶端。

2. 配置文件application.yml

server:
  port: 8081
spring:
  application:
    name: spring-cloud-consumers
eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka/

3. 啟動類ConsumersApplication.java

同上,增加@EnableEurekaClient,如果是其他註冊中心可以使用註解@EnableDiscoveryClient來進行服務的註冊

package com.springcloud.consumers;

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

@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients
public class ConsumersApplication {

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

}

@EnableFeignClients: 這個註解是通知SpringBoot在啟動的時候,掃描被 @FeignClient 修飾的類,@FeignClient這個註解在進行遠程調用的時候會用到。

4. Feign遠程調用

Feign是一個聲明式Web Service客戶端。使用Feign能讓編寫Web Service客戶端更加簡單, 它的使用方法是定義一個介面,然後在上面添加註解,同時也支持JAX-RS標準的註解。Feign也支持可拔插式的編碼器和解碼器。Spring Cloud對Feign進行了封裝,使其支持了Spring MVC標準註解和HttpMessageConverters。Feign可以與Eureka和Ribbon組合使用以支持負載均衡。

創建一個remote介面

package com.springcloud.consumers.remote;

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * @Author: shiyao.wei
 * @Date: 2019/7/2 11:14
 * @Version: 1.0
 * @Desc:
 */
@FeignClient(name= "spring-cloud-producer")
public interface HelloRemote {
    @RequestMapping(value = "/hello")
    String hello(@RequestParam(value = "name") String name);
}
  • name:遠程服務名,及spring.application.name配置的名稱
  • 此類中的方法和遠程服務中contoller中的方法名和參數需保持一致

5. web層調用遠程介面 Controller

package com.springcloud.consumers.controller;

import com.springcloud.consumers.remote.HelloRemote;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author: shiyao.wei
 * @Date: 2019/7/2 11:25
 * @Version: 1.0
 * @Desc:
 */
@RestController
public class HelloController {
    @Autowired
    HelloRemote helloRemote;

    @RequestMapping("/hello/{name}")
    public String index(@PathVariable("name") String name) {
        return helloRemote.hello(name);
    }
}

現在,一個最簡單的服務註冊和調用的例子就完成了。

3. 測試

簡單調用

順次啟動eureka、producer、consumer三個項目

啟動成功後,先在瀏覽器輸入http://localhost:8080/hello?name=springcloud

可以看到頁面顯示:hello springcloud,producer is ready

證明我們的producer已經正常啟動,提供的服務也正常

接下來,我們測試服務消費者,在瀏覽器中輸入:http://localhost:8081/hello/spring

可以看到頁面顯示:hello spring,producer is ready

說明客戶端已經成功的通過feign調用了遠程服務hello,並且將結果返回到了瀏覽器。

負載均衡

將上面的producer複製一份,修改名稱為producer2,修改pom.xml中的<name></name>為producer2,修改其中的Controller:

package com.springcloud.producer.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created with IntelliJ IDEA.
 *
 * @Date: 2019/7/2
 * @Time: 0:02
 * @email: [email protected]
 * Description:
 */
@RestController
public class HelloController {
    @RequestMapping("/hello")
    public String hello(@RequestParam String name) {
        return "hello "+name+",producer2 is ready";
    }
}

修改application.yml配置文件啟動埠為8082

啟動我們剛複製好的producer2,這時可以看一下註冊中心Eureka,我們現在已經有兩個producer服務了。

這時我們再去訪問:http://localhost:8081/hello/spring

第一次返回結果:hello spring,producer is ready

第二次返回結果:hello spring,producer2 is ready

連續刷新頁面,兩個結果會交替出現,說明註冊中心提供了服務負載均衡功能。將服務數提高到N個,會發現測試結果一樣,請求會自動輪詢到每個服務端來處理。

好了,現在可以將代碼打包扔到Github上去了,歡迎大家前往Github騷擾:)

示例代碼-Github


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 博客園添加背景音樂,背景效果 [TOC] 申請博客園JS許可權 申請話術 實例 開通以後就可以使用js代碼進行裝飾了 流程圖 添加網易雲背景音樂 單曲添加 打開網易雲登錄賬戶,搜索自己喜歡的歌曲 複製代碼到博客園 看看效果 添加歌單為背景音樂 創建歌單 把喜歡的音樂添加到歌單 拷貝代碼到博客園 點擊鼠 ...
  • 可以用 v-on 指令監聽 DOM 事件,併在觸發時運行一些 JavaScript 代碼,例如: 渲染結果為: 我們給測試按鈕添加了一個mouseenter和click事件,滑鼠移上去式控制台輸出: 當點擊時,輸出為: Vue的事件綁定有很多種寫法,例如: 可以看到v-on對應事件可以很多種格式的, ...
  • DOM(元素節點) 基本選擇器 常規 常規 <div id="box">div_id_1</div> <div id="box">div_id_2</div> <div id="char">div_id_2</div> <div class="cont">div_class_1</div> <div ...
  • 一、打開谷歌控制台:https://console.developers.google.com/apis 二、點擊創建憑據,如下圖,填寫項目地址等 三、創建好客戶端ID和秘鑰後,填寫對應的項目網址和登錄頁網址 四、修改OAuth同意屏幕網站首頁地址和隱私政策網址 五、代碼部分如下: ...
  • 一、兄弟元素的外邊距合併 效果圖如下:(二者之間的間距為100px,不是150px) 二、嵌套元素的外邊距合併 對於兩個嵌套關係的元素,如果父元素中沒有內容或者內容在子元素的後面並且沒有上內邊距及邊框,則父元素的上邊距會與子元素的上外邊距發生合併,且值為最大的那個上外邊距,同時該值作為父元素的上外邊 ...
  • NPM幾個常用命令和參數的意思: 安裝模塊如不指定版本號 預設會安裝最新的版本 安裝指定版本的模塊 這個命令會在當前目錄生成一個package.json文件,這個文件中會記錄一些關於項目的信息,比如:項目的作者,git地址,入口文件、命令設置、項目名稱和版本號等等,一般情況下這個文件是必須要有的,方 ...
  • // 購物車數量減少$('.reduce').click(function () { addMinus(this,0)});// 購物車數量增加$('.increase').click(function () { addMinus(this,1)});function addMinus(t,stat ...
  • 一、新建dist 文件夾; 二、新建src文件夾: 在其下麵創建 css 、js 、images文件夾及 index.html、main.js(這是項目Js的主入口) 三、html中簡單創建一個列表; main.js中設置單雙行變色; 四、由於ES6太高級,瀏覽器解析不了,需要轉換為低級的能識別的版 ...
一周排行
    -Advertisement-
    Play Games
  • 示例項目結構 在 Visual Studio 中創建一個 WinForms 應用程式後,項目結構如下所示: MyWinFormsApp/ │ ├───Properties/ │ └───Settings.settings │ ├───bin/ │ ├───Debug/ │ └───Release/ ...
  • [STAThread] 特性用於需要與 COM 組件交互的應用程式,尤其是依賴單線程模型(如 Windows Forms 應用程式)的組件。在 STA 模式下,線程擁有自己的消息迴圈,這對於處理用戶界面和某些 COM 組件是必要的。 [STAThread] static void Main(stri ...
  • 在WinForm中使用全局異常捕獲處理 在WinForm應用程式中,全局異常捕獲是確保程式穩定性的關鍵。通過在Program類的Main方法中設置全局異常處理,可以有效地捕獲並處理未預見的異常,從而避免程式崩潰。 註冊全局異常事件 [STAThread] static void Main() { / ...
  • 前言 給大家推薦一款開源的 Winform 控制項庫,可以幫助我們開發更加美觀、漂亮的 WinForm 界面。 項目介紹 SunnyUI.NET 是一個基於 .NET Framework 4.0+、.NET 6、.NET 7 和 .NET 8 的 WinForm 開源控制項庫,同時也提供了工具類庫、擴展 ...
  • 說明 該文章是屬於OverallAuth2.0系列文章,每周更新一篇該系列文章(從0到1完成系統開發)。 該系統文章,我會儘量說的非常詳細,做到不管新手、老手都能看懂。 說明:OverallAuth2.0 是一個簡單、易懂、功能強大的許可權+可視化流程管理系統。 有興趣的朋友,請關註我吧(*^▽^*) ...
  • 一、下載安裝 1.下載git 必須先下載並安裝git,再TortoiseGit下載安裝 git安裝參考教程:https://blog.csdn.net/mukes/article/details/115693833 2.TortoiseGit下載與安裝 TortoiseGit,Git客戶端,32/6 ...
  • 前言 在項目開發過程中,理解數據結構和演算法如同掌握蓋房子的秘訣。演算法不僅能幫助我們編寫高效、優質的代碼,還能解決項目中遇到的各種難題。 給大家推薦一個支持C#的開源免費、新手友好的數據結構與演算法入門教程:Hello演算法。 項目介紹 《Hello Algo》是一本開源免費、新手友好的數據結構與演算法入門 ...
  • 1.生成單個Proto.bat內容 @rem Copyright 2016, Google Inc. @rem All rights reserved. @rem @rem Redistribution and use in source and binary forms, with or with ...
  • 一:背景 1. 講故事 前段時間有位朋友找到我,說他的窗體程式在客戶這邊出現了卡死,讓我幫忙看下怎麼回事?dump也生成了,既然有dump了那就上 windbg 分析吧。 二:WinDbg 分析 1. 為什麼會卡死 窗體程式的卡死,入口門檻很低,後續往下分析就不一定了,不管怎麼說先用 !clrsta ...
  • 前言 人工智慧時代,人臉識別技術已成為安全驗證、身份識別和用戶交互的關鍵工具。 給大家推薦一款.NET 開源提供了強大的人臉識別 API,工具不僅易於集成,還具備高效處理能力。 本文將介紹一款如何利用這些API,為我們的項目添加智能識別的亮點。 項目介紹 GitHub 上擁有 1.2k 星標的 C# ...