您可以使用testStarted method 来初始化所有线程的连接。请注意,此方法在克隆线程之前运行一次,因此在testStarted 中,您需要一个连接池,然后线程可以从中获取。例如,一个非常原始的连接池将是一个映射,其中包含某个键的顺序 ID 和连接对象。每个线程将根据线程号从该池中获取一个连接:
所以这样简单的池可以初始化为:
@Override
public void testStarted()
{
int maxConnections = getThreadContext().getThreadGroup().getNumThreads();
ConcurrentMap<Integer, Object> connections = new ConcurrentHashMap<Integer, Object>();
for(int i = 0; i < maxConnections; i++)
{
Object connection = //... whatever you need to do to connect
connections.put(new Integer(i), connection);
}
// Put in the context of thread group
JMeterContextService.getContext().getVariables().putObject("MyConnections", connections);
}
(连接对象可以是更具体的类型,根据您的需要)。
稍后你可以在sample方法中使用它:
// Get connections pool from context
ConcurrentMap<Integer, Object> connections = (ConcurrentHashMap<Integer, Object>) JMeterContextService.getContext().getVariables().getObject("MyConnections");
// Find connection by thread ID, so each thread goes to a different connection
connections.get(getThreadContext().getThreadNum());
在这里,我天真地假设在运行时返回的线程号和用于连接初始化的初始顺序整数之间存在完美映射。不是最好的假设,可以改进,但它是一个有效的起点。
然后您可以关闭和删除testEnded method 中的连接。这个方法也运行一次,所以我们关闭所有连接:
@Override
public void testEnded()
{
for(Entry<Integer, Object> connection : connections.entrySet())
{
connection.close(); // or do whatever you need to close it
connections.remove(connection.getKey());
}
}
或者你也可以在所有连接都关闭后直接调用connections.clear()。
披露:我没有直接测试这个答案中的代码,而是使用了过去类似的代码片段,并重复使用它们来回答这个问题。如果您发现任何问题,请随时更新此答案。