广告位网站建设,建设机械网站案例分析,直播app开发多少钱,今年国内重大新闻一、Gateway整合sentinel限流
网关作为内部系统外的一层屏障,对内起到-定的保护作用#xff0c;限流便是其中之- - .网关层的限流可以简单地针对不同路由进行限流,也可针对业务的接口进行限流,或者根据接口的特征分组限流。
1、添加依赖 dependencygroupIdc…一、Gateway整合sentinel限流
网关作为内部系统外的一层屏障,对内起到-定的保护作用限流便是其中之- - .网关层的限流可以简单地针对不同路由进行限流,也可针对业务的接口进行限流,或者根据接口的特征分组限流。
1、添加依赖 dependencygroupIdcom.alibaba.cloud/groupIdartifactIdspring-cloud-alibaba-sentinel-gateway/artifactId
/dependency
dependencygroupIdcom.alibaba.cloud/groupIdartifactIdspring-cloud-starter-alibaba-sentinel/artifactId
/dependency2、添加配置 server:port: 8088
spring:application:name: api-gateway
# gateway的配置cloud:gateway:routes:- id: order_route #路由的唯一标识路由到orderuri: lb://order-service # 需要转发的地址 lb指的是从nacos中按照名称获取微服务并遵循负载均衡策略 order-service服务名#断言规则 用于路由规则的匹配predicates:- Path/order/**# http://localhost:8088/order-serve/order/add 路由到↓# http://localhost:8020/order-serve/order/add#- After2020-10-19T09:07:00.66008:00[Asia/Shanghai]#- HeaderX-Request-Id, \d#- MethodGET#- Queryname,xushu|zhuge#- CheckAuth xushu#filters:#- AddRequestHeaderX-Request-color,red#- AddRequestParametercolor,blue#- PrefixPath/mall-order #添加前缀对应微服务需要配置context-path#- StripPrefix1 # 转发之前去掉第一次的路径# http://localhost:8020/order/add#- RedirectTo302, https://www.baidu.com#- SetStatus 404#- CheckAuthxushu#- id: stock_route# 配置Nacos# 跨域的配置# globalcors:# cors-configurations:# [/**]: # 允许跨域访问的资源# allowedOrigins: * #跨域允许的来源 例如www.smsm.com# allowedMethods:# - GET# - POST# - PUT#配置Nacosnacos:discovery:server-addr: 127.0.0.1:8848username: nacospassword: nacos# 配置sentinelsentinel:transport:dashboard: 127.0.0.1:8858
3、完善测试接口
下载sentinel-dashboard-1.8.0.jar
https://github.com/alibaba/Sentinel/releases 运行jar包
java -Dserver.port8858 -Dsentinel.dashboard.auth.usernamexushu -Dsentinel.dashboard.auth.password123456 -jar C:\Users\ZHENG\Desktop\sentinel-dashboard-1.8.0.jar访问http://localhost:8858/
账号xushu 密码123456 http://127.0.0.1:8088/order/add 访问http://127.0.0.1:8088/order/add 不断点击连续访问
二、通过代码实现限流
1、编写配置类 Configuration
public class GatewayConfig {PostConstruct //设置初始化的时候public void init(){BlockRequestHandler blockRequestHandler new BlockRequestHandler() {Overridepublic MonoServerResponse handleRequest(ServerWebExchange serverWebExchange, Throwable t) {System.out.println(t);HashMapString,String map new HashMapString,String();map.put(code,HttpStatus.TOO_MANY_REQUESTS.toString());map.put(message,限流了);//自定义的异常处理return ServerResponse.status(HttpStatus.OK).contentType(MediaType.APPLICATION_JSON).body(BodyInserters.fromValue(map));}};GatewayCallbackManager.setBlockHandler(blockRequestHandler);}
} 访问http://127.0.0.1:8088/order/get 访问http://127.0.0.1:8088/order/get 连续不断访问
三、通过配置文件实现 scg:fallback:mode: responseresponse-body: {code:,messageL:}四、网管高可用
为了保证Gateway的高可用性可以同时启动多个Gateway实例进行负载,在Gateway的.上游使用Nginx或者F5进行负载转发以达到高可用。