策略创建API

API概览

创建策略(V2)

POST /api/v2/policies
Content-Type: application/json

创建策略绑定(V1)

POST /api/v1/policy-attachments
Content-Type: application/json

基础请求结构

CreatePolicyRequest (V2)

{
  "name": "策略名称",
  "className": "策略类型",
  "config": "策略配置JSON字符串",
  "description": "策略描述(可选)"
}

字段

类型

必填

说明

限制

name

string

策略名称

不能为空

className

string

策略类型

见支持的策略类型列表

config

string

策略配置的JSON字符串

需要根据策略类型提供对应的JSON配置

description

string

策略描述

最大200字符

CreatePolicyAttachmentRequest (V1)

{
  "attachResourceId": "资源ID1",
  "attachResourceType": "资源类型",
  "environmentId": "环境ID",
  "gatewayId": "网关ID",
  "policyId": "策略ID"
}

字段

类型

必填

说明

attachResourceId

string

要绑定的资源ID列表

attachResourceType

string

资源类型:Gateway/Domain/Route/LLMApi/AgentApi/Api/Operation/Service/ServicePort

environmentId

string

视情况

环境ID(Route/Api/Operation/LLMApi/AgentApi时必填)

gatewayId

string

视情况

网关ID(Route/Gateway/Domain/Service/ServicePort/LLMApi/AgentApi时必填)


支持的策略类型

通用流量控制策略

  • RateLimit - 流量限流

  • ConcurrencyLimit - 并发限流

  • CircuitBreaker - 熔断

  • Timeout - 超时控制

  • Retry - 重试策略

路由与转发策略

  • HttpRewrite - HTTP重写

  • HeaderModify - 请求头修改

  • Redirect - 重定向

  • DirectResponse - 直接响应

  • Fallback - 降级策略

  • DynamicRoute - 动态路由(泳道)

AI相关策略

  • AiStatistics - AI统计

  • AiSecurityGuard - AI安全护栏

  • AiFallback - AI降级

  • AiTokenRateLimit - AI Token限流

  • AiCache - AI缓存

  • AiNetworkSearch - AI网络搜索

  • AiToolSelection - AI工具选择

安全认证策略

  • Authentication - 统一认证

  • JWTAuth - JWT认证

  • OIDCAuth - OIDC认证

  • ExternalZAuth - 外部认证

  • Waf - Web应用防火墙

  • IpAccessControl - IP访问控制

跨域与复制策略

  • Cors - 跨域资源共享

  • FlowCopy - 流量复制

服务治理策略

  • ServiceTls - 服务TLS

  • ServiceLb - 服务负载均衡

  • ServicePortTls - 服务端口TLS

通用流量控制策略

RateLimit - 流量限流

适用范围: Route, Gateway, Domain, Service

配置说明:

{
  "threshold": 100,
  "behaviorType": 0,
  "bodyEncoding": 0,
  "responseStatusCode": 429,
  "responseContentBody": "{\"error\":\"Too Many Requests\"}",
  "responseRedirectUrl": "",
  "enable": true
}

字段

类型

必填

说明

threshold

int

限流阈值(每秒请求数)

behaviorType

int

行为类型:0=返回响应, 1=重定向

bodyEncoding

int

响应体编码:0=TEXT, 1=JSON

responseStatusCode

int

响应状态码

responseContentBody

string

响应体内容

responseRedirectUrl

string

重定向URL(behaviorType=1时)

enable

bool

是否启用

调用示例:

curl -X POST http://gateway-api/api/v2/policies \
  -H "Content-Type: application/json" \
  -d '{
    "name": "API限流策略",
    "className": "RateLimit",
    "config": "{\"threshold\":100,\"behaviorType\":0,\"bodyEncoding\":1,\"responseStatusCode\":429,\"responseContentBody\":\"{\\\"error\\\":\\\"请求过于频繁\\\"}\",\"enable\":true}",
    "description": "限制API每秒100次请求"
  }'

ConcurrencyLimit - 并发限流

适用范围: Route, Gateway, Domain

配置说明:

{
  "maxConcurrency": 50,
  "behaviorType": 0,
  "bodyEncoding": 0,
  "responseStatusCode": 503,
  "responseContentBody": "{\"error\":\"Service Overloaded\"}",
  "responseRedirectUrl": "",
  "enable": true
}

