• springBoot---@Async异步失效和处理


    1.失效的代码如下

     

     解决办法:单独定义一个异步类来进行处理

     

     运行结果如下

     

    package demo.controller;

    import demo.sync.MemberServiceSync;
    import lombok.extern.slf4j.Slf4j;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.scheduling.annotation.Async;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;

    @RestController
    @Slf4j
    public class MemberService {
    @Autowired
    private MemberServiceSync memberServiceSync;

    @RequestMapping("/addMember")
    public String addMember(){
    log.info("模拟插入到数据库0001");
    //发送短信
    /* new Thread(new Runnable(){
    @Override
    public void run(){
    sms();
    }
    }).start();*/
    memberServiceSync.sms();
    log.info("用户注册成功0004");
    return "用户注册成功";
    }
    /* @Async
    public String sms(){
    log.info("<0002>");
    try{
    log.info("正在发送短信");
    Thread.sleep(3000);
    }catch(Exception e){

    }
    log.info("<0003>");
    return "发送短信成功";
    }*/
    }









    package demo.sync;

    import lombok.extern.slf4j.Slf4j;
    import org.springframework.scheduling.annotation.Async;
    import org.springframework.stereotype.Component;

    @Slf4j
    @Component
    public class MemberServiceSync {
    @Async
    public String sms(){
    log.info("<0002>");
    try{
    log.info("正在发送短信");
    Thread.sleep(3000);
    }catch(Exception e){

    }
    log.info("<0003>");
    return "发送短信成功";
    }
    }















    package demo;

    import org.mybatis.spring.annotation.MapperScan;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.scheduling.annotation.EnableAsync;
    import org.springframework.scheduling.annotation.EnableScheduling;

    @SpringBootApplication
    //@ComponentScan("demo")
    @EnableScheduling
    @EnableAsync
    @MapperScan("demo.mapper")
    public class demoApplication {
    public static void main(String[] args){
    SpringApplication.run(demoApplication.class);
    }
    }






    沫笙
  • 相关阅读:
    Ajax函数
    javascript 重定向和打开新窗口(ZZ)
    asp.net 学习
    dojo杂谈
    Deciding between COALESCE and ISNULL in SQL Server
    从 Twitter 运维技术经验可以学到什么
    重新安装ASP.NET命令
    SQL Server 2008中新增的变更数据捕获(CDC)和更改跟踪
    SQL Server 2005/2008/2012中应用分布式分区视图
    数据库运维原则
  • 原文地址:https://www.cnblogs.com/wendy-0901/p/14357301.html
Copyright © 2020-2023  润新知