我正在研究一个解决方案,我正在尝试创建一个微服务,该微服务立即返回响应,然后处理请求。
我正在尝试为此使用 Java 8 和 Spring。
最佳答案
以下是 ExecutorService 的示例:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.annotation.PreDestroy;
import javax.servlet.http.HttpServletRequest;
@RestController
public class MyController {
// Instantiate an executor service
private ExecutorService executor = Executors.newSingleThreadExecutor();
@PreDestroy
public void shutdonw() {
// needed to avoid resource leak
executor.shutdown();
}
@GetMapping
public Object gerUrl(HttpServletRequest request) {
// execute the async action, you can use a Runnable or Callable instances
executor.submit(() -> doStuff());
return "ok";
}
private void doStuff(){}
}
您可以使用 Executors 工厂类来构建 ExecutorService。这些方法可能会帮助您:
java.util.concurrent.Executors
Executors.newSingleThreadExecutor() // jobs are queued and executed by a single thread
Executors.newCachedThreadPool() // new threads are instantiated as needed and cached
Executors.newFixedThreadPool(int nThreads) // user defined number of threads
.
@EnableAsync
@SpringBootApplication
public class MyApplication extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(MyApplication.class);
}
public static void main(String[] args) throws Exception {
SpringApplication.run(MyApplication.class, args);
}
}
import javax.annotation.PreDestroy;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurerSupport;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
@Configuration
public class AsyncConfiguration extends AsyncConfigurerSupport {
private ThreadPoolTaskExecutor executor;
@Override
public Executor getAsyncExecutor() {
executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(20);
executor.setMaxPoolSize(50);
executor.setQueueCapacity(1000);
executor.initialize();
return executor;
}
@PreDestroy
public void shutdownExecutors() {
executor.shutdown();
}
}
@Service
public class MyService {
@Async
public void doStuff(){
// Async method
}
}
这两种技术都非常好,但是第一个带有 ExecutorService 的技术可以让您更好地控制。
关于spring-boot - 微服务先返回响应再处理请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46668418/