zhubaomin
2 天以前 080c76ddb23b9f199ed2f59f3871b0058347d43e
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package com.dy.common.mw.channel.mqtt;
 
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.eclipse.paho.client.mqttv3.MqttClient;
 
/**
 * @Author: liurunyu
 * @Date: 2025/6/4 11:35
 * @Description
 */
public class MqttClientPool {
 
    private final GenericObjectPool<MqttClient> pool;
 
    public MqttClientPool(String broker, String username, String password, int maxConnections) {
        MqttClientPooledObjectFactory factory = new MqttClientPooledObjectFactory(broker, username, password);
        GenericObjectPoolConfig<MqttClient> config = new GenericObjectPoolConfig<>();
        config.setMaxTotal(maxConnections);
        config.setMaxIdle(maxConnections);
        config.setMinIdle(1);
        config.setTestOnBorrow(true);
        config.setTestOnReturn(true);
        config.setTestWhileIdle(true);
        this.pool = new GenericObjectPool<>(factory, config);
    }
 
    public MqttClient popClient() throws Exception {
        return pool.borrowObject();
    }
 
    public void pushClient(MqttClient client) {
        if (client != null) {
            pool.returnObject(client);
        }
    }
 
    public boolean isClose(){
        return pool.isClosed();
    }
 
    public void close() {
        pool.close();
    }
}