springcloud ali gateway介绍

2023-10-09 00:50

本文主要是介绍springcloud ali gateway介绍,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

一:Gateway简介

文档:Spring Cloud Gateway

小结:

nacos :注册中心,解决服务的注册与发现

Ribbon:客户端负载均衡器,解决微服务集群负载均衡的问题

Openfeign:声明式HTTP客户端,解决微服务之间远程调用问题

Sentinel:微服务流量防卫兵,以流量为入口,保护微服务,防止出现服务雪崩.

1.0:为什么使用网关

 

1.1:什么是Springcloud-gateway

 

1:springcloud-gateway是第二代网关,取代zuul

2:springcloud-gateway是基于 Spring Boot 2.x, Spring WebFlux和Project Reactor 构建的。netty服务器运行

3:是微服务的统一入口

1.2:Springcloud-gateway特点

1:性能强劲(是zuul1.x的1.6倍)

2:功能强大(转发、监控、限流)

1.3:gateway核心概念

 

  • Route(路由)

路由是构建网关的基本模块,它由ID,目标URI,一系列的断言和过滤器组成,如果断言为true则匹配该路由
  • Predicate(断言、谓词)

开发人员可以匹配HTTP请求中的所有内容(例如请求头或请求参数),如果请求与断言相匹配则进行路由
  • Filter(过滤)

指的是Spring框架中GatewayFilter的实例,使用过滤器,可以在请求被路由前或者之后对请求进行修改

1.4:gateway的工作流程

1:客户端向 Spring Cloud Gateway 发出请求。然后在 Gateway Handler Mapping 中找到与请求相匹配的路由
2:将其发送到 Gateway Web Handler。
3:Handler 再通过指 定的过滤器链来将请求发送到我们实际的服务执行业务逻辑,然后返回。过滤器之间用虚线分开是因为过滤器可能会在发送代理请求之前(“pre”)或之后(“post”)执行业务逻辑。

 

1.5:搭建网关wfx-gateway

1.5.1:pom依赖

注意:不要依赖spring-boot-starter-web

<dependency><groupId>org.springframework.boot</groupId><!--servlet编程模型、运行的服务器是tomcat--><artifactId>spring-boot-starter-web</artifactId>
</dependency>

依赖如下:

 <dependencies><!--   spring-cloud gateway,底层基于netty     --><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-gateway</artifactId></dependency><!-- 端点监控 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-actuator</artifactId></dependency>
​<!--  nacos注册中心      --><dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId></dependency></dependencies>

1.5.2:基本配置

配置文件采用yml

server:#gateway的端口port: 8040
​
spring:application:name: wfx-gatewaycloud:nacos:discovery:server-addr: 127.0.0.1:8848

1.5.3:引导类

package com.wfx;
​
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
​
/*** <p>title: com.wfx</p>* <p>Company: wendao</p>* author zhuximing* date 2020/10/29* description:*/
@SpringBootApplication
@EnableDiscoveryClient
public class WfxGateway {
​public static void main(String[] args) {SpringApplication.run(WfxGateway.class,args);}
​
}

二:路由配置姿势

2.1:路由到指定URL

spring:cloud:gateway:routes:- id: baiduuri: http://www.baidu.compredicates:- Path=/**

访问 http://localhost:8040/** 转发给 百度一下,你就知道**

http://localhost:8040/a => http://www.baidu.com/a

http://localhost:8040/a/b => http://www.baidu.com/a/b

2.2:路由到微服务

2.2.1:静态路由

spring:cloud:gateway:#路由是一个数组,可以配置多个路由routes:#配置商品微服务,静态配置- id: wfx-goodsuri: http://localhost:8001predicates:- Path=/goods/**

2.2.2:动态路由

server:#gateway启动端口port: 8040
spring:cloud:gateway:routes:#配置商品微服务- id: wfx-goodsuri: lb://wfx-goodspredicates:- Path=/goods/**#配置积分微服务- id: wfx-jifenuri: lb://wfx-jifenpredicates:- Path=/jifen/**#配置订单微服务- id: wfx-orderuri: lb://wfx-orderpredicates:- Path=/order/**nacos:discovery:server-addr: 127.0.0.1:8848application:name: wfx-gateway
​

