1. 程式人生 > >多執行緒使用場景一:使用者登入增加密碼輸入次數

多執行緒使用場景一:使用者登入增加密碼輸入次數

spring.xml配置檔案中

    <bean id="taskExecutor"
        class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
        <!-- 執行緒池維護執行緒的最少數量 -->
        <property name="corePoolSize" value="5" />
        <!-- 執行緒池維護執行緒所允許的空閒時間 -->
        <property name="keepAliveSeconds" value="10" />
        <!-- 執行緒池維護執行緒的最大數量 -->
        <property name="maxPoolSize" value="20" />
        <!-- 執行緒池所使用的緩衝佇列 -->
        <property name="queueCapacity" value="200" />
    </bean>

程式碼:

    @Autowired
    private TaskExecutor taskExecutor;

//這裡其實是一個生產執行緒池的工廠類,真正的執行緒池是ThreadPoolExecutor類,它首先繼承自AbstractExcutorService這個抽象類,AbstractExcutorService實現了ExcutorService這個介面,而ExcutorService最終繼承Excutor介面,所以七拐八繞的一句話ThreadPoolExecutor實現了Excutor介面。 --------------------- 本文來自 江湖蕭蕭聲 的CSDN 部落格 ,全文地址請點選:https://blog.csdn.net/ggshshgg/article/details/79101641?utm_source=copy

    if(!loginPwd.equalsIgnoreCase(entity.getPwd())){
            taskExecutor.execute(AddUserErrorTask.newInstance(entity.getId()));//JDK提供了一套Excutor框架來實現執行緒池
            throw new BusinessException(ErrCodeConstants.AdminUser.USER_NAME_OR_PWD_ERROR);
        }

 

public class AddUserErrorTask implements Runnable{
    
    
    private AddUserErrorTask(Integer userId){
        this.userId=userId;
    }

    public static AddUserErrorTask newInstance(Integer userId){
        AddUserErrorTask task= new AddUserErrorTask(userId);
        return task;
    }
    
    private Integer userId;
    
    @Override
    public void run() {
        AdminUserService service=SpringContextHolder.getBean(AdminUserService.class);
        service.addUserErrorCount(userId);
    }

    public Integer getUserId() {
        return userId;
    }

    public void setUserId(Integer userId) {
        this.userId = userId;
    }
   

}

-----------------------------------------------------------------------------------------------

<!--將這個bean加入到spring的ioc容器-->

     <bean class="com.qlzx.common.util.MailUtil" lazy-init="false">  

<!--給bean的name屬性賦值-->

        <property name="taskExecutor" ref="taskExecutor"/>
    </bean>

public class MailUtil implements Runnable {

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

    private static final String MAIL_USER_NAME = "mail.user.name";
    private static final String TO_MAIL_USER_NAME = "to.mail.user.name";
    private static final String MAIL_SMTP_HOST = "mail.smtp.host";
    private static final String MAIL_SMTP_AUTH = "mail.smtp.auth";
    private static final String MAIL_USER_PASSWORD = "mail.user.password";
    private static final String ECODING = "utf-8";
    public static final String TOUSERNAME = PropertiesUtil.getProperty(TO_MAIL_USER_NAME);
    public static final String USERNAME = PropertiesUtil.getProperty(MAIL_USER_NAME);
    private static final String PASSWORD = PropertiesUtil.getProperty(MAIL_USER_PASSWORD);
    private static final String AUTH = PropertiesUtil.getProperty(MAIL_SMTP_AUTH);
    private static final String HOST = PropertiesUtil.getProperty(MAIL_SMTP_HOST);

    private static final String DEFAULT_ERROR = "請確保您的收件郵件正確";

/*    private static final String USERNAME="[email protected]";
    private static final String PASSWORD="Jrzn2016";
    private static final String AUTH="true";
    private static final String HOST="smtp.mxhichina.com";*/
    /**
     * 通過spring 配置檔案引入
     */
    private static ThreadPoolTaskExecutor taskExecutor;  //這個值在配置檔案中賦值

    private MailMessage mailMessageInfo;

    private MailUtil() {

    }

    private MailUtil(MailMessage mailMessageInfo) {
        this.mailMessageInfo = mailMessageInfo;
    }

    /***
     * 安全驗證
     * @param userName
     * @param password
     * @return
     */
    private static Authenticator buildAuthentication(final String userName, final String password) {

        return new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(userName, password);
            }
        };
    }

    @Override
    public void run() {
        try {
            MailUtil.sendMail(getMailMessageInfo());
        } catch (Exception e) {
            logger.error("send mail fail:" + ExceptionUtils.getFullStackTrace(e));
        }
    }

    /**
     * @param mailMessageInfo
     * @throws Exception
     * @date 2016年6月2日
     * @desc: 非同步傳送郵件, 引數自行效驗
     */
    public static void asySendMail(MailMessage mailMessageInfo) throws Exception {
        MailUtil runMail = new MailUtil(mailMessageInfo);
        taskExecutor.execute(runMail);
    }

    /**
     * 傳送郵件引數自行效驗
     *
     * @param mailMessageInfo
     * @throws Exception
     * @throws MessagingException
     */
