具有隔离类加载器的Java插件
Sometimes it’s impossible to keep up with users’ demands. In these cases you may want to explore plugins, a mechanism to offload parts of your system’s logic to the user; the user writes the plugin, your system runs it. In this article, we explore how to support plugins on the JVM with isolating class loaders. Isolating class loaders prevent the problem named dependency hell where it becomes hard, or even impossible to find a set of dependencies that are interoperable. They do this by allowing each plugin to run in its own class loader, with its own set of dependencies. After reading this article you should be able to design and write your own plugin system on the JVM.
有时跟上用户的需求是不可能的。在这些情况下,你可能想要探索插件,一种将系统逻辑的部分卸载给用户的机制;用户编写插件,你的系统运行它。在本文中,我们探讨如何在JVM上使用隔离类加载器支持插件。隔离类加载器防止了名为依赖地狱的问题,在这种情况下,找到一组可互操作的依赖项变得困难,甚至不可能。它们通过允许每个插件在自己的类加载器中运行,并拥有自己的一组依赖项来实现这一点。阅读完本文后,你应该能够在JVM上设计和编写自己的插件系统。
In the Data and Analytics organisation of Adevinta we experimented by adding a framework to run message transformations on streaming data using plugins. We took this direction in the aftermath of an outage. The outage was caused by libraries with mismatching dependencies that managed to reach production.
在Adevinta的数据和分析组织中,我们通过添加一个框架来实验在流数据上使用插件进行消息转换。我们在一次故障之后采取了这个方向。故障是由于具有不匹配依赖关系的库成功进入生产环境所导致的。
We quickly realised that information on how to properly write a plugin-engine is not easy to find on the internet. This article hopefully fills the gap.
我们很快意识到,关于如何正确编写插件引擎的信息在互联网上并不容易找到。希望这篇文章能填补这个空白。
Note: all code examples are written in Scala, but they should all be simple to translate to Java or Kotlin.
注意:所有代码示例均使用Scala编写,但它们都应该很容易转换为Java或Kotlin。
Step 1 – define the plugin interface
步骤 1 – 定义插件接口
The plugin interface is the Java interface that will be implemented by the plugins. It is through this interface that the plugin engine will invoke the plugin.
插件接口是将由插件实现的Java接口。正是通过这个接口,插件引擎将调用插件。
This might be surprising in the world of agility, but a good definition, right from the start, is quite important. There are several reasons for that:
在...