title: Plugin Config keywords:
在很多情况下,我们在不同的路由中会使用相同的插件规则,此时就可以通过 Plugin Config 来设置这些规则。Plugin Config 属于一组通用插件配置的抽象。
plugins
的配置可以通过 Admin API /apisix/admin/plugin_configs
进行单独配置,在路由中使用 plugin_config_id
与之进行关联。
对于同一个插件的配置,只能有一个是有效的,优先级为 Consumer > Route > Plugin Config > Service。
你可以参考如下步骤将 Plugin Config 绑定在路由上。
:::note
您可以这样从 config.yaml
中获取 admin_key
并存入环境变量:
admin_key=$(yq '.deployment.admin.admin_key[0].key' conf/config.yaml | sed 's/"//g')
:::
创建 Plugin config。
curl http://127.0.0.1:9180/apisix/admin/plugin_configs/1 \ -H "X-API-KEY: $admin_key" -X PUT -i -d ' { "desc": "enable limit-count plugin", "plugins": { "limit-count": { "count": 2, "time_window": 60, "rejected_code": 503 } } }'
创建路由并绑定 Plugin Config 1
。
curl http://127.0.0.1:9180/apisix/admin/routes/1 \ -H "X-API-KEY: $admin_key" -X PUT -i -d ' { "uris": ["/index.html"], "plugin_config_id": 1, "upstream": { "type": "roundrobin", "nodes": { "127.0.0.1:1980": 1 } } }'
如果找不到对应的 Plugin Config,该路由上的请求会报 503
错误。
如果路由中已经配置了 plugins
,那么 Plugin Config 里面的插件配置将会与 plugins
合并。
相同的插件不会覆盖掉 plugins
原有的插件配置。详细信息,请参考 Plugin。
假设你创建了一个 Plugin Config。
curl http://127.0.0.1:9180/apisix/admin/plugin_configs/1 \ -H "X-API-KEY: $admin_key" -X PUT -i -d ' { "desc": "enable ip-restruction and limit-count plugin", "plugins": { "ip-restriction": { "whitelist": [ "127.0.0.0/24", "113.74.26.106" ] }, "limit-count": { "count": 2, "time_window": 60, "rejected_code": 503 } } }'
并在路由中引入 Plugin Config。
curl http://127.0.0.1:9180/apisix/admin/routes/1 \ -H "X-API-KEY: $admin_key" -X PUT -i -d ' { "uris": ["/index.html"], "plugin_config_id": 1, "upstream": { "type": "roundrobin", "nodes": { "127.0.0.1:1980": 1 } } "plugins": { "proxy-rewrite": { "uri": "/test/add", "host": "apisix.iresty.com" }, "limit-count": { "count": 20, "time_window": 60, "rejected_code": 503, "key": "remote_addr" } } }'
最后实现的效果如下。
curl http://127.0.0.1:9180/apisix/admin/routes/1 \ -H "X-API-KEY: $admin_key" -X PUT -i -d ' { "uris": ["/index.html"], "upstream": { "type": "roundrobin", "nodes": { "127.0.0.1:1980": 1 } } "plugins": { "ip-restriction": { "whitelist": [ "127.0.0.0/24", "113.74.26.106" ] }, "proxy-rewrite": { "uri": "/test/add", "host": "apisix.iresty.com" }, "limit-count": { "count": 20, "time_window": 60, "rejected_code": 503, "key": "remote_addr" } } }'