评论走起

批量插入redis

最近有个批量插入redis的需求,网上找了一下,自己如下写

批量插入redis,避免频繁的连接redis

@GetMapping("batchSet")
    @ResponseBody
    public Object batchSet(){
        List<String> strings = new ArrayList<>();
        int start = 40040072;
        for (int i = 0;i<1000;i++){
            strings.add(String.valueOf(start));
            start++;
        }
        String key = "chenweidong";
        // 获取key编码方式
        final RedisSerializer stringRedisSerializer =  stringRedisTemplate.getKeySerializer();
        final RedisSerializer valueSerializer =  stringRedisTemplate.getValueSerializer();
        //获取key对应的byte[]
        final byte[] rawKey = stringRedisSerializer.serialize(key);
        Stopwatch stopwatch = Stopwatch.createStarted();
        stringRedisTemplate.executePipelined(new RedisCallback() {

            @Override
            public Object doInRedis(RedisConnection redisConnection) throws DataAccessException {
                for(String s : strings){
                    redisConnection.sAdd(rawKey,valueSerializer.serialize(s));
                }
                redisConnection.close();
                return null;
            }
        });
        stopwatch.stop();
        logger.info(stopwatch.toString());
          return null;
    }

评论