有幸能支援新的项目组,今天有个需求前端传过来是多个商品编码,这里需要远程调用其他团队的远程服务,远程服务只能提供单个商品的查询,不支持批量的查询,所有需要我处理,今天使用了一个新的类,CountDownLatch,这个类之前有了解过,但是一直没有机会使用,这个也叫发令枪,这个每个线程去执行完后,等所有线程都执行完,再一起返回给客户端。
实现编码:
//多线程调用
ExecutorService executor = AbstractThreadExecuterService.getTe();
final CountDownLatch latch = new CountDownLatch(cmmList.size());
for (final String cmm : cmmList) {
executor.execute(new Runnable() {
@Override
public void run() {
try {
// to do ...
} catch (Exception e) {
LOGGER.error("信息异常", e);
} finally {
latch.countDown();
}
}
});
}
try {
latch.await();
} catch (InterruptedException e) {
LOGGER.error("多线程查询信息异常", e);
}
之前的项目中也有中批量的处理方式,使用BufferedAction
BufferedAction<Long> buffered = new BufferedAction<>(ids -> {
//批量处理
update(ids);
}, Long.class, 500);
try {
for (Long id : idList) {
buffered.doAction(id);
}
buffered.flush();
} catch (Exception e) {
log.error("批量更新异常", e);
}
package com.xg;
import java.io.IOException;
import java.lang.reflect.Array;
import java.util.Arrays;
public class BufferedAction<T> {
private int bufferSize;
private int next;
private T[] buffer;
private BufferedAction.Action<T> action;
public BufferedAction(BufferedAction.Action<T> action, Class<T> type, int bufferSize) {
this.action = action;
this.bufferSize = bufferSize;
this.buffer = (Object[])((Object[])Array.newInstance(type, bufferSize));
this.next = 0;
}
public void flush() throws BufferedAction.BatchedException {
this.flushBuffer();
}
public void doAction(T map) throws BufferedAction.BatchedException {
if (this.next >= this.bufferSize) {
this.flushBuffer();
}
this.buffer[this.next++] = map;
}
private void flushBuffer() throws BufferedAction.BatchedException {
if (this.next != 0) {
Object[] values = Arrays.copyOfRange(this.buffer, 0, this.next);
try {
this.action.action(values);
} catch (Exception var6) {
throw new BufferedAction.BatchedException(var6, values);
} finally {
this.next = 0;
}
}
}
public interface Action<T> {
void action(T[] var1) throws Exception;
}
public static class BatchedException extends IOException {
private static final long serialVersionUID = 1L;
private Object[] values;
public BatchedException(Exception cause, Object[] values) {
super(cause);
this.values = values;
}
public Object[] getValues() {
return this.values;
}
public void setValues(Object[] values) {
this.values = values;
}
}
}