soul入门 第十二章 插件divide原理
-
作用:divide插件用来处理http协议请求转发。
-
跑起来
先来启动起来再说。首先启动admin,启动网关(端口9195),启动第一个http服务端口(8188),启动第二个端口为(8288)。如果不通过网关访问http服务,以第一个服务为例,路径说这样 http://192.168.1.3:8188/test/findByUserId?userId=1。如果通过网关访问则是这样 http://localhost:9195/http/test/findByUserId?userId=1,http是服务的请求前缀,连续请求三次,看网关日志,如下:
The request urlPath is http://192.168.1.3:8188/test/findByUserId?userId=1, retryTimes is 0 The request urlPath is http://192.168.1.3:8288/test/findByUserId?userId=1, retryTimes is 0 The request urlPath is http://192.168.1.3:8188/test/findByUserId?userId=1, retryTimes is 0
由日志看出,轮流调用两个服务。
-
原理
由上面跑出来的结果,可以确定插件必须实现的功能:
1、网关接受到请求,提取前缀(http),匹配到相应插件(divide),交给它处理, 这一步是网关来实现。
2、转发
divide根据请求路径构造真实路径,比如通过http://localhost:9195/http/test/findByUserId?userId=1 转换成 http://192.168.1.3:8288/test/findByUserId?userId=1,这里关键要找到192.168.1.3:8288(这地址由admin同步过来),然后带上参数去请求真实的服务。
3、负载均衡
当有多个服务注册到网关时,需要根据指定的负载均衡算法找到目标服务的地址
4、服务探活
一个功能完备的一定要能及时感知下游服务是否还活,网关是通过启动线程定时去检测,调用socket的connet方法,当出异常时把该服务从可服务列表剔除。