RedisTemplate pipline

when a job need to update alot redis k/v
use normal command loop is low efficiency plan
that cause tcp connection time-wait exceed several ten thousand.
so we use redis pipline operation merge command connection.

Use RedisTemplate read obj

Set User class deserializer first

1
2
private static final Jackson2JsonRedisSerializer userSerializer = new Jackson2JsonRedisSerializer(User.class);
redisTemplate.setValueSerializer(userSerializer);

pip execute multi get command

1
2
3
4
5
6
7
8
List<User> result = redisTemplate.executePipelined(new RedisCallback<List<User>>() {
@Override
public List<User> doInRedis(RedisConnection connection) throws DataAccessException {
for (Object obj: keys)
connection.get((RedisConstant.USER + obj).getBytes());
return null;
}
}, redisTemplate.getValueSerializer());

Use RedisTemplate write obj

Same as above use User class serializer first

1
2
private static final Jackson2JsonRedisSerializer userSerializer = new Jackson2JsonRedisSerializer(User.class);
userSerializer.serialize(user);

pip execute multi set command

1
2
3
4
5
6
7
8
redisTemplate.executePipelined(new RedisCallback<List>() {
@Override
public List doInRedis(RedisConnection connection) throws DataAccessException {
for (Map.Entry<byte[], byte[]> entry : map.entrySet())
connection.set(entry.getKey(), entry.getValue());
return null;
}
});

Caution

  1. connection return is byte array, it need deserializer method.
  2. doInRedis return must be null, the return value has been take over by executePipelined.

    1
    2
    3
    if (result != null)
    throw new InvalidDataAccessApiUsageException(
    "Callback cannot return a non-null value as it gets overwritten by the pipeline");
  3. don’t call connection.closePipeline(), it will return result and no deserialize.

  4. Deserialize need deserializer object. like these
    QQ20181006095747.png

https://blog.csdn.net/xiaoliu598906167/article/details/82218525
https://blog.csdn.net/huilixiang/article/details/19484921
https://blog.csdn.net/xiaolyuh123/article/details/78682200
https://my.oschina.net/yuyidi/blog/499951
https://www.cnblogs.com/EasonJim/p/7803067.html#autoid-2-6-0