我的编程空间,编程开发者的网络收藏夹
学习永远不晚

关于JSCH使用自定义连接池的说明

短信预约 -IT技能 免费直播动态提醒
省份

北京

  • 北京
  • 上海
  • 天津
  • 重庆
  • 河北
  • 山东
  • 辽宁
  • 黑龙江
  • 吉林
  • 甘肃
  • 青海
  • 河南
  • 江苏
  • 湖北
  • 湖南
  • 江西
  • 浙江
  • 广东
  • 云南
  • 福建
  • 海南
  • 山西
  • 四川
  • 陕西
  • 贵州
  • 安徽
  • 广西
  • 内蒙
  • 西藏
  • 新疆
  • 宁夏
  • 兵团
手机号立即预约

请填写图片验证码后获取短信验证码

看不清楚,换张图片

免费获取短信验证码

关于JSCH使用自定义连接池的说明

1. JSCH使用方法

jsch使用方法

2. JSCH工具类

JSCH工具类

3. 创建连接池

ConnectionPool.java

@Slf4j
public class ConnectionPool {
    private String strictHostKeyChecking;
    private Integer timeout;
    
    private String ip = "";
    
    private Integer port = 22;
    
    private String username = "";
    
    private String password = "";
    
    private int incrementalConnections = 2;
    
    private int maxConnections = 10;
    
    private int maxIdle = 4;
    
    private int minIdel = 2;
    private Vector<PooledConnection> connections = null;
    @PostConstruct
    private void init() {
        createPool();
    }
    
    public ConnectionPool(String strictHostKeyChecking, Integer timeout) {
        this.strictHostKeyChecking = strictHostKeyChecking;
        this.timeout = timeout;
    }
    
    public ConnectionPool(String strictHostKeyChecking,
                          Integer timeout,
                          int incrementalConnections) {
        this.strictHostKeyChecking = strictHostKeyChecking;
        this.timeout = timeout;
        this.incrementalConnections = incrementalConnections;
    }
    
    public ConnectionPool(String strictHostKeyChecking,
                          Integer timeout,
                          int incrementalConnections,
                          int maxConnections) {
        this.strictHostKeyChecking = strictHostKeyChecking;
        this.timeout = timeout;
        this.incrementalConnections = incrementalConnections;
        this.maxConnections = maxConnections;
    }
    
    public synchronized void createPool() {
        if (Objects.nonNull(connections)) {
            return;
        }
        connections = new Vector<>();
        log.info("create shell connectionPool success!");
    }
    
    private void createConnections(int numConnections) throws JSchException {
        for (int x = 0; x < numConnections; x++) {
            // 判断是否已达连接池最大连接,如果到达最大连接数据则不再创建连接
            if (this.maxConnections > 0 && this.connections.size() >= this.maxConnections) {
                break;
            }
            //在连接池中新增一个连接
            try {
                connections.addElement(new PooledConnection(newConnection(), ip));
            } catch (JSchException e) {
                log.error("create shell connection failed {}", e.getMessage());
                throw new JSchException();
            }
            log.info("Session connected!");
        }
    }
    
    private Session newConnection() throws JSchException {
        // 创建一个session
        JSch jsch = new JSch();
        Session session = jsch.getSession(username, ip, port);
        session.setPassword(password);
        Properties sshConfig = new Properties();
        sshConfig.put("StrictHostKeyChecking", strictHostKeyChecking);
        session.setConfig(sshConfig);
        session.connect(timeout);
        session.setServerAliveInterval(1800);
        return session;
    }
    
    public synchronized Session getConnection(String ip, Integer port, String username, String password) throws JSchException {
        this.ip = ip;
        this.port = port;
        this.username = username;
        this.password = password;
        // 连接池还没创建,则返回 null
        if (Objects.isNull(connections)) {
            return null;
        }
        // 获得一个可用的数据库连接
        Session session = getFreeConnection();
        // 假如目前没有可以使用的连接,即所有的连接都在使用中,等一会重试
        while (Objects.isNull(session)) {
            wait(250);
            session = getFreeConnection();
        }
        return session;
    }
    
    private Session getFreeConnection() throws JSchException {
        Session session = findFreeConnection();
        // 如果没有可用连接,则创建连接,
        if (Objects.isNull(session)) {
            createConnections(incrementalConnections);
            session = findFreeConnection();
            if (Objects.isNull(session)) {
                return null;
            }
        }
        return session;
    }
    
