Spring Boot 데몬/서버 애플리케이션이 즉시 종료/셧다운되지 않도록 하려면 어떻게 해야 합니까?
Spring Boot 어플리케이션은 웹 서버는 아니지만 커스텀프로토콜을 사용하는 서버입니다(이 경우 Camel을 사용합니다).
단, Spring Boot는 시작 후 즉시 정지합니다(정상적으로).어떻게 하면 예방할 수 있을까요?
Ctrl+C 또는 프로그래밍 방식으로 앱을 정지하고 싶습니다.
@CompileStatic
@Configuration
class CamelConfig {
@Bean
CamelContextFactoryBean camelContext() {
final camelContextFactory = new CamelContextFactoryBean()
camelContextFactory.id = 'camelContext'
camelContextFactory
}
}
해결책을 찾았습니다.org.springframework.boot.CommandLineRunner
+Thread.currentThread().join()
예: (주: 아래 코드는 Java가 아닌 Groovy)
package id.ac.itb.lumen.social
import org.slf4j.LoggerFactory
import org.springframework.boot.CommandLineRunner
import org.springframework.boot.SpringApplication
import org.springframework.boot.autoconfigure.SpringBootApplication
@SpringBootApplication
class LumenSocialApplication implements CommandLineRunner {
private static final log = LoggerFactory.getLogger(LumenSocialApplication.class)
static void main(String[] args) {
SpringApplication.run LumenSocialApplication, args
}
@Override
void run(String... args) throws Exception {
log.info('Joining thread, you can press Ctrl+C to shutdown application')
Thread.currentThread().join()
}
}
Apache Camel 2.17에서는 더 명확한 답이 있습니다.http://camel.apache.org/spring-boot.html 견적을 내려면:
Camel이 계속 작동하도록 메인 스레드를 차단하려면 spring-boot-boot-web 종속성을 포함하거나 application.properties 또는 application.yml 파일에 camel.springboot.main-run-controller=true를 추가합니다.
다음과 같은 종속성도 필요합니다.
<dependency> <groupId>org.apache.camel</groupId> <artifactId>camel-spring-boot-starter</artifactId> <version>2.17.0</version> </dependency>
명확하게 교환하다<version>2.17.0</version>
또는 camel BOM을 사용하여 의존관계 관리 정보를 Import하여 일관성을 확보합니다.
Count Down Latch를 사용한 구현 예:
@Bean
public CountDownLatch closeLatch() {
return new CountDownLatch(1);
}
public static void main(String... args) throws InterruptedException {
ApplicationContext ctx = SpringApplication.run(MyApp.class, args);
final CountDownLatch closeLatch = ctx.getBean(CountDownLatch.class);
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
closeLatch.countDown();
}
});
closeLatch.await();
}
이제 응용 프로그램을 중지하려면 프로세스 ID를 검색하여 콘솔에서 kill 명령을 발행합니다.
kill <PID>
Spring Boot는 응용 프로그램을 실행하는 작업을 응용 프로그램이 구현되는 프로토콜에 맡깁니다.예를 들어, 이 메뉴얼을 참조해 주세요.
또한 다음과 같은 몇 가지 하우스키핑 오브젝트도 필요합니다.
CountDownLatch
본연의 실타래를 살리기 위해서...
예를 들어 Camel 서비스를 실행하는 방법은 메인 Spring Boot 어플리케이션클래스에서 스탠드아론 어플리케이션으로 Camel을 실행하는 것입니다.
이것은 이제 훨씬 더 간단해졌다.
추가만 하면 됩니다.camel.springboot.main-run-controller=true
application.properties로 이동합니다.
모든 스레드가 완료되고 프로그램이 자동으로 닫힙니다.따라서 빈 작업을 에 등록합니다.@Scheduled
셧다운을 방지하기 위해 루프 스레드를 만듭니다.
파일 application.yml
spring:
main:
web-application-type: none
파일 Demo Application.자바
@SpringBootApplication
@EnableScheduling
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
파일 KeepAlive.java
@Component
public class KeepAlive {
private static final Logger log = LoggerFactory.getLogger(ScheduledTasks.class);
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
@Scheduled(fixedRate = 1 * 1000 * 60) // 1 minute
public void reportCurrentTime() {
log.info("Keepalive at time {}", dateFormat.format(new Date()));
}
}
제 프로젝트는 NON WEB Spirng Boot입니다.저의 우아한 솔루션은 Command Line Runner에서 데몬 스레드를 만드는 것입니다.그 후, 애플리케이션은 곧바로 셧다운 되지 않습니다.
@Bean
public CommandLineRunner deQueue() {
return args -> {
Thread daemonThread;
consumer.connect(3);
daemonThread = new Thread(() -> {
try {
consumer.work();
} catch (InterruptedException e) {
logger.info("daemon thread is interrupted", e);
}
});
daemonThread.setDaemon(true);
daemonThread.start();
};
}
웹 응용 프로그램을 배포하지 않을 때 Java 프로세스를 활성 상태로 유지하려면 다음과 같이 webEnvironment 속성을 false로 설정합니다.
SpringApplication sa = new SpringApplication();
sa.setWebEnvironment(false); //important
ApplicationContext ctx = sa.run(ApplicationMain.class, args);
springboot 앱을 계속 실행하려면 컨테이너에서 실행해야 합니다.그렇지 않으면 모든 스레드가 완료되므로 추가할 수 있습니다.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
또, 실장중에 계속 유효하게 할 책임이 없는 경우는, Web 앱으로 변환됩니다.
언급URL : https://stackoverflow.com/questions/28017784/how-to-prevent-spring-boot-daemon-server-application-from-closing-shutting-down
'programing' 카테고리의 다른 글
여기서 발생하는 오류는 처리되지 않습니다. (0) | 2023.02.09 |
---|---|
Angular $q.는 일할 때 어떻게 됩니까? (0) | 2023.02.09 |
문서 프레임이 샌드박스로 인해 에서 스크립트 실행이 차단됨 - 각도 응용프로그램 (0) | 2023.02.09 |
값은 null일 수 없습니다.파라미터 이름: connectionString appsettings.json in starter (0) | 2023.02.09 |
Oracle 열에 HQL이 "null"이고 "!= null"입니다. (0) | 2023.02.09 |