SkyWalking源码-- Agent 服务

255 阅读1分钟

本文基于 SkyWalking-Java-agent 8.15.0 版本

image.png

// 4.启动服务  
ServiceManager.INSTANCE.boot();
...
...
private Map<Class, BootService> bootedServices = Collections.emptyMap();

public void boot() {  
    // 加载所有服务  
    bootedServices = loadAllServices();  

    // 调用服务的生命周期  
    prepare();  
    startup();  
    onComplete();  
}

服务组织

  • 服务需要实现 BootService 接口
  • 如果服务只有一种实现,直接创建一个类即可
  • 如果服务有多种实现
    • 默认实现需要使用 @DefaultImplementor
    • 覆盖实现需要使用 @OverrideImplementor
package org.apache.skywalking.apm.agent.core.boot;  
  
/**  
* The <code>BootService</code> is an interface to all remote, which need to boot when plugin mechanism begins to work.  
* {@link #boot()} will be called when <code>BootService</code> start up.  
*/  
public interface BootService {  
    /**  
    * 准备阶段  
    * @throws Throwable  
    */  
    void prepare() throws Throwable;  

    /**  
    * 启动阶段  
    * @throws Throwable  
    */  
    void boot() throws Throwable;  

    /**  
    * 启动完成阶段  
    * @throws Throwable  
    */  
    void onComplete() throws Throwable;  

    /**  
    * 关闭阶段  
    * @throws Throwable  
    */  
    void shutdown() throws Throwable;  

    /**  
    * 指定服务的优先级,优先级高的服务先启动  
    * {@code BootService}s with higher priorities will be started earlier, and shut down later than those {@code BootService}s with lower priorities.  
    *  
    * @return the priority of this {@code BootService}.  
    */  
    default int priority() {  
        return 0;  
    }  
}

加载流程

  • SPI 加载所有 BootService 的实现
  • 根据服务的实现模式进行服务的筛选
    • 两个注解都没有的服务直接加入集合
    • 对于 @DefaultImplementor
      • 直接加入集合
    • 对于 @OverrideImplementor
      • value 指向的服务有 @DefaultImplementor 则覆盖掉
      • value 指向的服务没有 @DefaultImplementor 则报错