在本文中,我们将创建一个基于Java的HTTP端点,用它创建一个可执行jar,将其打包在Docker中,然后立即在本地运行。
本文面向初学者,他们想要寻找一个简单的演练来在Docker中运行Java应用程序。
描述Dockerized环境中Java应用程序的绝大多数示例都包括使用Spring Boot之类的沉重框架。 我们想在这里表明,您不需要太多的钱就可以在Docker中使用Java运行端点。
实际上,我们仅将单个库用作依赖项: HttpMate core 。 对于此示例,我们将使用具有单个HTTP处理程序的HttpMate的LowLevel构建器 。
本示例使用的环境
- Java 11+
- Maven 3.5+
- Java友好的IDE
- Docker版本18+
- 对HTTP / bash / Java的基本了解
最终结果在此git repo中可用。
组织项目
让我们创建我们的初始项目结构:
mkdir -p simple-java-http-docker/src/main/java/com/envimate/examples/http
让我们从我们在这里称为simple-java-http-docker
的根目录中的项目的pom文件开始:
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.envimate.examples</groupId><artifactId>simple-java-http-docker</artifactId><version>0.0.1</version><dependencies><dependency><groupId>com.envimate.httpmate</groupId><artifactId>core</artifactId><version>1.0.21</version></dependency></dependencies>
</project>
这里我们有:
- 我们项目的标准groupId / artifactId / version定义
- 对HttpMate核心库的单一依赖关系
这足以开始在所选的IDE中开发我们的端点。 其中大多数都支持基于Maven的Java项目。
应用入口
要启动我们的小服务器,我们将使用一个简单的main方法。 让我们在src/main/java/com/envimate/examples/http
目录中作为Application.java
文件创建应用程序条目,该文件现在仅将时间输出到控制台。
package com.envimate.examples.http;import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;public final class Application {public static void main(String[] args) {final LocalDateTime time = LocalDateTime.now();final String dateFormatted = time.format(DateTimeFormatter.ISO_TIME);System.out.println("current time is " + dateFormatted);}
}
尝试运行此类,您将看到当前时间。
让我们使其更具功能,并将打印时间的部分分离为不带参数的lambda函数,即Supplier
。
package com.envimate.examples.http;import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.function.Supplier;public final class Application {public static void main(String[] args) {Supplier handler = () -> {final LocalDateTime time = LocalDateTime.now();final String dateFormatted = time.format(DateTimeFormatter.ISO_TIME);return "current time is " + dateFormatted;};System.out.println(handler.get());}
}
低级HttpMate提供的便捷接口看起来没有什么不同,除了返回一个String
,没有设置String
,而是将String
设置为响应,以及表示一切正常的指示(aka响应代码200)。
final HttpHandler httpHandler = (request, response) -> {final LocalDateTime time = LocalDateTime.now();final String dateFormatted = time.format(DateTimeFormatter.ISO_TIME);response.setStatus(200);response.setBody("current time is " + dateFormatted);
};
HttpMate还提供了一个简单的Java HttpServer包装器– PureJavaEndpoint
,该包装器允许您启动端点而无需任何进一步的依赖。
我们需要做的就是为其提供HttpMate的实例:
package com.envimate.examples.http;import com.envimate.httpmate.HttpMate;
import com.envimate.httpmate.convenience.endpoints.PureJavaEndpoint;
import com.envimate.httpmate.convenience.handler.HttpHandler;import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;import static com.envimate.httpmate.HttpMate.anHttpMateConfiguredAs;
import static com.envimate.httpmate.LowLevelBuilder.LOW_LEVEL;public final class Application {public static void main(String[] args) {final HttpHandler httpHandler = (request, response) -> {final LocalDateTime time = LocalDateTime.now();final String dateFormatted = time.format(DateTimeFormatter.ISO_TIME);response.setStatus(200);response.setBody("current time is " + dateFormatted);};final HttpMate httpMate = anHttpMateConfiguredAs(LOW_LEVEL).get("/time", httpHandler).build();PureJavaEndpoint.pureJavaEndpointFor(httpMate).listeningOnThePort(1337);}
}
注意,当使用方法GET调用时,我们已将httpHandler配置为提供路径/time
。
现在是时候启动我们的应用程序并提出一些要求了:
curl http://localhost:1337/time
current time is 15:09:34.458756
在将所有内容放入Dockerfile之前,我们需要将其打包为旧的jar。
建立罐子
为此,我们需要两个maven插件: maven-compiler-plugin和maven-assembly-plugin来构建可执行jar。
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.envimate.examples</groupId><artifactId>simple-java-http-docker</artifactId><version>0.0.1</version><dependencies><dependency><groupId>com.envimate.httpmate</groupId><artifactId>core</artifactId><version>1.0.21</version></dependency></dependencies><build><plugins><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId><version>3.8.1</version><configuration><release>${java.version}</release><source>${java.version}</source><target>${java.version}</target></configuration></plugin><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-assembly-plugin</artifactId><executions><execution><phase>package</phase><goals><goal>single</goal></goals><configuration><archive><manifest><mainClass>com.envimate.examples.http.Application</mainClass></manifest></archive><descriptorRefs><descriptorRef>jar-with-dependencies</descriptorRef></descriptorRefs></configuration></execution></executions></plugin></plugins></build>
</project>
一旦有了它,就让我们构建jar:
mvn clean verify
并运行生成的jar:
java -jar target/simple-java-http-docker-0.0.1-jar-with-dependencies.jar
相同的卷曲度:
curl http://localhost:1337/time
current time is 15:14:42.992563
Docker化罐子
Dockerfile看起来非常简单:
FROM openjdk:12ADD target/simple-java-http-docker-0.0.1-jar-with-dependencies.jar /opt/application.jarEXPOSE 1337ENTRYPOINT exec java -jar /opt/application.jar
它指定
-
FROM
:用作基础的图像。 我们将使用openjdk图像。 -
ADD
:我们想要的jar到我们想要的目录 -
EXPOSE
:我们正在监听的端口 -
ENTRYPOINT
:对于命令,我们要执行
为了构建和标记我们的docker镜像,我们从目录的根目录运行以下命令:
docker build --tag simple-java-http-docker .
这将产生一个我们可以运行的docker映像:
docker run --publish 1337:1337 simple-java-http-docker
请注意,我们传递了--publish
参数,该参数指示裸露的1337端口在计算机的1337端口下可用。
相同的卷曲度:
curl http://localhost:1337/time
current time is 15:23:04.275515
就是这样:我们已经将简单的HTTP端点泊坞窗化了!
结冰
当然,这是一个简化的示例,我们编写的端点并不完全有用。 它表明尽管您不需要大量的库就可以拥有一个正在运行的HTTP端点,打包一个可运行的jar,在您的Java应用程序中使用docker以及低级HttpMate的基本用法是多么容易。
当您需要快速旋转测试HTTP服务器时,这种两分钟的设置很方便。 前几天,我正在开发一个Twitter机器人(敬请关注有关该文章的文章),我必须调试接收方真正的请求。 显然,我无法要求Twitter将请求转储给我,因此我需要一个简单的终结点,该终结点将输出有关请求的所有信息。
HttpMate的处理程序提供对名为MetaData
的对象的访问,该对象几乎就是所谓的–请求的元数据,意味着有关请求的所有可用信息。
使用该对象,我们可以打印请求的所有内容。
public final class FakeTwitter {public static void main(String[] args) {final HttpMate httpMate = HttpMate.aLowLevelHttpMate().callingTheHandler(metaData -> {System.out.println(metaData);}).forRequestPath("/*").andRequestMethods(GET, POST, PUT).build();PureJavaEndpoint.pureJavaEndpointFor(httpMate).listeningOnThePort(1337);}
}
现在,请求路径/time
被替换为模式,捕获所有路径,并且我们可以添加所有我们感兴趣的HTTP方法。
运行我们的FakeTwitter服务器并发出请求:
curl -XGET http://localhost:1337/some/path/with?someParameter=someValue
我们将在控制台中看到以下输出(格式化输出以提高可读性:它是下面的地图,因此,如果您愿意,可以很好地设置其格式)
{PATH=Path(path=/some/path/with),BODY_STRING=,RAW_QUERY_PARAMETERS={someParameter=someValue},QUERY_PARAMETERS=QueryParameters(queryParameters={QueryParameterKey(key=someParameter)=QueryParameterValue(value=someValue)}),RESPONSE_STATUS=200,RAW_HEADERS={Accept=*/*,Host=localhost:1337,User-agent=curl/7.61.0},RAW_METHOD=GET,IS_HTTP_REQUEST=true,PATH_PARAMETERS=PathParameters(pathParameters={}),BODY_STREAM=sun.net.httpserver.FixedLengthInputStream@6053cef4,RESPONSE_HEADERS={},HEADERS=Headers(headers={HeaderKey(value=user-agent)=HeaderValue(value=curl/7.61.0),HeaderKey(value=host)=HeaderValue(value=localhost:1337),HeaderKey(value=accept)=HeaderValue(value=*/*)}),CONTENT_TYPE=ContentType(value=null),RAW_PATH=/some/path/with,METHOD=GET,LOGGER=com.envimate.httpmate.logger.Loggers$$Lambda$17/0x000000080118f040@5106c12f,HANDLER=com.envimate.examples.http.FakeTwitter$$Lambda$18/0x000000080118f440@68157191
}
最后的话
HttpMate本身提供了更多功能。 但是,它还很年轻,尚未用于生产,需要您的支持! 如果您喜欢阅读的内容,请给我们发送电子邮件至opensource@envimate.com,或者仅尝试HttpMate并在反馈问题中发表评论,让我们知道。
翻译自: https://www.javacodegeeks.com/2019/08/java-single-dependency-dockerized-http-endpoint.html