CDI扩展动态更新属性

时间:2019-02-05 18:17:03

标签: java-ee cdi java-ee-7 java-ee-8 cdi-2.0

我阅读了一些有关CDI自定义扩展的文档,并在以下链接上阅读了一些示例代码,例如Properties loader:Link-A-Link-B

我写了一个像这样的代码的简单cdi扩展名。

public class SystemStatisticExtension implements Extension {

    public <T> void processInjectionTarget(@Observes ProcessInjectionTarget<T> pit) {
        AnnotatedType<T> at = pit.getAnnotatedType();
        InjectionTarget<T> it = pit.getInjectionTarget();
        if (at.isAnnotationPresent(Monitor.class)) {
            pit.setInjectionTarget(new MemoryInjectionPoint<>(it, at));
        }
    }
}

这是我的InjectionPointTarget实现:

public class MemoryInjectionPoint<T> implements InjectionTarget<T> {

    private InjectionTarget<T> it;
    private AnnotatedType<T> at;
    private int kB = 1024;
    private int mB = kB / 1024;
    private int gB = mB / 1024;

    public MemoryInjectionPoint(InjectionTarget<T> it, AnnotatedType<T> at) {
        this.it = it;
        this.at = at;
    }

    @Override
    public void inject(T instance, CreationalContext<T> ctx) {
        it.inject(instance, ctx);
        int swapUsed = SystemPropertiesLoader.newInstance().getSwapUsed();
        Set<AnnotatedField<? super T>> annotatedFields = at.getFields();
        for (AnnotatedField<? super T> annotatedField : annotatedFields) {
            if (annotatedField.isAnnotationPresent(Memory.class)) {
                int memUsed = SystemPropertiesLoader.newInstance().getMemUsed();
                Memory memory = annotatedField.getAnnotation(Memory.class);
                Unit u = memory.unitType();
                switch (u) {
                    case KILOBYTE:
                        setFieldMemValue(instance, memUsed / kB, annotatedField);
                        break;
                    case MEGABYTE:
                        setFieldMemValue(instance, memUsed / mB, annotatedField);
                        break;
                    case GIGABYTE:
                        setFieldMemValue(instance, memUsed / gB, annotatedField);
                        break;
                }
            }
            if (at.isAnnotationPresent(Swap.class)) {
                Memory memory = annotatedField.getAnnotation(Memory.class);
                Unit u = memory.unitType();
                switch (u) {
                    case kILOBYTE:
                        setFieldSwapValue(instance, swapUsed / kB, annotatedField);
                        break;
                    case MEGABYTE:
                        setFieldSwapValue(instance, swapUsed / mB, annotatedField);
                        break;
                    case GIGABYTE:
                        setFieldSwapValue(instance, swapUsed / gB, annotatedField);
                        break;
                }
            }
        }
    }

