网上关于多线程调用webService全是一句话:”虽然直接使用多线程可以很好地解决这个问题,但比较麻烦。幸好Axis2的客户端提供了异步访问WebService的功能。 ”
我也知道比较麻烦,也知道幸好Axis2的客户端提供了异步访问WebService的功能。但是能别每篇文章都是一样的转载吗?我踏马就是想知道直接使用多线程调用webService的资料!
网上关于多线程调用axis2生成的stub,能否采用单例,全无资料.
求人不如求己,翻遍中文资料,英文文档得出以下结论及解决办法:
axis2生成客户端线程不安全,多线程调用webService时有两种解决办法:
1.每个线程新new一个stub对象
2.stub单例
这两种方法皆不可行,原因如下:
1方法不可行,因为stub为重量级对象,可类比JDBC Connection,创建大量消耗资源.
2方法不可行,因为stub线程不安全,不可多线程操作同一实例.
针对如上问题可采用对象池方法解决,在对象池初始化一部分对象,每个线程从对象池中取出所需要的stub实例,互不干扰.
对象池代码如下,需要stub实例时,从该对象池中取:
public final class StubFactory extends BasePooledObjectFactory<Stub> {
static GenericObjectPool<Stub> pool = null;
// 取得对象池实例
public synchronized static GenericObjectPool<Stub> getPoolInstance() {
if (pool == null) {
GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
poolConfig.setMaxTotal(SystemMessage.getInt("pool.max.total"));
poolConfig.setMaxIdle(SystemMessage.getInt("pool.max.idle"));
poolConfig.setMinIdle(SystemMessage.getInt("pool.min.idle"));
poolConfig.setMaxWaitMillis(SystemMessage.getLong("pool.max.wait.millis"));
poolConfig.setTestOnBorrow(SystemMessage.getBoolean("pool.test.on.borrow"));
pool = new GenericObjectPool<Stub>(new StubFactory(), poolConfig);
}
return pool;
}
public static Stub borrowObject() throws Exception{
return (Stub) StubFactory.getPoolInstance().borrowObject();
}
public static void returnObject(Stub stub) throws Exception{
StubFactory.getPoolInstance().returnObject(stub);
}
public static void close() throws Exception{
StubFactory.getPoolInstance().close();
}
@Override
public Stub create() throws Exception {
return new Stub(SystemMessage.getString("crm_url_async"));
}
@Override
public PooledObject<Stub> wrap(Stub obj) {
return new DefaultPooledObject<Stub>(obj);
}
public static void main(String[] args) {
while(true) {
try {
Stub stub = StubFactory.getPoolInstance().borrowObject();
System.out.println(stub.hashCode());
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
附上对象池配置参数:
pool.max.total=15
pool.max.idle=10
pool.min.idle=5
pool.max.wait.millis=5000
pool.test.on.borrow=false