1 В избранное 0 Ответвления 0

OSCHINA-MIRROR/aiyuntang-zuul-redislimiter-spring-boot

Присоединиться к Gitlife
Откройте для себя и примите участие в публичных проектах с открытым исходным кодом с участием более 10 миллионов разработчиков. Приватные репозитории также полностью бесплатны :)
Присоединиться бесплатно
Клонировать/Скачать
README-CN.md 9.5 КБ
Копировать Редактировать Web IDE Исходные данные Просмотреть построчно История
gitlife-traslator Отправлено 26.11.2024 10:14 52aba96

zuul-redislimiter-spring-boot

Основы Zuul: ограничитель на основе лимита

Быстрый старт

Клонирование, компиляция, установка

git clone https://github.com/tangaiyun/zuul-redislimiter-spring-boot.git
cd zuulredislimiter/zuul-redislimiter-spring-boot-starter
mvn clean install

Создание нового проекта Zuul

Создайте проект Zuul, следуя примеру проекта «zuulredislimiter / zuulapp», и добавьте необходимые зависимости в файл pom.xml.

package com.tay.zuulapp;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;


@SpringBootApplication
@EnableZuulProxy
public class ZuulappApplication {

    public static void main(String[] args) {
        SpringApplication.run(ZuulappApplication.class, args);
    }

}
<dependencies>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-zuul</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>com.tay</groupId>
        <artifactId>zuul-redislimiter-spring-boot-starter</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </dependency>
</dependencies>

Конфигурация

Измените файл resources/application.yml и добавьте следующие настройки:

server:
  port: 8000  

spring:
  application:
    name: service-zuul

