0

我正在使用以下设置处理一个简单的“hello-world”Camel3(Camel 版本 3.4.3)REST API 示例:

下面的示例按预期工作,但我无法设置jetty端口。因此,在每次运行时,Web 服务器都会在随机端口上运行。如何在 Java 代码中设置端口(例如设置为 8081)?似乎也可以在application.properties文件中设置端口。该选项的示例也值得赞赏。

// https://camel.apache.org/components/latest/others/main.html
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.main.Main;
import org.apache.camel.main.RestConfigurationProperties;

import rest.dsl.generated.Api101;

public class App {
    public static void main(String[] args) throws Exception {
        Main main = new Main();

        // How do I set the rest properties ?
        // The code below doesn't seem to have effect.
        RestConfigurationProperties p = main.configure().rest()
        .withComponent("jetty")
        .withHost("localhost")
        .withPort(8081)
        ;
        main.configure().addConfiguration(p);

        // The route generated by camel-restdsl-swagger-plugin
        main.configure().addRoutesBuilder(
            new Api101()
        );

        // The actual route.
        main.configure().addRoutesBuilder(
            new RouteBuilder() {
                public void configure() {
                    from("direct:rest1")
                    .routeId("Rest1Route")
                    .log("START:")
                    .setBody(constant("{hello: \"Hello, World!\"}"))
                    .log("END:")
                    ;
                }
            }
        );

        main.run(args);
    }
}

生成的Api101代码:

package rest.dsl.generated;

import javax.annotation.Generated;
import org.apache.camel.builder.RouteBuilder;

/**
 * Generated from Swagger specification by Camel REST DSL generator.
 */
@Generated("org.apache.camel.generator.swagger.PathGenerator")
public final class Api101 extends RouteBuilder {
    /**
     * Defines Apache Camel routes using REST DSL fluent API.
     */
    public void configure() {
        rest("/api101")
            .get("/hello")
                .description("Basic Hello World")
                .to("direct:rest1");
    }
}

编译&运行示例:

/tmp/openapi$ mvn clean compile exec:java
[INFO] Scanning for projects...
[INFO] 
[INFO] ----------------------< com.stackoverflow:openapi >----------------------
[INFO] Building openapi 1.0
[INFO] --------------------------------[ jar ]---------------------------------
[INFO] 
[INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ openapi ---
[INFO] Deleting /tmp/openapi/target
[INFO] 
[INFO] --- camel-restdsl-swagger-plugin:3.4.3:generate-with-dto (default) @ openapi ---
[INFO] reading from /tmp/openapi/swagger.yaml
[INFO] Generating Camel DSL source in directory: /tmp/openapi/target/generated-sources/restdsl-swagger
[INFO] Generating DTO classes using io.swagger:swagger-codegen-maven-plugin:2.4.12
[INFO] reading from /tmp/openapi/swagger.yaml
[WARNING] Output directory does not exist, or is inaccessible. No file (.swagger-codegen-ignore) will be evaluated.
[WARNING] 'host' not defined in the spec. Default to 'localhost'.
[INFO] writing file /tmp/openapi/target/generated-sources/swagger/src/main/java/io/swagger/client/model/InlineResponse200.java
[WARNING] 'host' not defined in the spec. Default to 'localhost'.
[INFO] 
[INFO] --- build-helper-maven-plugin:3.2.0:add-source (default) @ openapi ---
[INFO] Source directory: /tmp/openapi/target/generated-sources/restdsl-swagger added.
[INFO] 
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ openapi ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 1 resource
[INFO] 
[INFO] --- maven-compiler-plugin:3.8.1:compile (default-compile) @ openapi ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 3 source files to /tmp/openapi/target/classes
[INFO] 
[INFO] --- exec-maven-plugin:3.0.0:java (default-cli) @ openapi ---
[                    App.main()] BaseMainSupport                INFO  Using properties from: classpath:application.properties;optional=true
[                    App.main()] DefaultRoutesCollector         INFO  No additional Camel XML routes discovered from: classpath:camel/*.xml
[                    App.main()] DefaultRoutesCollector         INFO  No additional Camel XML rests discovered from: classpath:camel-rest/*.xml
[                    App.main()] AbstractCamelContext           INFO  Apache Camel 3.4.3 (camel-1) is starting
[                    App.main()] AbstractCamelContext           INFO  StreamCaching is not in use. If using streams then its recommended to enable stream caching. See more details at http://camel.apache.org/stream-caching.html
[                    App.main()] JettyHttpComponent             WARN  JMX disabled in CamelContext. Jetty JMX extensions will remain disabled.
[                    App.main()] log                            INFO  Logging initialized @8774ms to org.eclipse.jetty.util.log.Slf4jLog
[                    App.main()] Server                         INFO  jetty-9.4.29.v20200521; built: 2020-05-21T17:20:40.598Z; git: 77c232aed8a45c818fd27232278d9f95a021095e; jvm 11.0.8+10-post-Ubuntu-0ubuntu120.04
[                    App.main()] ContextHandler                 INFO  Started o.e.j.s.ServletContextHandler@4d9f9a55{/,null,AVAILABLE}
[                    App.main()] AbstractConnector              INFO  Started ServerConnector@157aa401{HTTP/1.1, (http/1.1)}{0.0.0.0:44267}
[                    App.main()] Server                         INFO  Started @8938ms
[                    App.main()] InternalRouteStartupManager    INFO  Route: route1 started and consuming from: jetty:http://0.0.0.0:0/api101/hello
[                    App.main()] InternalRouteStartupManager    INFO  Route: Rest1Route started and consuming from: direct://rest1
[                    App.main()] AbstractCamelContext           INFO  Total 2 routes, of which 2 are started
[                    App.main()] AbstractCamelContext           INFO  Apache Camel 3.4.3 (camel-1) started in 0.225 seconds
[              qtp1580225589-17] Rest1Route                     INFO  START:
[              qtp1580225589-17] Rest1Route                     INFO  END:
^C[ad #0 - CamelHangupInterceptor] DefaultMainShutdownStrategy    INFO  Received hang up - stopping the main instance.
[                    App.main()] AbstractCamelContext           INFO  Apache Camel 3.4.3 (camel-1) is shutting down
[ad #0 - CamelHangupInterceptor] DefaultMainShutdownStrategy    INFO  Waiting for CamelContext to graceful shutdown, elapsed: 0.000 seconds
[                    App.main()] DefaultShutdownStrategy        INFO  Starting to graceful shutdown 2 routes (timeout 45 seconds)
[el-1) thread #1 - ShutdownTask] DefaultShutdownStrategy        INFO  Route: Rest1Route shutdown complete, was consuming from: direct://rest1
[el-1) thread #1 - ShutdownTask] AbstractConnector              INFO  Stopped ServerConnector@157aa401{HTTP/1.1, (http/1.1)}{0.0.0.0:0}
[el-1) thread #1 - ShutdownTask] ContextHandler                 INFO  Stopped o.e.j.s.ServletContextHandler@4d9f9a55{/,null,UNAVAILABLE}
[el-1) thread #1 - ShutdownTask] DefaultShutdownStrategy        INFO  Route: route1 shutdown complete, was consuming from: rest://get:/api101:/hello
[                    App.main()] DefaultShutdownStrategy        INFO  Graceful shutdown of 2 routes completed in 0 seconds
[                    App.main()] MainLifecycleStrategy          INFO  CamelContext: camel-1 has been shutdown, triggering shutdown of the JVM.
[                    App.main()] AbstractCamelContext           INFO  Apache Camel 3.4.3 (camel-1) uptime 44.386 seconds
[                    App.main()] AbstractCamelContext           INFO  Apache Camel 3.4.3 (camel-1) is shutdown in 0.037 seconds
/tmp/openapi$

从上面可以看出,Web 服务器在端口 44267 中可用:

Started ServerConnector@157aa401{HTTP/1.1, (http/1.1)}{0.0.0.0:44267}

并且可以成功访问:

$ sudo netstat -tulpn | grep /java
tcp6       0      0 :::44267                :::*                    LISTEN      16926/java          
$ curl http://0.0.0.0:44267/api101/hello
{hello: "Hello, World!"}
$ 
4

1 回答 1

1

我找到了第二个问题的答案:这是使用属性定义端口的方法:

$ cat src/main/resources/application.properties 
camel.rest.port=8081
$

这也是如何设置文档中提到的所有其他配置选项的方法。对于 Java 老手来说可能很明显,但对我来说并不明显。

于 2020-10-27T10:28:34.917 回答