三:谓词工厂详解

Spring Cloud Gateway提供了十来种路由谓词工厂。为网关实现灵活的转发提供了基石。

Spring Cloud Gateway中内置的谓词工厂,包括:

 

Path

 gateway:#配置路由规则routes:- id: wfx-goods#请求转发到微服务集群uri: lb://wfx-goodspredicates:- Path=/goods/**    #http://localhost:8040/goods/hello ->lb://wfx-goods/goods/hello

After

示例:

spring:cloud:gateway:routes:- id: wfx-jifenuri: lb://wfx-goodspredicates:- Path=/goods/detail/100   //true- After=2020-10-29T22:24:40.626+08:00[Asia/Shanghai]   //true

Before

示例:

spring:cloud:gateway:routes:- id: wfx-jifenuri: lb://wfx-goodspredicates:- Path=/goods/detail/100- Before=2020-10-29T22:24:40.626+08:00[Asia/Shanghai]

Between

示例:

spring:cloud:gateway:routes:- id: wfx-jifenuri: lb://wfx-goodspredicates:- Path=/goods/detail/100- Between=2020-10-29T22:24:40.626+08:00[Asia/Shanghai], 2020-10-29T22:24:40.626+08:00[Asia/Shanghai]

Cookie

示例:

spring:cloud:gateway:routes:- id: wfx-jifenuri: lb://wfx-goodspredicates:- Path=/goods/detail/100- After=2020-10-29T22:26:40.626+08:00[Asia/Shanghai]- Cookie=age,18

Header

spring:cloud:gateway:routes:- id: wfx-jifenuri: lb://wfx-goodspredicates:- Path=/goods/detail/100- After=2020-10-29T22:26:40.626+08:00[Asia/Shanghai]- Cookie=name,jack- Header=token,123

Host

spring:cloud:gateway:routes:- id: wfx-jifenuri: lb://wfx-goodspredicates:- Path=/goods/detail/100- After=2020-10-29T22:26:40.626+08:00[Asia/Shanghai]- Cookie=name,jack- Header=token- Host=goods.wfx.com,**.jd.com

Method

spring:cloud:gateway:routes:- id: wfx-jifenuri: lb://wfx-goodspredicates:- Path=/goods/detail/100- After=2020-10-29T22:26:40.626+08:00[Asia/Shanghai]- Cookie=name,jack- Header=token- Host=**.wfx.com,**.jd.com- Method=GET

Query

示例:

spring:cloud:gateway:routes:- id: wfx-jifenuri: lb://wfx-goodspredicates:- Path=/goods/detail/100- After=2020-10-29T22:26:40.626+08:00[Asia/Shanghai]- Cookie=name,jack- Header=token- Host=**.wfx.com,**.jd.com- Method=GET- Query=baz,123

RemoteAddr

示例:

spring:cloud:gateway:routes:- id: wfx-jifenuri: lb://wfx-goodspredicates:- Path=/goods/detail/100- After=2020-10-29T22:26:40.626+08:00[Asia/Shanghai]
#            - Cookie=name,jack- Header=token- Host=**.wfx.com,**.jd.com- Query=baz- RemoteAddr=192.168.234.122,192.168.234.123

自定义RoutePredicateFactory

自定义谓词工厂的类名规范:后缀必须是RoutePredicateFactory

