多线程在项目中的引用(CountDownLatch)

    <bean id="exportThreadPoolExecutor"
          class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
        <property name="corePoolSize" value="5" />
        <property name="maxPoolSize" value="20" />
        <property name="keepAliveSeconds" value="60" />
        <property name="rejectedExecutionHandler">
            <bean class="java.util.concurrent.ThreadPoolExecutor$CallerRunsPolicy" />
        </property>
    </bean>
package com.suning.dpms.biz.customer;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.suning.dpms.dao.customer.CustDao;
import com.suning.dpms.entity.HistoryCumulativeVO;
import com.suning.dpms.intf.customer.ICustServicebiz;
import com.suning.dpms.util.Constants;
import com.suning.dpms.utils.AmountUtils;
import com.suning.dpms.utils.DateUtil;
import com.suning.dpms.vo.customer.DataAnalysisVO;
import com.suning.dpms.vo.customer.TransactionStatisticsVO;
import com.suning.dpms.vo.customer.UserFromResVO;
import com.suning.dpms.vo.customer.UserFromVO;
import com.suning.dpms.vo.customer.UserSummaryOverviewVO;
import com.suning.dpms.vo.customer.UserSummaryTrendVO;
import com.suning.dpms.vo.customer.UserSummaryVO;
import com.suning.srccore.exception.BusinessException;
import com.suning.srccore.vo.CoreRespCodeMsg;

@Service
public class CustServicebizImpl implements ICustServicebiz {

    private static final Logger logger = LoggerFactory.getLogger(CustServicebizImpl.class);
    @Autowired
    CustDao custDaobiz;
    @Resource(name = "exportThreadPoolExecutor")
    private ThreadPoolTaskExecutor exportThreadPoolExecutor;

    /**
     * pc端会员中心获取交易统计接口
     */
    @Override
    public TransactionStatisticsVO getTradeStatistics(String storeCode, String snCustNum) {
        Map<String, String> inParam = new HashMap<>();
        inParam.put("storeCd", storeCode);
        inParam.put("snCustNum", snCustNum);
        String yesterday = DateUtil.getYesterday();
        inParam.put("startDate", yesterday);
        TransactionStatisticsVO tradeStatistics = custDaobiz.getTradeStatistics(inParam);
        if (tradeStatistics == null) {
            tradeStatistics = new TransactionStatisticsVO();
            tradeStatistics.setTotalTradingMoney("0");
            tradeStatistics.setDeadline(DateUtil.formatDateStr2DateStr(yesterday));
            tradeStatistics.setTotalTradingNum("0");
        }
        tradeStatistics.setDeadline(DateUtil.formatDateStr2DateStr(tradeStatistics.getDeadline()));
        return tradeStatistics;
    }