字段

类型

必填

说明

maxConcurrency

int

最大并发数

behaviorType

int

行为类型:0=返回响应, 1=重定向

bodyEncoding

int

响应体编码:0=TEXT, 1=JSON

responseStatusCode

int

超限时的响应状态码

responseContentBody

string

超限时的响应体内容

responseRedirectUrl

string

重定向URL(behaviorType=1时)

enable

bool

是否启用

CircuitBreaker - 熔断

适用范围: Route, Service

配置说明:

{
  "strategy": 0,
  "minRequestAmount": 10,
  "maxAllowedMs": 5000,
  "triggerRatio": 50,
  "statDurationSec": 30,
  "recoveryTimeoutSec": 30,
  "responseStatusCode": 503,
  "bodyEncoding": 0,
  "responseContentBody": "{\"error\":\"Service Unavailable\"}",
  "responseRedirectUrl": "",
  "behaviorType": 0,
  "enable": true
}

字段

类型

必填

说明

strategy

int

熔断策略:0=慢调用, 1=异常

minRequestAmount

int

最小请求数阈值

maxAllowedMs

int

最大允许响应时间(毫秒,strategy=0时必填)

triggerRatio

int

触发熔断的比例(百分比)

statDurationSec

int

统计时长(秒)

recoveryTimeoutSec

int

熔断恢复时间(秒)

responseStatusCode

int

熔断时的响应状态码

bodyEncoding

int

响应体编码:0=TEXT, 1=JSON

responseContentBody

string

熔断时的响应体内容

responseRedirectUrl

string

重定向URL(behaviorType=1时)

behaviorType

int

行为类型:0=返回响应, 1=重定向

enable

bool

是否启用

Timeout - 超时控制

适用范围: Route, Service

配置说明:

{
  "unitNum": 30,
  "timeUnit": "s",
  "enable": true
}

字段

类型

必填

说明

unitNum

float64

超时时长数值

timeUnit

string

时间单位:s(秒)/m(分钟)/h(小时)

enable

bool

是否启用

Retry - 重试策略

适用范围: Route, Service

配置说明:

{
  "attempts": 3,
  "retryOn": ["5xx", "reset", "connect-failure"],
  "httpCodes": ["502", "503", "504"],
  "perTryTimeout": 10,
  "enable": true
}

字段

类型

必填

说明

attempts

int

最大重试次数

retryOn

[]string

重试条件:5xx/reset/connect-failure/refused-stream

httpCodes

[]string

触发重试的HTTP状态码列表

perTryTimeout

float64

每次重试的超时时间(秒)

enable

bool

是否启用

HttpRewrite - HTTP重写

适用范围: Route

配置说明:

{
  "pathType": "Exact",
  "path": "/v2/api",
  "pattern": "",
  "substitution": "",
  "host": "new-backend.example.com",
  "enable": true
}

字段

类型

必填

说明

pathType

string

路径匹配类型:Exact/Prefix/Regex

path

string

重写后的路径(pathType=Exact/Prefix时使用)

pattern

string

正则表达式模式(pathType=Regex时必填)

substitution

string

替换字符串(pathType=Regex时必填)

host

string

重写后的Host

enable

bool

是否启用

HeaderModify - 请求头修改

适用范围: Route, Gateway, Domain

配置说明:

{
  "enable": true,
  "headerOpItems": [
    {
      "directionType": "Request",
      "opType": "Add",
      "key": "X-Custom-Header",
      "value": "custom-value",
      "policyValueGenerateMode": "Custom"
    },
    {
      "directionType": "Request",
      "opType": "Update",
      "key": "Authorization",
      "value": "Bearer {{token}}",
      "policyValueGenerateMode": "Custom"
    },
    {
      "directionType": "Request",
      "opType": "Remove",
      "key": "X-Debug-Mode",
      "value": "",
      "policyValueGenerateMode": "Custom"
    }
  ]
}

字段

类型

必填

说明

enable

bool

是否启用

headerOpItems

[]object

请求头操作项列表

├─ directionType

string

方向类型:Request(请求)/Response(响应)

├─ opType

string

操作类型:Add(添加)/Update(更新)/Remove(删除)

├─ key

string

请求头键名

