性能优化实战之异步发送邮件解耦核心业务

内容:“发送邮件"逻辑相对于主业务逻辑而言是"次要”的,故而应当从主业务逻辑中解耦出来,降低接口的整体响应时间。、

service中修改成

    //用户注册
    @Transactional(rollbackFor = Exception.class)
    public void register(UsrDto usrDto) throws  Exception{
        //TODO:检查该邮箱账户是否已经存在
        if(usrMapper.countByEmail(usrDto.getEmail()) > 0){
            throw new RuntimeException("该邮箱账户已经存在,请进行更换!");
        }
        //TODO: 保存用户注册信息
        Usr entity = new Usr();
        BeanUtils.copyProperties(usrDto, entity);

        usrMapper.insertSelective(entity);
        Integer usrId = entity.getId();
        this.aysncSendEmail(usrDto, usrId);

    }
    //异步发送邮件
    @Async
    private void aysncSendEmail(UsrDto usrDto, final Integer usrId) throws Exception{

        //TODO:发送一封邮件到用户注册的邮箱

        MailDto mailDto = new MailDto();
        mailDto.setSubject(env.getProperty("user.register.email.subject"));
        mailDto.setTos(new String[]{usrDto.getEmail()});

        Map<String, Object> dataMap = Maps.newHashMap();
        dataMap.put("mailTos", usrDto.getEmail());

        String encryptInfo = env.getProperty("user.register.email.validate.url");
        //TODO:浏览器转义urlEncoder = 请求过来的时候 自动进行解义
        String encryptValue = getEncryptValue(usrDto);
        encryptInfo = String.format(encryptInfo, URLEncoder.encode(encryptValue, "utf-8"));
        System.out.println("encryptInfo: " + encryptInfo);
        dataMap.put("validateUrl", encryptInfo);

        int send = mailService.sendHTMLTemplateMailV2(mailDto, env.getProperty("user.register.email.temp.file"), dataMap);

        if(1 == send){
            MailEncrypt encrypt = new MailEncrypt(usrId, usrDto.getEmail(), encryptValue, DateTime.now().toDate());
            mailEncryptMapper.insertSelective(encrypt);
        }
    }

利用@Async注解来实现

猜你喜欢

转载自blog.csdn.net/weixin_37841366/article/details/109055105