/*    public static void sendMail(MailMessage mailMessageInfo){
        logger.debug("send mail start:"+mailMessageInfo.getReceive());
        if(StringUtils.isBlank(USERNAME) || StringUtils.isBlank(PASSWORD)
                || StringUtils.isBlank(HOST)){
            throw new JRZNException(ErrorCodeConstat.MAIL_CONFIG_ERROR);
        }
        Properties props=new Properties();
        props.setProperty(MAIL_SMTP_HOST, HOST);
        props.setProperty(MAIL_SMTP_AUTH, AUTH);
        try{
            Session session=Session.getInstance(props,buildAuthentication(USERNAME, PASSWORD));
            MimeMessage mimeMessage=null;
            switch (mailMessageInfo.getMailType()) {
                case MailMessage.HTML_MAIL:
                    mimeMessage=buildHtmlMailMessage(session, mailMessageInfo);
                break;
                default:
                    mimeMessage=buildTextMailMessage(session, mailMessageInfo);
                    break;
            }
            Transport.send(mimeMessage);
        }catch(Exception ex){
            logger.error(ExceptionUtils.getFullStackTrace(ex));
            throw new JRZNException(ErrorCodeConstat.SEND_MAIL_ERROR,DEFAULT_ERROR,ex.getMessage());
        }
        logger.debug("send mail success:"+mailMessageInfo.getReceive());
    }*/
    public static void sendMail(MailMessage mailMessageInfo) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("content", mailMessageInfo.getContent());
        map.put("subject", mailMessageInfo.getSubject());
        map.put("receive", mailMessageInfo.getReceive());
        map.put("mailType", mailMessageInfo.getMailType());
        HttpUtils.send(map, PropertiesUtil.getProperty(UrlConstant.MSG_SERVER), "/mail/send");
    }

    /**
     * 生成text檔案傳送的郵件
     *
     * @param session
     * @param mailMessageInfo
     * @return
     * @throws Exception
     */
    private static MimeMessage buildTextMailMessage(Session session, MailMessage mailMessageInfo) throws Exception {
        MimeMessage mailMessage = new MimeMessage(session);
        Address from = new InternetAddress(USERNAME);
        mailMessage.setFrom(from);
        Address to = new InternetAddress(mailMessageInfo.getReceive());
        mailMessage.setRecipient(javax.mail.Message.RecipientType.TO, to);
        mailMessage.setSubject(mailMessageInfo.getSubject(), ECODING);
        mailMessage.setSentDate(new Date());
        mailMessage.setText(mailMessageInfo.getContent(), ECODING);
        return mailMessage;
    }

    /**
     * 生成html傳送檔案
     *
     * @param session
     * @param mailMessageInfo
     * @return
     * @throws Exception
     */
    private static MimeMessage buildHtmlMailMessage(Session session, MailMessage mailMessageInfo) throws Exception {
        MimeMessage mailMessage = new MimeMessage(session);
        Address from = new InternetAddress(USERNAME);
        mailMessage.setFrom(from);
        Address to = new InternetAddress(mailMessageInfo.getReceive());
        mailMessage.setRecipient(javax.mail.Message.RecipientType.TO, to);
        mailMessage.setSubject(mailMessageInfo.getSubject(), ECODING);
        mailMessage.setSentDate(new Date());
        Multipart mainPart = new MimeMultipart();
        BodyPart html = new MimeBodyPart();
        html.setContent(mailMessageInfo.getContent(), "text/html;charset=utf-8");
        mainPart.addBodyPart(html);
        mailMessage.setContent(mainPart);
        return mailMessage;
    }


    public static void main(String[] args) throws Exception {
        MailMessage info = new MailMessage();
        info.setContent("<a onclick='alert('11')'>跳轉置百度</a>");
        info.setMailType(MailMessage.TEXT_MAIL);
        info.setReceive("[email protected]");
        info.setSubject("測試標題");
        sendMail(info);
//
//        MailMessage info = new MailMessage();
//        info.setContent("1111");
//        info.setMailType(1);
//        info.setReceive("[email protected]");
//        info.setSubject("sdasd");
//        java.util.Map<String, String> map = (java.util.Map<String, String>) DTOUtils.map(info, Map.class);
//        System.out.println(map);
    }

    public MailMessage getMailMessageInfo() {
        return mailMessageInfo;
    }

    public void setMailMessageInfo(MailMessage mailMessageInfo) {
        this.mailMessageInfo = mailMessageInfo;
    }

    public static ThreadPoolTaskExecutor getTaskExecutor() {
        return taskExecutor;
    }

    public static void setTaskExecutor(ThreadPoolTaskExecutor taskExecutor) {
        MailUtil.taskExecutor = taskExecutor;
    }

lazy-init(懶載入),表示該bean在容器初始化的時候不進行初始化。

例如:

<bean name="role1" class="com.fz.entity.Role" lazy-init="true">

以上配置表示:spring容器在初始化的時候不會初始化role1這個bean,當配置上lazy-init=true之後,表示該bean是懶載入模式,什麼時候用到了該bean才會進行初始化。

它有兩個值:true,false(預設)

true表示該bean是懶載入,容器初始化的時候不進行初始化。

當然,也可以配置在beans標籤上<beans default-lazy-init="true">