javasist埋点

package com.example.rabbit;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.MessageProperties;
import javassist.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @author xianmingyuan
 */
public class RabbitApplication {

    public static void main(String[] args) throws NotFoundException, CannotCompileException, IOException, TimeoutException {
        modifyChannelNClass();
        sendMsg();
    }

    private static void sendMsg() throws IOException, TimeoutException {
        String exchangeName = "test";
        String rk = "test";
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("*.*.*.*");
        factory.setUsername("guest");
        factory.setPassword("guest");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        String message = "RabbitMQ Demo Test:" + System.currentTimeMillis();
        channel.basicPublish(exchangeName, rk, MessageProperties.PERSISTENT_TEXT_PLAIN, message.getBytes());
        channel.close();
        connection.close();
    }


    private static void modifyChannelNClass() throws NotFoundException, CannotCompileException {
        ClassPool pool = ClassPool.getDefault();
        pool.importPackage("org.slf4j.Logger");
        pool.importPackage("org.slf4j.LoggerFactory");
        pool.importPackage("com.rabbitmq.client.impl.ChannelN");
        CtClass ctClass = pool.get("com.rabbitmq.client.impl.ChannelN");

        // 添加log字段
        CtField f = CtField.make("private static final Logger log = LoggerFactory.getLogger(ChannelN.class);", ctClass);
        ctClass.addField(f);

        // 修改方法
        CtClass[] params = new CtClass[6];
        params[0] = pool.get("java.lang.String");
        params[1] = pool.get("java.lang.String");
        params[2] = pool.get("boolean");
        params[3] = pool.get("boolean");
        params[4] = pool.get("com.rabbitmq.client.AMQP$BasicProperties");
        params[5] = pool.get("byte[]");
        CtMethod basicPublish = ctClass.getDeclaredMethod("basicPublish", params);
        basicPublish.setBody(basicPublish, null);
        basicPublish.insertBefore("{" +
                "log.info(\"exchange = [{}], routingKey = [{}]\", $1, $2);" +
                "}");
        // 重新加载
        ctClass.toClass();
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值