Hessian客户端调用理解

先上代码:

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数据对象通过序列化转成二进制数据进行传输




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值