RPC裏面如何計算TPS,如果讓你來計算這個TPS,你會怎麼去實現呢?
這是個有意思的問題,恰好這幾天看SOFA-RPC的example,看到了裏面是如果計算TPS的,這裏分享下。
如下List-1中是調用方的代碼
- 創建線程池,線程池的大小可按機器配置情況設置
- 每個線程循環發送請求,然後將AtomicLong加1
- 之後另一個線程,每隔1s,獲取當前AtomicLong的值,然後減去上次AtomicLong的值,這樣就是1s內請求的數量,即TPS
List-1
final int threads = 50;
final AtomicLong cnt = new AtomicLong(0);
final ThreadPoolExecutor service1 = new ThreadPoolExecutor(threads, threads, 0L, TimeUnit.MILLISECONDS,
new SynchronousQueue<Runnable>());// 無隊列
for (int i = 0; i < threads; i++) {
service1.execute(new Runnable() {
@Override
public void run() {
int n = 0;
while (true) {
try {
//echoService.echoStr("1234567890");
// 1k
//echoService.echoStr("..省略,1k個字符");
// 5k
LOGGER.info("send msg");
echoService.echoStr("..省略,5k個字符");
cnt.incrementAndGet();
} catch (Exception e) {
LOGGER.error("", e);
}
}
}
});
}
Thread thread = new Thread(new Runnable() {
private long last = 0;
@Override
public void run() {
while (true) {
long count = cnt.get();
long tps = count - last;
LOGGER.error("last 1s invoke: {}, queue: {}", tps, service1.getQueue().size());
last = count;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
}
}
}, "Print-tps-THREAD");
thread.start();
參考:SOFA-RPC的com.alipay.sofa.rpc.bolt.start.BoltClientMultipleMain