├─ value

string

请求头值(opType=Remove时可为空)

└─ policyValueGenerateMode

string

值生成模式:Custom(自定义)/Reference(引用)

Redirect - 重定向

适用范围: Route

配置说明:

{
  "code": "301",
  "host": "new-domain.com",
  "path": "/new-path",
  "enable": true
}

字段

类型

必填

说明

code

string

重定向状态码:301/302/303/307/308

host

string

重定向目标Host

path

string

重定向目标路径

enable

bool

是否启用

DirectResponse - 直接响应

适用范围: Route

配置说明:

{
  "code": "200",
  "body": "{\"status\":\"ok\",\"message\":\"Service Maintenance\"}",
  "enable": true
}

字段

类型

必填

说明

code

string

响应状态码

body

string

响应体内容

enable

bool

是否启用

Fallback - 降级策略

适用范围: Route, Service

配置说明:

{
  "enable": true,
  "fallBackDestination": [
    {
      "serviceId": "backup-service-1",
      "serviceName": "backup-service-name",
      "serviceVersion": "v1",
      "port": "8080"
    }
  ]
}

字段

类型

必填

说明

enable

bool

是否启用

fallBackDestination

[]object

降级目标列表

├─ serviceId

string

降级服务ID

├─ serviceName

string

降级服务名称

├─ serviceVersion

string

服务版本

└─ port

string

服务端口

IpAccessControl - IP访问控制

适用范围: Route, Gateway, Domain

配置说明:

{
  "name": "IP白名单策略",
  "description": "允许特定IP访问",
  "ipAccessControlResourceName": "api-route-1",
  "ipAccessControlResourceType": "Route",
  "ipAccessControlType": "White",
  "ipAccessControlContent": "192.168.1.0/24,10.0.0.1",
  "protocolLayer": "L7",
  "enable": true
}

字段

类型

必填

说明

name

string

策略名称

description

string

策略描述

ipAccessControlResourceName

string

资源名称

ipAccessControlResourceType

string

资源类型:Route/Gateway/Domain

ipAccessControlType

string

控制类型:White(白名单)/Black(黑名单)

ipAccessControlContent

string

IP列表(逗号分隔,支持CIDR)

protocolLayer

string

协议层:L7(应用层)/L4(传输层)

enable

bool

是否启用

Cors - 跨域资源共享

适用范围: Route, Gateway, Domain

配置说明:

{
  "allowOrigins": "https://example.com,https://app.example.com",
  "allowMethods": ["GET", "POST", "PUT", "DELETE"],
  "allowHeaders": "Content-Type,Authorization",
  "exposeHeaders": "X-Custom-Header",
  "timeUnit": "s",
  "unitNum": 3600,
  "allowCredentials": true,
  "enable": true
}

字段

类型

必填

说明

allowOrigins

string

允许的源(逗号分隔,使用*表示所有)

allowMethods

[]string

允许的HTTP方法

allowHeaders

string

允许的请求头(逗号分隔)

exposeHeaders

string

暴露的响应头(逗号分隔)

timeUnit

string

时间单位:s(秒)/m(分钟)/h(小时)

unitNum

int

预检请求缓存时长

allowCredentials

bool

是否允许携带凭证

enable

bool

是否启用

FlowCopy - 流量复制

适用范围: Route

配置说明:

{
  "targetServiceId": "test-service-id",
  "targetServiceName": "test-service",
  "port": "8080",
  "percentage": 10,
  "enable": true
}

字段

类型

必填

说明

targetServiceId

string

目标服务ID

targetServiceName

string

目标服务名称

port

string

目标服务端口

percentage

int

复制流量的百分比(1-100,默认100)

enable

bool

是否启用

DynamicRoute - 动态路由(泳道)

适用范围: Gateway

配置说明:

{
  "enable": true,
  "dynamicRouteSwimmingLaneConfigs": [
    {
      "swimmingLaneGroupId": 1001,
      "swimmingLaneId": 2001,
      "canaryModel": 0,
      "percentage": 20,
      "swimmingLaneTag": "lane-v2",
      "predicates": [
        {
          "type": "Header",
          "name": "x-env",
          "condition": "==",
          "value": "test"
        }
      ],
      "matchCondition": "And",
      "enable": true
    }
  ]
}

