springcloud gateway 限流

yml配置转发规则

spring:
  cloud:
     gateway:
       discovery:
         locator:
           lowerCaseServiceId: true
           enabled: true
       routes:
        # =====================================
        - id: test
          uri: http://localhost:9191
          order: 8888
          predicates:
          - Path=/test/**
          filters:
          - StripPrefix=1   
          - name: Hystrix
            args:
              name : default
              fallbackUri: 'forward:/defaultfallback'
          - name: RequestRateLimiter
            args:
              redis-rate-limiter.replenishRate: 1  # 令牌桶的容积
              redis-rate-limiter.burstCapacity: 3  # 流速 每秒
              key-resolver: "#{@ipAddressKeyResolver}" #SPEL表达式去的对应的bean
        - id: api-eureka
          uri: lb://eureka-server
          order: 8000
          predicates:
          - Path=/api-eureka/**
          filters:
          - StripPrefix=1   
          - name: Hystrix
            args:
              name : default
              fallbackUri: 'forward:/defaultfallback'
        
  datasource: 
    druid: 
      # JDBC 配置(驱动类自动从url的mysql识别,数据源类型自动识别)
      url: jdbc:mysql://59.110.164.254:3306/oauth-center?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true&useSSL=false 
      username: root
      password: root
      driver-class-name:  com.mysql.jdbc.Driver
      #连接池配置(通常来说,只需要修改initialSize、minIdle、maxActive
      initial-size: 1
      max-active: 20
      min-idle: 1
      # 配置获取连接等待超时的时间
      max-wait: 60000
      #打开PSCache,并且指定每个连接上PSCache的大小
      pool-prepared-statements: true
      max-pool-prepared-statement-per-connection-size: 20
      validation-query: SELECT 'x'
      test-on-borrow: false
      test-on-return: false 
      test-while-idle: true      
      #配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
      time-between-eviction-runs-millis: 60000
      #配置一个连接在池中最小生存的时间,单位是毫秒
      min-evictable-idle-time-millis: 300000
      filters: stat,wall
      # WebStatFilter配置,说明请参考Druid Wiki,配置_配置WebStatFilter
      #是否启用StatFilter默认值true
      web-stat-filter.enabled: false
      web-stat-filter.url-pattern:  /*
      web-stat-filter.exclusions: "*.js , *.gif ,*.jpg ,*.png ,*.css ,*.ico , /druid/*"
      web-stat-filter.session-stat-max-count: 1000
      web-stat-filter.profile-enable: true
      # StatViewServlet配置
      #展示Druid的统计信息,StatViewServlet的用途包括:1.提供监控信息展示的html页面2.提供监控信息的JSON API
      #是否启用StatViewServlet默认值true
      stat-view-servlet.enabled: false
      #根据配置中的url-pattern来访问内置监控页面,如果是上面的配置,内置监控页面的首页是/druid/index.html例如:
      #http://110.76.43.235:9000/druid/index.html
      #http://110.76.43.235:8080/mini-web/druid/index.html
      stat-view-servlet.url-pattern:  /druid/*
      #允许清空统计数据
      stat-view-servlet.reset-enable:  true
      stat-view-servlet.login-username: admin
      stat-view-servlet.login-password: admin
      #StatViewSerlvet展示出来的监控信息比较敏感,是系统运行的内部情况,如果你需要做访问控制,可以配置allow和deny这两个参数
      #deny优先于allow,如果在deny列表中,就算在allow列表中,也会被拒绝。如果allow没有配置或者为空,则允许所有访问
      #配置的格式
      #<IP>
      #或者<IP>/<SUB_NET_MASK_size>其中128.242.127.1/24
      #24表示,前面24位是子网掩码,比对的时候,前面24位相同就匹配,不支持IPV6。
      #stat-view-servlet.allow=
      #stat-view-servlet.deny=128.242.127.1/24,128.242.128.1
      # Spring监控配置,说明请参考Druid Github Wiki,配置_Druid和Spring关联监控配置
      #aop-patterns= # Spring监控AOP切入点,如x.y.z.service.*,配置多个英文逗号分隔
################### mysq end ##########################
  redis:
################### redis 单机版 start ########################## 
    host: 59.110.164.254
    port: 6379
    timeout: 6000
    database: 3
    lettuce:
      pool:
        max-active: 10 # 连接池最大连接数(使用负值表示没有限制),如果赋值为-1,则表示不限制;如果pool已经分配了maxActive个jedis实例,则此时pool的状态为exhausted(耗尽)
        max-idle: 8   # 连接池中的最大空闲连接 ,默认值也是8
        max-wait: 100 # # 等待可用连接的最大时间,单位毫秒,默认值为-1,表示永不超时。如果超过等待时间,则直接抛出JedisConnectionException  
        min-idle: 2    # 连接池中的最小空闲连接 ,默认值也是0
      shutdown-timeout: 100ms
################### redis 单机版 end ##########################   
#    cluster:
#      nodes: 130.75.131.237:7000,130.75.131.238:7000,130.75.131.239:7000,130.75.131.237:7001,130.75.131.238:7001,130.75.131.239:7001
#        #130.75.131.237:7000,130.75.131.238:7000,130.75.131.239:7000,130.75.131.237:7001,130.75.131.238:7001,130.75.131.239:7001
#        #192.168.3.157:7000,192.168.3.158:7000,192.168.3.159:7000,192.168.3.157:7001,192.168.3.158:7001,192.168.3.159:7001
#    timeout: 1000 # 连接超时时间(毫秒)
#    lettuce:
#      pool:
#        max-active: 10 # 连接池最大连接数(使用负值表示没有限制),如果赋值为-1,则表示不限制;如果pool已经分配了maxActive个jedis实例,则此时pool的状态为exhausted(耗尽)
#        max-idle: 8   # 连接池中的最大空闲连接 ,默认值也是8
#        max-wait: 100 # # 等待可用连接的最大时间,单位毫秒,默认值为-1,表示永不超时。如果超过等待时间,则直接抛出JedisConnectionException  
#        min-idle: 2    # 连接池中的最小空闲连接 ,默认值也是0
#      shutdown-timeout: 100ms
  
mybatis:
  config-location: classpath:mybatis.cfg.xml
  mapper-locations: classpath*:com/open/**/dao/*.xml  


auth:
  ignored:  /api-file/files-anon/**,/test163/** , /api-auth/** , /doc.html ,/test111 ,/api-user/users-anon/login,/user-center/users-anon/login,/document.html,**/v2/api-docs,/oauth/** ,/login.html ,/user/login,/**/**.css ,/**/**.js
    
 

ribbon:
  eureka:
    enabled: true
  ReadTimeout: 60000
  ConnectTimeout: 60000
  MaxAutoRetries: 0
  MaxAutoRetriesNextServer: 1
  OkToRetryOnAllOperations: false


#设置最大容错超时时间
hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds: 90000



#设置最大容错超时时间
hystrix:
  threadpool:
    default:
      coreSize: 100
      maximumSize: 5000
      allowMaximumSizeToDivergeFromCoreSize: true
      maxQueueSize: -1
  command:
    default:
      circuitBreaker:
        foreOpen: false
      execution:
        timeout:
          enabled: true
        isolation:
          thread:
            timeoutInMilliseconds: 900000


# hystrix 信号量隔离,3秒后自动超时
#hystrix:
#  command:
#    default:
#      execution:
#        isolation:
#          strategy: SEMAPHORE
#          thread:
#            timeoutInMilliseconds: 3000
#  shareSecurityContext: true
  
  

eureka:
  client:
    serviceUrl:
      defaultZone: http://127.0.0.1:1111/eureka/
      #http://192.168.3.170:1111/eureka,http://192.168.3.171:1111/eureka,http://192.168.3.173:1111/eureka
      #http://130.75.131.243:1111/eureka/,http://130.75.131.244:1111/eureka/,http://130.75.131.245:1111/eureka/  
    registry-fetch-interval-seconds: 3  
    instance-info-replication-interval-seconds: 3      
  instance:
    prefer-ip-address: true
    instance-id: ${
    
    spring.application.name}:${
    
    spring.cloud.client.ip-address}:${
    
    spring.application.instance_id:${
    
    server.port}}
#    instance-id: ${
    
    spring.application.name}:${
    
    docker.ipAddress}:${
    
    spring.application.instance_id:${
    
    server.port}}
    lease-renewal-interval-in-seconds: 5
    #注册实例文档
    status-page-url: http://${
    
    spring.cloud.client.ip-address}:${
    
    server.port}/swagger-ui.html # ${
    
    server.port}为该服务的端口号
#    status-page-url: http://${
    
    docker.ipAddress}:${
    
    server.port}/swagger-ui.html # ${
    
    server.port}为该服务的端口号
            

核心过滤器

@Component
public class AccessFilter implements GlobalFilter, Ordered {
    
    

	@Override
	public int getOrder() {
    
    
		return -500;
	}

	@Override
	public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
    
    
		// 未做逻辑处理,直接放行
		return chain.filter(exchange);
	}
}

限流配置


/**
 * 定义spring cloud gateway中的  key-resolver: "#{@ipAddressKeyResolver}" #SPEL表达式去的对应的bean
 *  ipAddressKeyResolver 要取bean的名字
 *
 */
@Configuration
public class RequestRateLimiterConfig {
    
    

    /**
     * 根据 HostName 进行限流
     * @return
     */
    @Bean("ipAddressKeyResolver")
    public KeyResolver ipAddressKeyResolver() {
    
    
        return exchange -> Mono.just(exchange.getRequest().getRemoteAddress().getHostName());
    }

    /**
     * 根据api接口来限流
     * @return
     */
    @Bean(name="apiKeyResolver")
    public KeyResolver apiKeyResolver() {
    
    
        return exchange ->  Mono.just(exchange.getRequest().getPath().value());
    }

    /**
     * 用户限流
     * 使用这种方式限流,请求路径中必须携带userId参数。
     *  提供第三种方式
     * @return
     */
    @Bean("userKeyResolver")
    KeyResolver userKeyResolver() {
    
    
        return exchange -> Mono.just(exchange.getRequest().getQueryParams().getFirst("userId"));
    }
}

猜你喜欢

转载自blog.csdn.net/qq_36382225/article/details/102478315