apisix实现四层转发

背景

来水一篇文章,其实官网都有,论如何在apisix上实现四层转发

什么是apisix

apisix是动态、实时、高性能的 API 网关,构建于 OpenResty 之上,支持热加载配置、灰度发布、蓝绿部署等功能,同时具有良好的可扩展性和易用性。

管理接口参考

参考:(以2.4版本为例)
https://625a57e513f19e48ae3a4468--old-docs-apache-apisix.netlify.app/zh/docs/apisix/2.4/admin-api/#route

基于tcp协议动态代理

参考:(以2.4版本为例)
https://625a57e513f19e48ae3a4468--old-docs-apache-apisix.netlify.app/zh/docs/apisix/2.4/stream-proxy/

步骤1:激活stream_routes模块

在 conf/config.yaml 配置文件设置 stream_proxy 选项,默认是开启的

apisix:
  stream_proxy:                 # TCP/UDP proxy
    tcp:                        # TCP proxy address list
      - 9100

重启服务,使其配置生效
验证模块是否生效:

curl http://xxx.xxx.xxx.xxx:xxx/apisix/admin/stream_routes -H 'X-API-KEY: edd1c9f034335f136f87ad84b625c8f1'

步骤2:添加配置

例如:
配置多节点代理,启动本机的1302端口,tcp协议,代理"172.16.10.251:1301","172.16.10.252:1301"
(请求打到本机的1302端口,轮询策略roundrobin,转发到后端的两个节点的1301端口上)
配置如下:

curl 'http://xxx.xxx.xxx.xxx:xxx/apisix/admin/stream_routes/1' \
  -H 'X-API-KEY: edd1c9f034335f136f87ad84b625c8f1' \
  -H 'Content-Type: application/json;charset=UTF-8' \
  -X PUT \
  -d '{"server_port":1302,"upstream":{"nodes":{"172.16.10.251:1301":1,"172.16.10.252:1301":1},"type":"roundrobin"},"plugins":{},"desc":"tcp1301"}' \
  --compressed \
  --insecure

响应报文:

{"node":{"createdIndex":121,"value":{"desc":"tcp1301","upstream":{"type":"roundrobin","hash_on":"vars","nodes":{"172.16.10.251:1301":1,"172.16.10.252:1301":1}},"server_port":1302,"id":"1","plugins":{}},"modifiedIndex":121,"key":"\/apisix\/stream_routes\/1"},"action":"set"}

查看配置:

curl 'http://xxx.xxx.xxx.xxx:xxx/apisix/admin/stream_routes/1' -H 'X-API-KEY: edd1c9f034335f136f87ad84b625c8f1'

响应报文:

{"node":{"createdIndex":121,"value":{"desc":"tcp1301","upstream":{"type":"roundrobin","hash_on":"vars","nodes":{"172.16.10.251:1301":1,"172.16.10.252:1301":1}},"server_port":1302,"id":"1","plugins":{}},"modifiedIndex":121,"key":"\/apisix\/stream_routes\/1"},"action":"get"}

如果添加错了,删除配置:

curl 'http://xxx.xxx.xxx.xxx:xxx/apisix/admin/stream_routes/1' -H 'X-API-KEY: edd1c9f034335f136f87ad84b625c8f1' -X DELETE

备注

1.修改(和创建一样,指定id=1,PUT正确的报文就行)
2.还有一种创建可以用POST,不指定id,随机生产id。

总结

Restful API 大法好啊

posted @ 2024-09-27 18:01  海yo  阅读(66)  评论(0编辑  收藏  举报