마이크로 서비스 반환 응답을 먼저 수행한 다음 요청을 처리합니다.
저는 즉시 응답을 반환하고 요청을 처리하는 마이크로 서비스를 만들기 위해 해결책을 찾고 있습니다.
저는 이것을 위해 자바 8과 스프링을 사용하려고 합니다.
이는 여러 가지 방법으로 달성할 수 있습니다.
일부 장기 실행 작업을 수행하는 동안 현재 스레드(이 경우 컨트롤러)에서 결과를 반환하려면 다른 스레드가 필요합니다.
- 사용하다
Executor
직접적으로.
컨트롤러:
@Controller
public class AsyncController {
private AsyncService asyncService;
@Autowired
public void setAsyncService(AsyncService asyncService) {
this.asyncService = asyncService;
}
private ResponseEntity asyncMethod(@RequestBody Object request) {
asyncService.process(new MyLongRunningRunnable());
// returns immediately
return ResponseEntity.ok("ok");
}
}
그리고 서비스:
@Service
public class AsyncService {
private ExecutorService executorService;
@PostConstruct
private void create() {
executorService = Executors.newSingleThreadExecutor();
}
public void process(Runnable operation) {
// no result operation
executorService.submit(operation);
}
@PreDestroy
private void destroy() {
executorService.shutdown();
}
}
자세한 내용은 https://docs.oracle.com/javase/tutorial/essential/concurrency/runthread.html 에서 확인할 수 있습니다.
- 또 다른 방법은 Spring 내장 비동기 기능을 사용하는 것입니다.
다음을 사용하여 메서드에 주석을 달 수 있습니다.@Async
,하고 있다void
또는Future
반환 활자
만약 당신이 여전히 당신 자신의 실행자를 제공하고 싶다면, 당신은 구현할 수 있습니다.AsyncConfigurer
인터페이스를 사용할 수 있습니다.이 접근 방식은 또한 다음을 요구합니다.@EnableAsync
주석
@Configuration
@EnableAsync
public class AsyncConfiguration implements AsyncConfigurer {
@Override
public Executor getAsyncExecutor() {
return Executors.newSingleThreadExecutor();
}
}
이 주제에 대한 더 많은 정보 https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/scheduling/annotation/Async.html
다음은 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 팩토리 클래스를 사용하여 Executor 서비스를 빌드할 수 있습니다.이러한 방법을 사용하면 다음과 같은 이점이 있습니다.
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가 포함된 첫 번째 기법을 사용하면 제어력이 향상됩니다.
언급URL : https://stackoverflow.com/questions/46668418/microservice-return-response-first-and-then-process-the-request
'sourcecode' 카테고리의 다른 글
'http setup.py 설치'와 'http 설치'의 차이점 (0) | 2023.07.18 |
---|---|
범위 간에 임의의 부동 소수점 배열 생성 (0) | 2023.07.18 |
누가 원래 이런 유형의 구문을 발명했는가: -*- 코딩: utf-8 -*- (0) | 2023.07.18 |
.NET Core 5.0의 ODP.Net 드라이버 던지기 예외 (0) | 2023.07.18 |
파이썬에서 동적 콘텐츠(자바스크립트로 작성)로 페이지를 스크랩하려면 어떻게 해야 합니까? (0) | 2023.07.18 |