1 Star 0 Fork 0

有理想的鱼 / ymate-embed

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
贡献代码
同步代码
取消
提示: 由于 Git 不支持空文件夾,创建文件夹后会生成空的 .keep 文件
Loading...
README
Apache-2.0

YMATE-EMBED

Maven Central status LICENSE

本项目为可执行嵌入式 Web 容器,在原始 WAR 包文件结构的基础上为其指定引导程序及相关依赖文件,并通过命令行方式直接启动 Web 服务,从而达到简化 Web 工程部署流程的目的。

目前支持以下 Web 容器:

命令行格式

java -jar <WAR包文件> [--参数项 [参数值]]

示例:

java -jar demo.war --port 8088 --contextPath /demo --redeploy

提示:

项目文件在运行时将默认被释放到 ${user.home}/.embeddedWorks 目录下,若需更改请使用 --targetDir 参数设置,当 --targetDir 取值为 . 则表示目标位置在当前目录,示例如下:

java -jar demo.war --targetDir /Temp/webapps --port 8088 --contextPath /demo

由于 JDK 9 及以上版本对反射进行了限制,调整参数配置,示例如下:

java --add-opens=java.base/java.lang=ALL-UNNAMED --add-opens=java.base/java.io=ALL-UNNAMED --add-opens=java.rmi/sun.rmi.transport=ALL-UNNAMED -jar demo.war --targetDir /Temp/webapps --port 8088 --contextPath /demo --redeploy

命令参数项

参数项 说明 默认值
--redeploy 重新部署
服务启动时将 WAR 包中的相关资源文件重新解压并覆盖
--cleanup 清理部署目录
删除上次部署的内容
--conf 指定配置文件名称(不包含扩展名) tomcat
--targetDir 指定目标目录(用于存放被释放的项目文件)

服务参数项

以下参数项可以通过命令行或使用文件进行配置,若两者同时存在则命令行配置优先,该文件必须放置在类路径下,默认名称为:tomcat.properties ,允许自定义名称,如:test.properties,但需要通过命令行参数项 --conf test 使其生效。

