在测试broker的性能时,常常需要关注在其应用场景的cpu及内存占用情况。
测试内容
- 100个Paho Client连接时,Moquette Broker的cpu及内存占用情况。
- 100个Paho Client以20ms为周期发布消息时,Moquette Broker的cpu及内存占用情况。
客户端代码修改
使用handler处理建立连接和发布消息的msg。
// 创建线程
HandlerThread handlerThread = new HandlerThread("client-thread");
handlerThread.start();
Handler handler = new Handler(handlerThread.getLooper()){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what){
case CONNECT:
try {
startClient();
} catch (MqttException e) {
throw new RuntimeException(e);
}
Toast.makeText(MainActivity.this,"connected to 100 clients",Toast.LENGTH_SHORT).show();
break;
case PUBLISH:
try {
startPublish();
} catch (MqttException | InterruptedException e) {
throw new RuntimeException(e);
}
break;
}
}
startClient:连接100个客户端。
private synchronized void startClient() throws MqttException {
String name;
for(int i = 0; i<100; i++){
if(sampleClient[i] == null){
clientId = "clientId"+i;
sampleClient[i] = new MqttClient(broker, clientId, persistence);
sampleClient[i].setCallback(new SampleCallback());
sampleClient[i].connect(connOpts);
//sampleClient[i].subscribe("willTopic2", 1);
}
}
}
startPublish:创建一个线程池,用100个线程同时发送消息。
private synchronized void startPublish() throws MqttException, InterruptedException {
MqttMessage message = new MqttMessage(content.getBytes());
message.setQos(qos);
ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(100);
LongAdder longAdder = new LongAdder();
ScheduledFuture<?>[] scheduledFutures = new ScheduledFuture[100];
for (int i = 0; i < 100; i++) {
final int index = i;
scheduledFutures[index] = scheduledThreadPool.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
try {
sampleClient[index].publish(publishedTopic,message);
} catch (MqttException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}, 0, 20, TimeUnit.MILLISECONDS);
}
}
最后记得在onDestroy里面关闭线程。
adb shell 指令
在adb shell中使用 top -d 1 | grep com.example.moquettetest
指令,获取broker的cpu以及部分内存信息。
PR:进程优先级,rt 或大于等于 0 的数字
NI:优先级切换等级,[-20, 19]之间的数字
VIRT:虚拟内存大小,表示进程所能访问的所有虚拟地址空间的总和,包括所有分配但未实际使用的内存。
RES:常驻内存大小,表示进程实际使用的物理内存大小,即该进程当前在物理内存中驻留的部分。
SHR:共享内存大小,表示进程所使用的共享内存的大小,包括共享库使用的内存和其他进程共享的内存部分。
S[%CPU]:瞬时CPU占用率。
%MEM:进程使用物理内存占系统总内存的百分比。
在adb shell中使用 procrank
指令,获取broker的内存信息。
VSS:虚拟耗用内存(包含共享库占用的内存)
RSS:实际使用物理内存(包含共享库占用的内存)
PSS:实际使用的物理内存(比例分配共享库占用的内存)
USS:进程独自占用的物理内存(不包含共享库占用的内存)
重点关注S[%CPU]、RSS和PSS,对比峰值和空闲值。