博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
hession
阅读量:7057 次
发布时间:2019-06-28

本文共 8404 字,大约阅读时间需要 28 分钟。

hession 远程调用框架,

粗略看了下源码,大致是一个客户端 通过代理模式创建代理对象,当代理对象去调用服务端的方法的时候 才去请求服务。(通过http协议post二进制数据过去) 
服务端通过发送过来的方法名字和参数(反序列化) 调用服务端的方法返回。
proxy+http+Serialization(代理模式,http请求,序列化)。

1.当代理对象去调用服务端的方法的时候 才去请求服务  过程

com.caucho.hessian.client.HessianProxy

/**   * Sends the HTTP request to the Hessian connection.   */  protected HessianConnection sendRequest(String methodName, Object []args)    throws IOException  {    HessianConnection conn = null;        conn = _factory.getConnectionFactory().open(_url);    boolean isValid = false;    try {      addRequestHeaders(conn);      OutputStream os = null;      try {        os = conn.getOutputStream();      } catch (Exception e) {        throw new HessianRuntimeException(e);      }      if (log.isLoggable(Level.FINEST)) {        PrintWriter dbg = new PrintWriter(new LogWriter(log));        HessianDebugOutputStream dOs = new HessianDebugOutputStream(os, dbg);        dOs.startTop2();        os = dOs;      }            AbstractHessianOutput out = _factory.getHessianOutput(os);      out.call(methodName, args);      out.flush();      conn.sendRequest();      isValid = true;      return conn;    } finally {      if (! isValid && conn != null)        conn.destroy();    }  }
View Code

通过java.net.URLConnection发生http post请求,连接获取过程

com.caucho.hessian.client.HessianURLConnectionFactory

