OpenShift 4 之Istio-Tutorial (9) 访问限流

荀靖
2023-12-01

OpenShift 4.x HOL教程汇总
说明:本文已经在OpenShift 4.6环境中验证

注意:下文的早期 OpenShift Service Mesh 支持的 访问限流 功能已有变化, 如要实现可参见官方说明:https://access.redhat.com/articles/6266191

Istio可以实现对服务访问的限流。通常限流可以保护被调用服务的可用性,以防止被调用服务由于频繁访问出现不稳定情况。本章节我们实现对服务访问的限流。

  1. 我们在开始之前先确保环境和完成《OpenShift 4 之Istio-Tutorial (2)
    部署三个微服务
    》一样,只部署了3个微服务和VirtualService、Gateway,没有DestinationRule。

  2. 此时使用脚本访问customer可以正常连续访问。

$ INGRESS_GATEWAY=$(oc get route -n ${ISTIO_SYSTEM} istio-ingressgateway -o 'jsonpath={.spec.host}')
$ ./scripts/run.sh $INGRESS_GATEWAY/customer
  1. 用以下内容覆盖 istiofiles/rate_limit_rule.yml 文件,它定义了对recommendation服务的访问限流(每5s只能访问1次),而其它服务是缺省的限流(1s可以访问500次)。
$ cat > istiofiles/rate_limit_rule1.yml << EOF
apiVersion: config.istio.io/v1alpha2
kind: memquota
metadata:
  name: handler
spec:
  quotas:
  - name: requestcount.quota.istio-system
    maxAmount: 500
    validDuration: 1s
    overrides:
    - dimensions:
        destination: recommendation
      maxAmount: 1
      validDuration: 5s
---
apiVersion: config.istio.io/v1alpha2
kind: quota
metadata:
  name: requestcount
spec:
  dimensions:
    source: request.headers["x-forwarded-for"] | "unknown"
    destination: destination.labels["app"] | destination.service.name | "unknown"
    destinationVersion: destination.labels["version"] | "unknown"
---
apiVersion: config.istio.io/v1alpha2
kind: QuotaSpec
metadata:
  name: request-count
  namespace: ${ISTIO_SYSTEM}
spec:
  rules:
  - quotas:
    - charge: 1
      quota: requestcount
---
apiVersion: config.istio.io/v1alpha2
kind: QuotaSpecBinding
metadata:
  name: request-count
  namespace: ${ISTIO_SYSTEM}
spec:
  quotaSpecs:
  - name: request-count
    namespace: ${ISTIO_SYSTEM}
  services:
  - name: recommendation
    namespace: ${ISTIO_APP}
---
apiVersion: config.istio.io/v1alpha2
kind: rule
metadata:
  name: quota
  namespace: ${ISTIO_SYSTEM}
spec:
  actions:
  - handler: handler.memquota
    instances:
    - requestcount.quota
EOF
  1. 执行脚本,先创建限流资源对象,然后持续访问customer服务。可以看到preference服务提示:访问已经超过限流了。
$ oc create -f istiofiles/rate_limit_rule1.yml
$ ./scripts/run.sh $INGRESS_GATEWAY/customer
customer => preference => recommendation v1 from '67976848-4l4s7': 8348
customer => preference => recommendation v1 from '67976848-4l4s7': 8349
customer => Error: 503 - preference => Error: 429 - RESOURCE_EXHAUSTED:Quota is exhausted for: requestcount
customer => Error: 503 - preference => Error: 429 - RESOURCE_EXHAUSTED:Quota is exhausted for: requestcount
customer => Error: 503 - preference => Error: 429 - RESOURCE_EXHAUSTED:Quota is exhausted for: requestcount
Ccustomer => Error: 503 - preference => Error: 429 - RESOURCE_EXHAUSTED:Quota is exhausted for: requestcount
  1. 最后恢复环境即可。
$ oc delete -f istiofiles/rate_limit_rule.yml -n ${ISTIO_SYSTEM}
 类似资料: