RedisTemplate同步大数据量性能实测

本文介绍了在SpringBoot项目中,使用RedisTemplate进行大数据量写入Redis时,对比常规操作与pipelined操作的性能差异。实测显示,pipelined方式性能远超常规方式,主要原因是pipelined减少了连接获取次数并采用了异步非阻塞IO,从而大幅提升效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近项目上有写入大量数据到 redis 中的需求,使用的是 springboot 集成 redis 客户端,就少不了使用 RedisTemplate 来操作。由于数据量比较多,是需要考虑写入性能问题的,如何才能高效写入到 redis 中呢?通过度娘知道了使用 pipelined 方式性能非常好,但是却没有解释为什么?带着这个疑惑进行了这次的实测。

环境

  • redis:使用本机 docker 启动的单节点服务
  • springboot 框架集成 redis 客户端

实测

RedisTemplate 的操作 api 有两种:

  1. 常规操作 API
  2. 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
@Async("asyncServiceExecutor") public void cleanUpLiveRoomData() { log.info("cleanUpLiveRoomData is start"); //获取不是正在直播的数据 Map<Long, Long> notLivingRoomIdMaps = liveRoomDatService.getNotLivingRoomIds(); if (CollectionUtil.isEmpty(notLivingRoomIdMaps)) { return; } Set<Long> notLivingRoomIds = notLivingRoomIdMaps.keySet(); //批量删除历史消息 liveMessageService.cleanLiveMessage(notLivingRoomIds); //清除待审核消息, 批量操作, 异步操作 liveMessageService.cleanLiveAuditMessage(notLivingRoomIds); //清除直播间数据看板数据,异步操作 assistantDashboardDatService.deleteAssistantDashboardByRoomIds(notLivingRoomIds); //批量清除redis中存储的人员列表数据, 异步处理 CompletableFuture.runAsync(()->{ // 生成需要删除的 key 列表 List<String> keysToDelete = new ArrayList<>(); for (Long roomId : notLivingRoomIds) { Long clientId = notLivingRoomIdMaps.get(roomId); if (roomId != null) { // 生成 status 为 1 和 2 的 key String keyWithStatus1 = RedisKeyConstant.getOnMemberList(clientId, roomId, CallbackOnMemberStateChangeEnum.ONLINE.getMsg()); String keyWithStatus2 = RedisKeyConstant.getOnMemberList(clientId, roomId, CallbackOnMemberStateChangeEnum.OFFLINE.getMsg()); keysToDelete.add(keyWithStatus1); keysToDelete.add(keyWithStatus2); } } List<List<String>> split = ListUtil.split(keysToDelete, 100); split.forEach(item -> { try { boolean delBatch = redisService.delBatch(item); log.info("delete is {}", delBatch); }catch (Exception e) { log.error("delete error", e); } }); }); }现在优化意见呢
最新发布
03-08
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值