package com.wfx.predicates;
​
import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
​
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
​
/*** <p>title: com.wfx.predicates</p>* author zhuximing* description:*/
@Component
public class MyHeaderRoutePredicateFactory extends AbstractRoutePredicateFactory<MyConfig> {public MyHeaderRoutePredicateFactory() {super(MyConfig.class);}
​@Overridepublic Predicate<ServerWebExchange> apply(MyConfig config) {
​
​
​return new Predicate<ServerWebExchange>() {@Overridepublic boolean test(ServerWebExchange exchange) {
​//获取请求头//需求:请求头中必须要有 指定的kv 键值对
//                String value = exchange.getRequest().getHeaders().getFirst(config.getKey());
//                if (value == null) {
//
//                    return false;
//                }else{
//                    if(value.equals(config.getValue())){
//                        return true;
//                    }else{
//                        return  false;
//                    }
//                }
​
​
​if(StringUtils.isEmpty(config.getValue())){//只配置了key,但是没有配置value
​if(exchange.getRequest().getHeaders().containsKey(config.getKey())){return true;}else{return  false;}
​
​}else{//同时配置了key和value
​//根据key获取valueString value = exchange.getRequest().getHeaders().getFirst(config.getKey());if(config.getValue().equals(value)){return  true;}else{return  false;}
​}
​
​
​
​
​}};}
​//获取配置参数@Overridepublic List<String> shortcutFieldOrder() {
​
​//- MyHeader=bbb,cccc//[bbb,cccc]//bbb赋值给MyConfig#key//cccc赋值给MyConfig#value
​return Arrays.asList("key","value");}
}

server:#网关微服务的启动端口port: 8040
spring:application:name: wfx-gateway #微服务的应用名cloud:nacos:discovery:server-addr: 127.0.0.1:8848 #nacos-server的服务地址gateway:#配置路由规则routes:- id: wfx-goods#请求转发到微服务集群uri: lb://wfx-goodspredicates:- Path=/goods/**    #http://localhost:8040/goods/hello ->lb://wfx-goods/goods/hello- After=2021-02-04T09:35:30.654+08:00[Asia/Shanghai]- Cookie=age,18- MyHeader=name,xx

四:过滤器工厂详解

 

4.1:内置过滤器

1 AddRequestHeader GatewayFilter Factory2 AddRequestParameter GatewayFilter Factory3 AddResponseHeader GatewayFilter Factory4 DedupeResponseHeader GatewayFilter Factory5 Hystrix GatewayFilter Factory6 FallbackHeaders GatewayFilter Factory7 PrefixPath GatewayFilter Factory8 PreserveHostHeader GatewayFilter Factory9 RequestRateLimiter GatewayFilter Factory10 RedirectTo GatewayFilter Factory11 RemoveHopByHopHeadersFilter GatewayFilter Factory12 RemoveRequestHeader GatewayFilter Factory13 RemoveResponseHeader GatewayFilter Factory14 RewritePath GatewayFilter Factory15 RewriteResponseHeader GatewayFilter Factory16 SaveSession GatewayFilter Factory17 SecureHeaders GatewayFilter Factory18 SetPath GatewayFilter Factory19 SetResponseHeader GatewayFilter Factory20 SetStatus GatewayFilter Factory21 StripPrefix GatewayFilter Factory22 Retry GatewayFilter Factory23 RequestSize GatewayFilter Factory24 Modify Request Body GatewayFilter Factory25 Modify Response Body GatewayFilter Factory26 Default Filters

4.2:使用内置过滤器

spring:cloud:gateway:routes:- id: add_request_header_routeuri: https://example.orgfilters:- AddRequestHeader=Foo, Bar

 @GetMapping("detail/{goodsId}")public Map detail(@PathVariable String goodsId,@RequestHeader("Foo") String foo){System.out.println(foo+"!!!!");return  new HashMap(){{put("goodName","华为meta10");put("price",99.99);}};}

4.3:自定义过滤器

命名规范:过滤器工厂的类名必须以GatewayFilterFactory为后缀

package com.wfx.filters;
​
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.factory.AbstractNameValueGatewayFilterFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
​
/*** <p>title: com.wfx.filters</p>* author zhuximing* description:*/
@Component
public class CalServiceTimeGatewayFilterFactory extends AbstractNameValueGatewayFilterFactory {@Overridepublic GatewayFilter apply(NameValueConfig config) {
​
​
​return new GatewayFilter() {@Overridepublic Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {//前处理long startTime = System.currentTimeMillis();
​System.out.println("name:"+config.getName());System.out.println("value:"+config.getValue());
​
​
//                return chain.filter(exchange);//放行
​return  chain.filter(exchange).then(//后置处理Mono.fromRunnable(()->{System.out.println("post come in");//获取系统当前时间戳为endTimelong entTime = System.currentTimeMillis();System.out.println("time="+(entTime-startTime));
​}));}};}
​@Overridepublic ShortcutType shortcutType() {return ShortcutType.DEFAULT;}
}

