多线程-Future+Callable实现并发查询

对于所查询的数据比较耗时,数据位于不同的数据源中,可以通过并发查询的方式加快获取想要的数据。记录项目中用到的方法。
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);
        }
    }
}
 

猜你喜欢

转载自blog.csdn.net/wb_zjp283121/article/details/89380461