总结--异步线程、队列、函数式编程
需求:
将该方法的所有请求记录到数据库中,由于面向范围广(省市级),请求多(开机等)。
解决:
把所有进来的请求放到队列中慢慢消费(入库),多的就丢弃。
代码:
创建仓库类Storage实现缓冲区
1 public class Storage 2 { 3 /** 4 * 仓库最大存储量 5 */ 6 private final int MAX_SIZE = 300_0000; 7 8 /** 9 * 仓库存储的载体 10 */ 11 private LinkedBlockingQueue<AAA> list = new LinkedBlockingQueue<AAA>(); 12 13 public void produce(AAA aaa){ 14 // 如果仓库剩余容量为0 15 if (list.size() >= MAX_SIZE) { 16 System.out.println("【库存量】:" + MAX_SIZE + "/t暂时不能执行生产任务!"); 17 }else{ 18 try{ 19 // 放入产品,自动阻塞 20 list.put(aaa); 21 }catch (InterruptedException e){ 22 e.printStackTrace(); 23 } 24 25 } 26 } 27 33 public LinkedBlockingQueue<AAA> getList(){ 34 return list; 35 } 36 37 public void setList(LinkedBlockingQueue<AAA> list){ 38 this.list = list; 39 } 40 41 public int getMAX_SIZE(){ 42 return MAX_SIZE; 43 } 44 }
仓库单例
1 public class StorageSingleton { 2 3 private static class LazyHolder { 4 5 private static final Storage INSTANCE = new Storage(); 6 } 7 8 private StorageSingleton(){} 9 10 public static final Storage getInstance() { 11 return LazyHolder.INSTANCE; 12 } 13 14 }
消费者
1 public class Consumer extends Thread { 2 private AAAService aaaService; 3 4 private Storage storage = StorageSingleton.getInstance(); 5 6 private Executor executor; 7 8 public Consumer() { 9 // 逻辑CPU数 10 int processors = Runtime.getRuntime().availableProcessors(); 11 // 线程池 12 executor = new ThreadPoolExecutor(processors, processors*2+1, 60L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(50_0000), 13 new RejectedExecutionHandler() { 14 @Override 15 public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) { 16 System.out.println("System busy, task count: " + executor.getTaskCount()); 17 } 18 }); 19 } 20 21 @Override 22 public void run() { 23 24 try { 25 while (true) { 26 if (!storage.getList().isEmpty()) { 27 AAA aaa= storage.getList().take(); 28 executor.execute(() -> { 29 try { 30 aaaService.saveAAA(aaa); 31 } catch (Exception e) { 32 e.printStackTrace(); 33 } 34 }); 35 } 36 Thread.sleep(2); 37 } 38 } catch (Exception e) { 39 40 e.printStackTrace(); 41 } 42 } 43 44 public Storage getStorage() { 45 return storage; 46 } 47 48 public void setStorage(Storage storage) { 49 this.storage = storage; 50 } 51 52 public AAAService getAAAService() { 53 return aaaService; 54 } 55 56 public void setAAAService(AAAService aaaService) { 57 this.aaaService = aaaService; 58 } 59 60 }
储存时
1 StorageSingleton.getInstance().produce(aaa);