javaweb使用线程池 队列解决订单并发问题.docx
- 文档编号:26001459
- 上传时间:2023-06-17
- 格式:DOCX
- 页数:8
- 大小:16.90KB
javaweb使用线程池 队列解决订单并发问题.docx
《javaweb使用线程池 队列解决订单并发问题.docx》由会员分享,可在线阅读,更多相关《javaweb使用线程池 队列解决订单并发问题.docx(8页珍藏版)》请在冰豆网上搜索。
javaweb使用线程池队列解决订单并发问题
javaweb使用线程池+队列解决“订单并发”问题
遇到问题:
最近做微信支付,项目上线一阵,发现一个问题。
有一条订单流水居然在数据库的出现两次。
这个问题非常严重。
查看微信回调系统的接口代码发现代码是没错的(正常情况下),而这次遇到非正常情况了
原因:
微信支付成功后回调我们系统接口在极短时间回调了2次,微信官方文档说明了,是最短15s回调一次。
前几天微信支付抽风了,可能业务出现了波动。
简单来说就是在并发情况下没有做数据唯一性处理,不管怎么样这类并发情况都是有必要的处理。
解决方式:
使用线程池+队列
项目基于Spring,如果不用spring需要自己把
ThreadPoolManager.java
改成单例模式
1.写一个Controller(Springmvc)
/**
*@authorHeyS1
*@date2016/12/1
*@description
*/
@Controller
publicclassThreadPoolController{
@Autowired
ThreadPoolManagertpm;
@RequestMapping("/pool")
public
@ResponseBody
Objecttest(){
for(inti=0;i<500;i++){
//模拟并发500条记录
tpm.processOrders(Integer.toString(i));
}
return"ok";
}
}
2.线程池管理
/**
*@authorHeyS1
*@date2016/12/1
*@descriptionthreadPool订单线程池,处理订单
*scheduler调度线程池用于处理订单线程池由于超出线程范围和队列容量而不能处理的订单
*/
@Component
publicclassThreadPoolManagerimplementsBeanFactoryAware{
privatestaticLoggerlog=LoggerFactory.getLogger(ThreadPoolManager.class);
privateBeanFactoryfactory;//用于从IOC里取对象
//线程池维护线程的最少数量
privatefinalstaticintCORE_POOL_SIZE=2;
//线程池维护线程的最大数量
privatefinalstaticintMAX_POOL_SIZE=10;
//线程池维护线程所允许的空闲时间
privatefinalstaticintKEEP_ALIVE_TIME=0;
//线程池所使用的缓冲队列大小
privatefinalstaticintWORK_QUEUE_SIZE=50;
//消息缓冲队列
Queue<Object>msgQueue=newLinkedList<Object>();
//用于储存在队列中的订单,防止重复提交
Map<String,Object>cacheMap=newConcurrentHashMap<>();
//由于超出线程范围和队列容量而使执行被阻塞时所使用的处理程序
finalRejectedExecutionHandlerhandler=newRejectedExecutionHandler(){
@Override
publicvoidrejectedExecution(Runnabler,ThreadPoolExecutorexecutor){
//System.out.println("太忙了,把该订单交给调度线程池逐一处理"+((DBThread)r).getMsg());
msgQueue.offer(((DBThread)r).getMsg());
}
};
//订单线程池
finalThreadPoolExecutorthreadPool=newThreadPoolExecutor(
CORE_POOL_SIZE,MAX_POOL_SIZE,KEEP_ALIVE_TIME,
TimeUnit.SECONDS,newArrayBlockingQueue(WORK_QUEUE_SIZE),this.handler);
//调度线程池。
此线程池支持定时以及周期性执行任务的需求。
finalScheduledExecutorServicescheduler=Executors.newScheduledThreadPool(5);
//访问消息缓存的调度线程,每秒执行一次
//查看是否有待定请求,如果有,则创建一个新的AccessDBThread,并添加到线程池中
finalScheduledFuturetaskHandler=scheduler.scheduleAtFixedRate(newRunnable(){
@Override
publicvoidrun(){
if(!
msgQueue.isEmpty()){
if(threadPool.getQueue().size()<WORK_QUEUE_SIZE){
System.out.print("调度:
");
StringorderId=(String)msgQueue.poll();
DBThreadaccessDBThread=(DBThread)factory.getBean("dBThread");
accessDBThread.setMsg(orderId);
threadPool.execute(accessDBThread);
}
//while(msgQueue.peek()!
=null){
//}
}
}
},0,1,TimeUnit.SECONDS);
//终止订单线程池+调度线程池
publicvoidshutdown(){
//true表示如果定时任务在执行,立即中止,false则等待任务结束后再停止
System.out.println(taskHandler.cancel(false));
scheduler.shutdown();
threadPool.shutdown();
}
publicQueue<Object>getMsgQueue(){
returnmsgQueue;
}
//将任务加入订单线程池
publicvoidprocessOrders(StringorderId){
if(cacheMap.get(orderId)==null){
cacheMap.put(orderId,newObject());
DBThreadaccessDBThread=(DBThread)factory.getBean("dBThread");
accessDBThread.setMsg(orderId);
threadPool.execute(accessDBThread);
}
}
//BeanFactoryAware
@Override
publicvoidsetBeanFactory(BeanFactorybeanFactory)throwsBeansException{
factory=beanFactory;
}
}
3.线程池中工作的线程
//线程池中工作的线程
@Component
@Scope("prototype")//spring多例
publicclassDBThreadimplementsRunnable{
privateStringmsg;
privateLoggerlog=LoggerFactory.getLogger(DBThread.class);
@Autowired
SystemLogServicesystemLogService;@Override
publicvoidrun(){
//模拟在数据库插入数据
Systemlogsystemlog=newSystemlog();
systemlog.setTime(newDate());
systemlog.setLogdescribe(msg);
//systemLogService.insert(systemlog);
log.info("insert->"+msg);
}
publicStringgetMsg(){
returnmsg;
}
publicvoidsetMsg(Stringmsg){
this.msg=msg;
}
}
浏览器输入地址127.0.0.1/pool
几秒后关闭tomcat。
模拟500条数据,订单线程池处理了117条。
调度线程池处理5条
关闭tomcat,后还有378条未处理(这里的实现需要用到spring监听器)。
加起来一共500
OK。
完毕
spring监听器,监听tomcat关闭事件:
publicclassMyApplicationListenerimplementsApplicationListener<ApplicationEvent>{
@Autowired
ThreadPoolManagerthreadPoolManager;
@Override
publicvoidonApplicationEvent(ApplicationEventevent){
if(eventinstanceofContextClosedEvent){
XmlWebApplicationContextx=(XmlWebApplicationContext)event.getSource();
//防止执行两次。
rootapplicationcontext没有parent,他就是老大
if(x.getDisplayName().equals("RootWebApplicationContext")){
threadPoolManager.shutdown();
Queueq=threadPoolManager.getMsgQueue();
System.out.println("关闭了服务器,还有未处理的信息条数:
"+q.size());
}
}elseif(eventinstanceofContextRefreshedEvent){
//System.out.println(event.getClass().getSimpleName()+"事件已发生!
");
}elseif(eventinstanceofContextStartedEvent){
//System.out.println(event.getClass().getSimpleName()+"事件已发生!
");
}elseif(eventinstanceofContextStoppedEvent){
//System.out.println(event.getClass().getSimpleName()+"事件已发生!
");
}else{
//System.out.println("有其它事件发生:
"+event.getClass().getName());
}
}
}
spring配置一下
<beanid="springStartListener"class="com.temp.MyApplicationListener"></bean>
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- javaweb使用线程池 队列解决订单并发问题 javaweb 使用 线程 队列 解决 订单 并发 问题