ITPub博客

首页 > 应用开发 > Java > 通过队列实现批量处理

通过队列实现批量处理

原创 Java 作者:壹頁書 时间:2016-06-14 17:21:40 0 删除 编辑
经常有这样一种需求
批量异步写数据库.
比如满50个对象,批量写入数据库.
或者每5秒,写一次.防止业务低峰由于数量不够,导致不能及时入库的问题.

原来做的比较呆板.
生产者每5秒,会向队列中put一种特殊类型的对象.(假如这种对象叫做 pBlock,普通对象叫做oBlock)
消费者从队列中获取信息,满50个oBlock写入.如果收到的是pBlock,则无论现在收到多少oBlock,都写入数据库.
这种方式呆板,是因为生产者和消费者的程序有耦合.

今天发现有一个新方式,感觉挺新颖.
  1. import java.util.ArrayList;  
  2. import java.util.List;  
  3. import java.util.concurrent.BlockingQueue;  
  4. import java.util.concurrent.LinkedBlockingQueue;  
  5. import java.util.concurrent.TimeUnit;  
  6.   
  7. import com.google.common.collect.Queues;  
  8.   
  9. public class T {  
  10.     public static void main(String[] args) {  
  11.         final BlockingQueue<Long> q = new LinkedBlockingQueue<Long>();  
  12.           
  13.         new Thread(new Runnable(){  
  14.   
  15.             public void run() {  
  16.                 long num=1L;  
  17.                 while(true)  
  18.                 {  
  19.                     try {  
  20.                         System.out.println(num);  
  21.                         q.put(num);  
  22.                         num++;  
  23.                         Thread.sleep(1000);  
  24.                     } catch (InterruptedException e) {  
  25.                         e.printStackTrace();  
  26.                     }  
  27.                 }  
  28.             }}).start();  
  29.           
  30.         while (true) {  
  31.             try {  
  32.                 List<Long> l = new ArrayList<Long>(10);  
  33.                 Queues.drain(q, l, 10, 5, TimeUnit.SECONDS);  
  34.                 System.out.println(l);  
  35.             } catch (InterruptedException e) {  
  36.                 e.printStackTrace();  
  37.             }  
  38.         }  
  39.     }  
  40. }  


来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/29254281/viewspace-2120130/ ,如需转载,请注明出处,否则将追究法律责任。

上一篇: 常见的排序算法
下一篇: MySQL存储过程
请登录后发表评论 登录
全部评论

注册时间:2013-10-19

  • 博文量
    620
  • 访问量
    6339954