assembly打包,多yml文件合并为一个yml文件

2024-02-24 09:52
文章标签 打包 合并 yml assembly

本文主要是介绍assembly打包,多yml文件合并为一个yml文件,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

这个接着前一个多个服务合并为一个服务的文章,详解yml配置文件合并的问题

由于每个微服务都有yml配置文件,如果合并打包的话,前一篇文章也说了,相同文件会进行覆盖,所以需要自己实现一个适配器,进行yml文件的合并。使用maven-assembly-plugin进行多文件合并逻辑的实现。

首先新建一个模块,实现yml合并的逻辑。

1、pom文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.1.5.RELEASE</version><relativePath/></parent><groupId>com.fql.merge</groupId><artifactId>preHandle</artifactId><version>1.0-SNAPSHOT</version><packaging>jar</packaging><dependencies><dependency><groupId>org.apache.maven.plugins</groupId><artifactId>maven-assembly-plugin</artifactId><version>3.3.0</version></dependency><dependency><groupId>org.apache.maven.plugin-tools</groupId><artifactId>maven-plugin-annotations</artifactId><version>3.5.2</version></dependency><dependency><groupId>org.yaml</groupId><artifactId>snakeyaml</artifactId><version>1.27</version></dependency></dependencies><build><plugins><plugin><groupId>org.codehaus.plexus</groupId><artifactId>plexus-component-metadata</artifactId><version>2.2.0</version><executions><execution><goals><goal>generate-metadata</goal></goals></execution></executions></plugin></plugins></build>
</project>

合并类实现