    private Session findFreeConnection() {
        Session session = null;
        PooledConnection conn;
        Enumeration<PooledConnection> enumerate = connections.elements();
        // 遍历所有的对象,看是否有可用的连接
        while (enumerate.hasMoreElements()) {
            conn = enumerate.nextElement();
            if (!ip.equals(conn.getTag())) {
                continue;
            }
            if (!conn.isBusy()) {
                session = conn.getSession();
                conn.setBusy(true);
                if (!testConnection(session)) {
                    try {
                        session = newConnection();
                    } catch (JSchException e) {
                        log.error("create shell connection failed {}", e.getMessage());
                        return null;
                    }
                    conn.setSession(session);
                }
                break;
            }
        }
        return session;
    }
    
    private boolean testConnection(Session session) {
        boolean connected = session.isConnected();
        if (!connected) {
            closeConnection(session);
            return false;
        }
        return true;
    }
    
    public synchronized void returnConnection(Session session) {
        // 确保连接池存在,假如连接没有创建(不存在),直接返回
        if (Objects.isNull(connections)) {
            log.error("ConnectionPool does not exist");
            return;
        }
        PooledConnection conn;
        Enumeration<PooledConnection> enumerate = connections.elements();
        // 遍历连接池中的所有连接,找到这个要返回的连接对象,将状态设置为空闲
        while (enumerate.hasMoreElements()) {
            conn = enumerate.nextElement();
            if (session.equals(conn.getSession())) {
                conn.setBusy(false);
            }
        }
    }
    
    public synchronized void refreshConnections() throws JSchException {
        // 确保连接池己创新存在
        if (Objects.isNull(connections)) {
            log.error("ConnectionPool does not exist");
            return;
        }
        PooledConnection conn;
        Enumeration<PooledConnection> enumerate = connections.elements();
        while (enumerate.hasMoreElements()) {
            conn = enumerate.nextElement();
            if (conn.isBusy()) {
                wait(5000);
            }
            closeConnection(conn.getSession());
            conn.setSession(newConnection());
            conn.setBusy(false);
        }
    }
    
    public synchronized void closeConnectionPool() {
        // 确保连接池存在,假如不存在,返回
        if (Objects.isNull(connections)) {
            log.info("Connection pool does not exist");
            return;
        }
        PooledConnection conn;
        Enumeration<PooledConnection> enumerate = connections.elements();
        while (enumerate.hasMoreElements()) {
            conn = enumerate.nextElement();
            if (conn.isBusy()) {
                wait(5000);
            }
            closeConnection(conn.getSession());
            connections.removeElement(conn);
        }
        connections = null;
    }
    
    private void closeConnection(Session session) {
        session.disconnect();
    }
    
    private void wait(int mSeconds) {
        try {
            Thread.sleep(mSeconds);
        } catch (InterruptedException e) {
            log.error("{} 线程暂停失败 -> {}", Thread.currentThread().getName(), e.getMessage());
        }
    }
    
    class PooledConnection {
        
        Session session;
        
        boolean busy = false;
        
        String tag;
        
        public PooledConnection(Session session, String tag) {
            this.session = session;
            this.tag = tag;
        }
        public Session getSession() {
            return session;
        }
        public void setSession(Session session) {
            this.session = session;
        }
        public boolean isBusy() {
            return busy;
        }
        public void setBusy(boolean busy) {
            this.busy = busy;
        }
        public String getTag() {
            return tag;
        }
        public void setTag(String tag) {
            this.tag = tag;
        }
    }
    public int getIncrementalConnections() {
        return this.incrementalConnections;
    }
    public void setIncrementalConnections(int incrementalConnections) {
        this.incrementalConnections = incrementalConnections;
    }
    public int getMaxConnections() {
        return this.maxConnections;
    }
    public void setMaxConnections(int maxConnections) {
        this.maxConnections = maxConnections;
    }
}

4. 改造shellUtil

ShellUtil.java

@Slf4j
@Component
@Scope(value = "prototype")
public class ShellUtil {
    
    private String ip = "";
    
    private Integer port = 22;
    
    private String username = "";
    
    private String password = "";
    private Session session;
    private Channel channel;
    private ChannelExec channelExec;
    private ChannelSftp channelSftp;
    private ChannelShell channelShell;
    private ConnectionPool connectionPool;
    public ShellUtil(ConnectionPool connectionPool) {
        this.connectionPool = connectionPool;
    }
    
