Hessian客户端调用理解

来源:互联网 发布:mac 文件编辑器 编辑:程序博客网 时间:2024/05/18 08:39

先上代码:

HessianProxyFactory factory = new HessianProxyFactory();Service exampleInterface = (IAPIHessian) factory.create(Service.class, url);exampleInterface.hello("zhang san");
1.HessianProxyFactory的构造方法是:

public HessianProxyFactory()  {    this(Thread.currentThread().getContextClassLoader());  }  /**   * Creates the new proxy factory.   */  public HessianProxyFactory(ClassLoader loader)  {    _loader = loader;    _resolver = new HessianProxyResolver(this);  }

无参的采用的是AppClassLoader加载的,有参的是自定义加载,比如下面:

URL jarUrl = new URL("file://localhost//user.jar");URL[] urls = new URL[] { jarUrl }; URLClassLoader cl = new URLClassLoader(urls);HessianProxyFactory factory = new HessianProxyFactory(cl);Service exampleInterface = (IAPIHessian) factory.create(cl.loadClass("com.**.api.Service"), url);

这个采用的是URLClassLoader来加载的,关于java的类加载涉及很多,这里只说一点点

2.factory.create方法是通过动态代理来实现的:

public Object create(Class<?> api, URL url, ClassLoader loader)  {    if (api == null)      throw new NullPointerException("api must not be null for HessianProxyFactory.create()");    InvocationHandler handler = null;    handler = new HessianProxy(url, this, api);    return Proxy.newProxyInstance(loader,                                  new Class[] { api,                                                HessianRemoteObject.class },                                  handler);  }

loader是类加载器,api是调用的服务类字节码(Service),有这几个必备的参数就可以动态生成一个调用服务端的接口对象

3.服务接口Service调用hello方法时运行HessianProxy的invoke方法,HessianProxy继承自InvocationHandler

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();    }  }

AbstractHessianOutput out = _factory.getHessianOutput(os);设置参数

把java数据对象通过序列化转成二进制数据进行传输




0 0