@Async 注解使用小例子

@Async注解源码:

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Async {
	String value() default "";
}

 

@Async 用于异步调用,由上面源码可知:@Async既可作用于类上,也可作用于方法上,当作用在方法上是只对方法有效,当作用在类上时,对类中的所有方法都有效。

示例:

controller:

@GetMapping("test_async")
public String testAsync(){
    countryService.TestAsync(1);
    countryService.TestAsync2(2);
    log.info("finish");
    return "finish";
}


service:

public interface ICountryService extends IService<Country> {

    void TestAsync(int num);

    void TestAsync2(int num);
}

serviceImpl:

@Service
@Slf4j
@EnableAsync
@EnableCaching
public class CountryServiceImpl extends ServiceImpl<CountryMapper, Country> implements ICountryService {

    @SneakyThrows
    @Override
    @Async
    public void TestAsync(int num) {
        log.info("start async request = {}",num);
        Thread.sleep(2000);
        log.info("finish this request = {}",num);
    }

    @SneakyThrows
    @Override
    @Async
    public void TestAsync2(int num) {
        log.info("start async request = {}",num);
        Thread.sleep(1000);
        log.info("finish this request = {}",num);
    }
}

运行程序,调用controller方法,获得打印结果如下:

2020-07-31 23:38:01.113  INFO 198416 --- [nio-9090-exec-2] c.e.mpdemo.controller.CountryController  : finish
2020-07-31 23:38:01.121  INFO 198416 --- [         task-2] c.e.m.service.impl.CountryServiceImpl    : start async request = 2
2020-07-31 23:38:01.121  INFO 198416 --- [         task-1] c.e.m.service.impl.CountryServiceImpl    : start async request = 1
2020-07-31 23:38:02.123  INFO 198416 --- [         task-2] c.e.m.service.impl.CountryServiceImpl    : finish this request = 2
2020-07-31 23:38:03.122  INFO 198416 --- [         task-1] c.e.m.service.impl.CountryServiceImpl    : finish this request = 1

由此可见,最先打出了finish,说明方法异步,在没有调用内部的方法时,就已经返回了结果。这打印了两个请求,第二个请求执行的时间短先结束,所以先打出了第二个请求结果;

注意:异步方法所在类必须要加上注解 @EnableAsync 开启异步。

 

©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页