经常有这样一种需求
批量异步写数据库.
比如满50个对象,批量写入数据库.
或者每5秒,写一次.防止业务低峰由于数量不够,导致不能及时入库的问题.
原来做的比较呆板.
生产者每5秒,会向队列中put一种特殊类型的对象.(假如这种对象叫做 pBlock,普通对象叫做oBlock)
消费者从队列中获取信息,满50个oBlock写入.如果收到的是pBlock,则无论现在收到多少oBlock,都写入数据库.
这种方式呆板,是因为生产者和消费者的程序有耦合.
今天发现有一个新方式,感觉挺新颖.
-
import java.util.ArrayList;
-
import java.util.List;
-
import java.util.concurrent.BlockingQueue;
-
import java.util.concurrent.LinkedBlockingQueue;
-
import java.util.concurrent.TimeUnit;
-
-
import com.google.common.collect.Queues;
-
-
public class T {
-
public static void main(String[] args) {
-
final BlockingQueue<Long> q = new LinkedBlockingQueue<Long>();
-
-
new Thread(new Runnable(){
-
-
public void run() {
-
long num=1L;
-
while(true)
-
{
-
try {
-
System.out.println(num);
-
q.put(num);
-
num++;
-
Thread.sleep(1000);
-
} catch (InterruptedException e) {
-
e.printStackTrace();
-
}
-
}
-
}}).start();
-
-
while (true) {
-
try {
-
List<Long> l = new ArrayList<Long>(10);
-
Queues.drain(q, l, 10, 5, TimeUnit.SECONDS);
-
System.out.println(l);
-
} catch (InterruptedException e) {
-
e.printStackTrace();
-
}
-
}
-
}
-
}
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/29254281/viewspace-2120130/
,如需转载,请注明出处,否则将追究法律责任。