找回密码
立即注册
搜索
热搜: Java Python Linux Go
发回帖 发新帖

2059

积分

0

好友

281

主题
发表于 昨天 04:41 | 查看: 3| 回复: 0

在实际开发中,我们有时会遇到这样的需求:系统提供一个接口,允许用户自定义该接口的实现,并将实现打包为JAR文件上传。系统需要能够动态加载这些JAR包并实现热部署,以便无缝切换接口的实现方式,从而避免繁琐的重启和手动部署过程。

定义简单的接口

我们以一个简单的计算器功能为例,接口定义如下:

public interface Calculator {
    int calculate(int a, int b);
    int add(int a, int b);
}

接口的简单实现

考虑到用户实现接口的两种方式——依赖Spring上下文管理的注解方式,以及不依赖Spring的反射方式,我们在实现类中分别对应calculate方法和add方法。以下是计算器接口的实现类代码:

@Service
public class CalculatorImpl implements Calculator {
    @Autowired
    CalculatorCore calculatorCore;

    /**
     * 注解方式
     */
    @Override
    public int calculate(int a, int b) {
        int c = calculatorCore.add(a, b);
        return c;
    }

    /**
     * 反射方式
     */
    @Override
    public int add(int a, int b) {
        return new CalculatorCore().add(a, b);
    }
}

这里注入CalculatorCore的目的是为了验证在注解模式下,系统能否完整地构造Bean的依赖体系,并将其注册到当前的Spring容器中。CalculatorCore的代码如下:

@Service
public class CalculatorCore {
    public int add(int a, int b) {
        return a+b;
    }
}

反射方式热部署

用户将JAR包上传到系统的指定目录下。我们假设上传JAR的文件路径为jarAddress,其URL路径为jarPath

private static String jarAddress = "E:/zzq/IDEA_WS/CalculatorTest/lib/Calculator.jar";
private static String jarPath = "file:/" + jarAddress;

同时,系统需要用户提供JAR包中接口实现类的完整类名。接下来,系统需要将该JAR包加载到当前线程的类加载器中,然后通过完整类名加载并得到对应的Class对象,最后通过反射进行调用。完整代码如下:

/**
 * 热加载Calculator接口的实现 反射方式
 */
public static void hotDeployWithReflect() throws Exception {
    URLClassLoader urlClassLoader = new URLClassLoader(new URL[]{new URL(jarPath)}, Thread.currentThread().getContextClassLoader());
    Class clazz = urlClassLoader.loadClass("com.nci.cetc15.calculator.impl.CalculatorImpl");
    Calculator calculator = (Calculator) clazz.newInstance();
    int result = calculator.add(1, 2);
    System.out.println(result);
}

注解方式热部署

如果用户上传的JAR包依赖了Spring上下文,那么我们就需要扫描JAR包中所有需要注入Spring容器的Bean,并将其动态注册到当前系统的Spring容器中。这本质上是一个类的热加载与动态注册相结合的过程。

直接上代码:

/**
 * 加入jar包后 动态注册bean到spring容器,包括bean的依赖
 */
public static void hotDeployWithSpring() throws Exception {
    Set<String> classNameSet = DeployUtils.readJarFile(jarAddress);
    URLClassLoader urlClassLoader = new URLClassLoader(new URL[]{new URL(jarPath)}, Thread.currentThread().getContextClassLoader());
    for (String className : classNameSet) {
        Class clazz = urlClassLoader.loadClass(className);
        if (DeployUtils.isSpringBeanClass(clazz)) {
            BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(clazz);
            defaultListableBeanFactory.registerBeanDefinition(DeployUtils.transformName(className), beanDefinitionBuilder.getBeanDefinition());
        }
    }
}

在这个过程中,将JAR加载到当前线程类加载器的步骤与反射方式相同。随后,扫描JAR包中的所有类文件,获取完整类名,并使用当前线程的类加载器加载对应的Class对象。判断该Class对象是否带有Spring的注解,如果包含,则将其注册到系统的Spring容器中。

DeployUtils工具类包含了读取JAR包所有类文件、判断Class对象是否包含Spring注解以及获取注册Bean对象名称的方法。代码如下:

