一、问题描述
在上一篇《由浅入深了解Thrift之服务模型和序列化机制》文章中,我们已经了解了thrift的基本架构和网络服务模型的优缺点。如今的互联网圈中,RPC服务化的思想如火如荼。我们又该如何将thrift服务化应用到我们的项目中哪?实现thrift服务化前,我们先想想这几个问题:服务注册、服务发现、服务健康检测、服务“Load Balance”、隐藏client和server端的交互细节、服务调用端的对象池化。
服务的注册、发现和健康检测,我们使用zookeeper可以很好的解决
服务“Load Balance",我们可以使用简单的算法“权重+随机”,当然也可以使用成熟复杂的算法
服务调用端的对象池化,我们可以使用common pool,使用简单又可以满足我们的需求
二、实现思路
1、thrift server端启动时,每个实例向zk集群以临时节点方式注册(这样,遍历zk上/server下有多少个临时节点就知道有哪些server实例)
thrift server端可以单机多端口多实例或多机部署多实例方式运行。
2、服务调用方实现一个连接池,连接池初始化时,通过zk将在线的server实例信息同步到本地并缓存,同时监听zk下的节点变化。
3、服务调用方与Server通讯时,从连接池中取一个可用的连接,用它实现RPC调用。
三、具体实现
1、thrift server端
thrift server端,向zk中注册server address
packagecom.wy.thriftpool.commzkpool;importjava.lang.instrument.IllegalClassFormatException;importjava.lang.reflect.Constructor;importorg.apache.thrift.protocol.TBinaryProtocol;importorg.apache.thrift.protocol.TBinaryProtocol.Factory;importorg.apache.thrift.server.TServer;importorg.apache.thrift.server.TThreadedSelectorServer;importorg.apache.thrift.transport.TFramedTransport;importorg.apache.thrift.transport.TNonblockingServerSocket;importorg.springframework.beans.factory.InitializingBean;importcom.wy.thrift.service.UserService.Processor;importcom.wy.thriftpool.commzkpool.support.ThriftServerAddressReporter;importcom.wy.thriftpool.commzkpool.support.ThriftServerIpTransfer;importcom.wy.thriftpool.commzkpool.support.impl.LocalNetworkIpTransfer;/*** thrift server端,向zk中注册server address
*
*@authorwy
**/
public class ThriftServiceServerFactory implementsInitializingBean {//thrift server 服务端口
privateInteger port;//default 权重
private Integer priority = 1;//service实现类
privateObject service;//thrift server 注册路径
privateString configPath;privateThriftServerIpTransfer ipTransfer;//thrift server注册类
privateThriftServerAddressReporter addressReporter;//thrift