package com.lfq.integ.util;import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.*;import org.apache.maven.plugins.assembly.filter.ContainerDescriptorHandler;
import org.apache.maven.plugins.assembly.utils.AssemblyFileUtils;
import org.codehaus.plexus.archiver.Archiver;
import org.codehaus.plexus.archiver.ArchiverException;
import org.codehaus.plexus.archiver.UnArchiver;
import org.codehaus.plexus.component.annotations.Component;
import org.codehaus.plexus.components.io.fileselectors.FileInfo;
import org.codehaus.plexus.logging.LogEnabled;
import org.codehaus.plexus.logging.Logger;
import org.codehaus.plexus.logging.console.ConsoleLogger;
import org.codehaus.plexus.util.IOUtil;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;/*** @author lifengqin*/
@Component(role = ContainerDescriptorHandler.class, hint = "yml-merge", instantiationStrategy = "per-lookup" )
public class MySimpleAggregatingDescriptorHandler implements  ContainerDescriptorHandler, LogEnabled{@SuppressWarnings( "FieldCanBeLocal" )private final String commentChars = "#";private final StringWriter aggregateWriter = new StringWriter();private final List<String> filenames = new ArrayList<>();private String filePattern;private String outputPath;private boolean overrideFilterAction;private Logger logger;private Archiver archiver;private File temp;@Overridepublic void finalizeArchiveCreation(Archiver archiver ){checkConfig();if ( this.outputPath.endsWith( "/" ) ) {throw new ArchiverException( "Cannot write aggregated properties to a directory. "+ "You must specify a file name in the outputPath configuration for this"+ " handler. (handler: " + getClass().getName() );}if ( this.outputPath.startsWith( "/" ) ) {this.outputPath = this.outputPath.substring( 1 );}this.temp = this.writePropertiesFile();this.overrideFilterAction = true;archiver.addFile(this.temp, this.outputPath);this.archiver = archiver;this.overrideFilterAction = false;}private File writePropertiesFile() {File f;Writer writer = null;try {f = File.createTempFile("maven-assembly-plugin", "tmp");f.deleteOnExit();writer = AssemblyFileUtils.isPropertyFile( f )? new OutputStreamWriter( new FileOutputStream( f , true), StandardCharsets.ISO_8859_1 ): new OutputStreamWriter( new FileOutputStream( f , true) );writer.write( "\n\n" );writer.write( aggregateWriter.toString() );writer.close();writer = null;}catch ( final IOException e ) {throw new ArchiverException("Error adding aggregated properties to finalize archive creation. Reason: " + e.getMessage(), e );}finally {IOUtil.close(writer);}return f;}@Overridepublic void finalizeArchiveExtraction( final UnArchiver unarchiver ) {}@Overridepublic List<String> getVirtualFiles() {checkConfig();return Collections.singletonList( outputPath );}@Overridepublic boolean isSelected(final FileInfo fileInfo ) throws IOException {if (fileInfo == null){throw new IllegalStateException("fileInfo not be none");}checkConfig();if ( overrideFilterAction ) {return true;}String name = AssemblyFileUtils.normalizeFileInfo( fileInfo );if ( fileInfo.isFile() && name.matches( filePattern ) ) {String content = readProperties( fileInfo );if (name.matches(".*/application.yml")) {writeFile(content);}return false;}return true;}private void checkConfig() {if ( filePattern == null || outputPath == null ) {throw new IllegalStateException("You must configure filePattern and outputPath in your containerDescriptorHandler declaration." );}}/***读取文件* @param fileInfo* @throws IOException*/private String readProperties( final FileInfo fileInfo ) throws IOException {try (StringWriter writer = new StringWriter();Reader reader = AssemblyFileUtils.isPropertyFile(fileInfo.getName())? new InputStreamReader(fileInfo.getContents(), StandardCharsets.ISO_8859_1): new InputStreamReader(fileInfo.getContents())) {IOUtil.copy(reader, writer);final String content = writer.toString();aggregateWriter.write("\n");aggregateWriter.write(content);return content;}}//输出合并后的yml文件private void writeFile(String content) {Writer writer = null;try {writer = AssemblyFileUtils.isPropertyFile( this.temp )? new OutputStreamWriter( new FileOutputStream( this.temp , false), StandardCharsets.ISO_8859_1 ): new OutputStreamWriter( new FileOutputStream( this.temp, false ) );//去掉{}样式DumperOptions options = new DumperOptions();options.setPrettyFlow(true);options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);// 创建YAML对象Yaml yam = new Yaml(options);Map<Object, Object> mergeYmlMap = new HashMap<>();// 将合并后的YAML文件加载到Map对象中for (Object o : yam.loadAll(String.valueOf(this.aggregateWriter))) {Map<Object, Object> ymlMap = (Map<Object, Object>) o;for (Map.Entry<Object, Object> entry : ymlMap.entrySet()) {if (!mergeYmlMap.containsKey(entry.getKey())) {mergeYmlMap.put(entry.getKey(), entry.getValue());} else if (entry.getValue() instanceof Map){mergeMaps((Map<Object, Object>) mergeYmlMap.get(entry.getKey()), (Map<Object, Object>) entry.getValue());}}}// 保存合并结果到目标文件yam.dump(mergeYmlMap, writer);writer.close();writer = null;}catch ( final IOException e ) {throw new ArchiverException("Error adding aggregated properties to finalize archive creation. Reason: " + e.getMessage(), e );}finally {IOUtil.close( writer );}}private static void mergeMaps(Map<Object, Object> target, Map<Object, Object> source) {for (Map.Entry<Object, Object> entry : source.entrySet()) {if (!target.containsKey(entry.getKey())) {target.put(entry.getKey(), entry.getValue());} else if (entry.getValue() instanceof Map){mergeMaps((Map<Object, Object>) target.get(entry.getKey()), (Map<Object, Object>) entry.getValue());}}}protected final Logger getLogger() {if ( logger == null ) {logger = new ConsoleLogger( Logger.LEVEL_INFO, "" );}return logger;}@Overridepublic void enableLogging( final Logger logger ) {this.logger = logger;}@SuppressWarnings( "UnusedDeclaration" )public String getFilePattern() {return filePattern;}@SuppressWarnings( "UnusedDeclaration" )public void setFilePattern( final String filePattern ) {this.filePattern = filePattern;}@SuppressWarnings( "UnusedDeclaration" )public String getOutputPath() {return outputPath;}@SuppressWarnings( "UnusedDeclaration" )public void setOutputPath( final String outputPath ) {this.outputPath = outputPath;}
}

合并的containerDescriptorHandler写好啦

在pom文件加上模块依赖

<!-- 将解开的执行包与本工程代码合并打包 -->
<plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-assembly-plugin</artifactId><version>3.3.0</version><configuration><recompressZippedFiles>false</recompressZippedFiles></configuration><executions><execution><id>make-assembly</id><phase>package</phase><goals><goal>single</goal></goals><configuration><archive><manifestFile>${project.build.directory}/work/addpack/mainweb/META-INF/MANIFEST.MF</manifestFile></archive><descriptors><descriptor>assembly.xml</descriptor>   <!-- 加载指定的assembly配置文件 --></descriptors></configuration></execution></executions> <dependencies><dependency><groupId>com.southgis.ibase</groupId><artifactId>preHandle</artifactId><version>1.0-SNAPSHOT</version></dependency></dependencies>
</plugin>

在assembly.xml文件加上containerDescriptorHandler

