Spring Boot 集成Fegin和Hystrix實現接口調用以及容錯處理

一、Spring Boot 簡介

Spring Boot是由Pivotal團隊提供的全新框架,其設計目的是簡化新的Spring應用的初始搭建以及開發過程。該框架使用了特定的方式進行配置,從而使開發人員不再需要定義樣板化的配置。Spring Boot致力於在蓬勃發展的快速應用開發領域(rapid application development)成爲領導者。 

在使用Spring Boot之前,我們需要搭建一個項目架構並配置各種第三方庫的依賴,還需要在XML中配置很多內容,繁雜且容易出錯。Spring Boot 完全打破了我們之前的使用習慣,一分鐘就可以創建一個Web開發的項目了通過Starter的方式輕鬆集成第三方的框架;去掉了XML的配置,全部用註解代替。

Spring Boot Starter 是用來簡化jar包依賴的,集成一個框架只需要引入一個Starter,然後在屬性文件中配置一些值,整個集成的過程就結束了。不得不說,Spring Boot 在內部做了很多的處理,讓開發人員使用起來更加簡單了。

下面總價性列幾個使用Spring Boot 開發的優點:

  • 基於 Spring 開發 Web 應用更加容易;
  • 採用基於註解方式的配置,避免了編寫大量重複的 XML 配置;
  • 可以輕鬆集成 Spring 家族的其他框架,比如:Spring JDBC、Spring Data等等;
  • 提供嵌入式服務器,令開發和部署都變的非常簡單。

二、聲明式 REST 客戶端 Fegin

在 JAVA 項目中接口調用怎麼做?比較常用的有 Httpclient 、Okhttp、HttpURLConnection、RestTemplate,這是幾種比較常見的調用接口的方法,下面介紹的方法比這幾個更簡單、方便,它就是 Fegin。

Fegin 是一個聲明式的REST客戶端,它能讓REST調用更加簡單。Fegin 提供了 HTTP 請求的模板,通過編寫簡單的接口和插入註解,就可以定義好 HTTP 請求的參數、格式、地址等信息。

Fegin 會完全代理 HTTP 請求,我們只需要像調用方法一樣調用它就可以完成服務請求以及相關處理。Spring Cloud 對 Fegin 進行了封裝,使其支持 SprngMVC 標準註解和 HttpMessageConverters 。Fegin 可以與 Eureka 和 Ribbon 組合使用以支持負載均衡。

三、Hystrix 服務容錯處理

Hystrix 是 Netflix 針對微服務分佈式系統採用的熔斷保護中間庫,相當於電路中的保險絲。在微服務架構下,很多微服務都相互依賴,如果不能對依賴的服務進行隔離,那麼服務本身也有很能發生故障,Hystrix 通過 HystrixCommand 對調用進行隔離,這樣可以阻止故障的連鎖效應,能夠讓接口調用快速失敗並迅速恢復正常,或者回退並優雅降級。

四、簡單使用

1、添加依賴

注意版本,這裏添加了依賴版本管理

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

		<!-- hystrix斷路器 -->
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
		</dependency>

		<!-- Actuator監控 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-actuator</artifactId>
		</dependency>

		<!-- 查看監控數據 -->
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId>
		</dependency>

	<!-- 依賴版本管理 -->
	<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>

2、application.properties

# feign
# 接口地址
feign.config.address.url=http://localhost:8080/bourse-web
# 名稱
feign.config.address.name=bourse-web

# 開啓hystrix熔斷
feign.hystrix.enabled=true

3、定義一個 Fegin 的客戶端

package com.modules.scistor.feign;

import com.modules.scistor.hystrix.HystrixClientFallback;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;

/**
 * @Auther: lc
 * @Date: 2020/3/14 13:45
 * @Description: 使用fegin調用第三方遠程接口
 */
@FeignClient(url = "${feign.config.address.url}", name = "${feign.config.address.name}", fallback = HystrixClientFallback.class)
public interface FeignClientService {

    /**
     * 違規交易行爲
     * @return
     */
    @GetMapping(value="serviceapi/v1/riskMoniter/keywordstats")
    String riskMoniter();

}

4、Fegin 整合 Hystrix 服務容錯

package com.modules.scistor.hystrix;

import com.modules.scistor.feign.FeignClientService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * @Auther: lc
 * @Date: 2020/3/15 13:36
 * @Description: hystrix接口調用熔斷器
 */
@Component
@Slf4j
public class HystrixClientFallback implements FeignClientService {

    @Override
    public String riskMoniter() {
        log.error("riskMoniter:第三方接口調用失敗!");
        return "第三方接口調用失敗!";
    }
}

5、Controller 控制層

package com.modules.scistor.controller;

import com.modules.scistor.entity.Result;
import com.modules.scistor.feign.FeignClientService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Auther: lc
 * @Date: 2020/3/15 11:54
 * @Description: 風險監測管理
 */
@Api(tags = "風險監測管理")
@Slf4j
@CrossOrigin
@RestController
@RequestMapping("/rest/risk")
public class RiskMonitorController extends BaseController{

    @Autowired
    private FeignClientService feignClientService;

    /**
     * 違規交易行爲
     * @return
     */
    @ApiOperation(value="違規交易行爲",notes = "違規交易行爲")
    @GetMapping(value = "/riskMoniter")
    public Result riskMoniter() {
        String str = feignClientService.riskMoniter();
        return success(str);
    }
}

6、Swagger 調用測試

7、Hystrix 監控

在微服務架構中,Hystrix 除了實現容錯外,還提供了實時監控功能。在服務調用時,Hystrix 會實時累積關於 HystrixCommand 的執行信息,比如每秒的請求書,成功數等。更多信息可查看官方文檔,在上面 XML 我已經加入了依賴 Actuator。

 8、整合 Dashboard 查看監控數據

我們已經知道 Hystrix 提供了監控功能,可以通過 hystrix .stream 端點來獲取監控數據,但是這些數據是以字符串的形式展示的,實際使用中不方便查看。我們可以藉助 Hystrix-dashboard 對監控進行圖形化展示。在上面 XML 我已經加入了依賴 Hystrix-dashboard。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章