1 1.0 Develop Guide of Plugin
吴晟 Wu Sheng edited this page 2016-12-14 10:59:08 +08:00
This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

本文档描述插件的开发方法

快速开发一个全新的RPC插件

  • 本节将以Dubbo为例,快速开发一个RPC插件。完整源码参考dubbo-plugin工程
  1. 需要熟悉Dubbo源码,了解dubbo的客户端、服务端调用的主体逻辑。找到客户端和服务端一定会调用的类(客户端服务端可以不一样),并且类的方法参数中,有所需要监控的基本数据,如:RPC的url,RPC的context上下文,返回值,异常等。dubbo我们选用com.alibaba.dubbo.monitor.support.MonitorFilter,其中包含所需的所有内容
  2. 定义插件定义类,此类需要扩展自标准底层实现com.a.eye.skywalking.plugin.interceptor.enhance.ClassEnhancePluginDefine,以及此子类。由于dubbo的插件,只需要拦截实例方法,则定义为public class DubboPluginDefine extends ClassInstanceMethodsEnhancePluginDefine
  3. 实现抽象方法。定义拦截的类,方法(一个或多个),对应的拦截器类名(一定是字符串返回)。
public class DubboPluginDefine extends ClassInstanceMethodsEnhancePluginDefine {
    @Override
    protected MethodMatcher[] getInstanceMethodsMatchers() {
        return new MethodMatcher[]{new SimpleMethodMatcher("invoke")};
    }

    @Override
    protected String getInstanceMethodsInterceptor() {
        return "com.a.eye.skywalking.plugin.dubbo.MonitorFilterInterceptor";
    }

    @Override
    protected String enhanceClassName() {
        return "com.alibaba.dubbo.monitor.support.MonitorFilter";
    }
}
  1. 定义拦截器。实例方法拦截器,需要实现InstanceMethodsAroundInterceptor接口。接口需实现如下方法。
public interface InstanceMethodsAroundInterceptor {
	public void onConstruct(EnhancedClassInstanceContext context, ConstructorInvokeContext interceptorContext);
	
	public void beforeMethod(EnhancedClassInstanceContext context, InstanceMethodInvokeContext interceptorContext, MethodInterceptResult result);
	
	public Object afterMethod(EnhancedClassInstanceContext context, InstanceMethodInvokeContext interceptorContext, Object ret);
	
	public void handleMethodException(Throwable t, EnhancedClassInstanceContext context, InstanceMethodInvokeContext interceptorContext);
}

如果拦截静态方法,需要拦截器实现StaticMethodsAroundInterceptor接口。接口需实现如下方法

public interface StaticMethodsAroundInterceptor {
	public void beforeMethod(StaticMethodInvokeContext interceptorContext, MethodInterceptResult result);
	
	public Object afterMethod(StaticMethodInvokeContext interceptorContext, Object ret);
	
	public void handleMethodException(Throwable t, MethodInvokeContext interceptorContext);
}
  1. 实现拦截器逻辑。构建RPCClientInvokeMonitor.beforeInvoke/afterInvoke和RPCServerInvokeMonitor.beforeInvoke/afterInvoke,并利用RPC框架在客户端和服务端间传递上下文ContextData(RPCClientInvokeMonitor.beforeInvoke的返回值)。构建MonitorFilterInterceptor。请直接参考工程源码