最近项目上有写入大量数据到 redis 中的需求,使用的是 springboot 集成 redis 客户端,就少不了使用 RedisTemplate 来操作。由于数据量比较多,是需要考虑写入性能问题的,如何才能高效写入到 redis 中呢?通过度娘知道了使用 pipelined 方式性能非常好,但是却没有解释为什么?带着这个疑惑进行了这次的实测。
环境
- redis:使用本机 docker 启动的单节点服务
- springboot 框架集成 redis 客户端
实测
RedisTemplate 的操作 api 有两种:
- 常规操作 API
- pipelined 操作 API
对两种操作 API 进行了简单的测试用例来实测,代码如下:
@SpringBootTest
@RunWith(SpringRunner.class)
public class PerformanceTest {
@Autowired
private RedisTemplate redisTemplate;
@Test
public void performanceTest() {
// 均执行 2 万次的写入
int batch = 20000;
// 常规API
System.out.println("************ 普通写法 ****************");
String keyPrefix = "pt/performance_";
long begin = System.currentTimeMillis();
for (int i = 0; i < batch; i++) {
redisTemplate.opsForValue().set(keyPrefix + i, keyPrefix + i);
}
System.out.println("普通执行结束,共耗时:" + (System.currentTimeMillis() - begin) + " ms");
// pipeline API
RedisSerializer keySerializer = redisTemplate.getKeySerializer();
RedisS