I need to periodically query the oid results with multiple threads. Every time I query, I will create a new snmp clent and finally close snmp. However, I found that the number of UDP connections will be more and more, with thousands of incremental connections. The final process leads to the inability to ping the local machine. Can I use only one SNMP client in multithreading? Will this lead to inefficiency or uncorrect result?
Snmp snmp = null;
Target target = null;
try {
snmp = SnmpComunication.getSnmp(snmpTarget.getSnmpVersion());
target = new CommunityTarget();
((CommunityTarget) target).setCommunity(new OctetString(snmpTarget.getReadCommunity()));
DefaultPDUFactory defaultPDUFactory = new DefaultPDUFactory(PDU.GETBULK);
if (target instanceof UserTarget) {
OctetString contextEngineId = new OctetString("");
OctetString contextName = new OctetString("");
defaultPDUFactory.setContextName(contextName);
defaultPDUFactory.setContextEngineID(contextEngineId);
}
tableUtils = new TableUtils(snmp, defaultPDUFactory);
tableUtils.setIgnoreMaxLexicographicRowOrderingErrors(300);
List<VariableBinding[]> returnList = new ArrayList<VariableBinding[]>();
List<VariableBinding[]> resultList=new ArrayList<>();
OID[] columns = new OID[oids.size()];
for (int i = 0; i < oids.size(); i++) {
columns[i] = new OID(oids.get(i));
}
List<TableEvent> events = null;
try {
events = tableUtils.getTable(target, columns, null, null);
} catch (Exception exception) {
logger.error("getTable exception:" + exception.getMessage());
}
if (events == null || (events.size() == 1 && events.get(0).getColumns() == null)) {
throw new Exception("Gettable result is null" );
} else {
for (TableEvent event : events) {
if (event.getException() != null) {
throw new Exception(event.getErrorMessage() + "," + event.getException().getMessage());
}
if (event.getColumns() == null || event.getColumns().length < 1) {
continue;
}
VariableBinding[] values = event.getColumns();
returnList.add(values);
}
}
return returnList;
} catch (Exception e) {
throw new Exception("error");
} finally {
if (snmp != null) {
snmp.close();
}
}
public static Snmp getSnmp(Integer version) {
try {
TransportMapping transport = new DefaultUdpTransportMapping();
Snmp snmp = new Snmp(transport);
if (version == MessageProcessingModel.MPv3) {
if (snmp.getUSM() == null) {
byte[] localEngineID = MPv3.createLocalEngineID();
engineId = new OctetString(localEngineID);
USM usm = new USM(SecurityProtocols.getInstance(), engineId, 0);
SecurityModels.getInstance().addSecurityModel(usm);
}
}
transport.listen();
return snmp;
} catch (Exception e) {
}
return null;
}