目 录CONTENT

文章目录

springboot采用网易服务发送邮件

不争
2024-01-02 / 0 评论 / 0 点赞 / 43 阅读 / 6186 字

springboot邮件

1.导入依赖

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>

2.yml配置

spring:
  mail:
    username: 邮箱号
    password: 密钥
    host: smtp.163.com

3.Controller层

@RestController
@RequiredArgsConstructor
public class SendEmailController {

    // 1.引入依赖
    // 2.配置文件
    // 3.使用api

    private final JavaMailSender javaMailSender;

    @GetMapping("getEmailCode")
    public String getEmailCode(String email) {
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setFrom("关山口职业技术学院<y86736734@163.com>"); // <y86736734@163.com> 账号不能写错
        simpleMailMessage.setTo(email);
        simpleMailMessage.setSubject("验证码");
        simpleMailMessage.setText("杨老哥富贵");
        javaMailSender.send(simpleMailMessage);
        return "ok";
    }
}

采用@Async注解实现异步发送邮件

1.开启

@EnableAsync // 开启异步任务
public class Demo2Application 

2.使用

@Component
@Slf4j
public class SendEmalService {


    @Autowired
    private JavaMailSender javaMailSender;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Async
    public void senEmail(String email) {
        // 耗时操作
        String code = UUID.randomUUID().toString().substring(0, 6);
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setFrom("XXXX"); // 邮箱号
        simpleMailMessage.setTo(email);
        simpleMailMessage.setSubject("验证码");
        simpleMailMessage.setText("66666");
        stringRedisTemplate.boundValueOps("redis:code").setIfAbsent(code, 5, TimeUnit.MINUTES);
        javaMailSender.send(simpleMailMessage);
        log.info("==================");
    }
}

3.修改线程池数量

spring:    
  task:
    execution:
      pool:
        core-size: 50

或:

@Bean
public ThreadPoolTaskExecutor threadPoolExecutor(){
    ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
    threadPoolTaskExecutor.setCorePoolSize(20);
    threadPoolTaskExecutor.setMaxPoolSize(50);
    return threadPoolTaskExecutor;
}

注意

注解@Async失效的情况

1.注解@Async的方法不是public方法

2.注解@Async的返回值只能为void或Future

3.注解@Async方法使用static修饰也会失效

4.spring无法扫描到异步类,没加注解@Async或@EnableAsync注解

5.调用方与被调用方不能在同一个类

6.类中需要使用@Autowired或@Resource等注解自动注入,不能自己手动new对象

7.在Async方法上标注@Transactional是没用的.但在Async方法调用的方法上标注@Transcational是有效的
原文链接:https://blog.csdn.net/u011413452/article/details/124844941

有默认线程池:线程有8 个

在controller中循环调用

0

评论区