Axis2-HTTP传输优化

前言

   今年开始从事医疗行业的开发工作,也是第一次接触到WebService,并重构某三甲医院互联网医院后台,其中就涉及到了大量的对第三方HIS调用的WebService接口、在客户端选择方面我选择了axis2、通过IDEA生成axis2客户端,并交给了spring管理、前期接口切入较少流量不大,没有发现错误,直到有陆陆续续切了10多个接口,这几个接口对院方HIS系统调用频繁,且HIS接口返回很不稳定,并导致出现了一系列问题。

问题

经过排查发现有两个原因:

  • 超时时间过短
  • Http Client连接池过小导致的,由于axis2默认值为每个主机分配了2个连接,请求量大、返回慢、导致连接池不够用。

解决

  • 超时时间过短,在Options加入套接字超和连接超时配置即可,也可以将参数加入构造参数,通过创建对象传入要设置的超时时间。你也创建私有变量,创建对象时set进去,只要能配置上,即可。

    1
    2
    3
    4
    5
    6
    7
    Options options = new Options();
    //套接字超时
    options.setProperty(HTTPConstants.SO_TIMEOUT, new Integer(timeOutInMilliSeconds));
    //连接超时
    options.setProperty(HTTPConstants.CONNECTION_TIMEOUT, new Integer(timeOutInMilliSeconds));
    // 或者
    options.setTimeOutInMilliSeconds(timeOutInMilliSeconds);
  • 配置连接池
      本来想直接在生成的客户端代理构造中添加配置来,配置上启动报错,原来是 ConfigurationContext为null造成的。
      于是debug org.apache.axis2.client.ServiceClient(configurationContext, _service)内部代码,果然内部有处理ConfigurationContext为null的话,将会创建一个,于是自己便构造了ConfigurationContext对象,并配置连接池,构建客户端代理对象的时候传入configurationContext()

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    /**
    * ConfigurationContext
    * @return {@link ConfigurationContext}
    * @throws AxisFault AxisFault
    */
    public ConfigurationContext configurationContext() throws AxisFault {
    //配置HTTP连接池
    ConfigurationContext configurationContext = ConfigurationContextFactory
    .createConfigurationContextFromFileSystem(null, null);
    MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
    //默认5
    connectionManager.getParams().setDefaultMaxConnectionsPerHost(5);
    //最大20
    connectionManager.getParams().setMaxTotalConnections(20);
    HttpClient client = new HttpClient(connectionManager);
    configurationContext.setProperty(HTTPConstants.CACHED_HTTP_CLIENT, client);

    return configurationContext;
    }

参考

http://axis.apache.org/axis2/java/core/docs/http-transport.html

总结

  配置还是蛮简单的、文章简单的讲了讲需要的API、配置方式可以很多、API都是一样的、如果和大家配置方式不一致、还希望举一反三、毕竟换汤不换药。

作者

SanLi

发布于

2019-12-24

更新于

2021-07-08

许可协议