做可配置的webservice接口调用

来源:互联网 发布:淘宝免费代收货服务 编辑:程序博客网 时间:2024/05/23 01:57

最近公司接个项目,要跟9个或者更多个系统对接,需要写webservice接口,但是这么多一个个写的话很麻烦,而且还是不定个数的对接,所以思来想去,还是写个可配置的吧,步骤如下:

1、给出统一的接口标准,统一使用cxf 的标准wsdl 格式的webservice

2、给出统一接口标准后,所有系统调用方法,所传的参数,返回值格式均一致,这样的话就可以开始表写配置文件(WebService.properties),配置对应的wsdl url路径

#下面为wsdl url路径,前面的URL1、2、3均随意,不重复即可,这里为了统一,统一使用该格式

URL1=http\://localhost\:8899/hello?wsdl 
URL2=http\://localhost\:8898/hello?wsdl
URL3=http\://localhost\:8897/hello?wsdl

#标记URL的个数,用来确认新配置的URL的key为URL(COUNT+1)
COUNT=3

3、解析WebService.properties配置文件,获取url

public static Map<String,String> urlMap = new HashMap<String,String>();
static{
InputStream ins = Test.class.getResourceAsStream("util.properties");  
        // 生成properties对象  
        Properties p = new Properties();  
        try {  
            p.load(ins);  
            Enumeration enu=p.propertyNames();
            while(enu.hasMoreElements()){
                String key = (String)enu.nextElement();
                urlMap.put(key, p.getProperty(key));
                System.out.println(key);
            } 
        } catch (Exception e) {  
            e.printStackTrace();  
        }  

}

这里由于key是不重复的,所以直接使用map

4、上面已经解析完全部的url,下面开始循环调用

public static void get(){
List<String> list = new ArrayList<String>();
for (String key : urlMap.keySet()) {  
if(!"COUNT".equals(key))
list.add(urlMap.get(key));
        } 
System.err.println(list.size());
String url = "";
for(int i = 0 ; i < list.size(); i++){
url = list.get(i);
System.err.println(url);
Client client = getClient(url);
   String method = "queryMenuList";//webservice的方法名 
   Object[] result = null;
   Object[] par = {"张三","1"};
   try {
      result = client.invoke(method, par);//调用webservice 
   } catch (Exception e) {
      e.printStackTrace();
   }
   System.err.println(result[0].toString());
}
}

5、至此我们的webservice循环调用结束,下面开始做可配置的webservice

int count = Integer.parseInt(Test.urlMap.get("COUNT"));//获取url数
count++;
String url = "http://localhost:8893/hello?wsdl";
String urlKey = "URL"+count;



Properties p = new Properties();

//将新的webservice URL写入配置文件,以便重启后仍然可以使用
try {
InputStream io = WriteURL.class.getResourceAsStream("util.properties");
p.load(io);


FileOutputStream f1 = null;

if(Test.getValue(url)){
p.setProperty(urlKey,url);
p.setProperty("COUNT",count+"");
}
io.close();
OutputStream outputFile = new FileOutputStream("src\\main\\java\\com\\webService\\util.properties"); 


p.store(outputFile,"更新新的配置"); 


outputFile.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

//将新的webservice URL写入map,以便在不重新启动程序的情况下使用
Test.urlMap.put(urlKey, url);

6、至此可配置的webservice实现完成

1 0