Khm*_*lex 8 java session timeout jsch jenkins
我正在使用JSch 0.1.50为我的CI Jenkins插件建立与远程服务器的连接.让我们假设我在这里使用session.connect(60000);超时60秒:
Session session = null;
try {
JSch jsch = new JSch();
if (rsaIdentity != null && !rsaIdentity.equals("")) {
jsch.addIdentity(rsaIdentity.trim());
}
session = jsch.getSession(serverLogin, serverHost, Integer.parseInt(serverPort));
session.setPassword(getDescriptor().getOpenPassword(encryptedPasswordString));
session.setConfig("StrictHostKeyChecking", "no"); // not use RSA key
int timeOut = Integer.parseInt(getDescriptor().getConnectionTimeOut());
session.connect(60000);
} catch (SocketTimeoutException e) {
logger.error(e.getMessage());
return false;
} catch (JSchException e) {
logger.error(e.getMessage());
return false;
}
Run Code Online (Sandbox Code Playgroud)
但实际上在连接到相当慢的服务器期间执行此代码期间,我Exception每次都会在大约20秒内面临超时:
2016-01-25 13:15:55.982 [INFO] Connecting to server: devsrv26:22 as [user] ...
2016-01-25 13:16:16.991 [ERROR] java.net.ConnectException: Connection timed out: connect
2016-01-25 13:16:16.992 com.jcraft.jsch.JSchException: java.net.ConnectException: Connection timed out: connect
2016-01-25 13:16:16.992 at com.jcraft.jsch.Util.createSocket(Util.java:389)
2016-01-25 13:16:16.993 at com.jcraft.jsch.Session.connect(Session.java:215)
2016-01-25 13:16:16.993 at com.mycomp.jenkins.MyPlugin.perform(MyPlugin.java:225)
Run Code Online (Sandbox Code Playgroud)
76991-55982 = 21008毫秒
有谁知道这20秒超时的原因是什么?
如果您检查 是如何Util.createSocket实现的,您会发现timeout只定义了连接的上限,而不是下限,因为timeout奇怪的是 没有传递给底层Socket。
这 20 秒可能是操作系统级别的默认限制。
要覆盖它,请尝试实现SocketFactory并将其附加到使用 的会话Session.setSocketFactory。
在工厂中使用Socket.connect(SocketAddress endpoint, int timeout).
就像是:
public class SocketFactoryWithTimeout implements SocketFactory {
public Socket createSocket(String host, int port) throws IOException,
UnknownHostException
{
socket=new Socket();
int timeout = 60000;
socket.connect(new InetSocketAddress(host, port), timeout);
return socket;
}
public InputStream getInputStream(Socket socket) throws IOException
{
return socket.getInputStream();
}
public OutputStream getOutputStream(Socket socket) throws IOException
{
return socket.getOutputStream();
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16121 次 |
| 最近记录: |