解决方式:使用线程池+队列

项目基于Spring,如果不用spring需要自己把

ThreadPoolManager.java

改成单例模式

1.写一个Controller(Spring mvc)

/**
* @author HeyS1
* @date 2016/12/1
* @description
*/
@Controller
public class ThreadPoolController {
@Autowired
ThreadPoolManager tpm; @RequestMapping("/pool")
public
@ResponseBody
Object test() {
for (int i = 0; i < 500; i++) {
  //模拟并发500条记录
tpm.processOrders(Integer.toString(i));
} return "ok";
}
}

2.线程池管理

/**
* @author HeyS1
* @date 2016/12/1
* @description threadPool订单线程池, 处理订单
* scheduler 调度线程池 用于处理订单线程池由于超出线程范围和队列容量而不能处理的订单
*/
@Component
public class ThreadPoolManager implements BeanFactoryAware {
private static Logger log = LoggerFactory.getLogger(ThreadPoolManager.class);
private BeanFactory factory;//用于从IOC里取对象
// 线程池维护线程的最少数量
private final static int CORE_POOL_SIZE = 2;
// 线程池维护线程的最大数量
private final static int MAX_POOL_SIZE = 10;
// 线程池维护线程所允许的空闲时间
private final static int KEEP_ALIVE_TIME = 0;
// 线程池所使用的缓冲队列大小
private final static int WORK_QUEUE_SIZE = 50;
// 消息缓冲队列
Queue<Object> msgQueue = new LinkedList<Object>(); //用于储存在队列中的订单,防止重复提交
Map<String, Object> cacheMap = new ConcurrentHashMap<>(); //由于超出线程范围和队列容量而使执行被阻塞时所使用的处理程序
final RejectedExecutionHandler handler = new RejectedExecutionHandler() {
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
//System.out.println("太忙了,把该订单交给调度线程池逐一处理" + ((DBThread) r).getMsg());
msgQueue.offer(((DBThread) r).getMsg());
}
}; // 订单线程池
final ThreadPoolExecutor threadPool = new ThreadPoolExecutor(
CORE_POOL_SIZE, MAX_POOL_SIZE, KEEP_ALIVE_TIME,
TimeUnit.SECONDS, new ArrayBlockingQueue(WORK_QUEUE_SIZE), this.handler); // 调度线程池。此线程池支持定时以及周期性执行任务的需求。
final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(5); // 访问消息缓存的调度线程,每秒执行一次
// 查看是否有待定请求,如果有,则创建一个新的AccessDBThread,并添加到线程池中
final ScheduledFuture taskHandler = scheduler.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
if (!msgQueue.isEmpty()) {
if (threadPool.getQueue().size() < WORK_QUEUE_SIZE) {
System.out.print("调度:");
String orderId = (String) msgQueue.poll();
DBThread accessDBThread = (DBThread) factory.getBean("dBThread");
accessDBThread.setMsg(orderId);
threadPool.execute(accessDBThread);
}
// while (msgQueue.peek() != null) {
// }
}
}
}, 0, 1, TimeUnit.SECONDS); //终止订单线程池+调度线程池
public void shutdown() {
//true表示如果定时任务在执行,立即中止,false则等待任务结束后再停止
System.out.println(taskHandler.cancel(false));
scheduler.shutdown();
threadPool.shutdown();
} public Queue<Object> getMsgQueue() {
return msgQueue;
} //将任务加入订单线程池
public void processOrders(String orderId) {
if (cacheMap.get(orderId) == null) {
cacheMap.put(orderId,new Object());
DBThread accessDBThread = (DBThread) factory.getBean("dBThread");
accessDBThread.setMsg(orderId);
threadPool.execute(accessDBThread);
}
} //BeanFactoryAware
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
factory = beanFactory;
}
}

3.线程池中工作的线程

//线程池中工作的线程
@Component
@Scope("prototype")//spring 多例
public class DBThread implements Runnable {
private String msg;
private Logger log = LoggerFactory.getLogger(DBThread.class); @Autowired
SystemLogService systemLogService; @Override
public void run() {
//模拟在数据库插入数据
Systemlog systemlog = new Systemlog();
systemlog.setTime(new Date());
systemlog.setLogdescribe(msg);
//systemLogService.insert(systemlog);
log.info("insert->" + msg);
} public String getMsg() {
return msg;
} public void setMsg(String msg) {
this.msg = msg;
}
}

浏览器输入地址127.0.0.1/pool

几秒后关闭tomcat。

模拟500条数据,订单线程池处理了117条。调度线程池处理5条

关闭tomcat,后还有378条未处理(这里的实现需要用到spring监听器)。加起来一共500

OK。完毕

spring监听器,监听tomcat关闭事件:

public class MyApplicationListener implements ApplicationListener<ApplicationEvent> {

    @Autowired
ThreadPoolManager threadPoolManager; @Override
public void onApplicationEvent(ApplicationEvent event) { if (event instanceof ContextClosedEvent) {
XmlWebApplicationContext x = (XmlWebApplicationContext) event.getSource();
//防止执行两次。root application context 没有parent,他就是老大
if (x.getDisplayName().equals("Root WebApplicationContext")) {
threadPoolManager.shutdown();
Queue q = threadPoolManager.getMsgQueue();
System.out.println("关闭了服务器,还有未处理的信息条数:" + q.size());
} } else if (event instanceof ContextRefreshedEvent) {
// System.out.println(event.getClass().getSimpleName()+" 事件已发生!");
} else if (event instanceof ContextStartedEvent) {
// System.out.println(event.getClass().getSimpleName()+" 事件已发生!");
} else if (event instanceof ContextStoppedEvent) {
// System.out.println(event.getClass().getSimpleName()+" 事件已发生!");
} else {
// System.out.println("有其它事件发生:"+event.getClass().getName());
}
}
}

