老熟女激烈的高潮_日韩一级黄色录像_亚洲1区2区3区视频_精品少妇一区二区三区在线播放_国产欧美日产久久_午夜福利精品导航凹凸

重慶分公司,新征程啟航

為企業(yè)提供網(wǎng)站建設(shè)、域名注冊、服務(wù)器等服務(wù)

如何實(shí)現(xiàn)springcloud2.x版本Gateway自定義過濾器

本篇內(nèi)容主要講解“如何實(shí)現(xiàn)spring cloud 2.x版本Gateway自定義過濾器”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實(shí)用性強(qiáng)。下面就讓小編來帶大家學(xué)習(xí)“如何實(shí)現(xiàn)spring cloud 2.x版本Gateway自定義過濾器”吧!

創(chuàng)新互聯(lián)提供高防服務(wù)器、云服務(wù)器、香港服務(wù)器、溫江服務(wù)器租用

前言

本文采用Spring cloud本文為2.1.8RELEASE,version=Greenwich.SR3

[toc]

本文基于前兩篇文章eureka-server、eureka-client、eureka-ribbon、eureka-feign和spring-gataway的實(shí)現(xiàn)。 參考

  • eureka-server

  • eureka-client

  • eureka-ribbon

  • eureka-feign

  • spring-gateway

概術(shù)

Spring Cloud Gateway內(nèi)部已經(jīng)提供非常多的過濾器filter,Hystrix Gateway Filter、Prefix PathGateway Filter等。感興趣的小伙伴可以直接閱讀Spring Cloud Gateway官網(wǎng)相關(guān)文檔或直接閱讀源碼。但是很多情況下自帶的過濾器并不能滿足我們的需求,所以自定義過濾器就顯得的非常重要。本文主要介紹全局過濾器(Global Filter)和局部過濾器(Gateway Filter)。

Gateway Filter

自定義過濾器需要實(shí)現(xiàn)GatewayFilter和Ordered。其中GatewayFilter主要是用來實(shí)現(xiàn)自定義的具體邏輯,Ordered中的getOrder()方法是來給過濾器設(shè)定優(yōu)先級(jí)別的,值越大優(yōu)先級(jí)別越低。

1.1 創(chuàng)建Filter

package spring.cloud.demo.spring.gateway.filter;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.core.Ordered;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

public class MyGatewayFilter implements GatewayFilter, Ordered {

    private static final Log log = LogFactory.getLog(MyGatewayFilter.class);

    private static final String TIME = "Time";

    @Override
    public Mono filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        exchange.getAttributes().put(TIME, System.currentTimeMillis());
        return chain.filter(exchange).then(
                Mono.fromRunnable(() -> {
                    Long start = exchange.getAttribute(TIME);
                    if (start != null) {
                        log.info("exchange request uri:" + exchange.getRequest().getURI() + ", Time:" + (System.currentTimeMillis() - start) + "ms");
                    }
                })
        );
    }

    @Override
    public int getOrder() {
        return Ordered.LOWEST_PRECEDENCE;
    }
}

我們在請求過來到達(dá)的時(shí)候,往ServerWebExchange中放了一個(gè)屬性TIME,屬性的值為當(dāng)前時(shí)間的毫秒數(shù),然后請求結(jié)束后,又會(huì)將請求的時(shí)間數(shù)取出來來和當(dāng)前時(shí)間數(shù)做差,得到耗時(shí)時(shí)間數(shù)。

如何區(qū)分“pre”和“post”?

  • pre就是chain.filter(exchange)部分.

  • post就是then()部分.

1.2 將Filter添加到Chain

package spring.cloud.demo.spring.gateway.config;

import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import spring.cloud.demo.spring.gateway.filter.MyGatewayFilter;

/**
 * @auther: fujie.feng
 * @DateT: 2019-10-12
 */
@Configuration
public class RoutesConfig {

    @Bean
    public RouteLocator routeLocator(RouteLocatorBuilder routeLocatorBuilder){
        return routeLocatorBuilder.routes().route(r -> r.path("/ribbon/**")
                .filters(f -> f.stripPrefix(1)
                        .filter(new MyGatewayFilter()) //增加自定義filter
                        .addRequestHeader("X-Response-Default-Foo", "Default-Bar"))
                .uri("lb://EUREKA-RIBBON")
                .order(0)
                .id("ribbon-route")
        ).build();
    }
}

1.2 啟動(dòng)相關(guān)服務(wù)

啟動(dòng)eureka-server、eureka-client、eureka-ribbon、spring-gateway相關(guān)服務(wù),訪問http://localhost:8100/ribbon/sayHello地址,頁面顯示結(jié)果如下:

如何實(shí)現(xiàn)spring cloud 2.x版本Gateway自定義過濾器 這時(shí)我打開控制臺(tái)可以看到日志輸出為:

如何實(shí)現(xiàn)spring cloud 2.x版本Gateway自定義過濾器

2.1 創(chuàng)建GlobalFilter

package spring.cloud.demo.spring.gateway.filter;

import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;


/**
 * 全局過濾器
 * 校驗(yàn)token
 */
public class MyGlobalFilter implements GlobalFilter, Ordered {

    private static final String TOKEN = "token";

    @Override
    public Mono filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String parm = exchange.getRequest().getQueryParams().getFirst(TOKEN);
        if (StringUtils.isBlank(parm)) {
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 1;
    }
}

2.2 添加Bean

將MyGlobalFilter添加到Bean中

package spring.cloud.demo.spring.gateway.filter;

import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;


/**
 * 全局過濾器
 * 校驗(yàn)token
 */
public class MyGlobalFilter implements GlobalFilter, Ordered {

    private static final String TOKEN = "token";

    @Override
    public Mono filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String parm = exchange.getRequest().getQueryParams().getFirst(TOKEN);
        if (StringUtils.isBlank(parm)) {
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 1;
    }
}

這里只是簡單模擬,如果感興趣的小伙伴可以自己嘗試將所有參數(shù)取出來并解析(可以利用反射來實(shí)現(xiàn))。

2.3 啟動(dòng)服務(wù)

重啟動(dòng)服務(wù),訪問http://localhost:8100/ribbon/sayHello,顯示如下: 如何實(shí)現(xiàn)spring cloud 2.x版本Gateway自定義過濾器 我可以看到顯示訪問是不生效的,我們在請求中加如token=xxx,顯示如下: 如何實(shí)現(xiàn)spring cloud 2.x版本Gateway自定義過濾器 這是看到正常返回。日志輸出入下:

2019-10-21 16:20:00.478  INFO 15322 --- [ctor-http-nio-2] c.netflix.config.ChainedDynamicProperty  : Flipping property: EUREKA-RIBBON.ribbon.ActiveConnectionsLimit to use NEXT property: niws.loadbalancer.availabilityFilteringRule.activeConnectionsLimit = 2147483647
2019-10-21 16:20:00.480  INFO 15322 --- [ctor-http-nio-2] c.n.l.DynamicServerListLoadBalancer      : DynamicServerListLoadBalancer for client EUREKA-RIBBON initialized: DynamicServerListLoadBalancer:{NFLoadBalancer:name=EUREKA-RIBBON,current list of Servers=[eureka1.server.com:8901],Load balancer stats=Zone stats: {defaultzone=[Zone:defaultzone;	Instance count:1;	Active connections count: 0;	Circuit breaker tripped count: 0;	Active connections per server: 0.0;]
},Server stats: [[Server:eureka1.server.com:8901;	Zone:defaultZone;	Total Requests:0;	Successive connection failure:0;	Total blackout seconds:0;	Last connection made:Thu Jan 01 08:00:00 CST 1970;	First connection made: Thu Jan 01 08:00:00 CST 1970;	Active Connections:0;	total failure count in last (1000) msecs:0;	average resp time:0.0;	90 percentile resp time:0.0;	95 percentile resp time:0.0;	min resp time:0.0;	max resp time:0.0;	stddev resp time:0.0]
]}ServerList:org.springframework.cloud.netflix.ribbon.eureka.DomainExtractingServerList@40585976
2019-10-21 16:20:01.293  INFO 15322 --- [ctor-http-nio-8] s.c.d.s.gateway.filter.MyGatewayFilter   : exchange request uri:http://localhost:8100/sayHello?token=xxx, Time:23ms
2019-10-21 16:20:01.467  INFO 15322 --- [erListUpdater-0] c.netflix.config.ChainedDynamicProperty  : Flipping property: EUREKA-RIBBON.ribbon.ActiveConnectionsLimit to use NEXT property: niws.loadbalancer.availabilityFilteringRule.activeConnectionsLimit = 2147483647

引用官網(wǎng)原文:The GlobalFilter interface has the same signature as GatewayFilter. These are special filters that are conditionally applied to all routes. (This interface and usage are subject to change in future milestones). 說明GlobalFilter在未來的版本中會(huì)又一些變化。

總結(jié)

至此,自定義filter的兩種方式就簡單的實(shí)現(xiàn)完成了。同樣的方式可以在feign做測試。

彩蛋

