赞
踩
最近有个项目需要开发一个预约系统,系统涉及到发送短信验证码;一般用户点击发送验证码,发送请求到后端后,调用短信接口,成功后就返回响应的状态码给用户;但是这样的过程,有时候会因为短信接口响应慢,而导致前端响应慢;所以这里需要做一个简单的优化,当用户点击发送短信时,将我们的短信调用放入一个队列中,放入之后,即给前端响应;后面通过阻塞队列,取出队列内容,进行短信发送即可,这样可以更好的提升系统的性能和用户体验度;
public class MessageProducer implements Runnable { private BlockingQueue<String> queue; private String phone; public MessageProducer(BlockingQueue<String> queue, String phone) { this.queue = queue; this.phone = phone; } @Override public void run() { try { queue.put(phone); System.out.println("手机号码:" + phone); } catch (InterruptedException e) { e.printStackTrace(); } } }
public class MessageConsumer implements Runnable { private BlockingQueue<String> queue; public MessageConsumer(BlockingQueue<String> queue) { this.queue = queue; } @Override public void run() { while (true) { System.out.println("等待中------------"); try { String phone = queue.take(); System.out.println("发送短信:" + phone); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("处理完成------------"); } } }
public static void main(String[] args) {
LinkedBlockingQueue<String> queue=new LinkedBlockingQueue<String>(10);
ExecutorService executorService = Executors.newCachedThreadPool();
executorService.submit(new MessageConsumer(queue));
for (int i=0;i<6;i++){
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
executorService.submit(new MessageProducer(queue,"消费者"+i));
}
}
结果:
当队列中没有消息时,它就会一直进行阻塞
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。