今日份鸡汤:这个世界,除了贫穷和衰老可以毫不费力,其他你想要的一切,都需要拼命努力~
场景:
当你有很大一个List的时候,有时候业务处理时就需要将List拆分处理,比如你调用依赖方接口,Get请求中包含这个超长的List入参,这样请求URL就会出现过长的问题,所以可以使用Lists.partition进行分割。进而通过并发(parallelStream)来处理数据。结合Semaphore是为了控制并发量,以防依赖方接口不能支撑住很大并发量,使用Semaphore控制并发量以保证不给依赖方接口打死。
实现:
引入maven依赖
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>21.0</version>
</dependency>
引入这个依赖是因为需要导入这个包:
import com.google.common.collect.Lists;
来吧,上代码:
public class ListPartitionDemo {
public static void main(String[] args) {
Semaphore semaphore = new Semaphore(2);
List<String> list = new ArrayList<>();
for (int i = 0; i < 35 ; i ++) {
list.add(UUID.randomUUID().toString());
}
Lists.partition(list, 10).parallelStream().forEach(l -> {
try {
semaphore.acquire();
Thread.sleep(2000);
System.out.println(l);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
semaphore.release();
}
});
}
}
执行结果:
image.png