---
title: "性能调优记录"
author: "dingjun1"
date: "2012-06-13T21:35:06Z"
tags: []
categories: ["企业架构"]
slug: "untitled"
draft: false
lastmod: "2012-06-13T21:35:06Z"
id: 1560286
url: "https://dingjun1.iteye.com/blog/1560286"
---

背景：
    最近需要开一个10分钟一期的彩种，需要测试下往第三方出票的速度、获取中奖名单和算奖比对执行时间，10分钟一期对性能要求比较高

出票优化：
    1、一次查询多票，开多线程并发投注。
    2、一次投注传输多票
    3、支付后启用消息驱动投注，为了保险会有一个定时任务扫描表往投注队列中补充遗漏的记录

获取中奖名单：
    按照习惯，开始我还以为是FOR循环中多次数据库交互是主要瓶颈，改造成批量后，由于按主键取，速度很快，并没有什么改进，分析日志，从第三方接口取名单会比较慢，交互185次，取了9205条记录，费时1分钟多钟，需要改成并发去取名单


算奖：
    还是开多线程进行算奖比对。

主要收获：
    如果按主键取记录，并没有我原来想象的那么慢，实际测试了一下

|单次取100条时间（ms）|循环100次（ms）|取单条（ms）|
|143,|565,|6|
|121,|571,|6|
|115,|778,|6|

100次相差5倍，但是还是在毫秒级，优化并不会效果明显。

多线程算奖代码：

```java


private void concurrentCalPrize(final LotteryIssue issue,final Collection<Long> orderIds){
    	if(orderIds == null || orderIds.isEmpty()){
    		return ;
    	}
    	
    	final CountDownLatch latch = new CountDownLatch(orderIds.size());

    	ExecutorService service = new ThreadPoolExecutor(5,5,100,TimeUnit.SECONDS,new LinkedBlockingQueue<Runnable>(Integer.MAX_VALUE));
    	 for (final long jdorderId : orderIds) {
	    	service.execute(new Runnable(){public void run(){
	    		try{
	    			calOrderPrize(issue,jdorderId);
	    		}catch(Exception e){
	    			log.error("",e);
	    		}finally{
	    			latch.countDown();
	    		}
	    	}});
    	 }
    	 
		try {
			latch.await();
		} catch (InterruptedException e) {
			log.error("", e);
		}
		try {
		service.awaitTermination(5, TimeUnit.SECONDS);
		} catch (InterruptedException e) {
			log.error("", e);
		}
		service.shutdown();
    }

```