微服务 - Kong Http Api 实现负载均衡、jwt认证、限流、黑白名单

2023-05-02 13:20:04

建立/激活链接

使用Kong的第一步是激活链接,登录Kong管理后台,找到 Connections,把Kong的Api链接上,因为我本地的端口进行了映射,所以需要找到Docker的network 上的ip,进行绑定, ip 地址 172.19.0.3


(资料图)

docker network inspect gateway_net
"dcb524ba2b30e16e6453b9159ceb4edb642c42ea84dd00ee4ce1cd158737a118": {    "Name": "kong-ee",    "EndpointID": "4bcabe9c26cb082ba55f95ff9257b5cc3ff57d6f80059ac76501c7bd7eeba09f",    "MacAddress": "02:42:ac:13:00:03",    "IPv4Address": "172.19.0.3/16",    "IPv6Address": ""},

配置负载均衡

上图是Kong实现负载均衡的流程图,Kong的使用非常简单,使用 Http Api的方式添加:

1.添加upstreams

POST http://127.0.0.1:9001/upstreams{    "name":"audio-upstream"}

2.添加Target

POST http://127.0.0.1:9001/upstreams/audio-upstream/targets{    "target":"127.0.0.1:9502",    "weight":100}

192.168.251.2

3.配置Service

POST http://127.0.0.1:9001/services{    "name":"audio-service",    "host":"audio-upstream"}

4.配置Route

配置Route的时候,paths参数必须以/开头

POST http://127.0.0.1:9001/services/audio-service/routes{    "name":"audio-service-route",    "paths[]":"/audio"}

认证

1.Basic认证

用户名密码的认证方式,在Konga的Consumers添加就可以了

POST http://127.0.0.1:9001/routes/audio-service-route/plugins{    "name":"basic-auth",    "config.hide_credentials":"true"}

2.jwt认证

1.添加jwt认证操作组件操作

POST http://127.0.0.1:9001/services/audio-service/plugins{    "name":"jwt"}

2.设置jwt加密方式,参数说明:

algorithm : 加密方式key :Consumers里面设置的keysecret:自定义32位的加密串
POST http://127.0.0.1:9001/consumers/test/jwt{    "algorithm":"HS256",    "key":"test",    "secret":"UmVZkyvSPOiGgVW2B1g1uhkM0tSPl5o3"}

限流

相较于权限验证,Kong的限流就比较简单了许多,Kong采用计数器的形式进行限流。

config.minute :没分5次config.limit_by:根据ip限流
POST http://127.0.0.1:9001/services/audio-service/plugins{    "name":"rate-limiting",    "config.minute":5,     "config.limit_by":"ip"}

黑/白名单

Kong的黑/白名单功能是根据限制ip实现的。

POST http://127.0.0.1:9001/services/audio-service/plugins{    "name":"ip-restriction",    "config.deny":"127.0.0.1"}

标签:

关闭
新闻速递