业务场景
比如发送邮件,发送短信这类,不是很着急获取结果的场景
在启动类上添加@EnableAsync注解开启异步执行方法
在需要执行异步的类上面添加 @Component 方法
在需要执行异步的方法上面添加@Async注解
下面是代码测试实现
Controller
//controller 没什么变化
@RestController
public class HelloController {
@Autowired
private Hello hello; //需要执行异步方法
@RequestMapping("/hello")
public String hello(){
hello.hello();
return "hello Word";
}
}
异步执行类和方法
@Component//添加注解
public class Hello {
private Logger logger = LoggerFactory.getLogger(Hello.class);
@Async//添加注解 组合使用
public void hello(){
try {
Thread.sleep(5000); //模拟测试异步执行 休眠五秒
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
logger.info("这是测试代码");
}
}
启动类
@SpringBootApplication
@EnableAsync
public class SpringbootSmsApplication {
protected final static Logger logger = LoggerFactory.getLogger(SpringbootSmsApplication.class);
public static void main(String[] args) {
SpringApplication.run(SpringbootSmsApplication.class, args);
}
}
测试可用
如果非controller中需要注入失败可参考点击这里