日韩成人免费在线_国产成人一二_精品国产免费人成电影在线观..._日本一区二区三区久久久久久久久不

當前位置:首頁 > 科技  > 軟件

深入探討API網關APISIX中自定義Java插件在真實項目中的運用

來源: 責編: 時間:2024-01-18 17:40:18 220觀看
導讀環境:APISIX3.4.1 + JDK11 + SpringBoot2.7.12一. APISIX簡介APISIX 網關作為所有業務的流量入口,它提供了動態路由、動態上游、動態證書、A/B 測試、灰度發布(金絲雀發布)、藍綠部署、限速、防攻擊、收集指標、監控報警

環境:APISIX3.4.1 + JDK11 + SpringBoot2.7.12bHb28資訊網——每日最新資訊28at.com

一. APISIX簡介

APISIX 網關作為所有業務的流量入口,它提供了動態路由、動態上游、動態證書、A/B 測試、灰度發布(金絲雀發布)、藍綠部署、限速、防攻擊、收集指標、監控報警、可觀測、服務治理等功能。bHb28資訊網——每日最新資訊28at.com

為什么使用APISIX?bHb28資訊網——每日最新資訊28at.com

  1. 高性能和可擴展性:APISIX是基于Nginx和OpenResty構建的,具有高性能和可擴展性。它支持動態路由、限流、緩存、認證等功能,并可以通過插件擴展其他功能。
  2. 社區活躍,易于使用:APISIX的社區非常活躍,提供了完整的文檔,使其易于使用。此外,它也支持類似于Kubernetes中的自動化部署,適合對網絡部署和管理要求高的團隊。
  3. 處理API和微服務流量的強大工具:Apache APISIX是一個動態、實時、高性能的開源API網關,可以快速、安全地處理API和微服務流量,包括網關、Kubernetes Ingress和服務網格等。全球已有數百家企業使用Apache APISIX處理關鍵業務流量,涵蓋金融、互聯網、制造、零售、運營商等各個領域。
  4. 云原生技術體系統一:APISIX從底層架構上避免了宕機、丟失數據等情況的發生。在控制面上,APISIX使用了etcd存儲配置信息,這與云原生技術體系更為統一,能更好地體現高可用特性。
  5. 實時配置更新:使用etcd作為存儲后,APISIX可以在毫秒級別內獲取到最新的配置信息,實現實時生效。相比之下,如果采用輪詢數據庫的方式,可能需要5-10秒才能獲取到最新的配置信息。

綜上所述,APISIX是一個優秀的開源API網關,具有高性能、可擴展性、社區活躍、易于使用等特點,并且能夠處理API和微服務流量,避免宕機、丟失數據等問題,實現實時配置更新。因此,許多企業和團隊選擇使用APISIX作為其API網關解決方案。bHb28資訊網——每日最新資訊28at.com

二. APISIX安裝

關于APISIX的安裝參考官方文檔即可bHb28資訊網——每日最新資訊28at.com


bHb28資訊網——每日最新資訊28at.com

APISIX安裝指南bHb28資訊網——每日最新資訊28at.com


bHb28資訊網——每日最新資訊28at.com

https://apisix.apache.org/zh/docs/apisix/installation-guide/bHb28資訊網——每日最新資訊28at.com

我使用的docker部署bHb28資訊網——每日最新資訊28at.com

三. 需求說明

  1. 目的與背景:

由于安全需要,現有系統接口的請求數據需要加密(調用方必須加密傳輸)。bHb28資訊網——每日最新資訊28at.com

考慮到對現有系統的最小化影響,決定采用APISIX作為中間件,通過自定義Java插件來實現數據加密的功能。bHb28資訊網——每日最新資訊28at.com

  1. 功能需求:
  • 數據加密:插件需要能夠接收并解析請求數據,然后對數據進行解密處理(解密后的數據再提交到上游服務)。bHb28資訊網——每日最新資訊28at.com

  • 安全性:加密算法和密鑰管理應遵循業界最佳實踐,確保數據安全。bHb28資訊網——每日最新資訊28at.com

  • 錯誤處理與日志記錄:插件應具備良好的錯誤處理機制,并能夠記錄詳細的日志,以便于問題排查。(這通過記錄日志即可)bHb28資訊網——每日最新資訊28at.com

  1. 非功能需求:bHb28資訊網——每日最新資訊28at.com

  • 可維護性:插件代碼應清晰、模塊化,便于后續的維護和升級。bHb28資訊網——每日最新資訊28at.com

  • 可擴展性:考慮到未來可能的加密需求變化,插件應具備良好的擴展性。bHb28資訊網——每日最新資訊28at.com