<containerDescriptorHandlers>
      <containerDescriptorHandler>
         <handlerName>yml-merge</handlerName>
         <configuration>
            <filePattern>.*/application.yml</filePattern>
            <outputPath>BOOT-INF/classes/application.yml</outputPath>
         </configuration>
      </containerDescriptorHandler>
   </containerDescriptorHandlers>

这篇关于assembly打包,多yml文件合并为一个yml文件的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/741720

相关文章

hdu2241(二分+合并数组)

题意:判断是否存在a+b+c = x,a,b,c分别属于集合A,B,C 如果用暴力会超时,所以这里用到了数组合并,将b,c数组合并成d,d数组存的是b,c数组元素的和,然后对d数组进行二分就可以了 代码如下(附注释): #include<iostream>#include<algorithm>#include<cstring>#include<stack>#include<que

springboot3打包成war包,用tomcat8启动

1、在pom中,将打包类型改为war <packaging>war</packaging> 2、pom中排除SpringBoot内置的Tomcat容器并添加Tomcat依赖,用于编译和测试,         *依赖时一定设置 scope 为 provided (相当于 tomcat 依赖只在本地运行和测试的时候有效,         打包的时候会排除这个依赖)<scope>provided

day-51 合并零之间的节点

思路 直接遍历链表即可,遇到val=0跳过,val非零则加在一起,最后返回即可 解题过程 返回链表可以有头结点,方便插入,返回head.next Code /*** Definition for singly-linked list.* public class ListNode {* int val;* ListNode next;* ListNode() {}*

【每日一题】LeetCode 2181.合并零之间的节点(链表、模拟)

【每日一题】LeetCode 2181.合并零之间的节点(链表、模拟) 题目描述 给定一个链表,链表中的每个节点代表一个整数。链表中的整数由 0 分隔开,表示不同的区间。链表的开始和结束节点的值都为 0。任务是将每两个相邻的 0 之间的所有节点合并成一个节点,新节点的值为原区间内所有节点值的和。合并后,需要移除所有的 0,并返回修改后的链表头节点。 思路分析 初始化:创建一个虚拟头节点

【Python从入门到进阶】64、Pandas如何实现数据的Concat合并

接上篇《63.Pandas如何实现数据的Merge》 上一篇我们学习了Pandas如何实现数据的Merge,本篇我们来继续学习Pandas如何实现数据的Concat合并。 一、引言 在数据处理过程中,经常需要将多个数据集合并为一个统一的数据集,以便进行进一步的分析或建模。这种需求在多种场景下都非常常见,比如合并不同来源的数据集以获取更全面的信息、将时间序列数据按时间顺序拼接起来以观察长期趋势等

android6/7 system打包脚本

1.android5打包system就是网站上常见的制作ROM必备的解包打包system脚本 指令如下:mkuserimg.sh -s out/target/product/$TARGET_PRODUCT/system out/target/product/$TARGET_PRODUCT/obj/PACKAGING/systemimage_intermediates/system.img

android打包解包boot.img,system.img

原帖地址:http://www.52pojie.cn/thread-488025-1-1.html 转载Mark一下,日后研究 最近工作需要对boot.img,system.img进行破解。顺便将心得分享一下。 我的工作环境是在linux下的。所以工具都是针对linux的。 boot.img破解相关工具: 1、split_boot    perl脚本 2、boot_i

MTK Android P/Q system/vendor/super快速打包

一、Android 新版本默认开启了动态分区,把system vendor  product等分区打包成一个super分区。这对于我们使用替换分区的方法来排查问题不是很方便,直接替换一个super也不知道到底是哪个部分导致的。所以我们需要自己制作super.img来缩小范围。下面讲讲如何快速生成system、vendor、super,以及vbmeta(校验image,不匹配可能会导致不开机) 二

MTK AndroidP/Q快速打包ramdisk

一、Android P/Q ramdisk与老版本的差异 Android老版本的ramdisk是out下的root/ramdisk打包而来,里面包含了init  /sbin  init.rc   default.prop等文件。是一个完整的ramdisk Android新版本ramdisk分为了out 下的ramdisk目录和root目录,init ,init.rc等文件大部分都放到了syst

Android P/Q MTK平台无依赖打包boot.img

背景:        有时排查版本问题,需要用到替换img的方式来查找问题出现在哪个img,若出现在bootimg,那到底是kernel、DTB 还是ramdisk。此时就需要单独替换其中一个的方式来打包,之前直接make bootimage-nodeps就可以了,但现在发现执行这个命令无效了。下面就分析下新版本如何找到正确的打包命令。 一、找到编译boot的命令 之前Android编译lo