起初,看skywalking agent源码的时候一直有个疑惑,万一应用中依赖的jar包跟skywalking agent依赖的jar包冲突了怎么办?后来研究一下,原来agent打包时将它依赖的jar包进行了重命名。那么它是怎么实现重名了的呢?其实是通过maven-shade-plugin来实现的。
一、概述
maven-shade-plugin提供了打包功能,包含了它所依赖的jar包,以及重命名依赖jar的包名解决依赖冲突。
二、使用
1、配置插件
<project>
...
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.2.4</version>
<configuration>
<!-- put your configurations here -->
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
...
</project>
2、选择打到jar包中的内容
<project>
...
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.2.4</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<filters>
<filter>
<artifact>junit:junit</artifact>
<includes>
<include>junit/framework/**</include>
<include>org/junit/**</include>
</includes>
<excludes>
<exclude>org/junit/experimental/**</exclude>
<exclude>org/junit/runners/**</exclude>
</excludes>
</filter>
<filter>
<artifact>*:*</artifact>
<excludes>
<exclude>META-INF/*.SF</exclude>
<exclude>META-INF/*.DSA</exclude>
<exclude>META-INF/*.RSA</exclude>
</excludes>
</filter>
</filters>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
...
</project>
标识需要打包到jar中的资源。
标识不需要打包到jar中的资源。
e g. junit artifact表示把junit/framework子包和org/junit子包,org/junit/experimental/和org/junit/runners/子包资源不打入jar。
如果你想自动异常项目里不依赖的资源,可以通过配置true。
3、重定向类
如果你打包出来的jar会被重用,那么很可能出现jar包冲突(即依赖你jar包的应用依赖的jar和你的jar中依赖的jar冲突),我们可以通过重定向类来解决这个问题。
<project>
...
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.2.4</version>
<configuration>
<artifactSet>
<includes>
<include>redis.clients:jedis</include>
</includes>
</artifactSet>
<relocations>
<relocation>
<pattern>redis</pattern>
<shadedPattern>com.kevin.shaded.redis</shadedPattern>
</relocation>
</relocations>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
...
</project>
打包重用jar时,可以重命名依赖的class。重命名class的同时,会修改引用了该class字节码文件。
eg.如上述,将jedis中redis包重命名为com.kevin.shaded.redis。
参考:http://maven.apache.org/plugins/maven-shade-plugin/index.html