All Downloads are FREE. Search and download functionalities are using the official Maven repository.

fun.fengwk.convention4j.tracer.propagation.TracerTransformer Maven / Gradle / Ivy

There is a newer version: 1.1.14
Show newest version
package fun.fengwk.convention4j.tracer.propagation;

import fun.fengwk.convention4j.common.util.LazyServiceLoader;
import fun.fengwk.convention4j.tracer.propagation.extract.Extract;
import fun.fengwk.convention4j.tracer.propagation.inject.Inject;
import io.opentracing.SpanContext;
import io.opentracing.propagation.Format;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author fengwk
 */
@Slf4j
public class TracerTransformer {

    private final Map, Inject> injectRegistry;
    private final Map, Extract> extractRegistry;

    public TracerTransformer() {
        this.injectRegistry = loadRegistry(Inject.class);
        this.extractRegistry = loadRegistry(Extract.class);
    }

    /**
     * @see io.opentracing.Tracer#inject(SpanContext, Format, Object)
     */
    public  void inject(SpanContext spanContext, Format format, C carrier) {
        Inject inject = (Inject) injectRegistry.get(format);
        if (inject == null) {
            log.warn("Inject not found, format: {}", format);
            return;
        }
        inject.inject(spanContext, carrier);
    }

    /**
     * @see io.opentracing.Tracer#extract(Format, Object)
     */
    public  SpanContext extract(Format format, C carrier) {
        Extract extract = (Extract) extractRegistry.get(format);
        if (extract == null) {
            log.warn("Extract not found, format: {}", format);
            return null;
        }
        return extract.extract(carrier);
    }

    private > Map, T> loadRegistry(Class clazz) {
        List services = LazyServiceLoader.loadServiceIgnoreLoadFailed(clazz);
        Map, T> registry = new HashMap<>();
        for (T service : services) {
            registry.put(service.format(), service);
        }
        return registry;
    }

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy