一个连接多个对象

One connection for multiple object

我 运行 在实现正确的代码时遇到了麻烦。 我有几个使用 ssh 隧道的对象,我不想每次都关闭并打开一个新连接。 所以我实现了单例模式来获取我的连接实例,并将它传递给每个对象。 阅读之后 单例模式似乎不是正确的编码方式,但我没有看到任何其他方式重新编码我的 classes.

实例class:

public class ServerConnection {

String ip = "localhost";
String user = "tom1";
String pass = "1";
int port = 22;
private static Session session;

private ServerConnection() throws JSchException {
    try {
        JSch jsch = new JSch();
        session = jsch.getSession(user, ip, port);
        session.setPassword(pass);
        java.util.Properties config = new java.util.Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config);
        session.connect();
    }catch(Exception e){
        System.out.println(e);
    }

}

public static Session getInstance() throws JSchException {
    if (session == null) {
        System.out.println("Creation de la connection");
        new ServerConnection();
    }else{
        System.out.println("La connection existe deja");
    }
    return session;
}

}

我的对象:

public class EchoText implements InterfaceScript
{

/**
*Message to display with the Echo.
*/
String message;

/**
* Params of the test.
*/
String params;

/**
*Result of the test.
*/
String result="Failed";

/**
*Constructor of EchoText.
*/
public void EchoText (){ 
}

@Override
public String run(String params) {
    this.params=params;
    treatParameters();
    Session session;
    try {
        //Verify if an instance of the server is running.
        session = ServerConnection.getInstance();

        //Open a channel to send informations
        ChannelExec channel = (ChannelExec) session.openChannel("exec");
        BufferedReader in = new BufferedReader(new InputStreamReader(channel.getInputStream()));

        //Set the command to send
        channel.setCommand("cmd /c echo "+this.message);
        channel.connect();

    // Read the outptut
    String msg = null;
    while ((msg = in.readLine()) != null) {
        System.out.println(msg);
    }

    channel.disconnect();
    this.result();
    return this.result;
    } catch (JSchException | IOException e)
    {
        System.out.println(e);
        return this.result;
    }
}   
}

据我所知,singleton 仍然是正确的,只是它将保留在您的垃圾收集器的永久生成中,这对 Web 应用程序不利(因为重新部署不会'不要从内存中删除这些 无法访问的 实例)。 当然最好每个应用程序实例只有 ONE 个单例。

但据我所知,SSH 连接可能会因不活动超时而关闭,这会使它失效,并使您的单身人士 无用
一种需要 重构 的选项是将命令调用分批放入队列中,然后分配 SSH 连接,然后在队列准备就绪时发送命令。