springboot异步操作之Async

简介: springboot异步操作之Async
前言

最近看了下springboot的异步操作,学到了使用async注解来实现异步操作的功能,这不就立马把项目中的发送邮件通知就都换成了异步的操作,而不是去新建一个线程来发送通知,虽然async注解也是通过新线程的方式来实现,但就很美观。下面就来看看async的简单示例

1. 启动类添加注解@EnableAsync
@SpringBootApplication
@MapperScan(basePackages = {"com.fyg.mapper"})
@ServletComponentScan
@EnableAsync
public class BlogApplication {
    public static void main(String[] args) throws UnknownHostException {
        ConfigurableApplicationContext application = SpringApplication.run(BlogApplication.class, args);
        Environment env = application.getEnvironment();
        String ip = InetAddress.getLocalHost().getHostAddress();
        String port = env.getProperty("server.port");
        String path = env.getProperty("server.servlet.context-path");
        System.out.println("\n----------------------------------------------------------\n\t" +
                "blog is running! Access URLs:\n\t" +
                "Local: \t\thttp://localhost:" + port + path + "/\n\t" +
                "External: \thttp://" + ip + ":" + port + path + "/\n\t" +
                "Knife4j-ui: \thttp://" + ip + ":" + port + path + "/doc.html\n\t" +
                "----------------------------------------------------------");
    }
}
2. 在使用的方法上添加注解@Async
@Async("threadPoolTaskExecutor")
    public void emailNoticeMe(String subject,String content) {
        // 构建一个邮件对象
        SimpleMailMessage message = new SimpleMailMessage();
        // 设置邮件主题
        message.setSubject(subject);
        // 设置邮件发送者
        message.setFrom(Objects.requireNonNull(javaMailSender.getUsername()));
        // 设置邮件接收者,可以有多个接收者,中间用逗号隔开
        message.setTo("1248954763@qq.com");
        // 设置邮件发送日期
        message.setSentDate(new Date());
        // 设置邮件的正文
        message.setText(content);
        // 发送邮件
        javaMailSender.send(message);
    }

可以指定线程池的名称,以上代码我是已经指定了,不指定名称就会使用默认的线程池

3.调用
@Transactional(rollbackFor = Exception.class)
    public ResponseResult applyFriendLink(FriendLink friendLink) {
        Assert.isTrue(StringUtils.isNotBlank(friendLink.getUrl()),"输入正确的网址!");
        friendLink.setStatus(APPLY.getCode());
        Assert.isTrue(!friendLink.getUrl().contains("fyg.com") &&
                !friendLink.getUrl().contains("baidu.com"),"不合法的网址!");
        //如果已经申请过友链 再次接入则会进行下架处理 需重新审核
        FriendLink entity = baseMapper.selectOne(new QueryWrapper<FriendLink>()
                .eq(SqlConf.URL,friendLink.getUrl()));
        if (entity != null) {
            friendLink.setId(entity.getId());
            baseMapper.updateById(friendLink);
        }else {
            baseMapper.insert(friendLink);
        }
        //异步操作邮箱发送
        emailService.emailNoticeMe("友链接入通知","网站有新的友链接入啦("+friendLink.getUrl()+"),快去审核吧!!!");
        return ResponseResult.success();
    }

需要注意的是调用方法和被调用方法不能在同类中,否则就会失效

目录
相关文章
|
2月前
|
druid Java 数据库
Spring Boot的定时任务与异步任务
Spring Boot的定时任务与异步任务
|
6月前
|
Java
springboot使用异步任务
springboot使用异步任务
60 0
|
7月前
|
Java API Spring
【Springboot】springboot 多线程@EnableAsync和@Async
【Springboot】springboot 多线程@EnableAsync和@Async
46 0
|
1月前
|
Java Spring
SpringBoot+async异步调用接口以及几个任务同时完成和异步接口实现和调用
SpringBoot+async异步调用接口以及几个任务同时完成和异步接口实现和调用
24 0
|
6月前
|
消息中间件 Java Kafka
SpringBoot中使用异步方法优化Service逻辑,提高接口响应速度
异步方法适用于逻辑与逻辑之间可以相互分割互不影响的业务中, 如生成验证码和发送验证码组成的业务, 其实无需等到真正发送成功验证码才对客户端进行响应, 可以让短信发送这一耗时操作转为异步执行, 解耦耗时操作和核心业务;
|
2月前
|
JavaScript Java API
spring boot使用异步多线程
一文讲清楚spring boot如何结合异步多线程实现文件的导出这类耗时间的操作优化以及常用的场景,了解异步思想
31 0
spring boot使用异步多线程
|
4月前
|
Java 容器
SpringBoot 异步任务处理
SpringBoot 异步任务处理
18 0
|
4月前
|
Java Spring
SpringBoot @Async 注解
【1月更文挑战第1天】SpringBoot @Async 注解
|
5月前
|
Java Spring
使用spring boot的@Async实现异步调用和线程池复用
使用spring boot的@Async实现异步调用和线程池复用
|
5月前
|
消息中间件 Java Spring
Spring Boot中异步消息JMS的讲解与通信实例
Spring Boot中异步消息JMS的讲解与通信实例
43 1