在前一片文章中,配置文件中有這樣一段配置:

filters:
  - StripPrefix=1
  - AddResponseHeader=X-Response-Default-Foo, Default-Bar

StripPrefix和AddResponseHeader這兩個(gè)配置實(shí)際上是兩個(gè)Filter的過濾器工廠(GatewayFilterFactory),接下來將介紹過濾器工廠的使用,相對來說這種方式更加靈活。

1.1 創(chuàng)建自定義過濾工廠

package spring.cloud.demo.spring.gateway.factory;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import reactor.core.publisher.Mono;

import java.util.Arrays;
import java.util.List;

/**
 * 自定義過濾器工廠
 */
public class MyGatewayFilterFactory extends AbstractGatewayFilterFactory {

    private static final Log log = LogFactory.getLog(MyGatewayFilterFactory.class);

    private static final String PARAMS = "myParams";

    private static final String START_TIME = "startTime";

    public MyGatewayFilterFactory() {
        super(Config.class);
    }

    @Override
    public List shortcutFieldOrder() {
        return Arrays.asList(PARAMS);
    }

    @Override
    public GatewayFilter apply(Config config) {
        return ((exchange, chain) -> {
            exchange.getAttributes().put(START_TIME, System.currentTimeMillis());
            return chain.filter(exchange).then(
                    Mono.fromRunnable(() -> {
                        Long startTime = exchange.getAttribute(START_TIME);
                        if (startTime == null) {
                            return;
                        }
                        StringBuilder sb = new StringBuilder();
                        sb.append("exchange request uri:" + exchange.getRequest().getURI() + ",");
                        sb.append("Time:" + (System.currentTimeMillis() - startTime) + "ms.");
                        if (config.isMyParams()) {
                            sb.append("params:" + exchange.getRequest().getQueryParams());
                        }
                        log.info(sb.toString());
                    })
            );
        });
    }

    /**
     * 配置參數(shù)類
     */
    public static class Config {

        private boolean myParams;

        public boolean isMyParams() {
            return myParams;
        }

        public void setMyParams(boolean myParams) {
            this.myParams = myParams;
        }
    }
}

注意:當(dāng)我們繼承AbstractGatewayFilterFactory的時(shí)候,要把自定義的Config類傳給父類,否者會(huì)報(bào)錯(cuò)。

1.2 添加自定義工廠Bean

package spring.cloud.demo.spring.gateway.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import spring.cloud.demo.spring.gateway.factory.MyGatewayFilterFactory;

@Configuration
public class FilterFactory {

    @Bean
    public MyGatewayFilterFactory myGatewayFilterFactory() {
        return new MyGatewayFilterFactory();
    }
}

1.3 修改application.yml

server:
  port: 8100
