這篇文章給大家分享的是有關(guān)SpringCloudGateway開發(fā)的示例分析的內(nèi)容。小編覺得挺實(shí)用的,因此分享給大家做個(gè)參考,一起跟隨小編過來看看吧。
創(chuàng)新互聯(lián)長期為千余家客戶提供的網(wǎng)站建設(shè)服務(wù),團(tuán)隊(duì)從業(yè)經(jīng)驗(yàn)10年,關(guān)注不同地域、不同群體,并針對(duì)不同對(duì)象提供差異化的產(chǎn)品和服務(wù);打造開放共贏平臺(tái),與合作伙伴共同營造健康的互聯(lián)網(wǎng)生態(tài)環(huán)境。為民豐企業(yè)提供專業(yè)的成都網(wǎng)站設(shè)計(jì)、成都網(wǎng)站制作,民豐網(wǎng)站改版等技術(shù)服務(wù)。擁有10多年豐富建站經(jīng)驗(yàn)和眾多成功案例,為您定制開發(fā)。路由簡(jiǎn)介:
1.SpringCloudGateWay 是用于替代zuul作為API網(wǎng)關(guān),在gateway中有三個(gè)重要的名詞:過濾器,斷言,路由
過濾器與斷言是路由的一部分,路由便是將請(qǐng)求進(jìn)行一系列的處理后分發(fā)到各個(gè)服務(wù)的一個(gè)過程。
路由的過程:首先會(huì)加載斷言以及路由,在接受到請(qǐng)求后根據(jù)斷言加載的順序會(huì)匹配到先加載的斷言,只有與斷言匹配了的請(qǐng)求才會(huì)進(jìn)入路由,沒有匹配到的服務(wù)會(huì)將請(qǐng)求當(dāng)成普通的訪問請(qǐng)求。
2:路由加載斷言的方式:
斷言加載的方式有四種,分別是配置文件,java編碼,數(shù)據(jù)庫以及注冊(cè)中心
第一種配置文件:
在官方文檔中主要介紹的就是配置文件的加載方式
官方地址:https://cloud.spring.io/spring-cloud-gateway/reference/html/#gateway-starter
一般的斷言有三種要素:id,uri,predicate.
id是斷言的標(biāo)識(shí),uri是ip+端口,predicate則是斷言匹配的規(guī)則
3:示例:
新建一個(gè)springboot項(xiàng)目,并且引入springcloudgateway的依賴
org.springframework.boot spring-boot-starter-test test org.springframework.cloud spring-cloud-starter-gateway
在啟動(dòng)類注冊(cè)三個(gè)全局過濾器
@SpringBootApplication public class GateWayApplication { public static void main(String[] args) { SpringApplication.run(GateWayApplication.class, args); } @Bean @Order(-1) public GlobalFilter a() { return (exchange, chain) -> { return chain.filter(exchange).then(Mono.fromRunnable(() -> { System.out.println(-1); })); }; } @Bean @Order(0) public GlobalFilter b() { return (exchange, chain) -> { return chain.filter(exchange).then(Mono.fromRunnable(() -> { System.out.println(0); })); }; } @Bean @Order(1) public GlobalFilter c() { return (exchange, chain) -> { return chain.filter(exchange).then(Mono.fromRunnable(() -> { System.out.println(1); })); }; } }
在配置文件類配置兩條路由
server.port: 7777 spring: application: name: gateway cloud: gateway: discovery: locator: enabled: true lower-case-service-id: true routes: - id: method_route uri: http://127.0.0.1:9999 predicates: - Method=GET - id: method_route uri: http://127.0.0.1:8006 predicates: - Method=GET
發(fā)送請(qǐng)求,請(qǐng)求到達(dá)后匹配的是第一條路由,由此可以知道路由匹配的順序會(huì)根據(jù)加載的順序來
4:SpringCloudGateWay從注冊(cè)中心獲得路由
在官方文檔中,我們可以看到有這樣的一段話
Configuring Predicates and Filters For DiscoveryClient Routes
By default the Gateway defines a single predicate and filter for routes created via a DiscoveryClient.
The default predicate is a path predicate defined with the pattern /serviceId/**, where serviceId is the id of the service from the DiscoveryClient.
The default filter is rewrite path filter with the regex /serviceId/(?
If you would like to customize the predicates and/or filters used by the DiscoveryClient routes you can do so by setting spring.cloud.gateway.discovery.locator.predicates[x] and spring.cloud.gateway.discovery.locator.filters[y]. When doing so you need to make sure to include the default predicate and filter above, if you want to retain that functionality. Below is an example of what this looks like.
地址 :https://cloud.spring.io/spring-cloud-gateway/reference/html/#_global_filters
spring.cloud.gateway.discovery.locator.predicates[0].name: Path spring.cloud.gateway.discovery.locator.predicates[0].args[pattern]: "'/'+serviceId+'/**'" spring.cloud.gateway.discovery.locator.predicates[1].name: Host spring.cloud.gateway.discovery.locator.predicates[1].args[pattern]: "'**.foo.com'" spring.cloud.gateway.discovery.locator.filters[0].name: Hystrix spring.cloud.gateway.discovery.locator.filters[0].args[name]: serviceId spring.cloud.gateway.discovery.locator.filters[1].name: RewritePath spring.cloud.gateway.discovery.locator.filters[1].args[regexp]: "'/' + serviceId + '/(?.*)'" spring.cloud.gateway.discovery.locator.filters[1].args[replacement]: "'/${remaining}'"
根據(jù)文檔介紹,依照這種方式,可以從注冊(cè)中心獲得斷言與過濾器的配置
5:SpringGateWay從數(shù)據(jù)庫配置路由
public class DBRouteDefinitionRepository implements RouteDefinitionRepository
項(xiàng)目中實(shí)現(xiàn)了RouteDefinitionRepository后,springgateway會(huì)采用你實(shí)現(xiàn)的這個(gè)類去加載路由,如果不實(shí)現(xiàn)則采用他默認(rèn)的方式加載路由
public class DBRouteDefinitionRepository implements RouteDefinitionRepository { //保存路由 private final Maproutes = synchronizedMap(new LinkedHashMap ()); private Logger log = LoggerFactory.getLogger(DBRouteDefinitionRepository.class); //初始標(biāo)準(zhǔn) private boolean init_flag = true; // private final GatewayProperties properties; private DynamicRouteServiceImpl service; public DBRouteDefinitionRepository(GatewayProperties properties) { this.properties = properties; this.service = new DynamicRouteServiceImpl(); } @Override public Flux getRouteDefinitions() { if(init_flag) { List routeDefinitions = new ArrayList<>(); List rs = new ArrayList<>(); try { routeDefinitions = service.quertAllRoutes();//從數(shù)據(jù)庫中加載route rs = this.properties.getRoutes();//獲得配置文件的route for (RouteDefinition rse : rs) { routeDefinitions.add(rse); } routes.clear(); routeDefinitions.forEach(x->routes.put(x.getId(), x)); init_flag=false; } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); log.error("Init Route Fail,Can't get Routes.",e); } return Flux.fromIterable(routeDefinitions); }else { return Flux.fromIterable(routes.values()); } } @Override public Mono delete(Mono routeId) { return routeId.flatMap(id -> { if (routes.containsKey(id)) { routes.remove(id); return Mono.empty(); } return Mono.defer(() -> Mono.error(new NotFoundException("RouteDefinition not found: "+routeId))); }); } @Override public Mono save(Mono route) { return route.flatMap( r -> { routes.put(r.getId(), r); return Mono.empty(); }); } }
這個(gè)是我自己實(shí)現(xiàn)的類,這個(gè)類可以從數(shù)據(jù)庫與配置文件中獲得路由配置,從數(shù)據(jù)庫中獲得路由配置可以根據(jù)個(gè)人的要求來
@Validated public class RouteDefinition { @NotEmpty private String id = UUID.randomUUID().toString(); @NotEmpty @Valid private Listpredicates = new ArrayList<>(); @Valid private List filters = new ArrayList<>(); @NotNull private URI uri; private int order = 0; public RouteDefinition() { } public RouteDefinition(String text) { int eqIdx = text.indexOf('='); if (eqIdx <= 0) { throw new ValidationException("Unable to parse RouteDefinition text '" + text + "'" + ", must be of the form name=value"); } setId(text.substring(0, eqIdx)); String[] args = tokenizeToStringArray(text.substring(eqIdx + 1), ","); setUri(URI.create(args[0])); for (int i = 1; i < args.length; i++) { this.predicates.add(new PredicateDefinition(args[i])); } } public String getId() { return id; } public void setId(String id) { this.id = id; } public List getPredicates() { return predicates; } public void setPredicates(List predicates) { this.predicates = predicates; } public List getFilters() { return filters; } public void setFilters(List filters) { this.filters = filters; } public URI getUri() { return uri; } public void setUri(URI uri) { this.uri = uri; } public int getOrder() { return order; } public void setOrder(int order) { this.order = order; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } RouteDefinition routeDefinition = (RouteDefinition) o; return Objects.equals(id, routeDefinition.id) && Objects.equals(predicates, routeDefinition.predicates) && Objects.equals(order, routeDefinition.order) && Objects.equals(uri, routeDefinition.uri); } @Override public int hashCode() { return Objects.hash(id, predicates, uri); } @Override public String toString() { return "RouteDefinition{" + "id='" + id + '\'' + ", predicates=" + predicates + ", filters=" + filters + ", uri=" + uri + ", order=" + order + '}'; } }
感謝各位的閱讀!關(guān)于“SpringCloudGateway開發(fā)的示例分析”這篇文章就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,讓大家可以學(xué)到更多知識(shí),如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到吧!
另外有需要云服務(wù)器可以了解下創(chuàng)新互聯(lián)建站www.cdcxhl.com,海內(nèi)外云服務(wù)器15元起步,三天無理由+7*72小時(shí)售后在線,公司持有idc許可證,提供“云服務(wù)器、裸金屬服務(wù)器、高防服務(wù)器、香港服務(wù)器、美國服務(wù)器、虛擬主機(jī)、免備案服務(wù)器”等云主機(jī)租用服務(wù)以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡(jiǎn)單易用、服務(wù)可用性高、性價(jià)比高”等特點(diǎn)與優(yōu)勢(shì),專為企業(yè)上云打造定制,能夠滿足用戶豐富、多元化的應(yīng)用場(chǎng)景需求。