/**
 * 读取jar包中所有类文件
 */
public static Set<String> readJarFile(String jarAddress) throws IOException {
    Set<String> classNameSet = new HashSet<>();
    JarFile jarFile = new JarFile(jarAddress);
    Enumeration<JarEntry> entries = jarFile.entries(); //遍历整个jar文件
    while (entries.hasMoreElements()) {
        JarEntry jarEntry = entries.nextElement();
        String name = jarEntry.getName();
        if (name.endsWith(".class")) {
            String className = name.replace(".class", "").replaceAll("/", ".");
            classNameSet.add(className);
        }
    }
    return classNameSet;
}
/**
 * 方法描述 判断class对象是否带有spring的注解
 */
public static boolean isSpringBeanClass(Class<?> cla) {
    if (cla == null) {
        return false;
    }
    //是否是接口
    if (cla.isInterface()) {
        return false;
    }
    //是否是抽象类
    if (Modifier.isAbstract(cla.getModifiers())) {
        return false;
    }
    if (cla.getAnnotation(Component.class) != null) {
        return true;
    }
    if (cla.getAnnotation(Repository.class) != null) {
        return true;
    }
    if (cla.getAnnotation(Service.class) != null) {
        return true;
    }
    return false;
}
/**
 * 类名首字母小写 作为spring容器beanMap的key
 */
public static String transformName(String className) {
    String tmpstr = className.substring(className.lastIndexOf(".") + 1);
    return tmpstr.substring(0, 1).toLowerCase() + tmpstr.substring(1);
}

删除JAR时,同时删除Spring容器中注册的Bean

在JAR包被切换或删除时,需要将之前注册到Spring容器中的Bean也一并删除。这是一个与注册操作相反的过程,需要注意的是,必须使用同一个Spring上下文。

代码如下:

/**
 * 删除jar包时 需要在spring容器删除注入
 */
public static void delete() throws Exception {
    Set<String> classNameSet = DeployUtils.readJarFile(jarAddress);
    URLClassLoader urlClassLoader = new URLClassLoader(new URL[]{new URL(jarPath)}, Thread.currentThread().getContextClassLoader());
    for (String className : classNameSet) {
        Class clazz = urlClassLoader.loadClass(className);
        if (DeployUtils.isSpringBeanClass(clazz)) {
            defaultListableBeanFactory.removeBeanDefinition(DeployUtils.transformName(className));
        }
    }
}

测试

测试类手动模拟了用户上传JAR包的功能。测试函数写了一个循环,初始时若未找到JAR包会抛出异常,捕获异常后让线程睡眠10秒。这期间,我们可以手动将JAR包放到指定的目录下,以模拟上传过程。

代码如下:

ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
DefaultListableBeanFactory defaultListableBeanFactory = (DefaultListableBeanFactory) applicationContext.getAutowireCapableBeanFactory();
while (true) {
    try {
        hotDeployWithReflect();
        // hotDeployWithSpring();
        // delete();
    } catch (Exception e) {
        e.printStackTrace();
        Thread.sleep(1000 * 10);
    }
}

通过上述方案,我们实现了一个支持动态上传JAR并完成热部署的插件化系统架构,这对于需要支持用户自定义扩展或模块热插拔的应用场景非常有用。

来源:https://blog.csdn.net/zhangzhiqiang_0912

如果你对Java进阶技术或系统设计感兴趣,欢迎到云栈社区与其他开发者交流探讨。

文章结束




上一篇:免费开源的一键重装工具LetRecovery,原生支持WIM/ESD/ISO系统镜像
下一篇:Antirez亲述:从抗拒到拥抱,我的AI编程实践与核心思考
您需要登录后才可以回帖 登录 | 立即注册

手机版|小黑屋|网站地图|云栈社区 ( 苏ICP备2022046150号-2 )

GMT+8, 2026-1-16 02:06 , Processed in 0.490283 second(s), 37 queries , Gzip On.

Powered by Discuz! X3.5

© 2025-2025 云栈社区.

快速回复 返回顶部 返回列表