/**   * Opens a new or recycled connection to the HTTP server.   */  public HessianConnection open(URL url)    throws IOException  {    if (log.isLoggable(Level.FINER))      log.finer(this + " open(" + url + ")");    URLConnection conn = url.openConnection();    // HttpURLConnection httpConn = (HttpURLConnection) conn;    // httpConn.setRequestMethod("POST");    // conn.setDoInput(true);    long connectTimeout = _proxyFactory.getConnectTimeout();    if (connectTimeout >= 0)      conn.setConnectTimeout((int) connectTimeout);    conn.setDoOutput(true);    long readTimeout = _proxyFactory.getReadTimeout();    if (readTimeout > 0) {      try {        conn.setReadTimeout((int) readTimeout);      } catch (Throwable e) {      }    }    /*    // Used chunked mode when available, i.e. JDK 1.5.    if (_proxyFactory.isChunkedPost() && conn instanceof HttpURLConnection) {      try {        HttpURLConnection httpConn = (HttpURLConnection) conn;        httpConn.setChunkedStreamingMode(8 * 1024);      } catch (Throwable e) {      }    }    */        return new HessianURLConnection(url, conn);  }
View Code

 

2.hession服务端

开发时,spring-web包提供org.springframework.remoting.caucho.HessianServiceExporter类。

<bean name="/**Service" class="org.springframework.remoting.caucho.HessianServiceExporter" depends-on="**Service">

<property name="service" ref="**Service" />
<property name="serviceInterface" value="**Service" />
</bean>

 

 

服务端接收请求过程

请求通过dispatcherServlet类的doDispatch方法。

/**     * Process the actual dispatching to the handler.     * 

The handler will be obtained by applying the servlet's HandlerMappings in order. * The HandlerAdapter will be obtained by querying the servlet's installed HandlerAdapters * to find the first that supports the handler class. *

All HTTP methods are handled by this method. It's up to HandlerAdapters or handlers * themselves to decide which methods are acceptable. * @param request current HTTP request * @param response current HTTP response * @throws Exception in case of any kind of processing failure */ protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception { HttpServletRequest processedRequest = request; HandlerExecutionChain mappedHandler = null; boolean multipartRequestParsed = false; WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request); try { ModelAndView mv = null; Exception dispatchException = null; try { processedRequest = checkMultipart(request); multipartRequestParsed = (processedRequest != request); // Determine handler for the current request. mappedHandler = getHandler(processedRequest); if (mappedHandler == null || mappedHandler.getHandler() == null) { noHandlerFound(processedRequest, response); return; } // Determine handler adapter for the current request. HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler()); // Process last-modified header, if supported by the handler. String method = request.getMethod(); boolean isGet = "GET".equals(method); if (isGet || "HEAD".equals(method)) { long lastModified = ha.getLastModified(request, mappedHandler.getHandler()); if (logger.isDebugEnabled()) { logger.debug("Last-Modified value for [" + getRequestUri(request) + "] is: " + lastModified); } if (new ServletWebRequest(request, response).checkNotModified(lastModified) && isGet) { return; } } if (!mappedHandler.applyPreHandle(processedRequest, response)) { return; } // Actually invoke the handler. mv = ha.handle(processedRequest, response, mappedHandler.getHandler()); if (asyncManager.isConcurrentHandlingStarted()) { return; } applyDefaultViewName(processedRequest, mv); mappedHandler.applyPostHandle(processedRequest, response, mv); } catch (Exception ex) { dispatchException = ex; } processDispatchResult(processedRequest, response, mappedHandler, mv, dispatchException); } catch (Exception ex) { triggerAfterCompletion(processedRequest, response, mappedHandler, ex); } catch (Error err) { triggerAfterCompletionWithError(processedRequest, response, mappedHandler, err); } finally { if (asyncManager.isConcurrentHandlingStarted()) { // Instead of postHandle and afterCompletion if (mappedHandler != null) { mappedHandler.applyAfterConcurrentHandlingStarted(processedRequest, response); } } else { // Clean up any resources used by a multipart request. if (multipartRequestParsed) { cleanupMultipart(processedRequest); } } } }

View Code

getHandlerAdapter

/**     * Return the HandlerAdapter for this handler object.     * @param handler the handler object to find an adapter for     * @throws ServletException if no HandlerAdapter can be found for the handler. This is a fatal error.     */    protected HandlerAdapter getHandlerAdapter(Object handler) throws ServletException {        for (HandlerAdapter ha : this.handlerAdapters) {            if (logger.isTraceEnabled()) {                logger.trace("Testing handler adapter [" + ha + "]");            }            if (ha.supports(handler)) {                return ha;            }        }        throw new ServletException("No adapter for handler [" + handler +                "]: The DispatcherServlet configuration needs to include a HandlerAdapter that supports this handler");    }
View Code

通过下图可以知道有3个handleAdapter

我们看下HttpRequestHandlerAdapter这个类

public class HttpRequestHandlerAdapter implements HandlerAdapter {    @Override    public boolean supports(Object handler) {        return (handler instanceof HttpRequestHandler);    }    @Override    public ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object handler)            throws Exception {        ((HttpRequestHandler) handler).handleRequest(request, response);        return null;    }    @Override    public long getLastModified(HttpServletRequest request, Object handler) {        if (handler instanceof LastModified) {            return ((LastModified) handler).getLastModified(request);        }        return -1L;    }}
View Code

HessianServiceExporter类实现了HttpRequestHandler接口。

所有这里返回HttpRequestHandlerAdapter。

最后((HttpRequestHandler) handler).handleRequest(request, response) 去处理请求。

 

转载于:https://www.cnblogs.com/shapeOfMyHeart/p/6219786.html

你可能感兴趣的文章
关于快速软件开发的常见误解,你掉坑里了么
查看>>
互联网下半场:消费升级背后的品牌激活之路
查看>>
广州恒大嘉奖郑智等三名国脚 冯潇霆下调预备队
查看>>
细数程序员出身的互联网大佬,你会是下一个他吗?
查看>>
如何看待程序员普遍缺乏数据结构和算法知识?
查看>>
香港城大学生用VR再现角岛鲸 冀大众关注自然生态
查看>>
许鞍华新片《七里地》催泪 网友:看完想回家过年
查看>>
致敬传统 津门传统曲艺更显“范儿”活动圆满落幕
查看>>
前端面试要求进一步提高,速成的程序员面试10家均未通过!
查看>>
连跳7个版本之后,MySQL 8.0.12有什么新特性?
查看>>
轻松掌握阿里Blink SQL关键技术及实现原理
查看>>
Android Studio 多环境打包
查看>>
设计师福利:新鲜上架一枚提供中国区 Dribbble 图片加速的 App
查看>>
docker-compose.yml配置详解
查看>>
react-native动态姿态tab组件
查看>>
现有项目中集成Flutter
查看>>
从源码分析非线程安全集合类的不安全迭代器
查看>>
我为什么要推荐《JavaScript 忍者秘籍(第2版)》
查看>>
内凹样式的另一个方案--v-coupon 一款基于 vue 的卡券组件
查看>>
基于Electron + nodejs + 小程序 实现弹幕小工具(开篇)
查看>>