参数项 说明 默认值
--port 服务监听的端口号 8080
--protocol 协议名称 HTTP/1.1
--contextPath 上下文映射路径 ""
--hostName 服务的主机名称 localhost
--uriEncoding URI 请求的编码格式 UTF-8
--fileEncoding 文件编码格式 UTF-8
--asyncTimeout 异步请求的默认超时时间(毫秒) 30000
--connectionTimeout 连接的默认超时时间(毫秒) 20000
--maxConnections 最大连接数 10000
--maxThreads 最大工作线程数 200
--useBodyEncodingForURI 请求参数的编码方式采用请求体的编码方式 true
--maxCookieCount The maximum number of cookies permitted for a request. Use a value less than zero for no limit. 200
--scheme Set the scheme that will be assigned to requests received through this connector. http
--allowTrace Set the allowTrace flag, to disable or enable the TRACE HTTP method. false
--discardFacades Set the recycling strategy for the object facades. false
--enableLookups Set the "enable DNS lookups" flag. false
--maxParameterCount Set the maximum number of parameters (GET plus POST) that will be automatically parsed by the container. A value of less than 0 means no limit. 10000
--maxPostSize Set the maximum size of a POST which will be automatically parsed by the container. 2097152
--parseBodyMethods Set list of HTTP methods which should allow body parameter parsing. POST
--proxyName Set the proxy server name for this Connector.
--proxyPort Set the proxy server port for this Connector. 0
--redirectPort The redirect port for non-SSL to SSL redirects. 443
--secure The secure connection flag that will be set on all requests received through this connector. false
--domain Specify the domain under which this component should be registered.
--server Set the server header name.
--useIPVHosts Enable the use of IP-based virtual hosting. false
--throwOnFailure Configure if a LifecycleException thrown by a sub-class during initInternal() , startInternal() , stopInternal() or destroyInternal() will be re-thrown for the caller to handle or if it will be logged instead. true
--ciphers Set the new cipher configuration. Note: Regardless of the format used to set the configuration, it is always stored in OpenSSL format.
--processorCache The maximum number of idle processors that will be retained in the cache and re-used with a subsequent request. A value of -1 means unlimited. 200
--allowHostHeaderMismatch Will Tomcat accept an HTTP 1.1 request where the host header does not agree with the host specified (if any) in the request line? true
--clientAuth
--connectionUploadTimeout Specifies a different (usually longer) connection timeout during data upload. 300000
--continueResponseTiming
--defaultSSLHostConfigName
--disableUploadTimeout Set the flag to control whether a separate connection timeout is used during upload of a request body. true
--keyAlias
--keyPass
--keystoreFile
--keystorePass
--keystoreProvider
--keystoreType JKS
--maxExtensionSize Maximum size of extension information in chunked encoding. 8192
--maxHttpHeaderSize Maximum size of the HTTP message header. 8192
--maxKeepAliveRequests Set the maximum number of Keep-Alive requests to allow. This is to safeguard from DoS attacks. Setting to a negative value disables the limit. 100
--maxSavePostSize Set the maximum size of a POST which will be buffered during FORM or CLIENT-CERT authentication. When a POST is received where the security constraints require a client certificate, the POST body needs to be buffered while an SSL handshake takes place to obtain the certificate. A similar buffering is required during FDORM auth. 4096
--maxSwallowSize Maximum amount of request body to swallow. 2097152
--maxTrailerSize Maximum size of trailing headers in bytes. 8192
--rejectIllegalHeader If an HTTP request is received that contains an illegal header name or value (e.g. the header name is not a token) should the request be rejected (with a 400 response) or should the illegal header be ignored? false
--serverRemoveAppProvidedValues Should application provider values for the HTTP Server header be removed. Note that if server is set, any application provided value will be over-ridden. false
--sessionCacheSize -1
--sessionTimeout 86400
--caCertificateFile
--caCertificatePath
--caRevocationFile
--caRevocationPath
--SSLEnabled false
--SSLProtocol
--SSLVerifyDepth 10
--sslProtocol TLS
--certificateChainFile
--certificateFile
--certificateKeyFile
--disableCompression true
--disableSessionTickets false
--trustManagerClassName
--useKeepAliveResponseHeader true
--acceptCount Allows the server developer to specify the acceptCount (backlog) that should be used for server sockets. 100
--acceptorThreadPriority Priority of the acceptor threads. 5
--clientCertProvider When client certificate information is presented in a form other than instances of java.security.cert.X509Certificate it needs to be converted before it can be used and this property controls which JSSE provider is used to perform the conversion. For example it is used with the AJP connectors, the HTTP APR connector and with the org.apache.catalina.valves.SSLValve. If not specified, the default provider will be used.
--maxHeaderCount The maximum number of headers in a request that are allowed. A value of less than 0 means no limit. 100
--keepAliveTimeout Keepalive timeout, if not set the soTimeout is used. 20000

配置说明

STEP 1:设置 Tomcat 及依赖包版本

<properties>
    <tomcat.version>8.5.90</tomcat.version>
    <ymate.module.embed.version>1.0.3</ymate.module.embed.version>
</properties>

STEP 2:添加必要依赖包

<dependency>
    <groupId>net.ymate.module</groupId>
    <artifactId>ymate-module-embed-tomcat</artifactId>
    <version>${ymate.module.embed.version}</version>
    <scope>provided</scope>
</dependency>

STEP 3:配置相关插件

  • 设置启动类
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-war-plugin</artifactId>
    <version>2.2</version>
    <configuration>
      <filteringDeploymentDescriptors>true</filteringDeploymentDescriptors>
      <archive>
        <manifest>
          <mainClass>net.ymate.module.embed.Main</mainClass>
        </manifest>
      </archive>
    </configuration>
