webservice 动态调用使用技巧

参考使用

  • maven 引用
 <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-rt-frontend-jaxws</artifactId>
            <version>${cxf.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-rt-transports-http</artifactId>
            <version>${cxf.version}</version>
        </dependency>
  • 代码
JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
Client client = dcf.createClient("echo.wsdl");
 
Object[] res = client.invoke("echo", "test echo");
System.out.println("Echo response: " + res[0]);

常见问题

  • org.apache.cxf.interceptor.Fault: Unmarshalling Error: unexpected element
    忽略错误即可 但是需要注意实际是否需要进行数据校验(以下代码同时添加了一个client 的cache 处理)
 
public class WsClient {
 
    private  static  final  Logger logger = LoggerFactory.getLogger(WsClient.class);
    private  static final Cache<String, Client> cache = Caffeine.newBuilder()
            .expireAfterAccess(10, TimeUnit.MINUTES)
            .maximumSize(10_000)
            .build();
 
    public static  Client createClient(String endpoint) {
        logger.info("create ws client:{}",endpoint);
        Client client = JaxWsDynamicClientFactory.newInstance().createClient(endpoint + "?wsdl");
        // ignore validation-event-handler fix https://access.redhat.com/solutions/2047853
        client.getRequestContext().put("set-jaxb-validation-event-handler", false);
        return client;
    }
    public static Client getClient(String endpoint) {
       return cache.get(endpoint,wsURL->createClient(wsURL));
    }
}

说明

JaxWsDynamicClientFactory 内部是比较复杂了,使用了动态代码编译以及类加载机制,可以简化我们很多ws 调用的处理

参考资料

https://cxf.apache.org/docs/dynamic-clients.html

原文地址:https://www.cnblogs.com/rongfengliang/p/15704251.html