spring配置一下

<bean id="springStartListener" class="com.temp.MyApplicationListener"></bean>

javaWeb 使用线程池+队列解决"订单并发"问题的更多相关文章

  1. 线程池 队列 synchronized

    线程池 BlockingQueue synchronized volatile 本章从线程池到阻塞队列BlockingQueue.从BlockingQueue到synchronized 和 volat ...

  2. 基于Django的乐观锁与悲观锁解决订单并发问题的一点浅见

    订单并发这个问题我想大家都是有一定认识的,这里我说一下我的一些浅见,我会尽可能的让大家了解如何解决这类问题. 在解释如何解决订单并发问题之前,需要先了解一下什么是数据库的事务.(我用的是mysql数据 ...

  3. 使用线程池测试cpu的并发计算能力

    接到一个需求是测试一下cpu并发计算能力,针对int和float求和单位时间能执行几次的问题.可能是服务器选型用到的参数. 开始使用的是fork-join,但是发现fork-join每次得到的结果值波 ...

  4. 【重学Java】多线程进阶(线程池、原子性、并发工具类)

    线程池 线程状态介绍 当线程被创建并启动以后,它既不是一启动就进入了执行状态,也不是一直处于执行状态.线程对象在不同的时期有不同的状态.那么Java中的线程存在哪几种状态呢?Java中的线程 状态被定 ...

  5. Java线程池队列吃的太饱,撑着了咋整?java 队列过大导致内存溢出

    Java的Executors框架提供的定长线程池内部默认使用LinkedBlockingQueue作为任务的容器,这个队列是没有限定大小的,可以无限向里面submit任务. 当线程池处理的太慢的时候, ...

  6. 踩坑 Spring Cloud Hystrix 线程池队列配置

    背景: 有一次在生产环境,突然出现了很多笔还款单被挂起,后来排查原因,发现是内部系统调用时出现了Hystrix调用异常.在开发过程中,因为核心线程数设置的比较大,没有出现这种异常.放到了测试环境,偶尔 ...

  7. Redis分布式队列解决文件并发的问题

    1.首先将捕获的异常写到Redis的队列中 public class MyExceptionAttribute : HandleErrorAttribute { public static IRedi ...

  8. 自定义ThreadPoolExecutor带Queue缓冲队列的线程池 + JMeter模拟并发下单请求

    .原文:https://blog.csdn.net/u011677147/article/details/80271174 拓展: https://github.com/jwpttcg66/GameT ...

  9. Java并发编程-并发工具类及线程池

    JUC中提供了几个比较常用的并发工具类,比如CountDownLatch.CyclicBarrier.Semaphore. CountDownLatch: countdownlatch是一个同步工具类 ...

随机推荐

  1. JQuery------图片幻灯片插件

    下载地址: http://www.jq22.com/jquery-info36

  2. log4j2设置日志文件读写权限(filePermissions)

    spring-boot使用log4j2作为日志插件的时候需要设置日志文件的读写权限,可以File 上增加filePermissions,如: <File name="File" ...

  3. hdu4525

    可以发现天的操作相当于*(k1+k2) 然后就很好判断了. 威威猫系列故事——吃鸡腿 Time Limit: 3000/1000 MS (Java/Others)    Memory Limit: 6 ...

  4. IOS模拟器

    IOS模拟器 目录 概述 实用操作 概述 实用操作 快速删除大量程序的方式 菜单栏 -> Reset Contain And Settings 或者:直接删除模拟器应用里面的想要去除的应用程序的 ...

  5. [SharePoint 2010] Visual Studio 2010內撰寫視覺化WebPart超簡單

    新一代的Visual Studio 2010對於SharePoint 2010的專案撰寫,有非常另人讚賞的改進. 以往寫一個WebPart要搞好多雜七雜八的步驟,也要硬寫HTML輸出,當然有人說可以寫 ...

  6. Maven开发系统

    Maven的优点: 自动从互联网中获取jar包,并实现了一步构建. pom.xml的配置 依赖管理(导入对应的jar包) 通过坐标(定位到仓库中的包的位置,并将jar包导入到项目中,如果版本升级,只需 ...

  7. Leetcode-Bianry Tree Maximum Path Sum

    Given a binary tree, find the maximum path sum. The path may start and end at any node in the tree. ...

  8. 160229-02、Sublime Text 3 快捷键总结

    选择类 Ctrl+D 选中光标所占的文本,继续操作则会选中下一个相同的文本. Alt+F3 选中文本按下快捷键,即可一次性选择全部的相同文本进行同时编辑.举个栗子:快速选中并更改所有相同的变量名.函数 ...

  9. Java基础之MySQL数据库与JDBC

    一.数据库 DBMS         数据库管理系统 是由多个程序构成的专门用来管理大量数据的计算机系统 Server       提供数据存储.检索.计算等服务的网络程序+系统服务 Notifier ...

  10. jQuery Mobile 总结

    转载  孟祥月 博客 http://blog.cshttp://blog.csdn.net/mengxiangyue/article/category/1313478/2dn.http://blog. ...