java - Spring boot - 没有嵌入式 tomcat 的 Rest Call 客户端
问题描述
我一直在试图找出 spring boot 的问题,因为我是 spring 新手,所以我想在这里获得一些帮助。
我有一个基于 Spring Boot 的 Java 应用程序,它作为守护进程运行并向远程服务器发出一些 GET 请求。(仅作为客户端)。
但是我的 Spring Boot 应用程序在内部启动了一个嵌入式 tomcat 容器。我的理解是,如果 java 应用程序充当服务器,它将需要 tomcat。但是我的应用程序只是远程机器的 GET API 的消费者,为什么它需要一个嵌入式 tomcat 呢?
在我的 pom 文件中,我指定了 spring-boot-starter-web,假设即使进行 GET 调用也需要它。
但是在对禁用嵌入式tomcat进行了一些研究之后,我找到了解决方案。
要进行以下更改,
@SpringBootApplication(exclude = {EmbeddedServletContainerAutoConfiguration.class,
WebMvcAutoConfiguration.class})
& 在 application.yml
spring:
main:
web-environment: false
随着 application.yml 的变化,我的 jar 甚至没有开始,直接中止,甚至没有在 logback 日志中记录任何内容。
现在,如果我删除 application.yml 更改,我的 jar 将启动(仅在 @SpringBootApplication anno 中进行第一次更改。)但会出现一些异常。
[main] o.s.boot.SpringApplication : Application startup failed
org.springframework.context.ApplicationContextException: Unable to start embedded container; nested exception is org.springframework.context.ApplicationContextException: Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean.
我的疑问是,
1) 仅对远程机器进行 GET API 调用的应用程序是否真的需要 tomcat,无论是独立的还是嵌入式的?
2) 我如何克服这个异常并安全地删除嵌入式 tomcat 并仍然执行 GET API 调用?
解决方案
您似乎完全走错了路,从 Web 应用程序模板开始,然后尝试关闭 Web 应用程序方面。
最好从常规的命令行客户端模板开始,然后从那里开始,如相关 Spring Guide中所述。
基本上应用程序减少到
@SpringBootApplication
public class Application {
private static final Logger log = LoggerFactory.getLogger(Application.class);
public static void main(String args[]) {
SpringApplication.run(Application.class);
}
@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
return builder.build();
}
@Bean
public CommandLineRunner run(RestTemplate restTemplate) throws Exception {
return args -> {
Quote quote = restTemplate.getForObject(
"http://gturnquist-quoters.cfapps.io/api/random", Quote.class);
log.info(quote.toString());
};
}
}
和 pom 到
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
</dependencies>
推荐阅读
- java - 如何使用java从特定行开始读取TextFile
- powershell - 无法从 JSON 数据中获取个人详细信息
- docker - 在存储库 docker.io/library/golang 中找不到标记 1.10.3 AS 基础
- java - Java 8 Stream API:如何将列表转换为地图
列表中有重复的键? - reactjs - 如何获取反应组件的一种特定道具的类型?
- android - android弹出窗口showAtLocation不起作用
- mdm - WSO2 设备管理代理 android 不适用于盒式电视
- mysql - 如何将 SQL 结果转换为百分比
- excel - Excel Application.Match 运行时错误“13”
- c# - 在控制台应用程序中使用 Async 和 await