Spring gateway的動態路由

2021-10-21 14:20:58 字數 2368 閱讀 1833

gateway官方文件

gateway是spring cloud中乙個用於替換zuul閘道器作用的子專案,基於webflux實現了非同步非阻塞處理。gateway工程首先需在啟動時注入route,在請求進來時,會根據route的predicate匹配路由規則,然後經過gatewayfilter以及globalfilter的逐層處理定向至真正的後台服務。下面講解下兩種動態路由的實現方式。

首先建立自定義的動態路由構造器,如下示例的是乙個匹配全部請求的路由構造器,路由位址需通過seturi動態注入。

@component

public class testroutelocator implements routelocator

public void seturi(string uri)

}

然後需要建立乙個監聽後台位址變化的處理器,我這裡使用zookeeper作為服務註冊中心,後台服務會在啟動時將自身位址寫入/test路徑

@component

public class testhosthandle implements nodecachelistener

/*** zookeeper發生變化是觸發該方法

*/public void nodechanged()

}

如上在觸發refreshroutesevent事件後,spring會重新呼叫的路由構造器的getroutes方法,這樣新的位址就被注入到了spring的路由列表中了。

這種方式是參照gateway整合ribbon負載均衡的方式編寫的,其動態位址轉換由reactiveloadbalancerclientfilter負責。

首先參照spring負載均衡字首lb定義乙個自己的字首,這裡我定義的是gateway,然後以gateway為字首編寫配置檔案。

spring:

cloud:

gateway:

routes:

- id: test-route

uri: gateway://test

predicates:

- path=/test/**

如上所示,我自定義了乙個位址gateway://test,然後針對這個位址我編寫了乙個globalfilter。

/**

* /test服務真實路徑解析及負載均衡

*/@component

public class testbalancerfilter implements globalfilter, ordered, pathchildrencachelistener

/*** 實現gateway過濾器方法 如果位址符合gateway://address格式則解析後台服務真實位址

*/public monofilter(serverwebexchange exchange, gatewayfilterchain chain)

// 替換路由位址為真實位址 並通過gateway_request_url_attr引數向下游傳遞

gateway = uricomponentsbuilder.fromuri(uri).scheme(gateway.getscheme()).host(gateway.gethost()).port(gateway.getport()).build().touri();

exchange.getattributes().put(gateway_request_url_attr, gateway);

}return chain.filter(exchange);

}public int getorder()

/*** 監聽zookeeper節點變化事件

*/public void childevent(curatorframework client, pathchildrencacheevent event) );

this.pathlist = pathlist;

}/**

* 提供隨機獲取方法的自定義集合 randomlist繼承arraylist 不支援併發讀寫

*/static class randomlist extends arraylist

int index = (int) (system.nanotime() % this.size());

return this.get(index);}}

}

這個類首先實現了zookeeper的pathchildrencachelistener監聽節點變化,然後實現globalfilter,針對以gateway為字首的位址轉換為從zookeeper中隨機獲取的位址,並將新位址放入gateway_request_url_attr引數中,這樣後續spring內建的filter就可以將請求**到我們動態注入的服務位址了。

spring gateway閘道器的使用

1建立module檔案 2匯入依賴 org.springframework.cloudgroupid spring cloud starter gatewayartifactid dependency 3配置yml檔案 server port 9527 spring name cloud gatew...

spring gateway 處理 跨域 問題

問題一 spring name nb web cloud nacos discovery server addr localhost 8848 gateway globalcors corsconfigurations allowedheaders allowedorigins allowcrede...

springgateway限流 令牌桶演算法

參見 lua指令碼 參見spring spring cloud gateway core包下的request rate limiter.lua redis從2.6版本開始引入對lua指令碼的支援,通過在伺服器中嵌入lua環境,redis客戶端可以使用lua指令碼,直接在伺服器端原子地執行多個redi...