Main class
@ComponentScan
@EnableAutoConfiguration
@SpringBootApplication
public class LearnAsynchronousApplication {
public static void main(String[] args) {
SpringApplication.run(LearnAsynchronousApplication.class, args);
System.out.println("LearnAsynchronous is running");
}
}
Controller Class
@RestController
@RequestMapping("/")
public class LearnRestAsyncController {
@Autowired
private LearnAsyncService learnasyncService;
@RequestMapping (value= "async/{name}",method=RequestMethod.GET)
public ResponseEntity<String> getAsyncMsg(@PathVariable String name)throws InterruptedException, ExecutionException {
String msg=learnasyncService.getAsyncMsg(name).get();
return new ResponseEntity<String>(msg,HttpStatus.OK);
}
@RequestMapping (value="log", method=RequestMethod.POST)
public ResponseEntity<Void> logMsg()throws InterruptedException, ExecutionException{
learnasyncService.logMsg();
return new ResponseEntity<Void>(HttpStatus.OK);
}
}
Service class
package Train.LearnAsync.LearnAsynchronous.service;
import java.util.Date;
import java.util.concurrent.Future;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;
@Service
public class LearnAsyncServiceImpl implements LearnAsyncService {
@Async
@Override
public Future<String> getAsyncMsg(final String name) throws InterruptedException{
System.out.println("Execute method Asynchronously. " + Thread.currentThread().getName());
Thread.sleep(10000);
System.out.println("---------thread done");
return new AsyncResult<String> ("Hello! Good Morning. " + name);
}
@Async
@Override
public void logMsg(){
System.out.println("Execute method Asynchronously." + Thread.currentThread().getName());
System.out.println("Today's Date." + new Date());
}
}
Config Class(@EnableAsync given here)
@EnableAsync
@Configuration
public class SpringAsyncConfigurer implements AsyncConfigurer {
@Override
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(10);
executor.setMaxPoolSize(25);
executor.setQueueCapacity(100);
executor.initialize();
return executor;
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
// TODO Auto-generated method stub
return new CustomAsyncExceptionHandler();
}
}
任何人都可以建议如何立即返回结果,async而不是 工作,如果我打电话给它等待完成这个洞 进程,之后只返回结果..
一旦从邮递员http://localhost:8080/async/xyz点击此网址 等待完成该过程,但@async优势是线程不应该等待完成。它应该立即返回结果。
等待有价值的建议