server:#网关微服务的启动端口port: 8040
spring:application:name: wfx-gateway #微服务的应用名cloud:nacos:discovery:server-addr: 127.0.0.1:8848 #nacos-server的服务地址gateway:#配置路由规则routes:- id: wfx-goods#请求转发到微服务集群uri: lb://wfx-goodspredicates:- Path=/goods/**    #http://localhost:8040/goods/hello ->lb://wfx-goods/goods/hello- After=2021-02-04T09:35:30.654+08:00[Asia/Shanghai]- Cookie=age,18- MyHeader=bbbfilters:- AddRequestHeader=token,123- AddRequestParameter=name,jack- CalServiceTime=a,b

过滤器执行的顺序,就是配置的顺序

4.4:全局过滤器

Spring Cloud Gateway内置的全局过滤器。包括:1 Combined Global Filter and GatewayFilter Ordering2 Forward Routing Filter3 LoadBalancerClient Filter4 Netty Routing Filter5 Netty Write Response Filter6 RouteToRequestUrl Filter7 Websocket Routing Filter8 Gateway Metrics Filter9 Marking An Exchange As Routed

自定义全局过滤器

package com.wfx.filters;
​
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jdk.nashorn.internal.parser.JSONParser;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
​
import java.util.HashMap;
import java.util.Map;
​
/*** <p>title: com.wfx.filters</p>* author zhuximing* description:*/
@Component
public class AuthFilter implements GlobalFilter, Ordered {@Overridepublic Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
​ServerHttpRequest request = exchange.getRequest();ServerHttpResponse response = exchange.getResponse();
​
​//获取jwt令牌String jwtToken = exchange.getRequest().getHeaders().getFirst("token");if (jwtToken == null) {
​//不能放行,直接返回,返回json信息response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
​Map res = new HashMap(){{put("success",false);put("msg","必须指定token");}};
​ObjectMapper objectMapper = new ObjectMapper();String jsonStr = null;try {jsonStr = objectMapper.writeValueAsString(res);} catch (JsonProcessingException e) {e.printStackTrace();}
​
​DataBuffer dataBuffer = response.bufferFactory().wrap(jsonStr.getBytes());
​return response.writeWith(Flux.just(dataBuffer));//响应json数据
​
​}else{//校验令牌if( jwtToken.equals("xx")){//校验成功return   chain.filter(exchange);  //放行}else{
​//不能放行,直接返回,返回json信息response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
​Map res = new HashMap(){{put("success",false);put("msg","令牌不合法");}};
​ObjectMapper objectMapper = new ObjectMapper();String jsonStr = null;try {jsonStr = objectMapper.writeValueAsString(res);} catch (JsonProcessingException e) {e.printStackTrace();}
​
​DataBuffer dataBuffer = response.bufferFactory().wrap(jsonStr.getBytes());
​return response.writeWith(Flux.just(dataBuffer));//响应json数据}}
​
​}
​
​//指定过滤器的执行顺序,值越小越先执行@Overridepublic int getOrder() {return 0;}
}