    private void setFieldMemValue(T instance, int memUsed, AnnotatedField<? super T> annotatedField) {
        try {
            Field field = annotatedField.getJavaMember();
            field.setAccessible(true);
            field.setInt(instance, memUsed);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    private void setFieldSwapValue(T instance, int swapUsed, AnnotatedField<? super T> annotatedField) {
        try {
            Field field = annotatedField.getJavaMember();
            field.setAccessible(true);
            field.setInt(instance, swapUsed);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void postConstruct(T instance) {
        it.postConstruct(instance);
    }

    @Override
    public void preDestroy(T instance) {
        it.preDestroy(instance);
    }

    @Override
    public T produce(CreationalContext<T> ctx) {
        return it.produce(ctx);
    }

    @Override
    public void dispose(T instance) {
        it.dispose(instance);
    }

    @Override
    public Set<InjectionPoint> getInjectionPoints() {
        return it.getInjectionPoints();
    }
}

这是我的SystemPropertiesLoader:

public class SystemPropertiesLoader {
    private static Supplier<Stream<String>> supplier;

    private SystemPropertiesLoader() {

    }

    public static SystemPropertiesLoader newInstance() {
        supplier = () -> {
            Stream<String> lines = Stream.empty();
            try {
                lines = Files.lines(Paths.get("/proc/meminfo"));
            } catch (IOException e) {
                e.printStackTrace();
            }
            return lines;
        };
        return new SystemPropertiesLoader();
    }

    public int getMemTotal() {
        return Integer.valueOf(
                supplier.get()
                        .findFirst()
                        .orElse("")
                        .split(":")[1]
                        .trim()
                        .replace(" kB", ""));
    }

    public int getMemFree() {
        return Integer.valueOf(
                supplier.get()
                        .skip(1)
                        .findFirst()
                        .orElse("")
                        .split(":")[1]
                        .trim()
                        .replace(" kB", ""));
    }

    public int getSwapTotal() {
        return Integer.valueOf(supplier.get()
                .skip(14)
                .findFirst()
                .orElse("")
                .split(":")[1]
                .trim()
                .replace(" kB", ""));
    }

    public int getSwapFree() {
        return Integer.valueOf(supplier.get()
                .skip(15)
                .findFirst()
                .orElse("")
                .split(":")[1]
                .trim()
                .replace(" kB", ""));
    }

    public int getMemUsed() {
        return getMemTotal() - getMemFree();
    }

    public int getSwapUsed() {
        return getSwapTotal() - getSwapFree();
    }
} 

和注释:

@Target({FIELD, PARAMETER})
@Retention(RUNTIME)
public @interface Memory {
    Unit unitType() default Unit.MEGABYTE;
}

@Target({METHOD,TYPE})
@Retention(RUNTIME)
public @interface Monitor {
}

这是我用过的情况:

@Monitor
public class MemoryMonitor {

    @Memory
    private int memUsed;

    public int getMemUsed() {
        return memUsed;
    }
}

现在我的问题是更新/ proc / meminfo之后,memUsed属性没有更改。
怎么了?
可以为此创建动态CDI扩展吗?
注意1:我复制并粘贴整个代码。
注2:/ proc / meminfo是Linux和Unix操作系统支持的proc文件系统中使用的内存信息。

1 个答案:

答案 0 :(得分:0)

扩大评论,让我首先说,每个bean实例仅发生一次注入。 Bean通常每个作用域创建一次,因此不会自动为它们提供适应生命中发生的更改的机会。我可以想到两件事:

1)使用事件将更改通知感兴趣的参与者

原理很简单(observer pattern)。我不知道如何跟踪/ proc / meminfo中的更改(java.nio.file.WatchService是否足够?),但是只要您检测到更改,就发出一个事件:

public class MemInfoEvent {
    private int memUsed;
    // constructor and getter
}

当您感觉到变化时,请调用以下bean:

import javax.enterprise.event.Event;
...

@ApplicationScoped
public class MemInfoEventEmitter {
    @Inject
    private Event<MemInfo> memInfoEvent;

    public void handleMemInfoChange(int memUsed) {
        memInfoEvent.fire(new MemInfoEvent(memUsed));
    }
}

随时随地观看更改:

public class BeanInterestedInMemChanges {
    public void memInfoChanged(@Observes MemInfoEvent e) {
        // do what you must
    }
}

2)使用java.util.function.IntSupplier(或等效版本)

供应商是一个CDI bean,它知道如何获取memUsed,例如:

@ApplicationScoped
public class MemUsedSupplier implements IntSupplier {
    private SystemPropertiesLoader systemPropertiesLoader = ...; // could be injected, if this is more appropriate

    @Override
    public int getAsInt() {
        return systemPropertiesLoader.getMemUsed();
    }
}

注意:上面的实现可能效率不高!用作起点-概念证明!如果频繁调用getAsInt(),效率低下将导致/ proc / meminfo读取过多。您可能要实现某种缓存/限制。

您甚至可以根据MemoryMonitor实施SystemPropertiesLoader,再次注意潜在的低效率。