    /**
     * 用户分析
     *
     * @throws BusinessException
     */
    @Override
    public DataAnalysisVO getDataAnalysis(String storeCode, final String dayType, final String trendType)
            throws BusinessException {
        // 入参设置
        final Map<String, String> inParam = new HashMap<>();
        String yesterday = DateUtil.getYesterday();
        inParam.put("storeCd", storeCode);
        inParam.put("startDate", yesterday);
        final UserFromResVO[] resVO = new UserFromResVO[1];
        final HistoryCumulativeVO[] historyCumulativeVO = new HistoryCumulativeVO[1];
        final UserSummaryOverviewVO[] userSummaryOverviewVO = new UserSummaryOverviewVO[1];
        final List<List<UserSummaryTrendVO>> dayUserSummaryTrendVOList = new ArrayList<>();
        final CountDownLatch latch = new CountDownLatch(4);

        // 顾客来源分析
        exportThreadPoolExecutor.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    resVO[0] = setUserFromVO(inParam);
                } catch (BusinessException e) {
                    logger.error("会员中心CustServicebizImpl.setUserFromVO异常", e);
                } finally {
                    latch.countDown();
                }
            }
        });

        // 历史累计
        exportThreadPoolExecutor.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    historyCumulativeVO[0] = setHistoryCumulativeVO(inParam);
                } finally {
                    latch.countDown();
                }
            }
        });
        // 设置顾客总览
        exportThreadPoolExecutor.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    userSummaryOverviewVO[0] = setUserSummaryOverviewVO(dayType, inParam);
                } catch (BusinessException e) {
                    logger.error("会员中心CustServicebizImpl.setUserSummaryOverviewVO异常", e);
                } finally {
                    latch.countDown();
                }
            }
        });
        // 趋势分析
        exportThreadPoolExecutor.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    dayUserSummaryTrendVOList.add(setDayUserSummaryTrendVO(dayType, trendType, inParam));
                } catch (BusinessException e) {
                    logger.error("会员中心CustServicebizImpl.setUserSummaryOverviewVO异常", e);
                } finally {
                    latch.countDown();
                }
            }
        });
        try {
            latch.await();
        } catch (Exception e) {
            logger.error("获取会员中心数据失败", e);
        }
        UserSummaryVO userSummaryVO = new UserSummaryVO();
        userSummaryVO.setUserSummaryOverviewVO(userSummaryOverviewVO[0]);
        List<UserSummaryTrendVO> dayUserSummaryTrendVO = dayUserSummaryTrendVOList.isEmpty() ? null
                : dayUserSummaryTrendVOList.get(0);
        userSummaryVO.setUserSummaryTrendVOList(dayUserSummaryTrendVO);
        DataAnalysisVO dataAnalysisVO = new DataAnalysisVO();
        dataAnalysisVO.setHistoryCumulativeVO(historyCumulativeVO[0]);

        dataAnalysisVO.setUserFromResVO(resVO[0]);
        dataAnalysisVO.setUserSummaryVO(userSummaryVO);
        return dataAnalysisVO;
    }

    /**
     * 历史累计
     *
     * @param inParam
     * @return
     */
    private HistoryCumulativeVO setHistoryCumulativeVO(Map<String, String> inParam) {
        HistoryCumulativeVO historyCumulativeVO = custDaobiz.getHistoryCumulativeVO(inParam);
        if (historyCumulativeVO != null) {
            historyCumulativeVO.setUserRepurchaseRate(AmountUtils.decimalToPercentage(historyCumulativeVO
                    .getUserRepurchaseRate()));
        } else {
            historyCumulativeVO = new HistoryCumulativeVO();
        }
        return historyCumulativeVO;
    }

    /**
     * 趋势分析
     *
     * @param dayType
     * @param trendType
     * @param inParam
     * @return
     * @throws BusinessException
     */
    private List<UserSummaryTrendVO> setDayUserSummaryTrendVO(String dayType, String trendType,
            Map<String, String> inParam) throws BusinessException {
        List<UserSummaryTrendVO> dayUserSummaryTrendVO = new ArrayList<>();
        if (Constants.DayType.DAY.equalsIgnoreCase(dayType) || Constants.DayType.WEEK.equalsIgnoreCase(dayType)) {
            String endDate = DateUtil.getWeekDate();
            inParam.put("endDate", endDate);
            if (Constants.TrendType.NEWUSERS.equalsIgnoreCase(trendType)) {
                dayUserSummaryTrendVO = custDaobiz.getUserSummaryTrendNewUsersVO(inParam);
            } else if (Constants.TrendType.NEWPAY.equalsIgnoreCase(trendType)) {
                dayUserSummaryTrendVO = custDaobiz.getUserSummaryTrendnewPayVO(inParam);
            } else if (Constants.TrendType.TOTALPAY.equalsIgnoreCase(trendType)) {
                dayUserSummaryTrendVO = custDaobiz.getUserSummaryTrendtotalPayVO(inParam);
            } else {
                logger.error("CustServicebizImpl.getDataAnalysis  pc端传值trendType={}有误", trendType);
                throw new BusinessException(CoreRespCodeMsg.DAS_COMMON_0002.getCode(),
                        CoreRespCodeMsg.DAS_COMMON_0002.getMsg());
            }
            // 补齐7天
            completionData(dayUserSummaryTrendVO, 7);
        }
        if (Constants.DayType.MOUTH.equalsIgnoreCase(dayType)) {
            String endDate = DateUtil.getMouthDate();
            inParam.put("endDate", endDate);
            if (Constants.TrendType.NEWUSERS.equalsIgnoreCase(trendType)) {
                dayUserSummaryTrendVO = custDaobiz.getUserSummaryTrendNewUsersVO(inParam);
            } else if (Constants.TrendType.NEWPAY.equalsIgnoreCase(trendType)) {
                dayUserSummaryTrendVO = custDaobiz.getUserSummaryTrendnewPayVO(inParam);
            } else if (Constants.TrendType.TOTALPAY.equalsIgnoreCase(trendType)) {
                dayUserSummaryTrendVO = custDaobiz.getUserSummaryTrendtotalPayVO(inParam);
            } else {
                logger.error("CustServicebizImpl.getDataAnalysis pc端传值trendType={}有误", trendType);
                throw new BusinessException(CoreRespCodeMsg.DAS_COMMON_0002.getCode(),
                        CoreRespCodeMsg.DAS_COMMON_0002.getMsg());
            }
            // 补齐30天
            completionData(dayUserSummaryTrendVO, 30);
        }

        return dayUserSummaryTrendVO;
    }

    /**
     * 补齐数据
     */
    public List<UserSummaryTrendVO> completionData(List<UserSummaryTrendVO> dayUserSummaryTrendVO, int date) {
        List<String> pastDate = DateUtil.getPastDate(date);
        // 如果没有查到数据直接全部补全
        if (CollectionUtils.isEmpty(dayUserSummaryTrendVO)) {
            for (String time : pastDate) {
                UserSummaryTrendVO temp = new UserSummaryTrendVO();
                temp.setxAxis(DateUtil.formatDateStr2DateStr(time));
                temp.setyAxis("0");
                dayUserSummaryTrendVO.add(temp);
            }
            listSort(dayUserSummaryTrendVO);
            return dayUserSummaryTrendVO;
        }
        // 如果查到数据,但数据不全,补全部分,并且要求转化时间格式
        List<String> dbTimeList = new ArrayList<>();
        for (UserSummaryTrendVO trendVO : dayUserSummaryTrendVO) {
            if (trendVO == null) {
                continue;
            }
            // 转化时间格式,下面两行有严格的顺序否则会出bug
            dbTimeList.add(trendVO.getxAxis());
            trendVO.setxAxis(DateUtil.formatDateStr2DateStr(trendVO.getxAxis()));

        }

        for (String time : pastDate) {
            if (!dbTimeList.contains(time)) {
                UserSummaryTrendVO temp = new UserSummaryTrendVO();
                temp.setxAxis(DateUtil.formatDateStr2DateStr(time));
                temp.setyAxis("0");
                dayUserSummaryTrendVO.add(temp);
            }

        }
        listSort(dayUserSummaryTrendVO);
        return dayUserSummaryTrendVO;
    }

    /**
     * 按照时间排序
     *
     * @param list
     */
    private void listSort(List<UserSummaryTrendVO> list) {
        Collections.sort(list, new Comparator<UserSummaryTrendVO>() {
            @Override
            public int compare(UserSummaryTrendVO o1, UserSummaryTrendVO o2) {
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                try {
                    Date dt1 = format.parse(o1.getxAxis());
                    Date dt2 = format.parse(o2.getxAxis());
                    if (dt1.getTime() > dt2.getTime()) {
                        return 1;
                    } else if (dt1.getTime() < dt2.getTime()) {
                        return -1;
                    } else {
                        return 0;
                    }
                } catch (Exception e) {
                    logger.error("会员中心时间对比排序出问题了:", e);
                }
                return 0;
            }
        });
    }

    /**
     * 顾客总览
     */
    private UserSummaryOverviewVO setUserSummaryOverviewVO(String dayType, Map<String, String> inParam)
            throws BusinessException {
        UserSummaryOverviewVO userSummaryOverviewVO = null;
        if (Constants.DayType.DAY.equalsIgnoreCase(dayType)) {
            userSummaryOverviewVO = custDaobiz.getDayUserSummaryOverview(inParam);
        } else if (Constants.DayType.WEEK.equalsIgnoreCase(dayType)) {
            userSummaryOverviewVO = custDaobiz.getWeekUserSummaryOverview(inParam);
        } else if (Constants.DayType.MOUTH.equalsIgnoreCase(dayType)) {
            userSummaryOverviewVO = custDaobiz.getMouthUserSummaryOverview(inParam);
        } else {
            logger.error("CustServicebizImpl.getDataAnalysis 获取dayType={}有误", dayType);
            throw new BusinessException(CoreRespCodeMsg.DAS_COMMON_0002.getCode(),
                    CoreRespCodeMsg.DAS_COMMON_0002.getMsg());
        }

        // 新增顾客人数
        if (userSummaryOverviewVO != null) {
            setUserSummaryOverviewVO(userSummaryOverviewVO);
            // 转换成百分比
            userSummaryOverviewVO.setUserPreRepurchaseRate(AmountUtils.decimalToPercentage(userSummaryOverviewVO
                    .getUserPreRepurchaseRate()));
            userSummaryOverviewVO.setUserRepurchaseRate(AmountUtils.decimalToPercentage(userSummaryOverviewVO
                    .getUserRepurchaseRate()));
        } else {
            userSummaryOverviewVO = new UserSummaryOverviewVO();
        }
        return userSummaryOverviewVO;
    }

    /**
     * 顾客来源设置
     *
     * @return
     * @throws BusinessException
     */
    private UserFromResVO setUserFromVO(Map<String, String> inParam) throws BusinessException {
        List<UserFromVO> userFromVO = custDaobiz.getUserFromVO(inParam);
        UserFromResVO resVO = new UserFromResVO();
        if (!CollectionUtils.isEmpty(userFromVO)) {
            for (UserFromVO vo : userFromVO) {
                if (vo == null) {
                    continue;
                }
                if (Constants.UserFromVO.STOREORDER.equals(vo.getCustomerSource())) {
                    resVO.setStoreOrder(vo.getNewCustomers());
                } else if (Constants.UserFromVO.NEWOPENS.equals(vo.getCustomerSource())) {
                    resVO.setNewOpens(vo.getNewCustomers());
                } else if (Constants.UserFromVO.SHOPPERSSTAMPS.equals(vo.getCustomerSource())) {
                    resVO.setShoppersstamps(vo.getNewCustomers());
                } else if (Constants.UserFromVO.SHOPORDER.equals(vo.getCustomerSource())) {
                    resVO.setShopOrder(vo.getNewCustomers());
                } else {
                    logger.error("CustServicebizImpl.getDataAnalysis 获取customerSource={}有误,请大数据确认数据问题",
                            vo.getCustomerSource());
                    throw new BusinessException(CoreRespCodeMsg.DAS_COMMON_0002.getCode(),
                            CoreRespCodeMsg.DAS_COMMON_0002.getMsg());
                }
            }
        }
        return resVO;
    }

    /**
     * 设置环比
     *
     * @param userSummaryOverviewVO
     */
    private void setUserSummaryOverviewVO(UserSummaryOverviewVO userSummaryOverviewVO) {
        // 上一周期新增顾客人数
        String newPreUsersNum = userSummaryOverviewVO.getNewPreUsersNum();
        // 新增顾客人数
        String newUsersNum = userSummaryOverviewVO.getNewUsersNum();
        // 获取百分比
        String newUsersNumChain = AmountUtils.getPercentage(newPreUsersNum, newUsersNum);
        // 设置新增顾客环比
        userSummaryOverviewVO.setNewUsersNumChain(newUsersNumChain);
        // 新增购买人数
        String newPayUser = userSummaryOverviewVO.getNewPayUser();
        // 上一周期新增购买人数
        String newPrePayUser = userSummaryOverviewVO.getNewPrePayUser();
        // 新增购买人数环比
        String newPayUserChain = AmountUtils.getPercentage(newPrePayUser, newPayUser);
        // 新增购买人数环比
        userSummaryOverviewVO.setNewPayUserChain(newPayUserChain);
        // 支付用户人数
        String totalPayUser = userSummaryOverviewVO.getTotalPayUser();
        // 上一周期支付用户人数
        String newtotalPayUser = userSummaryOverviewVO.getNewtotalPayUser();
        // 支付用户人数环比
        String totalPayUserChain = AmountUtils.getPercentage(newtotalPayUser, totalPayUser);
        userSummaryOverviewVO.setTotalPayUserChain(totalPayUserChain);
        // 新增用户转换率
        String userRepurchaseRate = userSummaryOverviewVO.getUserRepurchaseRate();
        // 上一周期新增用户转换率
        String userPreRepurchaseRate = userSummaryOverviewVO.getUserPreRepurchaseRate();
        // 新增用户转换率环比
        String userRepurchaseRateChain = AmountUtils
                .getPercentageSubtraction(userRepurchaseRate, userPreRepurchaseRate);
        userSummaryOverviewVO.setUserRepurchaseRateChain(userRepurchaseRateChain);
    }
}

原文地址:https://www.cnblogs.com/qingruihappy/p/10340244.html

时间: 2024-11-02 10:24:01

多线程在项目中的引用(CountDownLatch)的相关文章

[多线程] Web 项目中,少有涉及到的一次多线程编程的经验

如今框架横行,Spring 已经是非常成熟的容器体系,我们在日常开发 JavaWeb 的工作中,大多已经不需要考虑多线程的问题,这些问题都已经在Spring容器中实现,框架的意义就是让程序员们可以专注于逻辑的实现.然而这种编程工作是非常无趣无味的,如果长期从事这个工作,技术不一定见长,业务知识一定很熟悉!= =但说实在的,我并不喜欢这类工作,因为这种工作大多情况下知识对代码的简单复制,或是简单的一些编写,并没有什么真正的创造性,不会给人成就感. 需求背景 我们的项目,是 Mysql+Elasti

转 mvc项目中,解决引用jquery文件后智能提示失效的办法

mvc项目中,解决用Url.Content方法引用jquery文件后智能提示失效的办法 这个标题不知道要怎么写才好, 但是希望文章的内容对大家有帮助. 场景如下: 我们在用开发开发程序的时候,经常会引用jquery, 但是由于路由的关系,最终访问页面的地址相对js文件来说,是不固定的. 为了在view中能够引用到jquery文件,我们通常都是用如下的代码 <script src="@Url.Content("~/Scripts/jquery-1.4.4.min.js")

