redisTemplet如何批量插入数据

    之前已经写过一篇关于SpringBoot如何配置Redis的文章:SpringBoot如何配置Redis。但是在应用中遇到一个问题,批量插入数据时,当数据量过大时(大概6W+条数据),如果循环对每条数据使用set或者mset操作,需要时间非常长,查看源码发现使用RedisTemlate进行基本操作时,每次操作都需要拿到connection然后再进行操作,由于redis是单线程的,下一次请求必须等待上一次请求执行完成后才能继续执行,所以批量操作时就会很慢。

DefaultHashOperations中put实现:

public void put(K key, HK hashKey, HV value) {
        final byte[] rawKey = this.rawKey(key);
        final byte[] rawHashKey = this.rawHashKey(hashKey);
        final byte[] rawHashValue = this.rawHashValue(value);
        this.execute(new RedisCallback<Object>() {
            public Object doInRedis(RedisConnection connection) {
                connection.hSet(rawKey, rawHashKey, rawHashValue);
                return null;
            }
        }, true);
    }

DefaultHashOperations中set实现

public void set(K key, V value) {
        final byte[] rawValue = this.rawValue(value);
        this.execute(new AbstractOperations<K, V>.ValueDeserializingRedisCallback(key) {
            protected byte[] inRedis(byte[] rawKey, RedisConnection connection) {
                connection.set(rawKey, rawValue);
                return null;
            }
        }, true);
    }

      所以就在网上找有没有相关的解决方案,网上找到了使用jedis使用pipeline的方案,使用pipeline可以通过客户端一次发送多个请求,无需等待服务端返回,这样就能大大减少交互的时间,提高系统性能,这种方案确实可以解决问题,插入6W+条数据大概1s左右就可以插入,但是代码看着很别扭,因为使用了需要使用两套redis配置,为了让代码看着更统一,在想redisTemplate是否提供了pipeline的方式,果然redisTemplate是提供pipeline了相关接口:

public List<Object> executePipelined(RedisCallback<?> action) {
        return this.executePipelined(action, this.valueSerializer);
    }

public List<Object> executePipelined(final RedisCallback<?> action, final RedisSerializer<?> resultSerializer) {
        return (List)this.execute(new RedisCallback<List<Object>>() {
            public List<Object> doInRedis(RedisConnection connection) throws DataAccessException {
                connection.openPipeline();
                boolean pipelinedClosed = false;

                List var5;
                try {
                    Object result = action.doInRedis(connection);
                    if (result != null) {
                        throw new InvalidDataAccessApiUsageException("Callback cannot return a non-null value as it gets overwritten by the pipeline");
                    }

                    List<Object> closePipeline = connection.closePipeline();
                    pipelinedClosed = true;
                    var5 = RedisTemplate.this.deserializeMixedResults(closePipeline, resultSerializer, RedisTemplate.this.hashKeySerializer, RedisTemplate.this.hashValueSerializer);
                } finally {
                    if (!pipelinedClosed) {
                        connection.closePipeline();
                    }

                }

                return var5;
            }
        });
    }

可以看到在executePipelined方法中,使用了pipeline方式,其中的操作逻辑在action.doInRedis(connection),所以需要我们自定义一个RedisCallback的接口实现类,并且实现doInRedis方法,在该方法中实现我们自己的逻辑,主要是对redis的操作,例如:

private void batchCacheMarketInfo(List<CarSourceMarketInfo> dataList, long expire) {
        //使用pipeline方式
        redisTemplate.executePipelined(new RedisCallback<List<Object>>() {
            @Override
            public List<Object> doInRedis(RedisConnection connection) throws DataAccessException {
                for (CarSourceMarketInfo marketInfo : dataList) {
                    String key = MARKET + "#" + marketInfo.getCityId() + "#" + marketInfo.getTagId();
                    byte[] rawKey = redisTemplate.getKeySerializer().serialize(key);
                    connection.setEx(rawKey, expire, redisTemplate.getValueSerializer().serialize(marketInfo));
                }
                return null;
            }
        });

    }

这样就能使用redisTemplate实现pipeline的操作了。其实使用redisTemplate和jedis的思路类似,都是开启了pipeline,然后在进行数据的操作。

并不是所有场景都适合使用pipeline方式,有些系统可能对可靠性要求很高,每次操作都需要立马知道这次操作是否成功,是否数据已经写进redis了,这种场景就不适合了。像我这种需求就是对实时性没有那么强,对每条数据不需要马上知道结果,所以比较适用。

 



  • 4
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值