【SpringCloud】4.0 新一代負(fù)載均衡組件Open-feign

原先ribbon代碼存在的問(wèn)題:不規(guī)范,風(fēng)格不統(tǒng)一匀们,維護(hù)性比較差

什么是Feign

  • SpringCloud提供的偽http客戶端(本質(zhì)還是用http)塞赂,封裝了Http調(diào)用流程,更適合面向接口化,用Java接口注解的方式調(diào)用Http請(qǐng)求
  • 不用像Ribbon中通過(guò)封裝HTTP請(qǐng)求報(bào)文的方式調(diào)用 Feign默認(rèn)集成了Ribbon
  • Nacos支持Feign,可以直接集成實(shí)現(xiàn)負(fù)載均衡的效果

Ribbon和feign兩個(gè)的區(qū)別和選擇

  • 選擇feign
  • 默認(rèn)集成了ribbon
  • 寫(xiě)起來(lái)更加思路清晰和方便
  • 采用注解方式進(jìn)行配置,配置熔斷等方式方便

官方文檔

https://spring.io/projects/spring-cloud-openfeign

接入 Open-feign (相關(guān)代碼完整版放在本文最后部分)

在之前章節(jié)的基礎(chǔ)上酌住,online-edu\pom.xml增加依賴(lài):

            <!-- 負(fù)載均衡-openfeign -->
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-openfeign</artifactId>
                <version>4.1.3</version>
            </dependency>

online-edu-order-service/pom.xml

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>

online-edu-order-service/src/main/java/org/online_edu/OrderApplication.java


package org.online_edu;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication()
@MapperScan("org.online_edu.dao")
// 開(kāi)啟服務(wù)發(fā)現(xiàn)
@EnableDiscoveryClient
// 開(kāi)啟openfeign負(fù)載均衡支持
@EnableFeignClients
public class OrderApplication {

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

    @Bean
    @LoadBalanced
    public RestTemplate getRestTemplate() {
        return new RestTemplate();
    }
}

online-edu-order-service/src/main/java/org/online_edu/controller/VideoOrderController.java

package org.online_edu.controller;

import org.online_edu.domain.Video;
import org.online_edu.domain.VideoOrder;
import org.online_edu.service.VideoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

@RestController
@RequestMapping("/api/v1/video_order")
public class VideoOrderController {

    /**
     * 服務(wù)對(duì)象
     */
    @Autowired
    private VideoService videoService;

    @RequestMapping("/find_by_id")
    public Object save(@RequestParam(name = "videoId") int videoId) {

        Video video = videoService.findById(videoId);
        VideoOrder videoOrder = new VideoOrder();
        if (video != null) {
            videoOrder.setServeInfo(video.getServeInfo());
            videoOrder.setVideoId(video.getId());
            videoOrder.setVideoTitle(video.getTitle());
            videoOrder.setCreateTime(new Date());
        }
        return videoOrder;
    }
}


online-edu-order-service/src/main/java/org/online_edu/service/VideoService.java

package org.online_edu.service;

import org.online_edu.domain.Video;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

@FeignClient(value = "online-edu-video-service")
public interface VideoService {
    @GetMapping(value = "/api/v1/video/find_by_id")
    Video findById(@RequestParam("videoId") int videoId);
}

online-edu-video-service/src/main/java/org/online_edu/controller/VideoController.java

package org.online_edu.controller;

import jakarta.servlet.http.HttpServletRequest;
import org.online_edu.domain.Video;
import org.online_edu.service.VideoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("api/v1/video")
public class VideoController {
    @Autowired
    private VideoService videoService;


    @RequestMapping("/find_by_id")
    public Video findById(@RequestParam(name = "videoId") int videoId, HttpServletRequest request) {
        Video video = videoService.findById(videoId);
        // 拿到服務(wù)端的id+端口
        video.setServeInfo(request.getServerName() + ":" + request.getServerPort());
        return video;
    }
}