spring:
  application:
    name: spring-gateway
  cloud:
      gateway:
        discovery:
          locator:
            enabled: true # 開啟通過服務(wù)中心的自動(dòng)根據(jù) serviceId 創(chuàng)建路由的功能
        default-filters:
          - My=true
        routes:
          - id: ribbon-route
            uri: lb://EUREKA-RIBBON
            order: 0
            predicates:
              - Path=/ribbon/**
            filters:
              - StripPrefix=1 #去掉前綴,具體實(shí)現(xiàn)參考StripPrefixGatewayFilterFactory
              - AddResponseHeader=X-Response-Default-Foo, Default-Bar
          - id: feign-route
            uri: lb://EUREKA-FEIGN
            order: 0
            predicates:
              - Path=/feign/**
            filters:
              - StripPrefix=1
              - AddResponseHeader=X-Response-Default-Foo, Default-Bar


eureka:
  instance:
    hostname: eureka1.server.com
    lease-renewal-interval-in-seconds: 5
    lease-expiration-duration-in-seconds: 10
  client:
    service-url:
      defaultZone: http://eureka1.server.com:8701/eureka/,http://eureka2.server.com:8702/eureka/,http://eureka3.server.com:8703/eureka/

default-filters:- My=true 主要增加了這個(gè)配置。

1.4 啟動(dòng)服務(wù)

訪問http://localhost:8100/ribbon/sayHello?token=xxx,顯示如果下: 如何實(shí)現(xiàn)spring cloud 2.x版本Gateway自定義過濾器 日志輸出結(jié)果:

2019-10-21 17:40:20.191  INFO 18059 --- [ctor-http-nio-2] c.netflix.config.ChainedDynamicProperty  : Flipping property: EUREKA-RIBBON.ribbon.ActiveConnectionsLimit to use NEXT property: niws.loadbalancer.availabilityFilteringRule.activeConnectionsLimit = 2147483647
2019-10-21 17:40:20.192  INFO 18059 --- [ctor-http-nio-2] c.n.l.DynamicServerListLoadBalancer      : DynamicServerListLoadBalancer for client EUREKA-RIBBON initialized: DynamicServerListLoadBalancer:{NFLoadBalancer:name=EUREKA-RIBBON,current list of Servers=[eureka1.server.com:8901],Load balancer stats=Zone stats: {defaultzone=[Zone:defaultzone;	Instance count:1;	Active connections count: 0;	Circuit breaker tripped count: 0;	Active connections per server: 0.0;]
},Server stats: [[Server:eureka1.server.com:8901;	Zone:defaultZone;	Total Requests:0;	Successive connection failure:0;	Total blackout seconds:0;	Last connection made:Thu Jan 01 08:00:00 CST 1970;	First connection made: Thu Jan 01 08:00:00 CST 1970;	Active Connections:0;	total failure count in last (1000) msecs:0;	average resp time:0.0;	90 percentile resp time:0.0;	95 percentile resp time:0.0;	min resp time:0.0;	max resp time:0.0;	stddev resp time:0.0]
]}ServerList:org.springframework.cloud.netflix.ribbon.eureka.DomainExtractingServerList@46c172ce
2019-10-21 17:40:20.583  INFO 18059 --- [ctor-http-nio-7] s.c.d.s.g.f.MyGatewayFilterFactory       : exchange request uri:http://localhost:8100/ribbon/sayHello?token=xxx,Time:582ms.params:{token=[xxx]}
2019-10-21 17:40:21.181  INFO 18059 --- [erListUpdater-0] c.netflix.config.ChainedDynamicProperty  : Flipping property: EUREKA-RIBBON.ribbon.ActiveConnectionsLimit to use NEXT property: niws.loadbalancer.availabilityFilteringRule.activeConnectionsLimit = 2147483647

總結(jié)

過濾器工廠的頂級(jí)的接口是GatewayFilterFactory,我們可以直接繼承它們的兩個(gè)抽象類AbstractGatewayFilterFactory 和 AbstractNameValueGatewayFilterFactory來簡化開發(fā)。區(qū)別在于AbstractGatewayFilterFactory是接受一個(gè)參數(shù),AbstractNameValueGatewayFilterFactory是接收兩個(gè)參數(shù),例如:- AddResponseHeader=X-Response-Default-Foo, Default-Bar

到此,相信大家對“如何實(shí)現(xiàn)spring cloud 2.x版本Gateway自定義過濾器”有了更深的了解,不妨來實(shí)際操作一番吧!這里是創(chuàng)新互聯(lián)網(wǎng)站,更多相關(guān)內(nèi)容可以進(jìn)入相關(guān)頻道進(jìn)行查詢,關(guān)注我們,繼續(xù)學(xué)習(xí)!


網(wǎng)頁題目:如何實(shí)現(xiàn)springcloud2.x版本Gateway自定義過濾器
分享地址:http://www.xueling.net.cn/article/jeogds.html

其他資訊

在線咨詢
服務(wù)熱線
服務(wù)熱線:028-86922220
TOP
主站蜘蛛池模板: 五月天我淫我色 | 美女的大奶 | 日本一级囗交免费 | 国产亚洲精品第一综合另类灬 | 日本女人一区二区 | 免费看一级黄色大片 | 国产一级淫片a免费播放鬼片 | 国内精品久久久久精品 | 美女大秀一区二区三区 | 日日噜噜夜夜狠狠VA视频 | 免费看黄色大全 | 91在线在线观看 | 天堂av首页| 人人妻一区二区三区 | 国产裸舞福利在线视频合集 | 免费网站看gv片在线 | xxnxx日本19| 出租屋嫖妓大龄熟妇露脸在线播放 | 少妇一级淫片免费放正片 | 欧美日韩视频网站 | 自拍亚洲伦理 | 久艹在线免费观看 | 人人爽人人澡人人人妻 | 99久久中文 | 精品国产偷窥一区二区 | 成人免费毛片立即播放 | 沦为公交两奶头春药高潮迭起 | 亚洲另类激情综合偷自拍图 | 一级毛片aaaaaa免费看 | 综合精品影视国产 | 日韩av大片在线 | 日本毛片在线 | 色美av| av之家在线观看 | 一本久道综合在线无码人妻 | 日本免费一区二区三区视频 | 国产精品视频二区三区 | 国产精选大秀一区二区 | X8X8国产在线观看 | av在线免费看片 | 深夜免费在线观看 |