WebService如何设置基于cxf的wsdl2java生成的客户端超时

基于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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值