使用axis2构建webservice时,发现系统运行一段时间后客户端的内存使用一直不断增高,导致应用服务器无法承受而重启,这里提供了一种解决方案。
原因分析:客户端以stub方式请求服务,stub对象是一个非常重量级的对象,每次客户端向服务端请求服务时,stub对象不断被创建,占用大量系统资源
解决方案:考虑到所有的客户端stub都继承自org.apache.axis2.client.Stub类,考虑使用简单工厂模式+简单的对象池来提供stub对象实例,这样只需首次需要stub对象时实例化一次,以后需要用的时候从stub对象池中取得,工厂类本身做成单例模式。
代码实现:
- public class StubFactory{
- //从配置文件中取客户端应用context的绝对路径
- public static final String path=ServiceConfig.getPath();
- //从配置文件中取服务url
- public static final String serviceUrl=ServiceConfig.getServiceUrl();
- private static Map map=new HashMap();//这里可以是一个同步的Map,也可以直接用Hashtable
- private static ConfigurationContext configurationContext=null;
- private static StubFactory stubFactory=new StubFactory();
- private StubFactory(){};
- static{
- try{
- configurationContext=ConfigurationContextFactory.createConfigurationContextFromFileSystem(path+"/WEB-INF",path+"/WEB-INF/conf/axis2.xml");
- }catch(AxisFault e){
- e.printStackTrace();
- }
- }
- public Stub getStub(String type){
- Stub stub=null;
- if(map.get(type)==null){
- stub=(Stub)this.createStub(type);
- map.put(type,stub);
- }
- return (Stub)map.get(type);
- }
- private Stub createStub(String type){
- Stub stub=null;
- String targetEndpoint=null;
- try{
- if("SearchServiceStub".equals(type)){
- targetEndpoint=serviceUrl+"services/SearchService.SearchServiceHttpSoap12Endpoint/";
- stub=new SearchServiceStub(configurationContext,targetEndpoint);
- }
- if("CalculateServiceStub".equals(type)){
- targetEndpoint=serviceUrl+"services/CalculateService.CalculateServiceHttpSoap12Endpoint/";
- stub=new CalculateServiceStub(configurationContext,targetEndpoint);
- }
- if("MessageServiceStub".equals(type)){
- targetEndpoint=serviceUrl+"services/MessageService.MessageServiceHttpSoap12Endpoint/";
- stub=new MessageServiceStub(configurationContext,targetEndpoint);
- }
- }catch(Exception e){
- e.printStackTrace();
- }
- return stub;
- }
- public static StubFactory getInstance(){
- return stubFactory;
- }
- }
取stub对象只要如下代码:
- SearchServiceStub stub=(SearchServiceStub)StubFactory.getInstance().getStub("SearchServiceStub");