字段

类型

必填

说明

enable

bool

是否启用

dynamicRouteSwimmingLaneConfigs

[]object

泳道配置列表

├─ swimmingLaneGroupId

int64

泳道组ID

├─ swimmingLaneId

int64

泳道ID

├─ canaryModel

int

灰度模式:0=按内容, 1=按比例

├─ percentage

int

流量百分比(按比例模式时)

├─ swimmingLaneTag

string

泳道标签

├─ predicates

[]object

匹配条件(按内容模式时)

│ ├─ type

string

参数类型:Header/Cookie/Parameter

│ ├─ name

string

参数名

│ ├─ condition

string

条件:==/!=/Pre/Regex/List/%

│ ├─ value

string

匹配值

│ └─ names

[]string

列表值(condition=List时)

├─ matchCondition

string

匹配关系:And/Or

└─ enable

bool

是否启用该泳道

AI相关策略

AiStatistics - AI统计

适用范围: Route, LLMApi, AgentApi

配置说明:

{
  "enable": true,
  "aiStatisticsConfig": {
    "logRequestContent": true,
    "logResponseContent": true
  }
}

字段

类型

必填

说明

enable

bool

是否启用

aiStatisticsConfig

object

AI统计配置

├─ logRequestContent

bool

是否记录请求内容(默认true)

└─ logResponseContent

bool

是否记录响应内容(默认true)

AiSecurityGuard - AI安全护栏

适用范围: Service

配置说明:

{
  "enable": true,
  "serviceAddress": "http://security-guard-service:8080",
  "checkRequest": true,
  "checkResponse": true,
  "riskAlertLevel": "medium",
  "requestCheckService": "Security",
  "responseCheckService": "Security",
  "bufferLimit": 1000,
  "riskConfig": [
    {
      "type": "Global",
      "level": "high"
    },
    {
      "type": "ContentModeration",
      "level": "medium"
    }
  ]
}

字段

类型

必填

说明

enable

bool

是否启用

serviceAddress

string

安全服务地址

checkRequest

bool

是否检查请求

checkResponse

bool

是否检查响应

riskAlertLevel

string

风险等级:low/medium/high/max

requestCheckService

string

请求检查服务:LLM/Security

responseCheckService

string

响应检查服务:LLM/Security

bufferLimit

int

缓冲区限制(默认1000)

riskConfig

[]object

风险配置列表

├─ type

string

风险类型:Global/ContentModeration/PromptAttack/SensitiveData/MaliciousUrl/ModelHallucination

└─ level

string

风险等级:low/medium/high/max

AiTokenRateLimit - AI Token限流

适用范围: Route, LLMApi, AgentApi

配置说明:

{
  "enable": true,
  "rules": [
    {
      "limitType": "LimitByConsumer",
      "threshold": 10000,
      "timeWindow": 60,
      "responseStatusCode": 429,
      "responseContentBody": "{\"error\":\"Token limit exceeded\"}"
    }
  ],
  "enableGlobalRules": true,
  "globalRules": [
    {
      "limitType": "LimitByGlobal",
      "threshold": 100000,
      "timeWindow": 60
    }
  ],
  "redisConfig": {
    "serviceHost": "redis-service:6379",
    "servicePort": 6379,
    "database": 0,
    "username": "",
    "password": ""
  }
}

字段

类型

必填

说明

enable

bool

是否启用

rules

[]object

普通限流规则列表

├─ limitType

string

限流类型:LimitByConsumer/LimitByModel

├─ threshold

int

Token阈值

├─ timeWindow

int

时间窗口(秒)

├─ responseStatusCode

int

超限时响应状态码

└─ responseContentBody

string

超限时响应体内容

enableGlobalRules

bool

是否启用全局限流规则

globalRules

[]object

全局限流规则列表

├─ limitType

string

限流类型(必须为LimitByGlobal)

├─ threshold

int

Token阈值

└─ timeWindow

int

时间窗口(秒)

redisConfig

object

Redis配置

├─ serviceHost

string

Redis服务地址

├─ servicePort

int

Redis端口

├─ database

int

数据库编号(默认0)

├─ username

string

用户名

└─ password

string

密码

AiCache - AI缓存

适用范围: Route, LLMApi, AgentApi

配置说明:

