单例定时请求实现

开启单个线程,定时请求;

public final class ABTestRemoteSingle {

    private static final Logger logger = LoggerFactory.getLogger(ABTestRemoteSingle.class);

    private static volatile ABTestRemoteSingle instance;

    private final static ScheduledExecutorService m_executorService;

    private final static String DATA = "data";

    public static ConcurrentHashMap<String, List<Long>> unitOpenDTOBucketIdListContext = new ConcurrentHashMap<String, List<Long>>();

    public static ConcurrentHashMap<Long, Map<String, String>> bucketIdMethodContext = new ConcurrentHashMap<Long, Map<String, String>>();

    static {
        m_executorService = Executors.newScheduledThreadPool(1,
                ABTestThreadFactory.create("ABTestRemoteSingle", true));
    }

    public static ABTestRemoteSingle getInstance() {

        if (instance == null) {
            synchronized (ABTestRemoteSingle.class) {
                if (instance == null) {
                    instance = new ABTestRemoteSingle();
                }
            }
        }

        return instance;
    }

    private ABTestRemoteSingle() {
        schedulePeriodicRefresh();
    }

    public List<Long> getUnitOpenDTOBucketIdList(String abtestName) {

        if (unitOpenDTOBucketIdListContext.isEmpty()) {
            return null;
        }
        return unitOpenDTOBucketIdListContext.get(abtestName);
    }

    public String getMethodNameByBucketId(Long bucketId) {

        if (bucketIdMethodContext.isEmpty()) {
            return null;
        }

        Map<String, String> itemMap = bucketIdMethodContext.get(bucketId);

        if (itemMap == null) {
            return null;
        }
        String bucketIdMethod = "";
        for (String itemValue : itemMap.values()) {
            if (!StringUtils.isEmpty(itemValue)) {
                bucketIdMethod = itemValue;
            }
        }

        return bucketIdMethod;
    }

    private void schedulePeriodicRefresh() {
        m_executorService.scheduleAtFixedRate(
                new Runnable() {
                    @Override
                    public void run() {
                        logger.debug("refresh getAbtestRefresh {}");
                        getAbtestRefresh();
                    }
                }, 0, 60, TimeUnit.SECONDS);
    }

    private synchronized void getAbtestRefresh() {

        if (AbtestProUtil.getURL() == null) {
            return;
        }
        List<UnitOpenDTO> unitOpenDTOList;
        try {
            unitOpenDTOList = getABTestList(AbtestProUtil.getURL());
        } catch (Exception e) {
            logger.info("请求获取abtest列表报错,url:" + AbtestProUtil.getURL(), e.getMessage());
            return;
        }

        //cookie里bucketId保证选择版本,关闭的ab,cookie里还有这里会继续执行,每次做删减
        clearContext(unitOpenDTOList);

        if (CollectionUtils.isEmpty(unitOpenDTOList)) {
            return;
        }

        ConvertContext(unitOpenDTOList);
    }

    private void clearContext(List<UnitOpenDTO> unitOpenDTOList) {
        List<String> abtestNameNewTempList = Lists.newArrayList();
        List<Long> bucketIdNewTempList =Lists.newArrayList();

        for (UnitOpenDTO unitOpenDTO : unitOpenDTOList) {
            if (unitOpenDTO != null && !unitOpenDTO.getItemOpenDTOList().isEmpty()) {
                for (ItemOpenDTO itemOpenDTO : unitOpenDTO.getItemOpenDTOList()) {
                    if (itemOpenDTO != null && itemOpenDTO.getBucketId() != null) {
                        bucketIdNewTempList.add(itemOpenDTO.getBucketId());
                    }
                }

                abtestNameNewTempList.add(unitOpenDTO.getName());
            }
        }

        for (String  abtestNameTemp : unitOpenDTOBucketIdListContext.keySet()) {
           if(!abtestNameNewTempList.contains(abtestNameTemp)){
               unitOpenDTOBucketIdListContext.remove(abtestNameTemp);
           }
        }
        for (Long  bucketIdTemp : bucketIdMethodContext.keySet()) {
            if(!bucketIdNewTempList.contains(bucketIdTemp)){
                bucketIdMethodContext.remove(bucketIdTemp);
            }
        }
    }

    private static void ConvertContext(List<UnitOpenDTO> unitOpenDTOList) {
        for (UnitOpenDTO unitOpenDTO : unitOpenDTOList) {
            if (unitOpenDTO != null && !unitOpenDTO.getItemOpenDTOList().isEmpty()) {
                List<Long> bucketIdList = Lists.newArrayList();
                for (ItemOpenDTO itemOpenDTO : unitOpenDTO.getItemOpenDTOList()) {
                    if (itemOpenDTO != null && itemOpenDTO.getBucketId() != null) {
                        bucketIdList.add(itemOpenDTO.getBucketId());
                        bucketIdMethodContext.put(itemOpenDTO.getBucketId(), itemOpenDTO.getItemMaps());
                    }
                }
                unitOpenDTOBucketIdListContext.put(unitOpenDTO.getName(), bucketIdList);
            }
        }
    }

    public static List<UnitOpenDTO> getABTestList(String url) throws Exception {

        OkHttpClient httpClient = new OkHttpClient();
        Request request = new Request.Builder().url(url).build();

        List<UnitOpenDTO> unitOpenDTOList = Lists.newArrayList();
        String result = "";
        Response response = httpClient.newCall(request).execute();
        result = response.body().string();


        if (StringUtils.isEmpty(result)) {
            return unitOpenDTOList;
        }

        JSONObject abtestJsonObject = JSON.parseObject(result);
        if (abtestJsonObject.containsKey(DATA) && abtestJsonObject.getString(DATA) != null) {
            String abtestJsonList = abtestJsonObject.getString(DATA);
            unitOpenDTOList = JSON.parseArray(abtestJsonList, UnitOpenDTO.class);
        }


        return unitOpenDTOList;
    }
}

ABTestThreadFactory线程工厂类:

public class ABTestThreadFactory implements ThreadFactory {
    private static Logger log = LoggerFactory.getLogger(ABTestThreadFactory.class);
    private final AtomicLong threadNumber = new AtomicLong(1L);
    private final String namePrefix;
    private final boolean daemon;
    private static final ThreadGroup threadGroup = new ThreadGroup("ABTest");

    public static ThreadGroup getThreadGroup() {
        return threadGroup;
    }

    public static ThreadFactory create(String namePrefix, boolean daemon) {
        return new ABTestThreadFactory(namePrefix, daemon);
    }

    private ABTestThreadFactory(String namePrefix, boolean daemon) {
        this.namePrefix = namePrefix;
        this.daemon = daemon;
    }

    public Thread newThread(Runnable runnable) {
        Thread thread = new Thread(threadGroup, runnable, threadGroup.getName() + "-" + this.namePrefix + "-" + this.threadNumber.getAndIncrement());
        thread.setDaemon(this.daemon);
        if (thread.getPriority() != 5) {
            thread.setPriority(5);
        }

        return thread;
    }
}
发布了136 篇原创文章 · 获赞 65 · 访问量 16万+

猜你喜欢

转载自blog.csdn.net/jakeswang/article/details/92797303