spring-boot开启异步线程

版权声明:王为仁 https://blog.csdn.net/wangweiren_get/article/details/85330573

开启异步 方式1

@SpringBootApplication
@EnableAsync
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

@Component
public class AsyncTaskRequest {	
    @Async
    public void doSomething() {
		return ;
	}
}

异步任务 方式2

这种方式,是springBoot自身的一种异步方式,使用注解实现,非常方便,我们在想要异步执行的方法上加上@Async注解,在controller上加上@EnableAsync,即可。注意,这里的异步方法,只能在自身之外调用,在本类调用是无效的。

controller

@RestController
@RequestMapping("tmall")
@EnableAsync
public class LoginController {
    private final org.slf4j.Logger logger = 
LoggerFactory.getLogger(getClass());
    @Autowired
    private LoginService loginService;
    /**
     * 异步处理2:使用springBoot自带async注解
     */
    @RequestMapping(value = "test1",method = RequestMethod.GET)
    public String test1(){
        loginService.getTest1();
        logger.info("============>"+Thread.currentThread().getName());
        return "异步,正在解析......";
   }
}

参考链接

1.Spring Boot—(4)SpringBoot异步处理任务
2. ScheduledExecutorService定时周期执行指定的任务
感谢阅读~

猜你喜欢

转载自blog.csdn.net/wangweiren_get/article/details/85330573