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();
|
}
|
}
|