package com.wfx;
​
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.core.annotation.Order;
import reactor.core.publisher.Mono;
​
import java.time.ZonedDateTime;
​
/*** <p>title: com.wfx</p>* <p>Company: wendao</p>* author zhuximing* date 2020/10/29* description:*/
@SpringBootApplication
@EnableDiscoveryClient
public class WfxGateway {
​public static void main(String[] args) {SpringApplication.run(WfxGateway.class,args);
​}@Bean@Order(1)public GlobalFilter  aFilter(){
​return  new GlobalFilter() {@Overridepublic Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
​System.out.println("A come in ");
​
​return chain.filter(exchange).then(   Mono.fromRunnable(()->{System.out.println("A post come in");
​}));}};}
​
​@Bean@Order(2)public GlobalFilter  bFilter(){
​return  new GlobalFilter() {@Overridepublic Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
​System.out.println("b come in ");
​
​return chain.filter(exchange).then(   Mono.fromRunnable(()->{System.out.println("b post come in");
​}));}};}
​@Bean@Order(-1)public GlobalFilter a() {return (exchange, chain) -> {System.out.println("first pre filter");return chain.filter(exchange).then(Mono.fromRunnable(() -> {System.out.println("third post filter");}));};}
​@Bean@Order(0)public GlobalFilter b() {return (exchange, chain) -> {System.out.println("second pre filter");return chain.filter(exchange).then(Mono.fromRunnable(() -> {System.out.println("second post filter");}));};}
​@Bean@Order(1)public GlobalFilter c() {return (exchange, chain) -> {System.out.println("third pre filter");return chain.filter(exchange).then(Mono.fromRunnable(() -> {System.out.println("first post filter");}));};}
​
​
}

五:gateway整合sentinel

Sentinel从 1.6.0 版本开始提供了 Spring Cloud Gateway 的适配模块,可以提供两种资源维度的限流:

  • route 维度:即在 Spring 配置文件中配置的路由条目,资源名为对应的 routeId自定义

  • API 维度:用户可以利用 Sentinel 提供的 API 来自定义一些 API 分组

5.1:整合步骤

第一步:pom依赖

<dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
<dependency><groupId>com.alibaba.csp</groupId><artifactId>sentinel-spring-cloud-gateway-adapter</artifactId>
</dependency>

第二步:配置

spring:cloud:nacos:discovery:server-addr: 127.0.0.1:8848sentinel:transport:dashboard: 127.0.0.1:8888port: 8710

5.2:BlockException异常处理

默认BlockException异常全局处理器 SentinelGatewayBlockExceptionHandler