四. 插件工作原理

apisix-java-plugin-runner 設計為使用 netty 構建的 TCP 服務器,它提供了一個 PluginFilter 接口供用戶實現。用戶只需關注其業務邏輯,而無需關注 apisix java 插件運行程序如何與 APISIX 通信的細節;它們之間的進程間通信如下圖所示。bHb28資訊網——每日最新資訊28at.com

圖片圖片bHb28資訊網——每日最新資訊28at.com

核心運行原理

官方的包是基于springboot,所以它自身提供了一個CommandLineRunner類,該類會在Springboot容器啟動完成后運行,也就是下面的地方執行:
bHb28資訊網——每日最新資訊28at.com

public class SpringApplication {  public ConfigurableApplicationContext run(String... args) {    // ...這里ApplicationContext等相關的初始化    callRunners(context, applicationArguments);  }}

核心Runner類

public class ApplicationRunner implements CommandLineRunner {  private ObjectProvider<PluginFilter> filterProvider;  public void run(String... args) throws Exception {    if (socketFile.startsWith("unix:")) {      socketFile = socketFile.substring("unix:".length());    }    Path socketPath = Paths.get(socketFile);    Files.deleteIfExists(socketPath);    // 啟動netty服務    start(socketPath.toString());  }  public void start(String path) throws Exception {    EventLoopGroup group;    ServerBootstrap bootstrap = new ServerBootstrap();      // 判斷使用什么channel      bootstrap.group(group).channel(...)    try {      // 初始化netty服務      initServerBootstrap(bootstrap);      ChannelFuture future = bootstrap.bind(new DomainSocketAddress(path)).sync();      Runtime.getRuntime().exec("chmod 777 " + socketFile);      future.channel().closeFuture().sync();    } finally {      group.shutdownGracefully().sync();    }  }  private void initServerBootstrap(ServerBootstrap bootstrap) {    bootstrap.childHandler(new ChannelInitializer<DomainSocketChannel>() {      @Override      protected void initChannel(DomainSocketChannel channel) {        channel.pipeline().addFirst("logger", new LoggingHandler())          //...          // 核心Handler          .addAfter("payloadDecoder", "prepareConfHandler", createConfigReqHandler(cache, filterProvider, watcherProvider))          // ...      }    });  }}

五. 插件開發

5.1 依賴管理

<properties>  <java.version>11</java.version>  <spring-boot.version>2.7.12</spring-boot.version>  <apisix.version>0.4.0</apisix.version>  <keys.version>1.1.4</keys.version></properties><dependencies>  <dependency>    <groupId>org.apache.apisix</groupId>    <artifactId>apisix-runner-starter</artifactId>    <version>${apisix.version}</version>  </dependency>  <!-- 封裝了各類加解密功能如:SM,AES,RSA等算法-->  <dependency>    <groupId>com.pack.components</groupId>    <artifactId>pack-keys</artifactId>    <version>${keys.version}</version>  </dependency>  <dependency>    <groupId>com.fasterxml.jackson.core</groupId>    <artifactId>jackson-databind</artifactId>  </dependency>  <dependency>    <groupId>org.springframework</groupId>    <artifactId>spring-web</artifactId>  </dependency></dependencies>

5.2 配置文件

這里的配置可有可無,都有默認值bHb28資訊網——每日最新資訊28at.com

cache.config:  expired: ${APISIX_CONF_EXPIRE_TIME}  capacity: 1000socket:  file: ${APISIX_LISTEN_ADDRESS}

5.3 啟動類配置

@SpringBootApplication(scanBasePackages = { "com.pack", "org.apache.apisix.plugin.runner" })public class CryptoApisixPluginRunnerApplication {  public static void main(String[] args) {    new SpringApplicationBuilder(CryptoApisixPluginRunnerApplication.class).web(NONE).run(args);  }}

注意:關鍵就是上面的"org.apache.apisix.plugin.runner"包路徑。bHb28資訊網——每日最新資訊28at.com

5.4 Filter開發

總共2個插件:bHb28資訊網——每日最新資訊28at.com

