基于cxf 3.1.10版本
import org.apache.cxf.bus.spring.SpringBus;
import org.apache.cxf.policy.PolicyDataEngine;
@Bean(name = Bus.DEFAULT_BUS_ID)
public SpringBus springBus() {
SpringBus springBus = new SpringBus();
springBus.getExtension(PolicyDataEngine.class);
springBus.setExtension(new CustomizePolicyDataEngine(springBus), PolicyDataEngine.class);
return springBus;
}
import org.apache.cxf.Bus;
import org.apache.cxf.message.Message;
import org.apache.cxf.policy.PolicyCalculator;
import org.apache.cxf.transports.http.configuration.HTTPClientPolicy;
import org.apache.cxf.ws.policy.PolicyDataEngineImpl;
public class CustomizePolicyDataEngine extends PolicyDataEngineImpl {
public CustomizePolicyDataEngine(Bus bus) {
super(bus);
}
@Override
public <T> T getPolicy(Message message, T confPolicy, PolicyCalculator<T> intersector) {
T policy = super.getPolicy(message, confPolicy, intersector);
if (policy instanceof HTTPClientPolicy) {
((HTTPClientPolicy) policy).setConnectionTimeout(3_000);
((HTTPClientPolicy) policy).setReceiveTimeout(5_000);
}
return policy;
}
}
以上仅能设置实际调用接口时的超时时间,如果一开始对方的服务就没有启动,在创建客户端Service的时候还是会超时,可以在获取客户端Service时,判断下端口是否可达。
import cn.hutool.core.convert.Convert;
import cn.hutool.core.net.NetUtil;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
private static final Object mutex = new Object();
private static TestWebService testWebService;
public static TestWebService getClientInstance(String ipPort) {
if (null == testWebService) {
synchronized (mutex) {
if (null != testWebService) {
return testWebService;
}
try {
boolean isOpen = NetUtil.isOpen(new InetSocketAddress(StrUtil.split(ipPort, ":").get(0), Convert.toInt(StrUtil.split(ipPort, ":").get(1))), 3_000);
if (!isOpen) {
throw new RuntimeException("Web Service server is closed");
}
URL WSDL_LOCATION = new URL("http://" + ipPort + "/api/webservice/test?wsdl");
TestWebServiceImplService testWebServiceImplService = new TestWebServiceImplService(WSDL_LOCATION);
testWebService = testWebServiceImplService.getTestWebServiceImplPort();
} catch (MalformedURLException e) {
log.error("create TestWebService error", e);
throw new RuntimeException("create TestWebService error");
}
}
}
return testWebService;
}