当前位置: 首页 > news >正文

建设中网站首页网站seo诊断

建设中网站首页,网站seo诊断,专业型网站网站,网站开发做网站在频繁的网络请求时,服务有时候也会受到很大的压力,尤其是那种网络攻击,非法的。这样的情形有时候需要作一些限制。本文主要介绍了两种限流方法,感兴趣的可以了解一下 目录 一、实战基于 Spring cloud Gateway 的限流 二、基于阿…

在频繁的网络请求时,服务有时候也会受到很大的压力,尤其是那种网络攻击,非法的。这样的情形有时候需要作一些限制。本文主要介绍了两种限流方法,感兴趣的可以了解一下

目录

  • 一、实战基于 Spring cloud Gateway 的限流

  • 二、基于阿里开源限流神器:Sentinel

在频繁的网络请求时,服务有时候也会受到很大的压力,尤其是那种网络攻击,非法的。这样的情形有时候需要作一些限制。例如:限制对方的请求,这种限制可以有几个依据:请求IP、用户唯一标识、请求的接口地址等等。

当前限流的方式也很多:Spring cloud 中在网关本身自带限流的一些功能,基于 redis 来做的。同时,阿里也开源了一款:限流神器 Sentinel。今天我们主要围绕这两块来实战微服务的限流机制。

首先讲 Spring cloud 原生的限流功能,因为限流可以是对每个服务进行限流,也可以对于网关统一作限流处理。

一、实战基于 Spring cloud Gateway 的限流

pom.xml引入依赖:

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis-reactive</artifactId></dependency>

其基础是基于redis,所以:

spring:

  application:

    name: gateway-service

  redis: #redis相关配置

    database: 8

    host: 10.12.15.5

    port: 6379

    password: 123456 #有密码时设置

    jedis:

      pool:

        max-active: 8

        max-idle: 8

        min-idle: 0

    timeout: 10000ms

接下来需要注入限流策略的 bean:

