一、前言
之前遇到过rabbitmq队列卡死的问题,有消费者,但是就不消费队列里的消息;
后来发现是消费者执行webservice方法时,没有设置超时时间,默认永不超时,然后赶上对端系统出问题,方法就一直执行不完,队列消息也就一直卡住不动。(加try-catch是没有用的,catch不到,就是没有执行完一直卡住,因为超时时间默认永不超时)
在此总结下java webservice设置超时时间的方法。
二、代码
try {
JaxWsDynamicClientFactory dcf=JaxWsDynamicClientFactory.newInstance();
//这里有2种方法,不确定到底是哪种,就都写上了
dcf.getJaxbContextProperties().put("com.sun.xml.ws.request.timeout", 10000);
dcf.getJaxbContextProperties().put("com.sun.xml.ws.connect.timeout", 10000);
dcf.getJaxbContextProperties().put("com.sun.xml.internal.ws.connection.timeout", 10000);//建立连接的超时时间为10秒
dcf.getJaxbContextProperties().put("com.sun.xml.internal.ws.request.timeout", 10000);//指定请求的响应超时时间为10秒
LOGGER.info("设置超时时间");
Client client= dcf.createClient("http://128.0.0.1/A/services/BService?wsdl");
//这里再设置超时时间好像也行
//client.getRequestContext().put("com.sun.xml.ws.request.timeout", 10000);
//client.getRequestContext().put("com.sun.xml.ws.connect.timeout", 10000);
//client.getRequestContext().put("com.sun.xml.internal.ws.connection.timeout", 10000);//建立连接的超时时间为10秒
//client.getRequestContext().put("com.sun.xml.internal.ws.request.timeout", 10000);//指定请求的响应超时时间为10秒
//如果不设置超时时间,那么如果连接不通,就会卡在这一步
Object[] resultObj = client.invoke("createOrenableAccount", new Object[] { accountToXML("abc") });
String retXML = resultObj[0].toString();
StringReader read = new StringReader(retXML);
InputSource source = new InputSource(read);
SAXBuilder sb = new SAXBuilder();
Document doc = sb.build(source);
Element root = doc.getRootElement();
LOGGER.info(root.getChildText("code"));// 0 成功
LOGGER.info(root.getChildText("code") + ", " + root.getChildText("message"));
} catch (Exception e) {
LOGGER.error((new StringBuilder("invokeWS Exception:")).append(e).toString(),e);
}
------------------
public static String accountToXML(String userName) {
Document document = null;
Element et = new Element("account");
document = new Document(et);
document = addNode(document, "appname", "AI");
document = addNode(document, "uid", userName);
document = addNode(document, "eruid", userName);
return documentStr(document);
}
-------------------
public static String documentStr(Document document) {
XMLOutputter xop = new XMLOutputter();
String xmlStr = xop.outputString(document);
return xmlStr;
}
------------------------
pom.xml是这样:
<!-- Apache CXF -->
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-rs-client</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxws</artifactId>
<version>3.0.0</version>
</dependency>