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 first1
2private static final Jackson2JsonRedisSerializer userSerializer = new Jackson2JsonRedisSerializer(User.class);
redisTemplate.setValueSerializer(userSerializer);
pip execute multi get command1
2
3
4
5
6
7
8List<User> result = redisTemplate.executePipelined(new RedisCallback<List<User>>() {
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 first1
2private static final Jackson2JsonRedisSerializer userSerializer = new Jackson2JsonRedisSerializer(User.class);
userSerializer.serialize(user);
pip execute multi set command1
2
3
4
5
6
7
8redisTemplate.executePipelined(new RedisCallback<List>() {
public List doInRedis(RedisConnection connection) throws DataAccessException {
for (Map.Entry<byte[], byte[]> entry : map.entrySet())
connection.set(entry.getKey(), entry.getValue());
return null;
}
});
Caution
connection
return is byte array, it need deserializer method.doInRedis
return must be null, the return value has been take over byexecutePipelined
.1
2
3if (result != null)
throw new InvalidDataAccessApiUsageException(
"Callback cannot return a non-null value as it gets overwritten by the pipeline");don’t call
connection.closePipeline()
, it will return result and no deserialize.- Deserialize need deserializer object. like these
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