  • java插件
    該插件用來對數據解密。
  • LUA插件
    該插件用來改寫請求body,因為在java插件中無法改寫。

定義一個抽象類,實現了通過的功能bHb28資訊網——每日最新資訊28at.com

public abstract class AbstractDecryptPreFilter implements PluginFilter {  // 具體細節由子類實現  protected abstract void doFilterInternal(HttpRequest request, HttpResponse response, PluginFilterChain chain,     CryptModel cryptModel, CacheModel cache);  // 工具類專門用來讀取針對插件的配置信息  @Resource  protected ConfigProcessor<BaseCryptoModel> configCryptoProcessor;  // 工具類專門用來處理加解密  @Resource  protected CryptoProcessor cryptoProcessor;  // 工具類專門用來判斷路徑匹配  @Resource  protected PathProcessor pathProcessor ;  // 是否開啟了插件功能  protected boolean isEnabled(HttpRequest request, BaseCryptoModel cryptoModel) {    if (request == null || cryptoModel == null) {      return false;    }    return cryptoModel.isEnabled();  }  // 檢查請求,對有些請求是不進行處理的比如OPTIONS,HEADER。  protected boolean checkRequest(HttpRequest request, CryptModel cryptModel, CacheModel cache) {    if (isOptionsOrHeadOrTrace(request)) {      return false ;    }    String contentType = request.getHeader("content-type") ;    logger.info("request method: {}, content-type: {}", request.getMethod(), contentType) ;    if (isGetOrPostWithFormUrlEncoded(request, contentType)) {      Optional<Params> optionalParams = this.pathProcessor.queryParams(request, cryptModel.getParams()) ;      if (optionalParams.isPresent() && !optionalParams.get().getKeys().isEmpty()) {        cache.getParamNames().addAll(optionalParams.get().getKeys()) ;        return true  ;      }      return false ;    }    String body = request.getBody() ;    if (StringUtils.hasLength(body)) {      Body configBody = cryptModel.getBody();      if (this.pathProcessor.match(request, configBody.getExclude())) {        return false ;      }      if (configBody.getInclude().isEmpty()) {        return true ;      } else {        return this.pathProcessor.match(request, configBody.getInclude()) ;      }    }    return false ;  }    private boolean isOptionsOrHeadOrTrace(HttpRequest request) {      return request.getMethod() == Method.OPTIONS ||         request.getMethod() == Method.HEAD ||         request.getMethod() == Method.TRACE ;    }      private boolean isGetOrPostWithFormUrlEncoded(HttpRequest request, String contentType) {        return request.getMethod() == Method.GET ||                (request.getMethod() == Method.POST && PluginConfigConstants.X_WWW_FORM_URLENCODED.equalsIgnoreCase(contentType));    }  // PluginFilter的核心方法,內部實現都交給了子類實現doFilterInternal  @Override  public final void filter(HttpRequest request, HttpResponse response, PluginFilterChain chain) {    BaseCryptoModel cryptoModel = configCryptoProcessor.processor(request, this);    CryptModel model = null ;    if (cryptoModel instanceof CryptModel) {      model = (CryptModel) cryptoModel ;    }    logger.info("model: {}", model);    Assert.isNull(model, "錯誤的數據模型") ;    CacheModel cache = new CacheModel() ;    // 是否開啟了加解密插件功能 && 當前請求路徑是否與配置的路徑匹配,只有匹配的才進行處理    if (isEnabled(request, cryptoModel) && checkRequest(request, model, cache)) {      this.doFilterInternal(request, response, chain, model, cache);    }    chain.filter(request, response);  }  // 插件中是否需要請求正文  @Override  public Boolean requiredBody() {    return Boolean.TRUE;  }}

解密插件

@Component@Order(1)public class DecryptFilter extends AbstractDecryptPreFilter {  private static final Logger logger = LoggerFactory.getLogger(DecryptFilter.class) ;    @Override  public String name() {    return "Decrypt";  }  @Override  protected void doFilterInternal(HttpRequest request, HttpResponse response, PluginFilterChain chain,      CryptModel cryptModel, CacheModel cache    SecretFacade sf = this.cryptoProcessor.getSecretFacade(request, cryptModel) ;    String body = request.getBody() ;    if (StringUtils.hasLength(body)) {      logger.info("request uri: {}", request.getPath()) ;      // 解密請求body      String plainText = sf.decrypt(body);      request.setBody(plainText) ;      plainText = request.getBody() ;      // 下面設置是為了吧內容傳遞到lua腳本寫的插件中,因為在java插件中無法改寫請求body      request.setHeader(PluginConfigConstants.DECRYPT_DATA_PREFIX, Base64.getEncoder().encodeToString(plainText.getBytes(StandardCharsets.UTF_8))) ;      request.setHeader(PluginConfigConstants.X_O_E, "1") ;      // 必須設置,不然響應內容類型就成了text/plain      request.setHeader("Content-Type", MediaType.APPLICATION_JSON_VALUE) ;    }  }  @Override  public Boolean requiredBody() {    return Boolean.TRUE;  }}

LUA插件

local ngx = ngx;local core = require "apisix.core"local plugin_name = "modify-body"local process_java_plugin_decrypt_data = "p_j_p_decrypt_data_"local x_o_e_flag = "x-o-e-flag"local schema = {}local metadata_schema = {}local _M = {    version = 0.1,    priority = 10,    name = plugin_name,    schema = schema,    metadata_schema = metadata_schema,    run_policy = 'prefer_route',}function _M.check_schema(conf)    return core.schema.check(schema, conf)endfunction _M.access(conf, ctx)  -- local cjson = require 'cjson'  -- ngx.req.read_body()  -- local body = ngx.req.get_body_data()  -- ngx.log(ngx.STDERR, "access content: ", body)endfunction _M.rewrite(conf, ctx)  local params, err = ngx.req.get_headers() --ngx.req.get_uri_args()  local flag = params[x_o_e_flag]  ngx.log(ngx.STDERR, "processor body, flag: ", flag)  if flag and flag == '1' then     local plain_data = params[process_java_plugin_decrypt_data]    if plain_data then      local data = ngx.decode_base64(plain_data)      -- 清除附加請求header      ngx.req.set_header(process_java_plugin_decrypt_data, nil)      -- 重寫body數據      ngx.req.set_body_data(data)      -- 這里如果計算不準,最好不傳      ngx.req.set_header('Content-Length', nil)    end  endendfunction _M.body_filter(conf, ctx)endreturn _M ;

接下來就是將該項目打包成jar。bHb28資訊網——每日最新資訊28at.com

以上就完成插件的開發,接下來就是配置bHb28資訊網——每日最新資訊28at.com

5.5 插件配置

Java插件配置

將上一步打包后的jar長傳到服務器,在config.yaml中配置插件bHb28資訊網——每日最新資訊28at.com

ext-plugin:  cmd: ['java', '-Dfile.encoding=UTF-8', '-jar', '/app/plugins/crypto-apisix-plugin-runner-1.0.0.jar']

LUA插件配置bHb28資訊網——每日最新資訊28at.com

將lua腳本上傳到docker容器bHb28資訊網——每日最新資訊28at.com

docker cp modify-body.lua apisix-java-apisix-1:/usr/local/apisix/apisix/plugins/modify-body.lua

配置該插件bHb28資訊網——每日最新資訊28at.com

plugins:  - ext-plugin-pre-req  - ext-plugin-post-req  - ext-plugin-post-resp  - modify-body

要想在apisix-dashboard中能夠使用,需要導出schema.json文件bHb28資訊網——每日最新資訊28at.com

docker exec -it apisix-java-apisix-1 curl http://localhost:9092/v1/schema > schema.json

上傳該schema.json到apisix-dashboard中bHb28資訊網——每日最新資訊28at.com

docker cp schema.json apisix-java-apisix-dashboard-1:/usr/local/apisix-dashboard/conf

重啟相應服務bHb28資訊網——每日最新資訊28at.com

docker restart apisix-java-apisix-dashboard-1docker restart apisix-java-apisix-1

完成以上步驟后,接下來就可以通過dashboard進行路徑配置了。bHb28資訊網——每日最新資訊28at.com

六. 路由配置

這里直接貼插件的配置bHb28資訊網——每日最新資訊28at.com

"plugins": {  "ext-plugin-pre-req": {    "allow_degradation": false,    "conf": [      {        "name": "Decrypt",        "value": "{/"enabled/": /"true/",/"apiKey/": /"kzV7HpPsZfTwJnZbyWbUJw==/", /"alg/": /"sm/", /"params/": [{/"pattern/": /"/api-1/**/", /"keys/": [/"idNo/"]}],/"body/": {/"exclude/": [/"/api-a/**/"],/"include/": [/"/api-1/**/"]}}"      }    ]  },  "modify-body": {},  "proxy-rewrite": {    "regex_uri": [      "^/api-1/(.*)$",      "/$1"    ]  }}

注意:modify-body插件一定要配置,這個是專門用來改寫請求body內容的。bHb28資訊網——每日最新資訊28at.com

到此一個完整的插件就開發完成了,希望本篇文章能夠幫到你。如有需要,可提供其它代碼。bHb28資訊網——每日最新資訊28at.com

完畢!!!bHb28資訊網——每日最新資訊28at.com

本文鏈接:http://www.www897cc.com/showinfo-26-64508-0.html深入探討API網關APISIX中自定義Java插件在真實項目中的運用

聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。郵件:2376512515@qq.com

上一篇: 針對大型數據庫,如何優化MySQL事務的性能?

下一篇: 使用 Spring Boot 創建自己的 ChatGPT 應用程序

標簽:
  • 熱門焦點
  • vivo TWS Air開箱體驗:真輕 臻好聽

    在vivo S15系列新機的發布會上,vivo的最新款真無線藍牙耳機vivo TWS Air也一同發布,本次就這款耳機新品給大家帶來一個簡單的分享。外包裝盒上,vivo TWS Air保持了vivo自家產
  • 28個SpringBoot項目中常用注解,日常開發、求職面試不再懵圈

    前言在使用SpringBoot開發中或者在求職面試中都會使用到很多注解或者問到注解相關的知識。本文主要對一些常用的注解進行了總結,同時也會舉出具體例子,供大家學習和參考。注解
  • 如何通過Python線程池實現異步編程?

    線程池的概念和基本原理線程池是一種并發處理機制,它可以在程序啟動時創建一組線程,并將它們置于等待任務的狀態。當任務到達時,線程池中的某個線程會被喚醒并執行任務,執行完任
  • 19個 JavaScript 單行代碼技巧,讓你看起來像個專業人士

    今天這篇文章跟大家分享18個JS單行代碼,你只需花幾分鐘時間,即可幫助您了解一些您可能不知道的 JS 知識,如果您已經知道了,就當作復習一下,古人云,溫故而知新嘛。現在,我們就開始今
  • JVM優化:實戰OutOfMemoryError異常

    一、Java堆溢出堆內存中主要存放對象、數組等,只要不斷地創建這些對象,并且保證 GC Roots 到對象之間有可達路徑來避免垃 圾收集回收機制清除這些對象,當這些對象所占空間超過
  • 為什么你不應該使用Div作為可點擊元素

    按鈕是為任何網絡應用程序提供交互性的最常見方式。但我們經常傾向于使用其他HTML元素,如 div span 等作為 clickable 元素。但通過這樣做,我們錯過了許多內置瀏覽器的功能。
  • 10天營收超1億美元,《星鐵》比《原神》差在哪?

    來源:伯虎財經作者:陳平安即便你沒玩過《原神》,你一定聽說過的它的大名。恨它的人把《原神》開服那天稱作是中國游戲史上最黑暗的一天,有粉絲因為索尼在PS平臺上線《原神》,怒而
  • 網紅炒股不為了賺錢,那就是耍流氓!

    來源:首席商業評論6月26日高調宣布入市,網絡名嘴大v胡錫進居然進軍了股市。在一次財經媒體峰會上,幾個財經圈媒體大佬就&ldquo;胡錫進炒股是否知道認真報道&rdquo;展開討論。有
  • 回歸OPPO兩年,一加贏了銷量,輸了品牌

    成為OPPO旗下主打性能的先鋒品牌后,一加屢創佳績。今年618期間,一加手機全渠道銷量同比增長362%,憑借一加 11、一加 Ace 2、一加 Ace 2V三款爆品,一加
Top 主站蜘蛛池模板: 沈阳市| 化州市| 本溪市| 石门县| 上思县| 公主岭市| 潞西市| 敦化市| 牙克石市| 无锡市| 昔阳县| 儋州市| 郑州市| 北流市| 武冈市| 金川县| 越西县| 江油市| 湘乡市| 嵊州市| 贡觉县| 丹东市| 黄冈市| 呼和浩特市| 蓝山县| 普定县| 嵩明县| 黔西县| 玉龙| 峡江县| 江达县| 奉节县| 长汀县| 溧水县| 林芝县| 梅州市| 都匀市| 从江县| 铁岭县| 恩平市| 松滋市|