{
  "enable": true,
  "cacheTTL": 3600,
  "cacheMode": "exact",
  "cacheKeyStrategy": "messages",
  "redisConfig": {
    "serviceHost": "redis-service:6379",
    "servicePort": 6379,
    "database": 0
  }
}

字段

类型

必填

说明

enable

bool

是否启用

cacheTTL

int

缓存过期时间(秒)

cacheMode

string

缓存模式:exact(精确)/semantic(语义)

cacheKeyStrategy

string

缓存键策略

redisConfig

object

Redis配置

├─ serviceHost

string

Redis服务地址

├─ servicePort

int

Redis端口

├─ database

int

数据库编号(默认0)

├─ username

string

用户名

└─ password

string

密码

vectorConfig

object

向量数据库配置(semantic模式时)

├─ type

string

向量库类型:adb-postgres

├─ serviceHost

string

向量库服务地址

├─ apiKey

string

API密钥

├─ timeout

int

超时时间(毫秒)

├─ collectionId

string

集合ID

└─ threshold

float

相似度阈值(0-1)

embeddingConfig

object

Embedding配置(semantic模式时)

├─ type

string

Embedding类型:dashscope/azure

└─ serviceId

string

Embedding服务ID

AiFallback - AI降级

适用范围: Service

配置说明:

{
  "enable": true,
  "fallbackModelMappings": [
    {
      "model": "gpt-4",
      "fallbackModels": [
        {
          "serviceId": "backup-service-1",
          "model": "gpt-3.5-turbo"
        }
      ]
    }
  ]
}

字段

类型

必填

说明

enable

bool

是否启用

fallbackModelMappings

[]object

降级模型映射列表

├─ model

string

原始模型名称

└─ fallbackModels

[]object

降级模型列表

├─ serviceId

string

降级服务ID

└─ model

string

降级模型名称

AiNetworkSearch - AI网络搜索

适用范围: Route, LLMApi, AgentApi

配置说明:

{
  "enable": true,
  "provider": "bing",
  "apiKey": "your-search-api-key",
  "maxResults": 10,
  "timeout": 5000
}

字段

类型

必填

说明

enable

bool

是否启用

provider

string

搜索提供商

apiKey

string

搜索API密钥

maxResults

int

最大返回结果数

timeout

int

超时时间(毫秒)

AiToolSelection - AI工具选择

适用范围: Route, LLMApi, AgentApi

配置说明:

{
  "enable": true,
  "tools": [
    {
      "name": "calculator",
      "description": "用于数学计算",
      "enabled": true
    }
  ]
}

字段

类型

必填

说明

enable

bool

是否启用

tools

[]object

工具列表

├─ name

string

工具名称

├─ description

string

工具描述

└─ enabled

bool

是否启用该工具

安全认证策略

Authentication - 统一认证

适用范围: Route, Gateway, Domain

配置说明:

{
  "authenticationType": "key-auth",
  "enable": true
}

字段

类型

必填

说明

authenticationType

string

认证类型:key-auth/basic-auth/jwt-auth

enable

bool

是否启用

JWTAuth - JWT认证

适用范围: Route, Gateway, Domain

配置说明:

{
  "name": "jwt-policy",
  "issuer": "https://auth.example.com",
  "sub": "",
  "jwks": "https://auth.example.com/.well-known/jwks.json",
  "tokenPosition": "header",
  "tokenName": "Authorization",
  "tokenNamePrefix": "Bearer ",
  "tokenPass": true,
  "whiteOrBlack": "",
  "authResources": [],
  "resources": "",
  "enable": true
}

字段

类型

必填

说明

name

string

策略名称

issuer

string

JWT签发者

sub

string

Subject

jwks

string

JWKS URI地址

tokenPosition

string

Token位置:header/query/cookie

tokenName

string

Token字段名

tokenNamePrefix

string

Token前缀(如"Bearer ")

tokenPass

bool

是否透传Token

whiteOrBlack

string

白名单或黑名单模式

authResources

[]object

鉴权资源列表

resources

string

资源配置

enable

bool

是否启用

OIDCAuth - OIDC认证

适用范围: Route, Gateway, Domain

配置说明:

{
  "issuer": "https://accounts.google.com",
  "clientId": "your-client-id",
  "clientSecret": "your-client-secret",
  "redirectUri": "https://your-app.com/callback",
  "scopes": ["openid", "profile", "email"],
  "enable": true
}

字段

类型

必填

说明

issuer

string

OIDC提供者URL

clientId

string

客户端ID

clientSecret

string

客户端密钥

redirectUri

string

重定向URI

scopes

[]string

请求的权限范围

enable

bool

是否启用

ExternalZAuth - 外部认证

适用范围: Route, Gateway, Domain

配置说明:

{
  "authServiceUrl": "https://auth-service.example.com/verify",
  "timeout": 5000,
  "enable": true
}

字段

类型

必填

说明

authServiceUrl

string

外部认证服务URL

timeout

int

超时时间(毫秒)

enable

bool

是否启用

Waf - Web应用防火墙

适用范围: Route, Gateway, Domain

配置说明:

{
  "enable": true
}

字段

类型

必填

说明

enable

bool

是否启用

服务治理策略

ServiceLb - 服务负载均衡

适用范围: Service

配置说明:

{
  "loadBalancerType": "ROUND_ROBIN",
  "consistentHashLBConfig": {
    "parameterName": "user-id",
    "httpCookie": {
      "name": "session-id",
      "path": "/",
      "ttl": "3600s"
    },
    "minimumRingSize": 1024,
    "consistentHashLBType": "HEADER"
  },
  "warmupDuration": 60,
  "enable": true
}

字段

类型

必填

说明

loadBalancerType

string

负载均衡类型:ROUND_ROBIN/LEAST_CONN/RANDOM/CONSISTENT_HASH

consistentHashLBConfig

object

一致性哈希配置(loadBalancerType=CONSISTENT_HASH时)

├─ parameterName

string

参数名称

├─ httpCookie

object

Cookie配置

│ ├─ name

string

Cookie名称

│ ├─ path

string

Cookie路径

│ └─ ttl

string

Cookie过期时间

├─ minimumRingSize

int

最小环大小

└─ consistentHashLBType

string

哈希类型:HEADER/COOKIE/SOURCE_IP/QUERY_PARAMETER

warmupDuration

int

预热时长(秒)

enable

bool

是否启用

ServiceTls - 服务TLS

适用范围: Service

配置说明:

{
  "mode": "SIMPLE",
  "certId": "cert-id-123",
  "caCertId": "ca-cert-id-456",
  "caCertContent": "-----BEGIN CERTIFICATE-----\n...\n-----END CERTIFICATE-----",
  "subjectAltNames": ["*.example.com"],
  "sni": "backend-service.example.com",
  "enable": true
}

字段

类型

必填

说明

mode

string

TLS模式:DISABLE/SIMPLE/MUTUAL/ISTIO_MUTUAL

certId

string

证书ID

caCertId

string

CA证书ID

caCertContent

string

CA证书内容(PEM格式)

subjectAltNames

[]string

Subject Alternative Names

sni

string

SNI主机名

enable

bool

是否启用

ServicePortTls - 服务端口TLS

适用范围: ServicePort

配置说明: 与ServiceTls相同

错误示例与最佳实践

错误示例1:config字段格式错误

{
  "name": "限流策略",
  "className": "RateLimit",
  "config": {"threshold": 100}  //  错误:config应该是JSON字符串
}

正确写法

{
  "name": "限流策略",
  "className": "RateLimit",
  "config": "{\"threshold\":100,\"behaviorType\":0,\"bodyEncoding\":0,\"responseStatusCode\":429,\"enable\":true}"
}

错误示例2:遗漏enable字段

{
  "name": "限流策略",
  "className": "RateLimit",
  "config": "{\"threshold\":100,\"behaviorType\":0,\"bodyEncoding\":0,\"responseStatusCode\":429}"  // 缺少enable字段
}

正确写法

{
  "name": "限流策略",
  "className": "RateLimit",
  "config": "{\"threshold\":100,\"behaviorType\":0,\"bodyEncoding\":0,\"responseStatusCode\":429,\"enable\":true}"
}

响应格式

成功响应

{
  "policyId": "policy-abc123"
}

错误响应

{
  "errorCode": "ErrInvalidParameter",
  "errorMessage": "Invalid parameter: className",
  "requestId": "req-xxx"
}