zuul:
  routes:
    service1: /s1/**
    service2: /s2/**
  redis-limiter:
    redis-host: 127.0.0.1                             #Redis 服务器   
    policy-map:
      api-a:                                          #serviceId为api-a的限流规则 
        order: -1                                     #规则排序,但一个请求有多条规则匹配时,排序值最小的规则生效
        baseExp: Headers['userid']                    #基于header里key为“userid”的值统计,目前仅支持Headers['xxx'],Cookies['xxx']
        pathRegExp: /s1/.*                            #请求URI的匹配正则表达式 
        timeUnit: MINUTES                             #时间单位,支持SECONDS,MINUTES,HOURS,DAYS 
        permits: 2                                    #单位时间内可访问的次数
      api-a1:
        order: 0
        baseExp: Cookies['userid']
        pathRegExp: /s1.*
        timeUnit: MINUTES
        permits: 3
      api-b:
        order: 2
        baseExp: Headers['userid']
        pathRegExp: /s2/.*
        timeUnit: MINUTES
        permits: 5
eureka:
  client:
    serviceUrl:
          defaultZone: http://localhost:8761/eureka/
  instance:
      prefer-ip-address: true

Пример проекта zuulredislimiter / service1 для создания простого микросервиса

package com.tay.service1;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/demo1")
public class Controller1 {
    @GetMapping("/test11")
    public String test1() {
        return "test11!";
    }

    @GetMapping("/test12")
    public String test2() {
        return "test12!";
    }
}
server:
  port: 8001
spring:
  application:
    name: service1

eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/
  instance:
    prefer-ip-address: true

Пример проекта zuulredislimiter / service2 для создания простого микросервиса

package com.tay.service2;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/demo2")
public class Controller2 {
    @GetMapping("/test21")
    public String test1() {
        return "test21!";
    }

    @GetMapping("/test22")
    public

``` **Строка test2() {**

    **return «test22!»;**

**}**

Это похоже на язык Java.

server:
  port: 8002
spring:
  application:
    name: service2

eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/
  instance:
    prefer-ip-address: true

Данный фрагмент написан на языке YAML.

package com.tay.eurekaserver;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;

@EnableEurekaServer
@SpringBootApplication
public class EurekaserverApplication {

    public static void main(String[] args) {
        SpringApplication.run(EurekaserverApplication.class, args);
    }

}

Этот фрагмент также написан на языке Java.

server:
  port: 8761

eureka:
  client:
    register-with-eureka: false
    fetch-registry: false

Фрагмент написан на языке YAML.

sudo docker run -d -p 6379:6379 redis

Это язык командной оболочки UNIX Shell.

api-b:
  order: 2
  baseExp: Headers['userid']
  pathRegExp: /s2/.*
  timeUnit: MINUTES
  permits: 5

Язык YAML.

高级指南

所有的配置项


spring:
    redis-limiter: 
        redis-host: 127.0.0.1           # redis server IP                   default:127.0.0.1
        redis-port: 6379                # redis service port                default:6379  
        redis-password: test            # redis password                    default:null 
        redis-connection-timeout: 2000  # redis connection timeout          default:2000
        redis-pool-max-idle: 50         # redis pool max idle               default: 50
        redis-pool-min-idle: 10         # redis pool mim idle               default:10 
        redis-pool-max-wait-millis: -1 # max wait time for get connection  default:-1 
        redis-pool-max-total: 200       # max total connection              default:200
        redis-key-prefix: #RL           # key prefix for visit footprint    default: #RL
        check-action-timeout: 100       # check action execution timeout    default: 100
        channel: #RLConfigChannel      # conf change event pub/sub channel default: #RLConfigChannel
        policy-map:                     # rate limiting policies 
          api-a:                        # unique service id
            order: -1                   # order
            baseExp: Headers['userid']  # value to base on, Spel expression without "#", supports Headers['xxx'] or Cookies['xxx']  
            pathRegExp: /s1/.*          # URI path pattern, a Regular expression 
            timeUnit: MINUTES           # timeUnit supports SECONDS, MINUTES, HOURS,DAYS
            permits: 2                  # Number of visits allowed per a timeUnit
          api-a1:              
            order: 0
            baseExp: Headers['userid']
            pathRegExp: /s1.*
            timeUnit: MINUTES
            permits: 3
          ...  

Также язык YAML.

动态配置


@RequestMapping("/zuullimiterpolicy")
public class LimitingPolicyResource {
    ...

    @PostMapping
    public void add(@RequestBody LimitingPolicy limitingPolicy, HttpServletResponse response) throws IOException{
        ...
    }

    @PutMapping
    public void update(@RequestBody LimitingPolicy limitingPolicy, HttpServletResponse response) throws IOException {

        ...
    }
    @GetMapping("/{serviceId}")
    public LimitingPolicy get(@PathVariable("serviceId") String serviceId) {
        ...
    }

    @DeleteMapping("/{serviceId}")
    public void delete(@PathVariable("serviceId") String serviceId) {
        ...
    }

Это снова язык Java. Обновить правила ограничения потока, указав Content-Type как «application/json», отправив запрос PUT на http://localhost:8000/zuullimiterpolicy. Тело запроса должно выглядеть так:

{
  "serviceId": "api-a",
  "order": -1,
  "baseExp": "Headers['userid']",
  "pathRegExp": "/s1/.*",
  "timeUnit": "MINUTES",
  "permits": 10,
  "delete": false
}

Удалить правило ограничения потока с serviceId «api-b», выполнив DELETE на http://localhost:8000/zuullimiterpolicy/api-b.

Добавить правило ограничения потока, указав Content-Type как «application/json» и отправив POST на http://localhost:8000/zuullimiterpolicy. Тело запроса:

{
  "serviceId": "api-d",
  "order": -1,
  "baseExp": "Headers['userid']",
  "pathRegExp": "/s3/.*",
  "timeUnit": "MINUTES",
  "permits": 10,
  "delete": false
}

Обратите внимание, что при добавлении нового правила ограничения потока serviceId и pathRegExp не должны совпадать с уже существующими правилами, иначе добавление не удастся.

Опубликовать ( 0 )

Вы можете оставить комментарий после Вход в систему

1
https://api.gitlife.ru/oschina-mirror/aiyuntang-zuul-redislimiter-spring-boot.git
git@api.gitlife.ru:oschina-mirror/aiyuntang-zuul-redislimiter-spring-boot.git
oschina-mirror
aiyuntang-zuul-redislimiter-spring-boot
aiyuntang-zuul-redislimiter-spring-boot
master