Disclosure of Invention
Aiming at the defects of the prior art, the invention aims to solve the problem that multiple engines under SpringBoot frames cannot adapt to different scenes through automatic configuration.
The invention relates to a method for quickly switching a program bottom layer network engine based on SpringBoot framework, which comprises two separate projects, namely an operation project and a packaging project, wherein the operation project comprises a Layout realization class and a dynamic filtering rule engine, the packaging project comprises a built-in Layout factory and a class dynamic injection mechanism, the Layout factory packages business projects into customized classes through plug-ins based on official main class Layout, the packaging project is completed through custom starting of an entry class, custom Layout manager and custom ClassLoader, and quick switching of the bottom layer network engine is completed through use of the custom Layout manager.
Preferably, the custom starting entry class inherits JarLauncher and rewrites createClassLoader, dynamically eliminates dependent packets of non-target engines according to system parameters, and identifies JAR packets of different engines through a predefined dependency mapping table to realize accurate filtering. JarLauncher is a starter class introduced in JavaSE and higher for optimizing the starting mode of JAR packages. The Java type path management method belongs to a part of a Java modularized system, and mainly solves the problem of class path management when a traditional JAR package is started. And createClassLoader refers to a method of creating a custom class loader (ClassLoader). The class loader is one of the core components of the JVM and is responsible for dynamically loading Java classes into memory.
Preferably, the content after the packaging engineering is compiled is pushed to a Maven private service for subsequent engineering. The Maven private service refers to a private server built based on Maven warehouse management specifications and is used for storing JAR packages, plugins and custom components of project dependence. It is open only to internal team and can store internal project components, third party closed source dependencies or proxy caches of public warehouses.
Preferably, the custom Layout manager, the extension JarLayout, embeds the custom startup class into the final JAR package in the packaging stage, ensures that the startup entry points to custom logic, combines Maven plug-in configuration, covers default packaging behavior, realizes Layout logic injection, performs parameterized switching in the deployment stage, does not need recompilation or pre-packaging of multiple versions, and automatically eliminates conflict dependence by starting a parameter-specified target engine.
Preferably, the filter package is defined when customizing the ClassLoader, specifically, static application_server_ DEPENDENCIES is defined in the related class, and dependency package lists of different network engines are respectively configured.
Preferably, the method for customizing the ClassLoader also needs to rewrite the method, and specifically comprises the steps of obtaining the network engine type from a start parameter network. Engine. Type, counting a dependent packet prefix set excludedJarNamePrefixs of a non-designated network engine, traversing the URL array, filtering unnecessary URLs according to the comparison of jar packet names and prefix sets, and finally calling a parent class method by using the filtered URL array to create the ClassLoader. By specifying the network.engine type in the startup parameters, other network engine dependent packets can be excluded and network engine switching can be achieved. excludedJarNamePrefixs is a configuration parameter common in Maven, gradle, or custom build scripts that is used to exclude JAR packages for a particular prefix.
Preferably, the SpringBoot-supported network engine includes at least two of Tomcat, jetty, undertow, netty. Tomcat is an Apache foundation open source project, the community is active, the ecology is extremely rich, and almost all JavaWeb frameworks are compatible with Tomcat.
Jetty is an open source project maintained by Eclipse foundation, well integrated with Spring, quarkus, etc., framework, often used in scenarios where asynchronous features are required.
Undertow developed by RedHat is a default container of WildFly application server, is deeply integrated with OpenShift cloud platform, and ecologically depends on RedHat technology stack.
Netty is also an open source project, maintained by JBoss, which is the underlying foundation for many high performance middleware, suitable for development teams with customization needs.
Preferably, the SpringBoot-supported network engine further includes TongWeb. TongWeb is an enterprise-level Java application server, belongs to a domestic middleware product, and is mainly used for supporting deployment and operation of enterprise-level Web applications. Its location is similar to OracleWebLogic, IBMWebSphere, supports the JavaEE (now JakartaEE) specification, provides a complete application container environment, including enterprise-level functions of Servlet containers, EJB containers, JMS services, transaction management, etc.
The invention also relates to an electronic device comprising:
a memory for storing a computer program;
and the processor is used for realizing the method for rapidly switching the program bottom layer network engine based on SpringBoot frames when executing the programs stored in the memory.
The invention also relates to a computer readable storage medium having stored therein a computer program which when executed by a processor implements a method for switching a program-based network engine fast based on SpringBoot framework.
The scheme divides the complete engineering flow into two relevant stages of operation engineering and packaging engineering, and the maintainability, expansibility and flexibility of the system are finally improved through responsibility separation of the development stage, plug-in customization of the packaging stage and dynamic dependency management of the operation stage. Especially, by running dynamic dependency management, the zero-cost switching of the network engine is realized without pre-packing multi-version or modifying codes, the quick adaptation requirement of the domestic and foreign engines with certain difference is adapted, and the storage and maintenance expenditure of multi-version packing is avoided. By adopting the technical scheme, the invention solves the problems of complexity and technical thresholds of technical schemes such as modifying the pore file or manually mounting the dependent catalogue in the traditional scheme, reduces the deployment risk and greatly improves the flexibility and portability of the framework.
Detailed Description
The technical solutions in the embodiments of the present invention will be clearly and completely described below with reference to the accompanying drawings in the embodiments of the present invention. It is to be understood that the specific embodiments described herein are merely illustrative of the relevant content and not limiting of the present disclosure.
Various network engines are preset in SpringBoot frames, but in actual use, one network engine must be designated for SpringBoot, if a plurality of network engines exist at the same time, the SpringBoot program automatically discovers conflict and reports errors when started, and at the moment, the business program cannot be started normally.
For example, we do not exclude that the Tomcat network engine directly increases the Jetty network engine's dependence on the default Tomcat, corresponding to the complete dependence as follows:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jetty</artifactId>
</dependency>
after start-up, the error is reported as follows:
2025-03-10 13:47:37.163
ERROR 7060 o.s.boot.SpringApplication
[main]: Application run failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'serverEndpoint' defined in class path resource;
it is apparent that this increase in the reliance on the Jetty network engine is not normally used.
In order to embody the inventive aspects of the present invention, the applicant compared it with the prior art solutions. First, two conventional schemes existing in the prior art will be described:
prior Art 1. Adjust the pom.xml File
Some existing solutions are to manually remove the default Tomcat network engine dependency while adding new network engine dependencies when new network engines need to be used by explicitly modifying the dependencies of the engineering dependency declaration file pon.
Examples are as follows:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jetty</artifactId>
</dependency>
From the foregoing, it can be seen that this approach is achieved by explicitly excluding the Tomcat network engine by the developer during the development phase, while introducing the Jetty network engine's declaration, at which point the network engine can be switched.
However, since the specific network engine required by the client in the deployment stage cannot be predicted in advance in the development stage, the scheme can only be used when the initial engine is unsatisfied for reworking or modifying, and the network engine cannot be switched in real time in the deployment stage.
If a corresponding packet is formed for each network engine in the development stage in advance, the packing cost and the file storage cost rise exponentially, and the requirements of the business are not met.
Scheme 2 in the prior art, adjusting JVM Start parameters
Other solutions exist at present, wherein all network engine dependent packages are removed in advance when packaging is adopted, the package which is made does not contain any network engine dependent package, a program is issued, then an implementation personnel designates an extra dependent catalog by means of a starting parameter of the JVM in the deployment stage of a client site, and a specific network engine dependent package is placed in the catalog according to the actual requirement of the client, and examples are as follows:
java -Dloader.paths=libs -jar your-app.jar
At this time, a client-specified network engine dependency package is placed under the libs directory, and the objective can be achieved.
Although the network engine can be flexibly switched in the deployment stage, the problem is that deployment personnel are required to know the corresponding dependent package file, correctly find the dependent package file, upload and download the file on the deployment site and correctly edit the starting script according to the requirements of clients, the technical capability requirements of the deployment personnel are extremely high, the steps are more and very troublesome, the whole program is started in error due to the error of any step, and the maintenance cost of the whole system is very high.
As shown in figure 1, aiming at the problems existing in the prior art, the invention adopts a specific scheme that a method for quickly switching a program bottom layer network engine based on SpringBoot frames is provided, and comprises two separated projects, namely an operation project and a packaging project, wherein the operation project comprises a Layout realization class and a dynamic filtering rule engine, the packaging project comprises a built-in Layout factory and a class dynamic injection mechanism, the Layout factory packages business projects into customized classes through plug-ins based on official main class Layout, the packaging project is completed through custom starting an entry class, custom Layout manager and custom ClassLoader, and quick switching of the bottom layer network engine is completed through using the custom Layout Layout manager. Defining filtering package when customizing ClassLoader, defining static application_SERVER_ DEPENDENCIES in related class, and configuring dependency package list of different network engines respectively. The method specifically comprises the steps of obtaining a network engine type from a start parameter network.engine.type, counting a dependent packet prefix set excludedJarNamePrefixs of a non-designated network engine, traversing a URL array, filtering unnecessary URLs according to the comparison of jar packet names and the prefix set, and finally calling a parent class method by using the filtered URL array to create the ClassLoader. And pushing the content which completes the packaging project to a Maven private service after compiling, and providing for the subsequent project. The custom start entry class inheritance JarLauncher and the method of rewriting createClassLoader dynamically exclude dependent packages of non-target engines according to system parameters, and identify JAR packages of different engines through a predefined dependency mapping table. The custom Layout manager is expanded JarLayout, the custom starting class is embedded into the final JAR package in the packaging stage, the starting entry is ensured to point to custom logic, the default packaging behavior is covered by combining with Maven plug-in configuration, the Layout logic injection is realized, the parameterization switching is carried out in the deployment stage, and the target engine is specified through starting parameters, so that the conflict dependence is automatically eliminated.
The SpringBoot-supported network engine includes at least two of Tomcat, jetty, undertow, netty and also includes TongWeb.
The relevant terms therein need to be explained here:
the running engineering is responsible for the actual running logic of the application program and comprises two core components, namely a layout realization class and a dynamic filtering rule engine.
Layout implementation class, defining the whole structure and component relation of application, such as page layout, service layer and interaction mode of data layer.
Dynamic filtering rules engine-a network engine class that dynamically filters or eliminates specific dependencies at runtime based on conditions, e.g., decides whether to load Tomcat or TongWeb based on startup parameters.
Packaging engineering, which is to focus on the construction and packaging process of the application and comprises a built-in layout factory and a class dynamic injection mechanism.
The built-in layout factory converts business engineering into a customized class structure through a plug-in based on Spring official main class layout, and ensures that the packaged application meets specific deployment requirements.
And the class dynamic injection mechanism is used for injecting custom components such as a starting class and a layout manager into a final JAR package in a packaging stage to replace default implementation.
The official main class layout refers to SpringBoot default application starting structure, and uses the main class annotated by @ SpringBootApplication as an entry to start the application context through the springapplication. Based on this, the layout factory realizes customized packaging by expanding or modifying its behavior.
The custom Layout manager, expansion JarLayout, springBoot default Layout policy, is used to implement embedded custom startup classes, or modify the packing structure and support parameterized switching during the packing phase.
Embedding custom boot classes, namely embedding custom boot entry classes into META-INF/MANIFEST.MF of the final JAR package, and covering default boot logic.
Modifying the packing structure, namely adjusting the directory organization in the JAR package to ensure that the dependency is loaded in an expected manner.
Parameterized switching, namely, through Maven plug-in configuration, the layout logic can be dynamically adjusted through starting parameters in a deployment stage.
Customization ClassLoader, classLoader is a custom class loader that implements dependency filtering through static dependency lists and URL filtering.
Static dependency list the dependent package names of different network engines, like servlet-api. Jar of Tomcat, tangweb. Jar of TongWeb, are predefined by application_server_ DEPENDENCIES constant.
Application_server_ DEPENDENCIES, a static constant, a list of dependent package names for different APPLICATION SERVER network engines.
And (3) URL filtering, namely traversing all URLs to be loaded when the method of createClassLoader () is rewritten, and eliminating the dependent packet prefix of the non-target engine to ensure that only the class of the appointed engine is loaded.
Custom startup entry class in SpringBoot framework, default through JarLauncher class as startup entry for executable JAR. The custom startup entry class realizes accurate control over the class loading process by inheriting JarLauncher and rewriting its core method. Therefore, the custom start entry class inheritance JarLauncher and the rewriting createClassLoader method dynamically exclude dependent packets of non-target engines according to system parameters, and identify JAR packets of different engines through a predefined dependency mapping table to realize accurate filtering.
And pushing the content which completes the packaging project to a Maven private service after compiling, and providing for the subsequent project. And storing the compiled custom JAR package by a Maven warehouse server in the Maven private service enterprise. By pushing the packaging engineering to the private service, other items can directly refer to the package, so that the quick switching of the bottom-layer network engine is realized, and repeated compiling is not needed.
As shown in fig. 2, the technical scheme adopted by the present invention is described in the following specific embodiment, in which the service engineering needs to be switched to any one of the 2 network engines of tomcat/eastern common tongweb at any time to provide services to the outside, and the network engines are switched rapidly and flexibly in the deployment stage.
Step1, custom starting an entry class:
newly creating an engineering jar-laboratory, and then creating a class
public class MyJarLauncher extends JarLauncher {
Key function
public static void main(String[] args) throws Exception {
new MyJarLauncher().launch(args);
}
}
Step2, self-defining a Layout manager:
public class MyJarLayout extends Jar implements CustomLoaderLayout {
@Override
public void writeLoadedClasses(LoaderClassesWriter w) throws Exception {
Key/code
writer.writeLoaderClasses("META-INF/loader/jar-launch.jar");
}
Class of boot
@Override
public String getLauncherClassName() {
Return MyJarLauncher class paths;
}
}
The specific content of MyLayoutfactor.java is:
public class MyLayoutFactory extends DefaultLayoutFactory {
@Override
public Layout getLayout(File source) {
String lowerCaseFileName = source.getName().toLowerCase(Locale.ENGLISH);
if (lowerCaseFileName.endsWith(".jar")) {
return new MyJarLayout();
}
return super.getLayout(source);
}
}
Engineering compilation is pushed to a maven private service for subsequent use.
Step 3, business engineering uses a custom Layout manager:
The business objective in this step is to adjust the behavior of the maven package plug-in any business engineering that needs to switch the network engine quickly, specifically as follows:
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<id>repackage</id>
<goals>
<goal>repackage</goal>
</goals>
<configuration>
<layoutFactory implementation="com.fingard.rdc.avatar.cd.MyLayoutFactory"/>
</configuration>
</execution>
</executions>
</plugin>
By using MyLayoutFactory class in the packing repackage stage, according to the above description, a custom layout implementation class MyJarLayout object is returned, which mainly implements the following 2 behaviors:
1) Writing the related class of jar-launch engineering into the final jar package
2) Modifying the name of a startup class
So far, the final executable package is executed from the user-defined startup class, and the startup class entry replacement is smoothly realized.
And 4, customizing a ClassLoader:
Based on the fact that in the embodiment, the business engineering needs to switch to any one of the 2 network engines of the tomcat/eastern communication tongweb at any time to provide services to the outside, the definition of the ClassLoader is explained to achieve the point.
Filter bag
private static final Map<String, String[]>APPLICATION_SERVER_DEPENDENCIES = new ConcurrentHashMap<String, String[]>();
static {
Dependence of// tomcat
APPLICATION_SERVER_DEPENDENCIES.put("tomcat", new String[] {
"tomcat-embed-core",
"tomcat-embed-el",
"tomcat-embed-websocket",
"spring-boot-starter-tomcat"
});
Dependence of/(eastern general tongweb)
APPLICATION_SERVER_DEPENDENCIES.put("tongweb",
new String[] {
"tongweb-dependencies-check",
"tongweb-embed-core",
"tongweb-embed-el",
});
}
@Override
protected ClassLoader createClassLoader(URL[] urls) throws Exception {
Dependency package for other network engines requiring exclusion according to network engine type- > statistics
String engine = System.getProperty("network.engine.type", "tomcat");
Set<String>excludedJarNamePrefixs = new HashSet<String>();
for (Entry<String, String[]>entry : APPLICATION_SERVER_DEPENDENCIES.entrySet()) {
if (!entry.getKey().equalsIgnoreCase(engine)) { excludedJarNamePrefixs.addAll(Arrays.asList(entry.getValue()));
}
}
List<URL>filteredUrlList = new ArrayList<>();
Current url/traversal
for (final URL url : urls) {
String path = url.getPath();
Name normalization
if (path.endsWith(".jar!/")) {
path = path.substring(0, path.length() - 2);
}
Direct reservation of/(non-jar)
if (!path.endsWith(".jar")) {
filteredUrlList.add(url);
continue;
}
The comparison is carried out according to the jar name
String jarName = path.substring(path.lastIndexOf('/') + 1);
if (excludedJarNamePrefixs.stream().noneMatch(jarName::startsWith)) {
Keep-on-demand
filteredUrlList.add(url);
} else {
I/need to discard
System.out.println ("discard- >" +url);
}
}
return super.createClassLoader(filteredUrlList.toArray(new URL[0]));
}
By specifying the type of network engine type in the start-up parameter, the other network engines can be excluded from being dependent on the packet, thereby realizing the switching of the underlying network engine.
The method is characterized in that a custom-starting entry class inheritance JarLauncher and a rewriting createClassLoader method are used, a pre-defined application_SERVER_ DEPENDENCIES dependence mapping table is combined, a dependence package of a non-target engine is dynamically filtered according to starting parameters, meanwhile, a custom-starting class is embedded into a JAR package and a MANIFAST.MF starting entry is modified in a packaging stage through a custom-starting Layout manager extension JarLayout, layout logic injection is realized by combining with Maven plug-in configuration, the type of the target engine is designated only through the starting parameters in deployment, a ClassLoader automatically traverses a URL array and filters conflict dependence according to dependence prefixes, so that seamless switching of multiple engines such as Tomcat, tongWeb is realized.
The following table shows the comparison of response times employed in the present invention versus the corresponding directions in the prior art:
it should be noted that, although the units are seconds, in the financial services industry, the effects of differing seconds are very dramatic.
In addition, the invention also comprises an electronic device, comprising:
a memory for storing a computer program;
And the processor is used for realizing a method for rapidly switching the program bottom layer network engine based on SpringBoot framework when executing the program stored on the memory.
The invention also includes a computer readable storage medium having a computer program stored therein, which when executed by a processor, implements a method for switching a program-based network engine rapidly based on SpringBoot framework.
While the application has been described in terms of preferred embodiments, it is not intended to limit the scope of the application. It is intended that all modifications within the scope of the application, i.e., all equivalents thereof, be embraced by the application as they come within their scope without departing from the application. In the description of the present specification, reference to the terms "one embodiment/manner," "some embodiments/manner," "example," "a particular example," "some examples," etc., means that a particular feature, structure, material, or characteristic described in connection with the embodiment/manner or example is included in at least one embodiment/manner or example of the application. In this specification, the schematic representations of the above terms are not necessarily for the same embodiment/manner or example. Furthermore, the particular features, structures, materials, or characteristics described may be combined in any suitable manner in any one or more embodiments/modes or examples. Furthermore, the various embodiments/modes or examples described in this specification and the features of the various embodiments/modes or examples can be combined and combined by persons skilled in the art without contradiction.
Furthermore, the terms "first," "second," and the like, are used for descriptive purposes only and are not to be construed as indicating or implying a relative importance or implicitly indicating the number of technical features indicated. Thus, a feature defining "a first" or "a second" may explicitly or implicitly include at least one such feature. In the description of the present application, the meaning of "plurality" means at least two, for example, two, three, etc., unless specifically defined otherwise.
It will be appreciated by those skilled in the art that the above-described embodiments are merely for clarity of illustration of the disclosure, and are not intended to limit the scope of the disclosure. Other variations or modifications will be apparent to persons skilled in the art from the foregoing disclosure, and such variations or modifications are intended to be within the scope of the present disclosure.