    public void init(String ip, Integer port, String username, String password) throws JSchException {
        this.ip = ip;
        this.port = port;
        this.username = username;
        this.password = password;
    }
    public void init(String ip, String username, String password) throws JSchException {
        this.ip = ip;
        this.username = username;
        this.password = password;
    }
    private void getSession() throws JSchException {
        session = connectionPool.getConnection(ip, port, username, password);
        if (Objects.isNull(session)) {
            connectionPool.refreshConnections();
            session = connectionPool.getConnection(ip, port, username, password);
            if (Objects.isNull(session)){
                throw new RuntimeException("无可用连接");
            }
        }
    }
    
    public String execCmd(String command) throws Exception {
        initChannelExec();
        log.info("execCmd command - > {}", command);
        channelExec.setCommand(command);
        channel.setInputStream(null);
        channelExec.setErrStream(System.err);
        channel.connect();
        StringBuilder sb = new StringBuilder(16);
        try (InputStream in = channelExec.getInputStream();
             InputStreamReader isr = new InputStreamReader(in, StandardCharsets.UTF_8);
             BufferedReader reader = new BufferedReader(isr)) {
            String buffer;
            while ((buffer = reader.readLine()) != null) {
                sb.append("\n").append(buffer);
            }
            log.info("execCmd result - > {}", sb);
            return sb.toString();
        }
    }
    
    public String execCmdAndClose(String command) throws Exception {
        String result = execCmd(command);
        close();
        return result;
    }
    
    public String execCmdByShell(String... cmds) throws Exception {
        return execCmdByShell(Arrays.asList(cmds));
    }
    