androidstudio导入外部库文件,以及将项目中module引用依赖

一:导入如百度地图等的外部类. 步骤:1.首先 将androidstudio项目显示切换到 project 状态显示项目 2.然后添加.jar文件,将所有的.jar文件放入libs文件夹内(libs文件夹就在项目文件夹下),然后在引入的.jar文件上右键然后点击 Add As Library... OK jar文件引入. 3.添加.so文件,在项目下的src目录下的main目录下新建jniLibs文件夹,然后将so文件连带着他外面的文件夹整个复制到jniLibs文件夹下(注意:so文件不能直接存

BIZTALK项目中WEB引用WEBSERVICES服务时候报错

最近工作中需要完成通过BIZTALK完成调用WEBLOGIC发布的WebServices服务,环境搭建好后,打开VS开发工具新建一个BIZTALK项目,添加WEB引用将对方发布的地址拷贝上去,可以正常浏览到,然后点击添加引用按钮,这个时候意外发生了,Visual Studio 报了个错误,弹出了个对话框见下图 开始觉得很奇怪,然后我新建了一个WINFORM程序,添加WEB引用这个时候居然正常引用上了,看来是BIZTALK的问题,我在网上也查了一下相关资料,一种我认为是BIZTALK对WEBSER

纯AS3项目中如何引用fl包中的类

fl包在Flash IDE中是独立的类库,在Flex中是无法直接引用的,那么如果Flex想要使用Flash IDE中fl包该怎么办呢? 需要在Flash IDE安装路径下,找到下面的flash.swc文件添加到Flex项目的libs中 C:\Program Files\Adobe\Adobe Flash CC 2015\Common\Configuration\ActionScript 3.0\libs\flash.swc 或者在文件 C:\Program Files\Adobe\Adobe F

Angular6 + Typescript 项目中怎么引用包装到jquery里面的插件

Angular6 + Typescript项目中用到了一个包含到jquery里面的插件 fontIconPicker https://github.com/fontIconPicker/fontIconPicker https://codeb.it/fonticonpicker/ 首先根据github上面的readme 安装 jquery 和 fonticonpicker npm install [email protected] @fonticonpicker/fonticonpicker -

vue项目中正确引用jquery

1.安装jquery依赖 npm install jquery --save 2.修改两处配置文件 a.引入webpack b.配置jquery插件 3.在页面中使用jquery 完毕! 原文地址:https://www.cnblogs.com/lewis-messi/p/8375921.html

Java并发编程:Callable、Future和FutureTask及在项目中的引用

在前面的文章中我们讲述了创建线程的2种方式,一种是直接继承Thread,另外一种就是实现Runnable接口. 这2种方式都有一个缺陷就是:在执行完任务之后无法获取执行结果. 如果需要获取执行结果,就必须通过共享变量或者使用线程通信的方式来达到效果,这样使用起来就比较麻烦. 而自从Java 1.5开始,就提供了Callable和Future,通过它们可以在任务执行完毕之后得到任务执行结果. 今天我们就来讨论一下Callable.Future和FutureTask三个类的使用方法.以下是本文的目录

[转]在VS2010 VC++项目中引用Lib静态库(以Openssl为例)

本文转自:http://kb.cnblogs.com/page/94467/ Openssl是个为网络通信提供安全及数据完整性的一种安全协议,囊括了主要的密码算法.常用的密钥和证书封装管理功能以及SSL协议,并提供了丰富的应用程序供测试或其它目的使用. 首先下载Openssl包:(http://www.openssl.org/),这是一个C语言类库包,在Windows下可以通过Perl对该类库包进行MakeBuild,产生libeay32.ssleay32的Lib以及Dll文件,具体操作详见:h