多執行緒Future+Callable實現併發查詢
阿新 • • 發佈:2019-01-06
對於所查詢的資料比較耗時,資料位於不同的資料來源中,可以通過併發查詢的方式加快獲取想要的資料。記錄專案中用到的方法。
package com.lancy.interfaces.util;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import javax.annotation.Resource;
import org.springframework.stereotype.Component;
import com.lancy.interfaces.lnt.service.LntCardService;
import com.lancy.interfaces.ykt.service.YktCardService;
/**
* @ClassName: CardUtil.java
* @Description: 檢查卡資訊所在資料表
*/
@Component
public class CardUtil {
private static YktCardService yktCardService;
private static LntCardService lntCardService;
private static ExecutorService threadPool = null;
static {
threadPool = Executors.newFixedThreadPool(200);
}
@Resource
public void setYktCardService (YktCardService service){
yktCardService = service;
}
@Resource
public void setLntCardService(LntCardService service){
lntCardService = service;
}
/**
* 判斷卡型別
* @param cardId 卡號
* @return 1:儲值卡,2:記賬卡
*/
public static int checkCardType(String cardId) {
//用執行緒併發查詢
Future<Integer> lntCaball = threadPool.submit(new LntCardThread(cardId));
Future<Integer> yktCaball = threadPool.submit(new YktCardThread(cardId));
Integer result = null;
try {
result = lntCaball.get();
if (result != null) {
return result;
}
} catch (Exception e) {
lntCaball.cancel(true);
}
try {
result = yktCaball.get();
} catch (Exception e) {
yktCaball.cancel(true);
}
if (result == null)
return -1;
return result;
}
//實現Callable介面的執行緒類1,call方法執行業務邏輯
private static class LntCardThread implements Callable<Integer> {
private String cardId;
public LntCardThead(String cardId) {
this.cardId= cardId;
}
public Integer call() throws Exception {
return lntCardService.getCardType(this.cardId);
}
}
//實現Callable介面的執行緒類2,call方法執行業務邏輯
private static class YktCardThread implements Callable<Integer> {
private String cardId;
public YktCardThead(String cardId) {
this.cardId= cardId;
}
public Integer call() throws Exception {
return yktCardService.getCardType(cardId);
}
}
}