使用RedisTemplate的PipeLine没有返回值原因分析

1、现象

背景: 想通过redis的key值进行去重,采取pipeLine批量向redis进行setNx,根据返回结果判断是否重复,但是却遇到了pipeLine没有返回值的情况。

测试代码:

private List<Boolean> test1() {
	List<Boolean> list = redisTemplate.executePipelined(new RedisCallback<Boolean>() {
		@Override
		public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
			for (int i = 0; i < 10; i++) {
				String key = "aaa" + i;
				connection.set(key.getBytes(), "1".getBytes(), Expiration.seconds(100L), RedisStringCommands.SetOption.ifAbsent());
			}

			/* 必须返回null,不然会抛异常 */
			return null;
		}
	});

	return list;
}

运行结果:
图1
图1
可以看到,返回值是一个空的数组,和想象中不太一致,而redisTemplate的executePipeline的返回值是一个列表,但是为什么返回的是一个空数组?

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

2、分析原因:SET操作的返回结果被RedissionConnection的filterResults方法过滤掉了

1、RedisTemplate的executePipelined方法源码

/*
* (non-Javadoc)
 * @see org.springframework.data.redis.core.RedisOperations#executePipelined(org.springframework.data.redis.core.RedisCallback)
 */
@Override
public List<Object> executePipelined(RedisCallback<?> action) {
	return executePipelined(action, valueSerializer);
}

/*
 * (non-Javadoc)
 * @see org.springframework.data.redis.core.RedisOperations#executePipelined(org.springframework.data.redis.core.RedisCallback, org.springframework.data.redis.serializer.RedisSerializer)
 */
@Override
public List<Object> executePipelined(RedisCallback<?> action, @Nullable RedisSerializer<?> resultSerializer) {

	return execute((RedisCallback<List<Object>>) connection -> {
		connection.openPipeline();
		boolean pipelinedClosed = false;
		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;
			return deserializeMixedResults(closePipeline, resultSerializer, hashKeySerializer, hashValueSerializer);
		} finally {
			if (!pipelinedClosed) {
				connection.closePipeline();
			}
		}
	});
}

进入executePipelined的源码,可以先看21行,这里的doInRedis就是在第一部分测试代码中匿名类中实现的doInRedis方法,从第22-25行,可以看出,如果所实现的doInRedis的返回结果不是null,则会抛出异常,显然,没有返回结果不是这个问题。
继续往下分析,可以看到第26行调用了RedissionConnection的closePipeline()方法,进入该方法的源码。

2、RedissionConnection的closePipeline方法源码

@Override
public List<Object> closePipeline() throws RedisPipelineException {
    if (isPipelined()) {
        CommandBatchService es = (CommandBatchService) executorService;
        try {
            BatchResult<?> result = es.execute();
            filterResults(result);
            if (isPipelinedAtomic()) {
                return Arrays.<Object>asList((List<Object>) result.getResponses());
            }
            return (List<Object>) result.getResponses();
        } catch (Exception ex) {
            throw new RedisPipelineException(ex);
        } finally {
            resetConnection();
        }
    }
    return Collections.emptyList();
}

在这部分的第7行,filterResults(result)是对返回结果的一个过滤,进入其源代码,

protected void filterResults(BatchResult<?> result) {
    int t = 0;
    for (Integer index : indexToRemove) {
        index -= t;
        result.getResponses().remove((int)index);
        t++;
    }
    for (ListIterator<Object> iterator = (ListIterator<Object>) result.getResponses().listIterator(); iterator.hasNext();) {
        Object object = iterator.next();
        if (object instanceof String) {
            iterator.set(((String) object).getBytes());
        }
    }
}

这部分代码中,2-7行是对返回结果的过滤,8-13行是对过滤后结果的赋值给result的迭代器。主要对返回结果产生影响的是2-7行,这里就需要弄清楚indexToRemove是什么?
图2
图2
从上图中可以看出,indexToRemove是RedissionConnection的私有成员变量,初始化是空数组,其在indexCommand方法中被赋值,

