spring-boot - 微服务先返回响应再处理请求

标签 spring-boot java-8 microservices

我正在研究一个解决方案,我正在尝试创建一个微服务,该微服务立即返回响应,然后处理请求。

我正在尝试为此使用 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/

相关文章:

domain-driven-design - 上下文映射 - 关系

java - 使用 TreeMap 的流返回不连贯的结果

java - 在流中使用 Java 8 foreach 循环移至下一项

spring-boot tomcat 安全漏洞修补

java - 使用 Project Reactor 并行调用其余 Web 服务?

java - 我可以在枚举内的值之间进行映射吗?

elasticsearch - CQRS:在 ElasticSearch 读取模型中项目乱序通知

spring-boot - 微服务和去中心化应用程序有什么区别

java - JUnit 5 中多个扩展的顺序

java - 自定义过滤器突然破坏@WebMvcTest