Spring boot实现异步

2020/01/16 16:54
阅读数 58

1.首先去主类上开启@EnableAsync

@SpringBootApplication
@EnableScheduling
@EnableAsync  //开启异步
public class NginxApplication {

	public static void main(String[] args) {
		SpringApplication.run(NginxApplication.class, args);
	}

}

2.新建一个类,添加@Async注解

@Service
public class Testasync {
	

	@Async
	public void async1() {

		System.out.println("async1异步id:"+Thread.currentThread().getId());
	}
	
	@Async
	public void async2() {
		System.out.println("async2异步id:"+Thread.currentThread().getId());
	}
}

3.调用此方法

@Controller
@RequestMapping("/test")
public class zhu {
	
  @Autowired
  private Testasync async;

@RequestMapping("/async")
@ResponseBody
   public String test() {
		
		System.out.println("Thread id:"+Thread.currentThread().getId());
		async.async1();
		async.async2();
		return "进入了异步方法";
	
}
    
}

打印出显示出不同的线程id:

展开阅读全文
加载中

作者的其它热门文章

打赏
0
0 收藏
分享
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部