</plugin>
  • 配置构建规则
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-dependency-plugin</artifactId>
    <version>2.8</version>
    <executions>
        <execution>
            <id>embedded-main</id>
            <phase>generate-resources</phase>
            <goals>
                <goal>unpack-dependencies</goal>
            </goals>
            <configuration>
                <includeGroupIds>net.ymate.module</includeGroupIds>
                <includeArtifactIds>ymate-module-embed</includeArtifactIds>
                <includeScope>provided</includeScope>
                <includes>**/*.class</includes>
                <outputDirectory>${project.build.directory}/${project.build.finalName}</outputDirectory>
            </configuration>
        </execution>
        <execution>
            <id>copy-dependencies</id>
            <phase>generate-resources</phase>
            <goals>
                <goal>copy</goal>
            </goals>
            <configuration>
                <artifactItems>
                    <artifactItem>
                        <groupId>org.apache.tomcat</groupId>
                        <artifactId>tomcat-annotations-api</artifactId>
                        <version>${tomcat.version}</version>
                    </artifactItem>
                    <artifactItem>
                        <groupId>org.apache.tomcat.embed</groupId>
                        <artifactId>tomcat-embed-core</artifactId>
                        <version>${tomcat.version}</version>
                    </artifactItem>
                    <artifactItem>
                        <groupId>org.apache.tomcat.embed</groupId>
                        <artifactId>tomcat-embed-jasper</artifactId>
                        <version>${tomcat.version}</version>
                    </artifactItem>
                    <artifactItem>
                        <groupId>org.apache.tomcat.embed</groupId>
                        <artifactId>tomcat-embed-el</artifactId>
                        <version>${tomcat.version}</version>
                    </artifactItem>
                    <artifactItem>
                        <groupId>org.apache.tomcat.embed</groupId>
                        <artifactId>tomcat-embed-websocket</artifactId>
                        <version>${tomcat.version}</version>
                    </artifactItem>
                    <artifactItem>
                        <groupId>org.eclipse.jdt</groupId>
                        <artifactId>ecj</artifactId>
                        <version>3.18.0</version>
                    </artifactItem>
                    <artifactItem>
                        <groupId>net.ymate.module</groupId>
                        <artifactId>ymate-module-embed-tomcat</artifactId>
                        <version>${ymate.module.embed.version}</version>
                    </artifactItem>
                </artifactItems>
                <outputDirectory>${project.build.directory}/${project.build.finalName}/META-INF/dependencies</outputDirectory>
                <stripVersion>false</stripVersion>
                <overWriteIfNewer>true</overWriteIfNewer>
                <overWriteReleases>false</overWriteReleases>
                <overWriteSnapshots>true</overWriteSnapshots>
            </configuration>
        </execution>
    </executions>
</plugin>

STEP 4:配置 SSL 证书(可选)

示例一: 通过服务参数配置 JKS 格式证书,配置参数项如下:

--SSLEnabled=true
--keystoreFile=${root}/keystore.jks
--keystorePass=12345678x
--keystoreType=JKS

注: 请根据实际情况调整以上配置,可以直接通过命令行或者通过 tomcat.properties 文件进行设置。

另外,在配置中与路径相关的参数项均支持 ${root}${user.dir}${user.home} 变量占位,其中 ${root} 表示当前应用的 WEB-INF/classes 所在位置。

若程序运行加载类路径下 JKS 文件出现 Invalid keystore format 异常时,请确认 maven-resources-plugin 插件是否存在如下列配置:

<configuration>
  <nonFilteredFileExtensions>
      <nonFilteredFileExtension>jks</nonFilteredFileExtension>
  </nonFilteredFileExtensions>
</configuration>

示例二: 本例以配置 JKS 格式证书为例,演示如何通过 SPI 方式对嵌入式 Tomcat 容器进行自定义配置,代码如下:

package net.ymate.demo;

import net.ymate.module.embed.CommandLineHelper;
import net.ymate.module.embed.Main;
import net.ymate.module.embed.tomcat.ITomcatCustomizer;
import org.apache.catalina.Context;
import org.apache.catalina.Host;
import org.apache.catalina.connector.Connector;
import org.apache.catalina.startup.Tomcat;
import org.apache.coyote.http11.AbstractHttp11Protocol;

public class TomcatCustomizer implements ITomcatCustomizer {

    @Override
    public void customize(CommandLineHelper configs, Tomcat tomcat, Connector connector, Host host, Context context) {
        if (connector.getProtocolHandler() instanceof AbstractHttp11Protocol) {
            AbstractHttp11Protocol<?> http11NioProtocol = (AbstractHttp11Protocol<?>) connector.getProtocolHandler();
            http11NioProtocol.setSSLEnabled(true);
            http11NioProtocol.setKeystoreFile(Main.replaceEnvVariable("${root}keystore.jks"));
            http11NioProtocol.setKeystorePass("12345678x");
            http11NioProtocol.setKeystoreType("JKS");
        }
    }
}

将此实现类的名称配置到目标工程中的资源目录下 META-INF/services/net.ymate.module.embed.tomcat.ITomcatCustomizer 文件中使其能够被 SPI 服务正确加载,在本例中的实现类名称如下:

net.ymate.demo.TomcatCustomizer

示例三: 本例演示如何将 HTTP 请求强制重定向至 HTTPS 以及重置 Cookie 处理器方法。

工程类路径下 tomcat.properties 文件内容如下:

# 默认连接器配置
port=8443
scheme=https
secure=true
SSLEnabled=true
keystoreFile=${root}/keystore.jks
keystorePass=12345678x
keystoreType=JKS

# 自定义连接器配置
httpPort=8080
httpScheme=http

Tomcat 自定义 SPI 接口实现类代码如下:

package net.ymate.demo;

import net.ymate.module.embed.CommandLineHelper;
import net.ymate.module.embed.tomcat.ITomcatCustomizer;
import org.apache.catalina.Context;
import org.apache.catalina.Host;
import org.apache.catalina.connector.Connector;
import org.apache.catalina.startup.Tomcat;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import org.apache.tomcat.util.descriptor.web.SecurityCollection;
import org.apache.tomcat.util.descriptor.web.SecurityConstraint;

public class TomcatCustomizer implements ITomcatCustomizer {

    private static final Log LOG = LogFactory.getLog(TomcatCustomizer.class);

    @Override
    public void customize(CommandLineHelper configs, Tomcat tomcat, Connector connector, Host host, Context context) {
        // 重置 Cookie 处理器避免出现警告
        context.setCookieProcessor(new LegacyCookieProcessor());
        // 设置 HTTP 请求强制重定向至 HTTPS
        SecurityConstraint securityConstraint = new SecurityConstraint();
        securityConstraint.setUserConstraint("CONFIDENTIAL");
        SecurityCollection collection = new SecurityCollection();
        collection.addPattern("/*");
        securityConstraint.addCollection(collection);
        context.addConstraint(securityConstraint);
        // 新增 HTTP 连接器用于请求重定向至默认连接器端口
        Connector connectorNew = new Connector();
        connectorNew.setScheme(configs.getString("httpScheme", "http"));
        connectorNew.setPort(configs.getIntValue("httpPort", 8080));
        connectorNew.setSecure(false);
        connectorNew.setRedirectPort(connector.getPort());
        tomcat.getService().addConnector(connectorNew);
        //
        if (LOG.isInfoEnabled()) {
            LOG.info(">>>>>>>>>>>>>>>>>>> TomcatCustomizer");
        }
    }
}

One More Thing

YMP 不仅提供便捷的 Web 及其它 Java 项目的快速开发体验,也将不断提供更多丰富的项目实践经验。

感兴趣的小伙伴儿们可以加入官方 QQ 群:480374360,一起交流学习,帮助 YMP 成长!

如果喜欢 YMP,希望得到你的支持和鼓励!

Donation Code

了解更多有关 YMP 框架的内容,请访问官网:https://ymate.net

Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

简介

本项目为可执行嵌入式 Web 容器,在原始 WAR 包文件结构的基础上为其指定引导程序及相关依赖文件,并通过命令行方式直接启动 Web 服务,从而达到简化 Web 工程部署流程的目的。 展开 收起
Java
Apache-2.0
取消

发行版 (4)

全部

贡献者

全部

近期动态

加载更多
不能加载更多了
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Java
1
https://gitee.com/suninformation/ymate-embed.git
git@gitee.com:suninformation/ymate-embed.git
suninformation
ymate-embed
ymate-embed
master

搜索帮助

344bd9b3 5694891 D2dac590 5694891