多线程使用场景一:用户登录增加密码输入次数

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="kefu@namizx.com";
    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 οnclick='alert('11')'>跳转置百度</a>");
        info.setMailType(MailMessage.TEXT_MAIL);
        info.setReceive("893574878@qq.com");
        info.setSubject("测试标题");
        sendMail(info);
//
//        MailMessage info = new MailMessage();
//        info.setContent("1111");
//        info.setMailType(1);
//        info.setReceive("417006291@163.com");
//        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">

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值