package com.wfx.config;
​
import com.alibaba.csp.sentinel.adapter.gateway.sc.SentinelGatewayFilter;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.codec.ServerCodecConfigurer;
import org.springframework.web.reactive.result.view.ViewResolver;
​
import java.util.Collections;
import java.util.List;
​
@Configuration
public class GatewayConfiguration {
​private final List<ViewResolver> viewResolvers;private final ServerCodecConfigurer serverCodecConfigurer;
​public GatewayConfiguration(ObjectProvider<List<ViewResolver>> viewResolversProvider,ServerCodecConfigurer serverCodecConfigurer) {this.viewResolvers = viewResolversProvider.getIfAvailable(Collections::emptyList);this.serverCodecConfigurer = serverCodecConfigurer;}
​@Bean//order不能为-1  必须优先级最高@Order(Ordered.HIGHEST_PRECEDENCE)public SentinelGatewayBlockExceptionHandler sentinelGatewayBlockExceptionHandler() {// Register the block exception handler for Spring Cloud Gateway.return new SentinelGatewayBlockExceptionHandler(viewResolvers, serverCodecConfigurer);}
​@Beanpublic GlobalFilter sentinelGatewayFilter() {// By default the order is HIGHEST_PRECEDENCEreturn new SentinelGatewayFilter();}
}

自定义BlockException异常处理器

package com.wfx.sentinel;
​
import com.alibaba.csp.sentinel.adapter.gateway.sc.SentinelGatewayFilter;
import com.alibaba.csp.sentinel.adapter.gateway.sc.exception.SentinelGatewayBlockExceptionHandler;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.codec.ServerCodecConfigurer;
import org.springframework.web.reactive.result.view.ViewResolver;
​
import java.util.Collections;
import java.util.List;
​
@Configuration
public class GatewayConfiguration {
​private final List<ViewResolver> viewResolvers;private final ServerCodecConfigurer serverCodecConfigurer;
​public GatewayConfiguration(ObjectProvider<List<ViewResolver>> viewResolversProvider,ServerCodecConfigurer serverCodecConfigurer) {this.viewResolvers = viewResolversProvider.getIfAvailable(Collections::emptyList);this.serverCodecConfigurer = serverCodecConfigurer;}
​@Bean// 必须优先级最高@Order(Ordered.HIGHEST_PRECEDENCE)public MySentinelGatewayBlockExceptionHandler sentinelGatewayBlockExceptionHandler() {// Register the block exception handler for Spring Cloud Gateway.return new MySentinelGatewayBlockExceptionHandler(viewResolvers, serverCodecConfigurer);}
​@Beanpublic GlobalFilter sentinelGatewayFilter() {// By default the order is HIGHEST_PRECEDENCEreturn new SentinelGatewayFilter();}
}

package com.wfx.sentinel;
​
import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.GatewayCallbackManager;
import com.alibaba.csp.sentinel.adapter.gateway.sc.exception.SentinelGatewayBlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.util.function.Supplier;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.codec.HttpMessageWriter;
import org.springframework.http.codec.ServerCodecConfigurer;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.reactive.function.server.ServerResponse;
import org.springframework.web.reactive.result.view.ViewResolver;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebExceptionHandler;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
​
import java.util.HashMap;
import java.util.List;
import java.util.Map;
​
/*** <p>title: com.wfx.sentinel</p>* author zhuximing* description:*/
​
public class MySentinelGatewayBlockExceptionHandler  implements WebExceptionHandler {private List<ViewResolver> viewResolvers;private List<HttpMessageWriter<?>> messageWriters;private final Supplier<ServerResponse.Context> contextSupplier = () -> {return new ServerResponse.Context() {public List<HttpMessageWriter<?>> messageWriters() {return MySentinelGatewayBlockExceptionHandler.this.messageWriters;}
​public List<ViewResolver> viewResolvers() {return MySentinelGatewayBlockExceptionHandler.this.viewResolvers;}};};
​public MySentinelGatewayBlockExceptionHandler(List<ViewResolver> viewResolvers, ServerCodecConfigurer serverCodecConfigurer) {this.viewResolvers = viewResolvers;this.messageWriters = serverCodecConfigurer.getWriters();}
​
​//自定义异常处理private Mono<Void> writeResponse(ServerResponse response1, ServerWebExchange exchange) {
​ServerHttpResponse response = exchange.getResponse();
​//不能放行,直接返回,返回json信息response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
​Map res = new HashMap(){{put("success",false);put("msg","系统繁忙,请稍后重试!!");}};
​ObjectMapper objectMapper = new ObjectMapper();String jsonStr = null;try {jsonStr = objectMapper.writeValueAsString(res);} catch (JsonProcessingException e) {e.printStackTrace();}
​
​DataBuffer dataBuffer = response.bufferFactory().wrap(jsonStr.getBytes());
​return response.writeWith(Flux.just(dataBuffer));//响应json数据
​}
​public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {if (exchange.getResponse().isCommitted()) {return Mono.error(ex);} else {return !BlockException.isBlockException(ex) ? Mono.error(ex) : this.handleBlockedRequest(exchange, ex).flatMap((response) -> {return this.writeResponse(response, exchange);});}}
​private Mono<ServerResponse> handleBlockedRequest(ServerWebExchange exchange, Throwable throwable) {return GatewayCallbackManager.getBlockHandler().handleRequest(exchange, throwable);}
}

六:gateway跨域

由于gateway使用的是webflux,而不是springmvc,所以需要先关闭springmvc的cors,再从gateway的filter里边设置cors就行了。

​
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
import org.springframework.web.util.pattern.PathPatternParser;
​
@Configuration
public class CorsConfig {@Beanpublic CorsWebFilter corsFilter() {CorsConfiguration config = new CorsConfiguration();config.addAllowedMethod("*");config.addAllowedOrigin("*");config.addAllowedHeader("*");
​UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser());source.registerCorsConfiguration("/**", config);
​return new CorsWebFilter(source);}
}

这篇关于springcloud ali gateway介绍的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/169151

相关文章

JVM 的类初始化机制

