Async 调度(异步)
引入调度相关的插件
<dependency>
<groupId>org.noear</groupId>
<artifactId>solon-scheduling</artifactId>
</dependency>
启用异步调度
@EnableAsync
public class DemoApp{
public void static void main(String[] args){
Solon.start(DemoApp.class, args);
}
}
定义异步执行的服务
//定义个服务
@Component
public class AsyncTask {
//会被异步运行(提交到异步执行器运行)//不要返回值(返回也拿不到)
@Async
public void test(String hint){
System.out.println(Thread.currentThread().getName());
}
}
应用示例
//应用
@Controller
public class DemoController{
@Inject
AsyncTask asyncTask;
@Mapping("/test")
public void test(){
//调用
asyncTask.test("test");
}
}
自定义异步执行器
@Component
public class AsyncExecutorImpl implements AsyncExecutor {
//定义个线程池
ExecutorService executor = ...;
@Override
public Future submit(Invocation inv, Async anno) throws Throwable{
if (inv.method().getReturnType().isAssignableFrom(Future.class)) {
return (Future) inv.invoke();
} else {
return executor.submit(() -> {
try {
return inv.invoke();
} catch (Throwable e) {
throw new RuntimeException(e);
}
});
}
}
}