@Primary@Bean(value = "ipKeyResolver")KeyResolver ipKeyResolver() {return exchange -> Mono.just(exchange.getRequest().getRemoteAddress().getHostName());//return exchange -> Mono.just(exchange.getRequest().getRemoteAddress().getAddress().getHostAddress());//return exchange -> Mono.just(exchange.getRequest().getRemoteAddress().getAddress().getHostAddress());}@Bean(value = "apiKeyResolver")KeyResolver apiKeyResolver() {return exchange -> Mono.just(exchange.getRequest().getPath().value());}@Bean(value = "userKeyResolver")KeyResolver userKeyResolver() {return exchange -> Mono.just(exchange.getRequest().getQueryParams().getFirst("userId"));}

这里引入ipKeyResolver、apiKeyResolver、userKeyResolver三种策略,可以利用注解 @Primary 来决定其中一个被使用。

注入bean后,需要在配置中备用:

spring:

  application:

    name: gateway-service

  redis: #redis相关配置

    database: 8

    host: 10.12.15.5

    port: 6379

    password: 123456 #有密码时设置

    jedis:

      pool:

        max-active: 8

        max-idle: 8

        min-idle: 0

    timeout: 10000ms

后面是限流的主要配置:

spring

  cloud:

    gateway:

      routes: #路由配置:参数为一个List

      - id: cas-server #唯一标识

        uri: lb://cas-server-service #转发的地址,写服务名称

        order: -1

        predicates:

        - Path=/cas-server/** #判断匹配条件,即地址带有/ribbon/**的请求,会转发至lb:cas-server-service

        filters:

        - StripPrefix=1 #去掉Path前缀,参数为1代表去掉/ribbon

        - name: RequestRateLimiter #基于redis的Gateway的自身限流

          args:

            redis-rate-limiter.replenishRate: 1  # 允许用户每秒处理多少个请求

            redis-rate-limiter.burstCapacity: 3  # 令牌桶的容量,允许在一秒钟内完成的最大请求数

            key-resolver: "#{@ipKeyResolver}" #SPEL表达式取的对应的bean

      - id: admin-web

        uri: lb://admin-web-service

        order: -1

        predicates:

        - Path=/admin-web/**

        filters:

        - StripPrefix=1

        - name: RequestRateLimiter

          args:

            redis-rate-limiter.replenishRate: 1  # 允许用户每秒处理多少个请求

            redis-rate-limiter.burstCapacity: 3  # 令牌桶的容量,允许在一秒钟内完成的最大请求数

            key-resolver: "#{@ipKeyResolver}" #SPEL表达式取的对应的bean

这里是在原有的路由基础上加入 RequestRateLimiter限流过滤器,包括三个参数:

- name: RequestRateLimiter #基于redis的Gateway的自身限流

          args:

            redis-rate-limiter.replenishRate: 3  #允许用户每秒处理多少个请求

            redis-rate-limiter.burstCapacity: 5  #令牌桶的容量,允许在一秒钟内完成的最大请求数

            key-resolver: "#{@ipKeyResolver}" #SPEL表达式取的对应的bean

  • 其中 replenishRate,其含义表示允许每秒处理请求数;

  • burstCapacity 表示允许在一秒内处理的最大请求数;

  • key-resolver 这里采用请求 IP 限流,利用SPEL 表达式取对应的 bean

写一个小脚本来压测一下:

for i in $(seq 1 30000); do echo $(expr $i \\* 3 + 1);curl -i -H "Accept: application/json" -H "Authorization:bearer b064d95b-af3f-4053-a980-377c63ab3413" -X GET http://10.10.15.5:5556/order-service/api/order/getUserInfo;donefor i in $(seq 1 30000); do echo $(expr $i \\* 3 + 1);curl -i -H "Accept: application/json" -H "Authorization:bearer b064d95b-af3f-4053-a980-377c63ab3413" -X GET http://10.10.15.5:5556/admin-web/api/user/getCurrentUser;done

上面两个脚本分别对2个服务进行压测,打印结果:

{"message":{"status":200,"code":0,"message":"success"},"data":"{\"message\":{\"status\":200,\"code\":0,\"message\":\"get user success\"},\"data\":{\"id\":23,\"isAdmin\":1,\"userId\":\"fbb18810-e980-428c-932f-848f3b9e7c84\",\"userType\":\"super_admin\",\"username\":\"admin\",\"realName\":\"super_admin\",\"password\":\"$2a$10$89AqlYKlnsTpNmWcCMvgluRFQ/6MLK1k/nkBpz.Lw6Exh.WMQFH6W\",\"phone\":null,\"email\":null,\"createBy\":\"admin\",\"createTime\":1573119753172,\"updateBy\":\"admin\",\"updateTime\":1573119753172,\"loginTime\":null,\"expireTime\":null,\"remarks\":\"super_admin\",\"delFlag\":0,\"loginType\":null}}"}ex

在用测试工具Jmeter在同一秒内多次请求后:

HTTP/1.1 429 Too Many Requests

X-RateLimit-Remaining: 0

X-RateLimit-Burst-Capacity: 3

X-RateLimit-Replenish-Rate: 1

content-length: 0

expr: syntax error

HTTP/1.1 429 Too Many Requests

X-RateLimit-Remaining: 0

X-RateLimit-Burst-Capacity: 3

X-RateLimit-Replenish-Rate: 1

content-length: 0

expr: syntax error

从上面可以看到,执行后,会出现调用失败的情况,状态变为429 (Too Many Requests) 。

二、基于阿里开源限流神器:Sentinel

首先引入依赖:

<!--基于 阿里的sentinel作限流 --><dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-sentinel</artifactId></dependency>

在配置文件 application.yaml 文件中配置,需要新增2个配置:

spring:

  application:

    name: admin-web

  cloud:

    kubernetes:

      discovery:

        all-namespaces: true

    sentinel:

      eager: true #取消Sentinel控制台的懒加载

      transport:

        dashboard: 10.12.15.2:8080 #sentinel的Dashboard地址

        port: 8719 #是sentinel应用端和控制台通信端口

        heartbeat-interval-ms: 500 #心跳时间

      scg:

        fallback: #scg.fallback为sentinel限流后的响应配置

          mode: response

          response-status: 455

          response-body: 已被限流

其中,这里面配置了一个服务:spring.cloud.sentinel.transport.dashboard,配置的是 sentinel 的 Dashboard 地址。同时 spring.cloud.sentinel.transport.port 这个端口配置会在应用对应的机器上启动一个Http Server,该 Server 会与 Sentinel 控制台做交互。

Sentinel 默认为所有的 HTTP 服务提供限流埋点,上面配置完成后自动完成所有埋点,只需要控制配置限流规则即可。

这里我们讲下通过注解来给指定接口函数加上限流埋点,写一个RestController,在接口函数上加上注解

@SentinelResource:@GetMapping(value = "/getToken")@SentinelResource("getToken")public Response<Object> getToken(Authentication authentication){//Authentication authentication = SecurityContextHolder.getContext().getAuthentication();authentication.getCredentials();OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails)authentication.getDetails();String token = details.getTokenValue();return Response.ok(200, 0, "get token success", token);}

以上代码部分完成了,接下来先安装SentinelDashBoard,Sentinel DashBoard下载地址:github.com/alibaba/Sentinel/releases。

下载完成后,命令启动:

java -jar sentinel-dashboard-1.6.2.jar

默认启动端口为8080,访问 IP:8080,就可以显示 Sentinel 的登录界面,用户名与密码均为sentinel。登录 Dashboard 成功后,多次访问接口"/getToken",可以在 Dashboard 看到相应数据,这里不展示了。接下来可以设置接口的限流功能,在 “+流控” 按钮点击打开设置界面,设置阈值类型为 qps,单机阈值为5。

浏览器重复请求 http://10.10.15.5:5556/admin-web/api/user/getToken 如果超过阀值就会出现如下界面信息:

Blocked by Sentinel (flow limiting)

此时,就看到Sentinel 限流起作用了,可以加上 spring.cloud.sentinel.scg.fallback 为sentinel 限流后的响应配置,亦可自定义限流异常信息:

@GetMapping(value = "/getToken")@SentinelResource(value = "getToken", blockHandler = "handleSentinelException", blockHandlerClass = {MySentinelException.class}))public Response<Object> getToken(Authentication authentication){//Authentication authentication = SecurityContextHolder.getContext().getAuthentication();authentication.getCredentials();OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails)authentication.getDetails();String token = details.getTokenValue();return Response.ok(200, 0, "get token success", token);}public class MySentinelException {public static Response<Object> handleSentinelException(BlockException e) {Map<String,Object> map=new HashMap<>();logger.info("Oops: " + ex.getClass().getCanonicalName());return Response.ok(200, -8, "通过注解 @SentinelResource 配置限流埋点并自定义限流后的处理逻辑", null);}}

这里讲下注解 @SentinelResource 包含以下属性:

  • value:资源名称,必需项;

  • entryType:入口类型,可选项(默认为 EntryType.OUT);

  • blockHandler:blockHandlerClass中对应的异常处理方法名,参数类型和返回值必须和原方法一致;

  • blockHandlerClass:自定义限流逻辑处理类

Sentinel 限流逻辑处理完毕了,但每次服务重启后,之前配置的限流规则就会被清空。因为是内存形式的规则对象。所以下面就讲下用 Sentinel 的一个特性 ReadableDataSource 获取文件、数据库或者配置中心设置限流规则,目前支持 Apollo、Nacos、ZK 配置来管理。

首先回忆一下,一条限流规则主要由下面几个因素组成:

  • resource:资源名,即限流规则的作用对象,即为注解 @SentinelResource 的value;

  • count:限流阈值;grade:限流阈值类型(QPS 或并发线程数);

  • limitApp:流控针对的调用来源,若为 default 则不区分调用来源;

  • strategy:基于调用关系的限流策略;

  • controlBehavior:流量控制效果(直接拒绝、排队等待、匀速器模式)

理解了意思,接下来通过文件来配置:

#通过文件读取限流规则

spring.cloud.sentinel.datasource.ds1.file.file=classpath:flowrule.json

spring.cloud.sentinel.datasource.ds1.file.data-type=json

spring.cloud.sentinel.datasource.ds1.file.rule-type=flow

在resources新建一个文件,比如 flowrule.json 添加限流规则:

[

  {

    "resource": "getToken",

    "count": 1,

    "controlBehavior": 0,

    "grade": 1,

    "limitApp": "default",

    "strategy": 0

  },

  {

    "resource": "resource",

    "count": 1,

    "controlBehavior": 0,

    "grade": 1,

    "limitApp": "default",

    "strategy": 0

  }

]

重新启动项目,出现如下日志说明成功:

DataSource ds1-sentinel-file-datasource start to loadConfig

DataSource ds1-sentinel-file-datasource load 2 FlowRule

如果采用 Nacos 作为配置获取限流规则,可在文件中加如下配置:

spring:

  application:

    name: order-service

  cloud:

    nacos:

      config:

        server-addr: 10.10.15.5:8848

      discovery:

        server-addr: 10.10.15.5:8848

    sentinel:

      eager: true

      transport:

        dashboard: 10.10.15.5:8080

      datasource:

        ds1:

          nacos:

            server-addr: 10.10.15.5:8848

            dataId: ${spring.application.name}-flow-rules

            data-type: json

            rule-type: flow


文章转载自:
http://usual.c7627.cn
http://inviolacy.c7627.cn
http://ragtag.c7627.cn
http://jet.c7627.cn
http://icelandic.c7627.cn
http://endonuclease.c7627.cn
http://windbell.c7627.cn
http://felonious.c7627.cn
http://maline.c7627.cn
http://pertinently.c7627.cn
http://souther.c7627.cn
http://dassie.c7627.cn
http://roband.c7627.cn
http://dehypnotize.c7627.cn
http://djinni.c7627.cn
http://cartopper.c7627.cn
http://playground.c7627.cn
http://octoroon.c7627.cn
http://genevieve.c7627.cn
http://cluj.c7627.cn
http://aeronautical.c7627.cn
http://caseinogen.c7627.cn
http://infecundity.c7627.cn
http://camlet.c7627.cn
http://rampion.c7627.cn
http://scabwort.c7627.cn
http://unappropriated.c7627.cn
http://heterophile.c7627.cn
http://carking.c7627.cn
http://breastwork.c7627.cn
http://penally.c7627.cn
http://lecithal.c7627.cn
http://lightplane.c7627.cn
http://homograph.c7627.cn
http://sincipital.c7627.cn
http://tinclad.c7627.cn
http://thermomechanical.c7627.cn
http://trimorphous.c7627.cn
http://jaywalk.c7627.cn
http://pentarchy.c7627.cn
http://hoosh.c7627.cn
http://zinjanthropine.c7627.cn
http://safrol.c7627.cn
http://eyealyzer.c7627.cn
http://lulu.c7627.cn
http://canadienne.c7627.cn
http://stannate.c7627.cn
http://vicinity.c7627.cn
http://prelatical.c7627.cn
http://typewriter.c7627.cn
http://technify.c7627.cn
http://broker.c7627.cn
http://psychotherapeutics.c7627.cn
http://anaplasty.c7627.cn
http://lecithinase.c7627.cn
http://tad.c7627.cn
http://punky.c7627.cn
http://rumpy.c7627.cn
http://rhythmization.c7627.cn
http://bridecake.c7627.cn
http://redeliver.c7627.cn
http://macchinetta.c7627.cn
http://undergrad.c7627.cn
http://remasticate.c7627.cn
http://beagle.c7627.cn
http://unhesitatingly.c7627.cn
http://surcease.c7627.cn
http://necessitarian.c7627.cn
http://contrasty.c7627.cn
http://unspeak.c7627.cn
http://commeasure.c7627.cn
http://rhodanize.c7627.cn
http://held.c7627.cn
http://enphytotic.c7627.cn
http://deary.c7627.cn
http://libidinous.c7627.cn
http://cellarway.c7627.cn
http://pierage.c7627.cn
http://meletin.c7627.cn
http://redistribution.c7627.cn
http://interconvert.c7627.cn
http://sexologist.c7627.cn
http://squaloid.c7627.cn
http://kingstown.c7627.cn
http://arrogance.c7627.cn
http://chunk.c7627.cn
http://transliterator.c7627.cn
http://cainozoic.c7627.cn
http://hepatin.c7627.cn
http://cecal.c7627.cn
http://numinous.c7627.cn
http://polychromasia.c7627.cn
http://castelet.c7627.cn
http://bagasse.c7627.cn
http://mythical.c7627.cn
http://senator.c7627.cn
http://nizamate.c7627.cn
http://bt.c7627.cn
http://ozocerite.c7627.cn
http://trihydrate.c7627.cn
http://www.zhongyajixie.com/news/53183.html

相关文章:

  • jsp 网站建设百度权重是什么
  • 可以做网站的appgoogle 浏览器
  • 网站评论管理怎么做东莞海外网络推广
  • 网站建设公司代理网站seo优化教程
  • 如何加强网站建设和信息宣传百度文库官网入口
  • 一个网站建设10万元免费网站建设
  • 注册公司流程和要求seo提升关键词排名
  • 做招标应该关注什么网站抖音关键词优化排名靠前
  • 如何手机做网站cpu游戏优化加速软件
  • 网站前端开发无锡百度正规推广
  • dedecms企业网站模板关键词优化排名
  • b2b电子商务网站主要是以零售为主2022近期时事热点素材
  • 阿里云ECS1M做影院网站网络营销推广及优化方案
  • 荔湾做网站公北京网站优化对策
  • 有哪些设计网站app快速收录域名
  • 长沙商城网站制作谷歌paypal官网登录入口
  • 网站建设学校成人本科报考官网
  • 淘宝客为什么做网站网页开发需要学什么
  • 临沂专业网站建设公司电话武汉网站seo公司
  • 网站设计 网络推广的服务内容网站优化团队
  • 不懂代码怎么做网站推广营销软件app
  • 保险网站建设平台百度开店怎么收费
  • 个人可以做网站吗seo优化员
  • 平面设计师个人网站九江seo公司
  • 廊坊网站制作套餐品牌营销策划公司排名
  • wordpress 主题 保存宁波谷歌优化
  • 涿州网站制作策划方案网站
  • 网站内容填写上海seo服务
  • 中山市建设工程网站推广优化价格
  • 上海松江做网站建设网站制作公司排名