    public String execCmdByShell(List<String> cmds) throws Exception {
        String result = "";
        initChannelShell();
        InputStream inputStream = channelShell.getInputStream();
        channelShell.setPty(true);
        channelShell.connect();
        OutputStream outputStream = channelShell.getOutputStream();
        PrintWriter printWriter = new PrintWriter(outputStream);
        for (String cmd : cmds) {
            printWriter.println(cmd);
        }
        printWriter.flush();
        byte[] tmp = new byte[1024];
        while (true) {
            while (inputStream.available() > 0) {
                int i = inputStream.read(tmp, 0, 1024);
                if (i < 0) {
                    break;
                }
                String s = new String(tmp, 0, i);
                if (s.contains("--More--")) {
                    outputStream.write((" ").getBytes());
                    outputStream.flush();
                }
                System.out.println(s);
            }
            if (channelShell.isClosed()) {
                System.out.println("exit-status:" + channelShell.getExitStatus());
                break;
            }
            try {
                Thread.sleep(1000);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        outputStream.close();
        inputStream.close();
        close();
        return result;
    }
    
    public void put(String class="lazy" data-src, String dst) throws Exception {
        put(class="lazy" data-src, dst, ChannelSftp.OVERWRITE);
    }
    
    public void put(String class="lazy" data-src, String dst, int mode) throws Exception {
        initChannelSftp();
        log.info("Upload File {} -> {}", class="lazy" data-src, dst);
        channelSftp.put(class="lazy" data-src, dst, mode);
        log.info("Upload File Success!");
        close();
    }
    
    public void putMonitorAndClose(String class="lazy" data-src, String dst) throws Exception {
        putMonitorAndClose(class="lazy" data-src, dst, ChannelSftp.OVERWRITE);
    }
    
    public void putMonitorAndClose(String class="lazy" data-src, String dst, int mode) throws Exception {
        initChannelSftp();
        FileProgressMonitor monitor = new FileProgressMonitor(new File(class="lazy" data-src).length());
        log.info("Upload File {} -> {}", class="lazy" data-src, dst);
        channelSftp.put(class="lazy" data-src, dst, monitor, mode);
        log.info("Upload File Success!");
        close();
    }
    
    public void get(String class="lazy" data-src, String dst) throws Exception {
        initChannelSftp();
        log.info("Download File {} -> {}", class="lazy" data-src, dst);
        channelSftp.get(class="lazy" data-src, dst);
        log.info("Download File Success!");
        close();
    }
    
    public void getMonitorAndClose(String class="lazy" data-src, String dst) throws Exception {
        initChannelSftp();
        FileProgressMonitor monitor = new FileProgressMonitor(new File(class="lazy" data-src).length());
        log.info("Download File {} -> {}", class="lazy" data-src, dst);
        channelSftp.get(class="lazy" data-src, dst, monitor);
        log.info("Download File Success!");
        close();
    }
    
    public void deleteFile(String path) throws Exception {
        initChannelSftp();
        channelSftp.rm(path);
        log.info("Delete File {}", path);
        close();
    }
    
    public void deleteDir(String path) throws Exception {
        initChannelSftp();
        channelSftp.rmdir(path);
        log.info("Delete Dir {} ", path);
        close();
    }
    
    public void close() {
        connectionPool.returnConnection(session);
    }
    private void initChannelSftp() throws Exception {
        getSession();
        channel = session.openChannel("sftp");
        channel.connect(); // 建立SFTP通道的连接
        channelSftp = (ChannelSftp) channel;
        if (session == null || channel == null || channelSftp == null) {
            log.error("请先执行init()");
            throw new Exception("请先执行init()");
        }
    }
    private void initChannelExec() throws Exception {
        getSession();
        // 打开执行shell指令的通道
        channel = session.openChannel("exec");
        channelExec = (ChannelExec) channel;
        if (session == null || channel == null || channelExec == null) {
            log.error("请先执行init()");
            throw new Exception("请先执行init()");
        }
    }
    private void initChannelShell() throws Exception {
        getSession();
        // 打开执行shell指令的通道
        channel = session.openChannel("shell");
        channelShell = (ChannelShell) channel;
        if (session == null || channel == null || channelShell == null) {
            log.error("请先执行init()");
            throw new Exception("请先执行init()");
        }
    }
}

5. 添加配置

ConnectionPoolConfig.java

@Configuration
public class PoolConfiguration {
    @Value("${ssh.strictHostKeyChecking:no}")
    private String strictHostKeyChecking;
    @Value("${ssh.timeout:30000}")
    private Integer timeout;
    @Value("${ssh.incrementalConnections:2}")
    private Integer incrementalConnections;
    @Value("${ssh.maxConnections:10}")
    private Integer maxConnections;
    @Bean
    public ConnectionPool connectionPool(){
        return new ConnectionPool(strictHostKeyChecking, timeout,incrementalConnections,maxConnections);
    }
}

6. 线程安全问题解决

6.1

public class SessionThreadLocal {
    private static ThreadLocal<Session> threadLocal = new ThreadLocal<>();
    public static synchronized void set(Session session) {
        threadLocal.set(session);
    }
    public static synchronized Session get( ) {
        return threadLocal.get();
    }
    public static synchronized void remove( ) {
        threadLocal.remove();
    }
}

6.2 使用springboot中bean的作用域prototype

使用@Lookup注入方式

 @Lookup
    public ShellUtil getshellUtil(){
        return null;
    };
    @GetMapping("/test")
    public void Test() throws Exception {
        int i = getshellUtil().hashCode();
        System.out.println(i);
    }

以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

关于JSCH使用自定义连接池的说明

下载Word文档到电脑,方便收藏和打印~

下载Word文档

猜你喜欢

vue中标签自定义属性的使用及说明

这篇文章主要介绍了vue中标签自定义属性的使用及说明,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
2023-05-19

python自定义函数中的return和print使用及说明

这篇文章主要介绍了python自定义函数中的return和print使用及说明,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
2023-01-04

编程热搜

  • Python 学习之路 - Python
    一、安装Python34Windows在Python官网(https://www.python.org/downloads/)下载安装包并安装。Python的默认安装路径是:C:\Python34配置环境变量:【右键计算机】--》【属性】-
    Python 学习之路 - Python
  • chatgpt的中文全称是什么
    chatgpt的中文全称是生成型预训练变换模型。ChatGPT是什么ChatGPT是美国人工智能研究实验室OpenAI开发的一种全新聊天机器人模型,它能够通过学习和理解人类的语言来进行对话,还能根据聊天的上下文进行互动,并协助人类完成一系列
    chatgpt的中文全称是什么
  • C/C++中extern函数使用详解
  • C/C++可变参数的使用
    可变参数的使用方法远远不止以下几种,不过在C,C++中使用可变参数时要小心,在使用printf()等函数时传入的参数个数一定不能比前面的格式化字符串中的’%’符号个数少,否则会产生访问越界,运气不好的话还会导致程序崩溃
    C/C++可变参数的使用
  • css样式文件该放在哪里
  • php中数组下标必须是连续的吗
  • Python 3 教程
    Python 3 教程 Python 的 3.0 版本,常被称为 Python 3000,或简称 Py3k。相对于 Python 的早期版本,这是一个较大的升级。为了不带入过多的累赘,Python 3.0 在设计的时候没有考虑向下兼容。 Python
    Python 3 教程
  • Python pip包管理
    一、前言    在Python中, 安装第三方模块是通过 setuptools 这个工具完成的。 Python有两个封装了 setuptools的包管理工具: easy_install  和  pip , 目前官方推荐使用 pip。    
    Python pip包管理
  • ubuntu如何重新编译内核
  • 改善Java代码之慎用java动态编译

目录