天天看點

用心Coding之一spring中的多線程應用以及對象的autowared

記錄一次自己的代碼優化曆程,希望對大家有所幫助。

項目背景:系統A(可能多個)将自己收集到的資料傳送給系統B,系統B接收後進行業務處理

項目要求:低延遲,高效率

采用協定:hession協定

開發過程中總共經曆了三個開發者,對此做如下記錄也激勵自己寫出更加優美的代碼。

1.開發者A的思路和過程(第一次項目代碼)

1.1設計思路和實作

通過在hession實作類中定義static 屬性的List的對象儲存收到的資料,再通過線程循環處理。

@Service
@Transactional 
public class HessianServiceImpl implements HessianService {
	//入口List
	public  static List<EriInfo> eriInEnterfoList = new LinkedList<EriInfo>();
	@Override
	public void setEriInfo(EriInfo eriInfo){
		eriInEnterfoList.add(eriInfo);
	}
}
           

線程處理

public class EnterThread extends Thread {	
	private BmdcxService bmdcxService;
	// 上下文事件
	private ServletContextEvent event = InitThread.event;
	WebApplicationContext context = WebApplicationContextUtils.getRequiredWebApplicationContext(event.getServletContext());
	@Override
	public void run() {
		bmdcxService = (BmdcxService) context.getBean("bmdcxService");
		while (true) {
			System.console();
			if (HessianServiceImpl.eriInEnterfoList.size() > 0) {
				EriInfo eriInfo = HessianServiceImpl.eriInEnterfoList.get(0);
				if (eriInfo != null) {
					String carPlateo = eriInfo.getPlateNo();
					// 查詢處理
					 bmdcxService.queryByplateno(carPlateo, "0");
				}
			}
		}
	}
}
           

業務可以跑起來,沒毛病。

1.2問題歸納

單線程

服務注冊方式太醜陋

資料丢失(debuge調試時發生資料丢失,可能是線程調用問題。自己調查發現System.console();可以解決。一直心存疑問)

2.開發者B的思路和過程(第一次優化)

功能實作,可是使用spring的優勢一點都沒有展現出來,決心優化一次。

優化點:

使用消費者生産者模式做資料接收處理,避免上面的低效率問題。

使用spring的注解,進行對象的引用

2.1實作代碼

定義阻塞隊列,先将資料放入隊列,再通過多線程進行處理。

hession接口實作,将資料塞入隊列中

@Service
@Transactional 
public class HessianServiceImpl implements HessianService {
	
	@Override
	public void setEriInfo(EriInfo eriInfo) throws InterruptedException {
		EriInfoQueue.getEriInfoQueue().produce(eriInfo);
		
	}
}
           

消息隊列定義

public class EriInfoQueue {
	//隊列大小
    static final int QUEUE_MAX_SIZE   = 1000000;

    static BlockingQueue<EriInfo> blockingQueue = new LinkedBlockingQueue<EriInfo>(QUEUE_MAX_SIZE);
    
    /**
     * 私有的預設構造子,保證外界無法直接執行個體化
     */
    
    private EriInfoQueue(){};
    
    
    /**
     * 類級的内部類,也就是靜态的成員式内部類,該内部類的執行個體與外部類的執行個體
     * 沒有綁定關系,而且隻有被調用到才會裝載,進而實作了延遲加載
     */
    private static class SingletonHolder{
    	
        /**
         * 靜态初始化器,由JVM來保證線程安全
         */
        private  static EriInfoQueue queue = new EriInfoQueue();
    }
    
    //單例隊列
    public static EriInfoQueue getEriInfoQueue(){
        return SingletonHolder.queue;
    }
    
    //生産入隊
    public  void  produce(EriInfo eriInfo) throws InterruptedException {
        blockingQueue.put(eriInfo);
    }
    
    //消費出隊
    public  EriInfo consume() throws InterruptedException {
        return blockingQueue.take();
    }
    
    // 擷取隊列大小
    public int size() {
        return blockingQueue.size();
    }
}
           

生産者定義

@Component
public class ConsumeEriInfoQueue {

	private static final Logger logger = LoggerFactory.getLogger(ConsumeEriInfoQueue.class);
	@Autowired //對象注入
	public YxsjService yxsjService ;
	
	@PostConstruct
	    public void startThread() {
	        ExecutorService e = Executors.newFixedThreadPool(2);// 兩個大小的固定線程池
	        e.submit(new PollEriInfo(yxsjService));//缺點1 引用的對象放到了構造方法中
	        e.submit(new PollEriInfo(yxsjService));
	    }
	 @PreDestroy
	    public void stopThread() {
	        logger.info("destroy");
	    }
}
           

具體實作類

public class PollEriInfo implements Runnable {
	
	private static final Logger logger = LoggerFactory
			.getLogger(PollEriInfo.class);

	public YxsjService yxsjService ;
	
	 public PollEriInfo(YxsjService yxsjService) {
         this.yxsjService = yxsjService;
     }
			
	@Override
	public void run() {
		while (true) {
			try {
				EriInfo eriInfo = EriInfoQueue.getEriInfoQueue().consume();
		          	if (eriInfo != null) {
					yxsjService.saveYxsj(yxsjInfo);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}
           

2.2問題歸納

引用的對象寫到了構造方法中,如果引用對象太多是個問題(需要定義一個總的接口)。

3.開發者C的再次優化

優化思路:使用spring的Async注解,将對象autowared注入再次優化

線程池配置

@Configuration
@EnableAsync
public class TaskExecutorConfig implements AsyncConfigurer{

	@Override
	public Executor getAsyncExecutor() {
		ThreadPoolTaskExecutor taskExecutor =  new ThreadPoolTaskExecutor();
		taskExecutor.setCorePoolSize(5);
		taskExecutor.setMaxPoolSize(10);
		taskExecutor.setQueueCapacity(200);
		taskExecutor.setThreadNamePrefix("receiveRFID");
		taskExecutor.initialize();
		return taskExecutor;
	}

	@Override
	public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
		return null;
	}

}
           

hession接口實作

@Service
@Transactional 
public class HessianServiceImpl implements HessianService {

	@Autowired 
	ReceiveRFIDService receiveRFIDService;
	@Override
	public void setEriInfo(EriInfo eriInfo) throws InterruptedException {
		receiveRFIDService.receiveRFID(eriInfo);
	}

}
           

重點來了,資料處理服務類

@Service
public class ReceiveRFIDService{
	

    @autowared //對象的注入,看不出差别
    private IInstallInfoService installInfoService;

    @Async("receiveRFID") 
	public void receiveRFID(EriInfo eriInfo) {
		 installInfoService.recordInstallInfo(installInfo);
	}
}
           

記錄一段代碼的優化過程,希望給大家有所啟發。

繼續閱讀