前言 当你在 Java 程序中new对象时,有没有考虑过 JVM 是如何把静态的字节码(byte code)转化为运行时对象的呢,这个问题看似简单,但清楚的同学相信也不会太多,这篇文章首先介绍 JVM 类初始化的机制,然后给出几个易出错的实例来分析,帮助大家更好理解这个知识点。 JVM 将字节码转化为运行时对象分为三个阶段,分别是:loading 、Linking、initialization

Spring Security 基于表达式的权限控制

前言 spring security 3.0已经可以使用spring el表达式来控制授权,允许在表达式中使用复杂的布尔逻辑来控制访问的权限。 常见的表达式 Spring Security可用表达式对象的基类是SecurityExpressionRoot。 表达式描述hasRole([role])用户拥有制定的角色时返回true (Spring security默认会带有ROLE_前缀),去

浅析Spring Security认证过程

类图 为了方便理解Spring Security认证流程,特意画了如下的类图,包含相关的核心认证类 概述 核心验证器 AuthenticationManager 该对象提供了认证方法的入口,接收一个Authentiaton对象作为参数; public interface AuthenticationManager {Authentication authenticate(Authenti

Spring Security--Architecture Overview

1 核心组件 这一节主要介绍一些在Spring Security中常见且核心的Java类,它们之间的依赖,构建起了整个框架。想要理解整个架构,最起码得对这些类眼熟。 1.1 SecurityContextHolder SecurityContextHolder用于存储安全上下文(security context)的信息。当前操作的用户是谁,该用户是否已经被认证,他拥有哪些角色权限…这些都被保

Spring Security基于数据库验证流程详解

Spring Security 校验流程图 相关解释说明(认真看哦) AbstractAuthenticationProcessingFilter 抽象类 /*** 调用 #requiresAuthentication(HttpServletRequest, HttpServletResponse) 决定是否需要进行验证操作。* 如果需要验证,则会调用 #attemptAuthentica

Spring Security 从入门到进阶系列教程

Spring Security 入门系列 《保护 Web 应用的安全》 《Spring-Security-入门(一):登录与退出》 《Spring-Security-入门(二):基于数据库验证》 《Spring-Security-入门(三):密码加密》 《Spring-Security-入门(四):自定义-Filter》 《Spring-Security-入门(五):在 Sprin

Java架构师知识体认识

源码分析 常用设计模式 Proxy代理模式Factory工厂模式Singleton单例模式Delegate委派模式Strategy策略模式Prototype原型模式Template模板模式 Spring5 beans 接口实例化代理Bean操作 Context Ioc容器设计原理及高级特性Aop设计原理Factorybean与Beanfactory Transaction 声明式事物

性能测试介绍

性能测试是一种测试方法,旨在评估系统、应用程序或组件在现实场景中的性能表现和可靠性。它通常用于衡量系统在不同负载条件下的响应时间、吞吐量、资源利用率、稳定性和可扩展性等关键指标。 为什么要进行性能测试 通过性能测试,可以确定系统是否能够满足预期的性能要求,找出性能瓶颈和潜在的问题,并进行优化和调整。 发现性能瓶颈:性能测试可以帮助发现系统的性能瓶颈,即系统在高负载或高并发情况下可能出现的问题

水位雨量在线监测系统概述及应用介绍

在当今社会,随着科技的飞速发展,各种智能监测系统已成为保障公共安全、促进资源管理和环境保护的重要工具。其中,水位雨量在线监测系统作为自然灾害预警、水资源管理及水利工程运行的关键技术,其重要性不言而喻。 一、水位雨量在线监测系统的基本原理 水位雨量在线监测系统主要由数据采集单元、数据传输网络、数据处理中心及用户终端四大部分构成,形成了一个完整的闭环系统。 数据采集单元:这是系统的“眼睛”,

Hadoop数据压缩使用介绍

一、压缩原则 (1)运算密集型的Job,少用压缩 (2)IO密集型的Job,多用压缩 二、压缩算法比较 三、压缩位置选择 四、压缩参数配置 1)为了支持多种压缩/解压缩算法,Hadoop引入了编码/解码器 2)要在Hadoop中启用压缩,可以配置如下参数