Gaea源码阅读(二):客户端流程
转载地址:http://blog.csdn.net/m_vptr/article/details/9147279
以GaeaClientTest为入口
- GaeaInit.init("conf/gaea.config");
- /**
- * 调用URL 格式:tcp://服务名//接口实现类
- * 备注:
- * 服务名:需要与gaea.config中的服务名一一对应
- * 接口实现类:具体调用接口的接口实现类
- */
- final String url = "tcp://demo/NewsService";
- INewsService newsService = ProxyFactory.create(INewsService.class, url);
- List<News> list = newsService.getNewsByCateID();
- for (News news : list) {
- System.out.println("ID is " + news.getNewsID() + " title is "
- + news.getTitle());
- }
如注释所言,客户端通过Restfull格式url"tcp://serviceName/lookup "访问服务。
关键的一句:INewsService newsService = ProxyFactory. create (INewsService. class ,url); ,这句话创建了一个实现了INewsService接口的代理,返回的这个代理对象将作为getNewsByCateID的调用句柄。
让我们看看代理的内部如何实现的,跟踪ProxyFactory.create
- InvocationHandler handler = new ProxyStandard(type,serviceName, lookup);
- return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
- newClass[]{type},
- handler);
- //代理的作用就是将所有调用转交到Handler
InvocationHandler接口实现类ProxyStandard
- public ProxyStandard(Class<?> interfaceClass, String serviceName, String lookup){
- this.interfaceClass =interfaceClass;
- this.methodCaller = newMethodCaller(serviceName, lookup);
InvocationHandler主要由methodCaller完成功能,在invoke()中交给methodCaller
Object obj= methodCaller.doMethodCall(args, method);
MethodCaller机制 //doMethodCall
- //准备参数
- Type[]typeAry = methodInfo.getGenericParameterTypes();
- Class<?>[] clsAry = methodInfo.getParameterTypes();
- if (args== null) {
- args = newObject[0];
- }
- Parameter[]paras = new Parameter[args.length];
- List<Integer> outParas = newArrayList<Integer>();
- if(typeAry != null) {
- for (int i = 0;i < typeAry.length; i++) {
- if(args[i] instanceof Out) {
- paras[i] = newParameter(args[i], clsAry[i], typeAry[i], ParaType.Out);
- outParas.add(i);
- } else {
- paras[i] = newParameter(args[i], clsAry[i], typeAry[i], ParaType.In);
- }
- }
- }
- //规范化方法名
- StringmethodName = methodInfo.getName();
- OperationContract ann =methodInfo.getAnnotation(OperationContract.class);
- if (ann !=null) {
- if(!ann.methodName().equals(AnnotationUtil.DEFAULT_VALUE)) {
- methodName = "$" + ann.methodName();
- }
- }
- ParameterreturnPara = new Parameter(null,methodInfo.getReturnType(), methodInfo.getGenericReturnType());
- //调用方法
- ServiceProxy proxy = ServiceProxy.getProxy(serviceName);
- InvokeResultresult = proxy.invoke(returnPara, lookup,methodName, paras);
- //设置返回值
- if (result!= null && result.getOutPara() != null) {
- for (int i = 0;i < outParas.size() && i < result.getOutPara().length; i++) {
- Object op = args[outParas.get(i)];
- if(op instanceof Out){
- ((Out)op).setOutPara(result.getOutPara()[i]);
- }
- }
- }
- returnresult.getResult();
这里出现了OperationContract注解,这是在方法上面注解的。注解有一个methodName属性。
关键点是ServiceProxy的getProxy和invoke方法。
ServiceProxy.getProxy:构造ServiceProxy
- config =ServiceConfig.GetConfig(serviceName);
- dispatcher = newDispatcher(config);
- requestTime = config.getSocketPool().getReconnectTime();
- intserverCount = 1;
- if(dispatcher.GetAllServer()!= null && dispatcher.GetAllServer().size()> 0){
- serverCount = dispatcher.GetAllServer().size();
- }
- ioreconnect =serverCount - 1;
- // count = max {ioreconnect,requestTime}
- count = requestTime;
- if(ioreconnect > requestTime){
- count = ioreconnect;
- }
首先读取配置文件中属性为//Service[@name= serviceName]的节点
创建实现负载均衡的dispatcher,在这里创建了Server
- for(ServerProfile ser : config.getServers()) {
- if(ser.getWeithtRate() > 0) {
- Server s = newServer(ser);
- if(s.getState() != ServerState.Disable) {
- ScoketPool sp = newScoketPool(s, config);
- s.setScoketpool(sp);
- ServerPool.add(s);
- }
- }
- }
ServiceProxy.Invoke方法
- //构造RequestProtocol
- RequestProtocol requestProtocol = newRequestProtocol(typeName, methodName, listPara);
- ProtocolsendP = new Protocol(createSessionId(),
- (byte) config.getServiceid(),
- SDPType.Request,
- CompressType.UnCompress,
- config.getProtocol().getSerializerType(),
- PlatformType.Java,
- requestProtocol);
- ProtocolreceiveP = null;
- Serverserver = null;
- for(int i = 0;i <= count; i++){
- server = dispatcher.GetServer();
- if (server== null) {
- logger.error("cannotget server");
- throw newException("cannot get server");
- }
- try{
- //本地存根调用
- receiveP = server.request(sendP);
- break;
- } catch(IOExceptionio){
- } catch(RebootExceptionrb){
- this.createReboot(server);
- }catch(TimeoutExceptionte){
- } catch(Throwable ex){
- }
- }
- if(receiveP== null){
- throw newException("userdatatype error!");
- }
- if(receiveP.getSDPType() == SDPType.Response) {
- ResponseProtocol rp = (ResponseProtocol)receiveP.getSdpEntity();
- logger.debug("invoketime:" + (System.currentTimeMillis() - watcher) + "ms");
- return new InvokeResult(rp.getResult(),rp.getOutpara());
- } else if(receiveP.getSDPType()== SDPType.Reset){
- logger.info(server.getName()+"server is reboot,system will change normal server!");
- this.createReboot(server);
- returninvoke(returnType, typeName, methodName, paras);
- }else if(receiveP.getSDPType() == SDPType.Exception) {
- ExceptionProtocol ep = (ExceptionProtocol)receiveP.getSdpEntity();
- throwThrowErrorHelper.throwServiceError(ep.getErrorCode(), ep.getErrorMsg());
- } else {
- throw newException("userdatatype error!");
- }
Server.request()过程
- //每个CSocket有个WaitWindows注册了SessionId到WindowData的表
- increaseCU();
- CSocketsocket = null;
- try {
- try {//发送消息
- socket = this.scoketpool.getSocket();
- byte[] data= p.toBytes(socket.isRights(),socket.getDESKey());
- socket.registerRec(p.getSessionID());
- socket.send(data);
- } catch(Throwable ex) {
- logger.error("Serverget socket Exception", ex);
- throw ex;
- }finally {
- if(socket!= null){
- socket.dispose();
- }
- }
- //接收应答
- byte[]buffer = socket.receive(p.getSessionID(), currUserCount);
- Protocol result = Protocol.fromBytes(buffer,socket.isRights(),socket.getDESKey());
- if (this.state ==ServerState.Testing) {
- relive();
- }
- return result;
- } catch(IOException ex) {
- } catch(Throwable ex) {
- } finally {
- }
Receive接收应答时,通过sessionId对应的AutoResetEvent等待
- //CSocket.receive
- AutoResetEvent event = wd.getEvent();
- int timeout= getReadTimeout(socketConfig.getReceiveTimeout(), queueLen);
- if(!event.waitOne(timeout)) {
- throw newTimeoutException("Receive data timeout or error!timeout:" +timeout + "ms,queue length:" +queueLen);
- }
返回应答可能为Response、Reset、Exception
Response -> 返回InvokeResult结构体
Reset -> 重启则再调用invoke(returnType,typeName, methodName, paras)
Exception -> 抛出异常
frameHandler从Socket接收数据,并根据协议反解出session id,然后从waitWindows中取出对应的WindowData,然后调用对应的Event的set()通知CSocket.receive 返回
客户端做的工作主要就是这些
Gaea源码阅读(二):客户端流程相关推荐
- mybatis源码阅读(二):mybatis初始化上
转载自 mybatis源码阅读(二):mybatis初始化上 1.初始化入口 //Mybatis 通过SqlSessionFactory获取SqlSession, 然后才能通过SqlSession与 ...
- LeGo-LOAM激光雷达定位算法源码阅读(二)
文章目录 1.featureAssociation框架 1.1节点代码主体 1.2 FeatureAssociation构造函数 1.3 runFeatureAssociation()主体函数 2.重 ...
- nginx源码阅读(二).初始化:main函数及ngx_init_cycle函数
前言 在分析源码时,我们可以先把握主干,然后其他部分再挨个分析就行了.接下来我们先看看nginx的main函数干了些什么. main函数 这里先介绍一些下面会遇到的变量类型: ngx_int_t: t ...
- DBFace: 源码阅读(二)
上篇链接 看LZ上篇博客的时间竟然是7月18日,着实是懈怠了,其实有很多东西需要总结归纳,这周末就补一下之前欠的债吧 上篇主要介绍了DBFace的大体框架,这篇主要介绍数据的预处理部分 5. 数据预处 ...
- Gaea源码阅读(一):使用
转载地址:http://blog.csdn.net/m_vptr/article/details/9145321 Gaea:58同城开源的中间层服务框架 https://github.com/58co ...
- Gaea源码阅读(五):C客户端
转载地址:http://blog.csdn.net/m_vptr/article/details/9245763 除了Java客户端外,Gaea还提供了C语言和.NET实现. 基本都是相同的,只是序列 ...
- Gaea源码阅读(三):服务端启动流程
转载地址:http://blog.csdn.net/m_vptr/article/details/9163319 相对于客户端,服务器端工作就比较多了.服务器端需要load jar包,利用fliter ...
- datax源码阅读二:Engine流程
一.根据前面python文件知道,java的main函数是com.alibaba.datax.core.Engine public static void main(String[] args) th ...
- ThinkPHP源码阅读1-------访问流程
ThinkPHP访问流程在手册1.11系统流程里就有介绍,我阅读的ThinkPHP的版本是3.1.3,大家可以看下手册,基本的流程也有,现在就是详细去介绍一下ThinkPHP的访问流程.(调试模式下的 ...
最新文章
- android shell hello world,Android Framework 之HelloWorld(三)
- iOS开发常用的RGB色值和宏
- html导航教程视频,导航_HTML+CSS前端基础知识教程_腾讯视频
- delphi控件切图界面闪烁_先本设计教你跳过UI小程序的七个坑
- Python - 遍历列表时删除元素的正确做法
- (转)游戏程序员养成计划 (更新2010.11.6)
- matlab的数值计算方法,数值计算方法中的一些常用算法的Matlab源码
- (44)FPGA面试题CMOS和TTL电路区别
- arguments.callee 指向正在执行的函数的指针
- html5 的 webScoket 和 C# 建立Socket连接
- HDU 1465 不容易系列之一 (错排)
- 深入解析Windows操作系统(笔记7)
- 基于stm32 ESP8266WiFi模块的基本通信
- Python实现一键翻译英文论文,实现了pdf文档英译汉,pdf格式不变
- 算法设计与分析 ——10-7课程总结
- python不用api爬twitter
- 分享解决方法:为什么QQ聊天框中无法使用输入法输入中文?
- DPDK-实战之load_balancer(负载均衡)
- 个人日记——用来激励自己
- matlab实现PS算法之亮度调整