RedisTemplate每一次操作都会从连接池中获取链接然后释放,批量操作时,效率比较低,所以使用管道来解决此问题
List < String >
@Autowired
@Qualifier(value="strRedisTemplate")
private StringRedisTemplate strRedisTemplate;
/**
* 批量数据插入到redis中,不要使用单个插入,多个数据时,使用管道来节省网络链接的开销
*
* @param listKey 插入的Key
* @param lists 待插入的集合
*/
@Async("threadPoolTaskExecutor")
public void batchInsertStringListToRedis(String listKey,List<String> lists) {
long startTime=System.currentTimeMillis();
strRedisTemplate.executePipelined((RedisCallback<Object>) connection -> {
StringRedisConnection stringRedisConn=(StringRedisConnection) connection;
lists.forEach(bigDecimal -> stringRedisConn.lPush(listKey,bigDecimal));
return null;
});
log.info("Redis->batchInsertStringListToRedis批量插入耗时:{}",(System.currentTimeMillis() - startTime));
}
List < T >
/**
* RedisTemplate
*/
@Autowired
private RedisTemplate redisTemplate;
/**
* 批量插入数据到List集合中,重载泛型方法
*
* @param key listKeys
* @param list 集合信息
*/
@Async("threadPoolTaskExecutor")
public void batchInsertObjectListToRedis(String key,List<T> list) {
long startTime=System.currentTimeMillis();
redisTemplate.executePipelined(new SessionCallback<List<Object>>() {
@Override
public <K,V> List<Object> execute(final RedisOperations<K,V> operations) throws DataAccessException {
final BoundListOperations boundListOperations=operations.boundListOps((K) key);
if (!CollectionUtils.isEmpty(list)) {
list.stream().filter(t -> !ObjectUtils.isEmpty(t)).forEachOrdered(boundListOperations::leftPush);
}
return null;
}
});
log.info("Redis->batchInsertObjectListToRedis批量插入耗时:{}",(System.currentTimeMillis() - startTime));
}
Map<String,String>
/**
* RedisTemplate
*/
@Autowired
private RedisTemplate redisTemplate;
/**
* 批量数据插入到redis中,不要使用单个插入,多个数据时,使用管道来节省网络链接的开销
*
* @param mapKey mapKey
* @param all map集合
*/
@Async("threadPoolTaskExecutor")
public void batchInsertMapToRedis(String mapKey,Map<String,String> all) {
long startTime=System.currentTimeMillis();
strRedisTemplate.executePipelined((RedisCallback<Object>) connection -> {
StringRedisConnection stringRedisConn=(StringRedisConnection) connection;
all.forEach((key,value) -> stringRedisConn.hSet(mapKey,key,value));
return null;
});
log.info("Redis->batchInsertMapToRedis批量插入耗时:{}",(System.currentTimeMillis() - startTime));
}