apisix~ApisixPluginConfig的使用(yong)
1. ApisixPluginConfig 的作用
- 插件配置復用:將插件配置定義為獨立的資源,供多個路由或服務引用。
- 解耦插件與路由:修改插件配置時,只需更新
ApisixPluginConfig,無需逐個修改路由。 - 支持復雜配置:避免在
Ingress的 Annotations 中編寫冗長的 JSON。 - plugin_config_id: 通過這種方式添加的插件,將不會在apisix dashboard上顯示,這塊需要注意,但插件本身是生效的。
2. 使用步驟
(1) 創建 ApisixPluginConfig 資源
定義插件的具體配置(例如限流插件 limit-count):
apiVersion: apisix.apache.org/v2
kind: ApisixPluginConfig
metadata:
name: limit-config
spec:
plugins:
- name: limit-count
enable: true
config:
_meta:
disable: false #注意這行是必須的,否則在dashboard的路由>高級特性>插件模板配置中會出現白屏的情況
count: 100
time_window: 60
key: remote_addr
policy: local
(2) 在 ApisixRoute 或 Ingress 中引用
通過 plugin_config_name 字段關聯到路由:
方式一:在 ApisixRoute 中引用
apiVersion: apisix.apache.org/v2
kind: ApisixRoute
metadata:
name: my-route
spec:
http:
- name: rule1
match:
hosts: ["example.com"]
paths: ["/*"]
backends:
- serviceName: my-service
servicePort: 80
# 引用插件配置
plugin_config_name: limit-config
注意:如果(guo)apisix-ingress中使(shi)用了(le)(le)自已(yi)的域(yu)名,那網(wang)關(guan)的域(yu)名就失效了(le)(le),這塊需(xu)要注意一下
方式二:在 Ingress 中通過注解引用
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: my-ingress
annotations:
k8s.apisix.apache.org/plugin-config-name: "limit-config" # 指定插件配置名稱
spec:
ingressClassName: apisix
rules:
- host: example.com
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: my-service
port:
number: 80
3. 驗證配置
(1) 檢查 ApisixPluginConfig 狀態
kubectl get apisixpluginconfig limit-config -o yaml

如(ru)果是阿里云容器平臺(tai)上,它(ta)會在自(zi)定義資源里出現

apisix-dashboard的路(lu)由(you)》高級特性》插件模板會(hui)展示你的插件配置(zhi)

(2) 查看 APISIX 路由詳情
通過 Admin API 檢(jian)查路由是否關聯(lian)了插件:
curl //<APISIX_ADMIN_IP>:9180/apisix/admin/routes -H 'X-API-KEY: <ADMIN_KEY>'
預期輸出中應包含 limit-count 插件的配置。
4. 優勢對比
| 方式 | 維護成本 | 復用性 | 靈活性 | 適用場景 |
|---|---|---|---|---|
ApisixPluginConfig |
低 | 高 | 高 | 多個路由共享同一插件 |
Ingress Annotations |
高 | 低 | 中 | 簡單插件、單路由配置 |
5. 注意事項
- 作用域限制:
- 默認情況下,
ApisixPluginConfig是命名空間級別的資源,需確保路由和插件配置在同一命名空間。若需跨命名空間引用,需配置 APISIX Ingress Controller 的scope參數為cluster。
- 默認情況下,
- 版本兼容性:
- 確保 APISIX Ingress Controller 版本支持
ApisixPluginConfig(v2.7+ 推薦使用)。
- 確保 APISIX Ingress Controller 版本支持
- 配置沖突:
- 如果同時在
ApisixRoute和ApisixPluginConfig中定義了同名插件,ApisixRoute中的配置會覆蓋ApisixPluginConfig。
- 如果同時在
6. 高級用法:組合多個插件
可以在一個 ApisixPluginConfig 中定義多個插件:
apiVersion: apisix.apache.org/v2
kind: ApisixPluginConfig
metadata:
name: global-plugins
spec:
plugins:
- name: limit-count
enable: true
config:
_meta:
disable: false
count: 200
time_window: 60
- name: cors
enable: true
config:
_meta:
disable: false
allow_origins: "*"
allow_methods: "GET,POST"
總結
通過 ApisixPluginConfig 可以實現插件的集中管理和復用,特別適合以下場景:
- 多個路由需要相同插件配置(如全局限流、鑒權)。
- 插件配置復雜,需避免在
Ingress中維護冗長的 JSON。 - 需要動態更新插件配置而不影響路由定義。
如果此前通過 Ingress Annotations 管理插件,可以逐步遷移到 ApisixPluginConfig,提升配置的可維(wei)護(hu)性。