protected void indexCommand(RedisCommand<?> command) {
    if (isQueueing() || isPipelined()) {
        index++;
        if (commandsToRemove.contains(command.getName())) {
            indexToRemove.add(index);
        }
    }
}

indexCommand是对于将RedisCommand命令包含在commandsToRemove中的命令的index记录在indexToRemove中,
commandsToRemove所包含的命令那么indexCommand是在什么时候被使用的,一个是在read方法里,一个是在wirte方法里。

<T> T read(byte[] key, Codec codec, RedisCommand<?> command, Object... params) {
    RFuture<T> f = executorService.readAsync(key, codec, command, params);
    indexCommand(command);
    return sync(f);
}

<T> T write(byte[] key, Codec codec, RedisCommand<?> command, Object... params) {
    RFuture<T> f = executorService.writeAsync(key, codec, command, params);
    indexCommand(command);
    return sync(f);
}

而我们所测试代码中所使用的set方法,是调用的wirte方法,而且其对应的RedisCommand是SET,是被包含在commandsToRemove列表中的。也就是说,测试代码中每次的pipeLine命令都调用了一次wirte方法,其使用SET命令,于是在indexCommand方法中,每次命令的index都被记录到indexToRemove列表中。
在这里插入图片描述
图3
已经弄清楚了indexToRemove的值,再回去看filterResults方法的2-7行代码,这部分代码是将indexToRemove列表中所存第index个命令的返回值删掉,对于测试代码中的情况,也就是删除所有的返回结果,到这里也就解释清楚了为什么测试代码中没有想要的返回值了。

3、如何获取返回值

既然在commandsToRemove中的命令会被删除结果,那么就避开这些命令就可以了,但是从图3可以看出RedissionConnection的set方法最后都是使用的SET命令,也就是不可用,可以使用下面的代码进行实现:

private List<Boolean> test2() {
	List<Boolean> list = redisTemplate.executePipelined(new SessionCallback<Boolean>() {
		@Override
		public Boolean execute(RedisOperations operations) throws DataAccessException {
			for (int i = 0; i < 10; i++) {
				String key = "bbb" + i;
				operations.opsForValue().setIfAbsent(key, "1");
				operations.expire(key, 100, TimeUnit.SECONDS);
			}

			return null;
		}
	});

	return list;
}

为什么要把set和设置过期时间分开,看下面的DefaultValueOperations源代码就清楚了,不加过期时间的setIfAbsent调用的是RedissionConnection的setNx方法,其最终使用的是SETNX方法,不在commandsToRemove中;而加过期时间的setIfAbsent方法调用的是RedissionConnection的set方法,和第一部分测试代码一样,最终使用SET命令,返回结果会被删除。

/*
* (non-Javadoc)
 * @see org.springframework.data.redis.core.ValueOperations#setIfAbsent(java.lang.Object, java.lang.Object)
 */
@Override
public Boolean setIfAbsent(K key, V value) {

	byte[] rawKey = rawKey(key);
	byte[] rawValue = rawValue(value);
	return execute(connection -> connection.setNX(rawKey, rawValue), true);
}

/*
 * (non-Javadoc)
 * @see org.springframework.data.redis.core.ValueOperations#setIfAbsent(java.lang.Object, java.lang.Object, long, java.util.concurrent.TimeUnit)
 */
@Override
public Boolean setIfAbsent(K key, V value, long timeout, TimeUnit unit) {

	byte[] rawKey = rawKey(key);
	byte[] rawValue = rawValue(value);

	Expiration expiration = Expiration.from(timeout, unit);
	return execute(connection -> connection.set(rawKey, rawValue, expiration, SetOption.ifAbsent()), true);
}

但是这样会将发送给redis的命令增加一倍,同样redis的返回结果数量也增加了一倍。
也使用过ShardedJedis的pipeLine方法,但是无法解析其返回值Response,也就无法使用。
在这里插入图片描述
图4

各位大佬如有更好的解决方法,请指教

  • 4
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值