如何用POST测试以太坊性能,从原理到实战的完整指南
以太坊节点的性能直接影响DApp的用户体验和链上服务的稳定性,无论是自建节点、使用私有链,还是评估RPC服务商的质量,我们都可以通过HTTP POST请求向以太坊节点的JSON-RPC接口发送指令,来测量延迟、吞吐量等关键性能指标,本文将系统介绍具体的测试方法与实战技巧。
准备工作
搭建以太坊节点
以Geth为例,启动一个开启HTTP RPC服务的节点:
# 开发模式(适合本地测试)
geth --dev --http --http.port 8545
# 连接主网或测试网
geth --http --http.addr 0.0.0.0 --http.port 8545 \
--http.api eth,net,web3,txpool
理解JSON-RPC的POST格式
以太坊所有RPC调用都通过HTTP POST发送,请求体为JSON格式:
{
"jsonrpc": "2.0",
"method": "方法名",
"params": ["参数"],
"id": 1
}
基础性能测试:单次请求延迟
用curl测试节点连通性与响应速度
# 查询最新区块高度
curl -X POST http://localhost:8545 \
-H "Content-Type: application/json" \
-d '{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":1}'
加上-w参数可以直观看到耗时:
curl -X POST http://localhost:8545 \
-H "Content-Type: application/json" \
-d '{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":1}' \
-w "\n耗时: %{time_total}s\n"
用Python脚本精确测量
import requests
import time
url = "http://localhost:8545"
def rpc_call(method, params):
payload = {
"jsonrpc": "2.0",
"method": method,
"params": params,
"id": 1
}
start = time.perf_counter()
resp = requests.post(url, json=payload)
elapsed = (time.perf_counter() - start) * 1000
return resp.json(), elapsed
result, ms = rpc_call("eth_blockNumber", [])
print(f"最新区块: {result['result']}, 耗时: {ms:.2f} ms")
核心性能指标测试
区块出块时间
通过连续区块的时间戳计算平均出块间隔:
def get_block(number):
_, result = rpc_call("eth_getBlockByNumber", [hex(number), False])
return result
latest = int(get_latest_number(), 16)
block1 = get_block(latest)
block2 = get_block(latest - 10)
interval = (int(block1['timestamp'], 16) - int(block2['timestamp'], 16)) / 10
print(f"平均出块时间: {interval:.2f} 秒")
RPC接口吞吐量(QPS)
使用Apache Bench进行并发压测,先准备请求体文件payload.json:
{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":1}
然后执行:
# 1000个请求,100并发 ab -n 1000 -c 100 \ -p payload.json \ -T application/json \ http://localhost:8545/
输出结果中的Requests per second即为QPS,Time per request为平均延迟。
批量请求性能
JSON-RPC支持批量调用,可测试节点处理复合请求的能力:
curl -X POST http://localhost:8545 \
-H "Content-Type: application/json" \
-d '[
{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":1},
{"jsonrpc":"2.0","method":"eth_gasPrice","params":[],"id":2},
{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":3}
]'
The End
发布于:2026-10-14,除非注明,否则均为原创文章,转载请注明出处。