完整代碼如下:
online-edu\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>org.online_edu</groupId>
    <artifactId>online-edu</artifactId>
    <version>1.0-SNAPSHOT</version>

    <modules>
        <module>online-edu-common</module>
        <module>online-edu-video-service</module>
        <module>online-edu-user-service</module>
        <module>online-edu-order-service</module>
        <module>online-edu-generator</module>
    </modules>
    <!-- 一般來(lái)說(shuō)父級(jí)項(xiàng)目的packaging都為pom伴挚,packaging默認(rèn)類(lèi)型jar類(lèi)型-->
    <packaging>pom</packaging>

    <properties>
        <java.version>21</java.version>
        <maven.compiler.source>21</maven.compiler.source>
        <maven.compiler.target>21</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <spring-boot-dependencies.version>3.3.3</spring-boot-dependencies.version>
        <spring-cloud-dependencies.version>2023.0.3</spring-cloud-dependencies.version>
        <spring-cloud-alibaba-dependencies.version>2023.0.1.2</spring-cloud-alibaba-dependencies.version>
        <org.mapstruct.version>1.6.0</org.mapstruct.version>
    </properties>
    <!--鎖定版本-->
    <dependencyManagement>
        <dependencies>
            <!-- **************************** 分布式核心 **************************** -->
            <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-dependencies -->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>${spring-boot-dependencies.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-dependencies -->
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud-dependencies.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <!-- https://mvnrepository.com/artifact/com.alibaba.cloud/spring-cloud-alibaba-dependencies -->
            <dependency>
                <groupId>com.alibaba.cloud</groupId>
                <artifactId>spring-cloud-alibaba-dependencies</artifactId>
                <version>${spring-cloud-alibaba-dependencies.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-loadbalancer -->
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-loadbalancer</artifactId>
                <version>4.1.4</version>
            </dependency>
            <!-- 負(fù)載均衡-openfeign -->
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-openfeign</artifactId>
                <version>4.1.3</version>
            </dependency>
            <!-- **************************** 分布式核心 **************************** -->

            <!-- **************************** 數(shù)據(jù)庫(kù)依賴(lài) **************************** -->
            <!-- MyBatis-Plus啟動(dòng)器,增強(qiáng)版MyBatis沦辙,提供更高效的操作和動(dòng)態(tài)SQL能力 -->
            <!-- https://mvnrepository.com/artifact/com.baomidou/mybatis-plus-spring-boot3-starter -->
            <dependency>
                <groupId>com.baomidou</groupId>
                <artifactId>mybatis-plus-spring-boot3-starter</artifactId>
                <version>3.5.7</version>
            </dependency>
            <!-- https://mvnrepository.com/artifact/com.baomidou/mybatis-plus-generator -->
            <dependency>
                <groupId>com.baomidou</groupId>
                <artifactId>mybatis-plus-generator</artifactId>
                <version>3.5.7</version>
            </dependency>
            <!-- PostgreSQL的JDBC驅(qū)動(dòng) -->
            <!-- https://mvnrepository.com/artifact/org.postgresql/postgresql -->
            <dependency>
                <groupId>org.postgresql</groupId>
                <artifactId>postgresql</artifactId>
                <version>42.7.3</version>
            </dependency>
            <!-- Druid組件 -->
            <!-- https://mvnrepository.com/artifact/com.alibaba/druid-spring-boot-3-starter -->
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>druid-spring-boot-3-starter</artifactId>
                <version>1.2.23</version>
            </dependency>

            <!-- https://mvnrepository.com/artifact/com.github.pagehelper/pagehelper-spring-boot-starter -->
            <dependency>
                <groupId>com.github.pagehelper</groupId>
                <artifactId>pagehelper-spring-boot-starter</artifactId>
                <version>2.1.0</version>
            </dependency>

            <!-- **************************** 數(shù)據(jù)庫(kù)依賴(lài) **************************** -->

            <!-- **************************** 工具類(lèi) **************************** -->
            <!-- 一個(gè)用于在 Java Bean 之間轉(zhuǎn)換的代碼生成工具夫植。-->
            <!-- 官網(wǎng):https://mapstruct.org/ -->
            <!-- https://mvnrepository.com/artifact/org.mapstruct/mapstruct -->
            <dependency>
                <groupId>org.mapstruct</groupId>
                <artifactId>mapstruct</artifactId>
                <version>${org.mapstruct.version}</version>
            </dependency>
            <!-- https://mvnrepository.com/artifact/org.mapstruct/mapstruct-processor -->
            <dependency>
                <groupId>org.mapstruct</groupId>
                <artifactId>mapstruct-processor</artifactId>
                <version>${org.mapstruct.version}</version>
            </dependency>
            <!--         commons-lang3:  通用的、可復(fù)用的 Java 組件油讯,已其他包引入-->
            <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->

            <!--(Map详民、List、Set集合全覆蓋)集合開(kāi)發(fā)工具-->
            <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-collections4 -->
            <dependency>
                <groupId>org.apache.commons</groupId>
                <artifactId>commons-collections4</artifactId>
                <version>4.5.0-M2</version>
            </dependency>
            <!-- Java增強(qiáng)器陌兑,像Java Next版本-->
            <!-- 集合 [collections] 沈跨、緩存 [caching] 、原生類(lèi)型支持 [primitives support] 兔综、
            并發(fā)庫(kù) [concurrency libraries] 饿凛、通用注解 [common annotations] 狞玛、
            字符串處理 [string processing] 、I/O 等等-->
            <!-- https://mvnrepository.com/artifact/com.google.guava/guava -->
            <dependency>
                <groupId>com.google.guava</groupId>
                <artifactId>guava</artifactId>
                <version>33.3.0-jre</version>
            </dependency>
            <!-- Java必備工具庫(kù) -->
            <!-- https://mvnrepository.com/artifact/cn.hutool/hutool-all -->
            <dependency>
                <groupId>cn.hutool</groupId>
                <artifactId>hutool-all</artifactId>
                <version>5.8.32</version>
            </dependency>
            <!-- JSON序列化和反序列化 :已由別的包引入-->
            <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
            <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
            <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
            <!-- **************************** 工具類(lèi) **************************** -->

        </dependencies>
    </dependencyManagement>
    <build>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                    <configuration>
                        <addResources>true</addResources>
                    </configuration>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>
</project>

online-edu-order-service/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.online_edu</groupId>
        <artifactId>online-edu</artifactId>
        <version>1.0-SNAPSHOT</version>
    </parent>

    <artifactId>online-edu-order-service</artifactId>

    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-web -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.online_edu</groupId>
            <artifactId>online-edu-common</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>

        <!--        <dependency>-->
        <!--            <groupId>com.alibaba.cloud</groupId>-->
        <!--            <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>-->
        <!--        </dependency>-->
        <!-- 添加nacos客戶端——服務(wù)注冊(cè) -->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-spring-boot3-starter</artifactId>
        </dependency>
        <!-- PostgreSQL的JDBC驅(qū)動(dòng) -->
        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-3-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-loadbalancer</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>
    </dependencies>
</project>

運(yùn)行:


image.png

Post傳輸對(duì)象

online-edu-order-service/src/main/java/org/online_edu/controller/VideoOrderController.java

    @PostMapping("/save")
    public void save(@RequestBody Video video) {
        videoService.save(video);
    }

online-edu-order-service/src/main/java/org/online_edu/service/VideoService.java

    @PostMapping(value = "/api/v1/video/save")
    int save(@RequestBody Video video);

online-edu-video-service/src/main/java/org/online_edu/controller/VideoController.java

    /**
     * 測(cè)試 feign 調(diào)用 使用post方法傳輸對(duì)象
     *
     * @param video
     * @return
     */
    @PostMapping("/save")
    public Object save(@RequestBody Video video) {
        int rows = videoService.save(video);
        System.out.println(video.getTitle());
        HashMap<String, Object> map = new HashMap<>();
        map.put("row", rows);
        return map;
    }

online-edu-video-service/src/main/java/org/online_edu/service/VideoService.java


    int save(Video video);

online-edu-video-service/src/main/java/org/online_edu/service/impl/VideoServiceImpl.java

    /**
     * @param video
     * @return
     */
    @Override
    public int save(Video video) {
        return 1;
    }

運(yùn)行:
Header中的Content-Type設(shè)置成application/json

image.png

image.png

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末涧窒,一起剝皮案震驚了整個(gè)濱河市心肪,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌纠吴,老刑警劉巖硬鞍,帶你破解...
    沈念sama閱讀 216,372評(píng)論 6 498
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異戴已,居然都是意外死亡固该,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,368評(píng)論 3 392
  • 文/潘曉璐 我一進(jìn)店門(mén)恭陡,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)蹬音,“玉大人,你說(shuō)我怎么就攤上這事休玩≈” “怎么了?”我有些...
    開(kāi)封第一講書(shū)人閱讀 162,415評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵拴疤,是天一觀的道長(zhǎng)永部。 經(jīng)常有香客問(wèn)我,道長(zhǎng)呐矾,這世上最難降的妖魔是什么苔埋? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,157評(píng)論 1 292
  • 正文 為了忘掉前任,我火速辦了婚禮蜒犯,結(jié)果婚禮上组橄,老公的妹妹穿的比我還像新娘。我一直安慰自己罚随,他們只是感情好玉工,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,171評(píng)論 6 388
  • 文/花漫 我一把揭開(kāi)白布。 她就那樣靜靜地躺著淘菩,像睡著了一般遵班。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上潮改,一...
    開(kāi)封第一講書(shū)人閱讀 51,125評(píng)論 1 297
  • 那天狭郑,我揣著相機(jī)與錄音,去河邊找鬼汇在。 笑死翰萨,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的糕殉。 我是一名探鬼主播缨历,決...
    沈念sama閱讀 40,028評(píng)論 3 417
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼以蕴,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了辛孵?” 一聲冷哼從身側(cè)響起丛肮,我...
    開(kāi)封第一講書(shū)人閱讀 38,887評(píng)論 0 274
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎魄缚,沒(méi)想到半個(gè)月后宝与,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,310評(píng)論 1 310
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡冶匹,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,533評(píng)論 2 332
  • 正文 我和宋清朗相戀三年习劫,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片嚼隘。...
    茶點(diǎn)故事閱讀 39,690評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡诽里,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出飞蛹,到底是詐尸還是另有隱情谤狡,我是刑警寧澤,帶...
    沈念sama閱讀 35,411評(píng)論 5 343
  • 正文 年R本政府宣布卧檐,位于F島的核電站墓懂,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏霉囚。R本人自食惡果不足惜捕仔,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,004評(píng)論 3 325
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望盈罐。 院中可真熱鬧榜跌,春花似錦、人聲如沸盅粪。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,659評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)湾揽。三九已至,卻和暖如春笼吟,著一層夾襖步出監(jiān)牢的瞬間库物,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 32,812評(píng)論 1 268
  • 我被黑心中介騙來(lái)泰國(guó)打工贷帮, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留戚揭,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 47,693評(píng)論 2 368
  • 正文 我出身青樓撵枢,卻偏偏與公主長(zhǎng)得像民晒,于是被迫代替她去往敵國(guó)和親精居。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,577評(píng)論 2 353

推薦閱讀更多精彩內(nèi)容