热部署instrumentation工具类

简介: 利用jvm的instrumentation类实现实时修改class文件,用来更新线上代码。

import lombok.extern.slf4j.Slf4j;
import net.bytebuddy.agent.ByteBuddyAgent;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.lang.instrument.Instrumentation;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
public class ReloadClassUtil {

/**
 * 手动上传class文件实时更新jvm内存中的字节码文件
 * @param classFile newClassFile
 * @param classPath com.xxx.xxx.xxx
 * @return success/fail
 */
@PostMapping("/reloadClass")
public Result<String> reloadClass(List<MultipartFile> classFiles, String classPath) {
    log.info("reloadClass start, classPath:{}", classPath);
    if (!permission) return new Result<>(ResultCodeEnum.UNAUTHORIZED);
    return reTransformClass(classFiles, classPath);
}

private Result<String> reTransformClass(List<MultipartFile> files, String path){
    try {
        Map<String, String> fileByteMap = new HashMap<>();
        for (MultipartFile file : files) {
            String className = path + "." + file.getOriginalFilename().replace(".class", "");
            reTransform(file.getBytes(), className);
            fileByteMap.put(className, Base64Utils.encodeBase64String(file.getBytes()));
        }
        syncOthersClient(fileByteMap);
        return new Result<>(ResultCodeEnum.SUCCESS);
    } catch (Exception e) {
        log.error("reloadClass exception", e);
        return new Result<>(ResultCodeEnum.INTERNAL_SERVER_ERROR, e.getMessage());
    }
}

/**
 * 重载class
 * @param fileBytes 字节码文件
 * @param classPath 目标包+类名
 */
public static boolean reTransform(byte[] fileBytes, String classPath) throws Exception{
    inst = inst != null ? inst : ByteBuddyAgent.install();
    String targetClass = classPath.replace(".", "/");
    inst.addTransformer((loader, className, classBeingRedefined, protectionDomain, classfileBuffer) ->
            className.equals(targetClass) ? fileBytes : classfileBuffer, true);
    inst.retransformClasses(Class.forName(classPath));
    return true;
}

/**
 * 同步class文件给集群内其他服务器
 */
private void syncOthersClient(Map<String, String> fileByteMap){
    StringBuilder sb = new StringBuilder();
    fileByteMap.forEach((k,v) -> {
        sb.append(k).append(",");
        redisTemplate.opsForValue().set(k, v, cacheSecond, TimeUnit.SECONDS);
    });
    ReloadClassDto body = ReloadClassDto.builder().classPath(sb.substring(0, sb.length()-1)).build();
    mq.sendMsg(body);
}

@Value("${reload.cacheSecond:60}")
private long cacheSecond;

@Value("${reload.permission:false}")
private boolean permission;

private static Instrumentation inst;

@Resource
private RedisTemplate<String, String> redisTemplate;

}

相关文章
|
移动开发 网络协议 算法
TCP中的粘包、拆包问题产生原因及解决方法
TCP中的粘包、拆包问题产生原因及解决方法
2472 0
TCP中的粘包、拆包问题产生原因及解决方法
|
消息中间件 存储 Kafka
RocketMQ 工作原理图解,看这篇就够了!
本文详细解析了 RocketMQ 的核心架构、消息领域模型、关键特性和应用场景,帮助深入理解消息中间件的工作原理。关注【mikechen的互联网架构】,10年+BAT架构经验倾囊相授。
RocketMQ 工作原理图解,看这篇就够了!
|
缓存 网络协议 算法
TCP粘包、拆包原因与解决方案
TCP粘包、拆包原因与解决方案
1146 0
|
Java Android开发 Windows
|
8天前
|
域名解析 人工智能 Linux
|
18天前
|
Linux Go 开发工具
手机上跑 DeepSeek 智能体:开源安卓客户端 DSH Go 安装与使用指南
DSH Go 是一款开源安卓客户端,将 DeepSeek Harness 智能体引擎装进手机:免 Root、免 Termux,一键安装即用;支持本机运行(内置 Ubuntu+Node.js)或远程接管电脑会话;具备插话打断、过程折叠、屏幕操控、端到端加密分享等特色功能,真正实现智能体“口袋化”。
16802 62
|
16天前
|
人工智能
Google 提示「所在地区不可用」?进不去 Antigravity 或 Gemini,先查账号这个设置
进不去 Antigravity 或 Gemini,提示所在地区不可用?三步查清 Google 账号关联地区、官方更正表单理由选法与改区注意事项。
Google 提示「所在地区不可用」?进不去 Antigravity 或 Gemini,先查账号这个设置
|
2天前
|
人工智能 安全 网络安全
|
5天前
|
云安全 数据采集 人工智能
|
6天前
|
Linux API iOS开发
【DSH】DeepSeek Harness新手保姆教程(下载+安装+配置+使用,2026最新实测)
DeepSeek Harness(dsh)是 DeepSeek AI 开源的智能体框架,秉持“一切皆插件”理念,支持读文件、改代码、执行命令、处理表格等自动化任务;免费开源,兼容 Win/macOS,需配 API 密钥使用。(239字)
1206 2