zoukankan      html  css  js  c++  java
  • 基于Influxdb对InfluxDBResultMapper的一点扩展

    理想很饱满,现实很骨感。

    由于业务需要“灵活可配置”的功能需求,在使用java开发Influxdb查询功能的时候,遇到了一个问题,Measurement注解的名称有可能需要动态变化。

    我们先看下 @Measurement 注解的代码:

    package org.influxdb.annotation;
    
    import java.lang.annotation.ElementType;
    import java.lang.annotation.Retention;
    import java.lang.annotation.RetentionPolicy;
    import java.lang.annotation.Target;
    import java.util.concurrent.TimeUnit;
    
    /**
     * @author fmachado
     */
    @Retention(RetentionPolicy.RUNTIME)
    @Target(ElementType.TYPE)
    public @interface Measurement {
    
      String name();
    
      String database() default "[unassigned]";
    
      String retentionPolicy() default "autogen";
    
      TimeUnit timeUnit() default TimeUnit.MILLISECONDS;
    

    问题可以转换为:
    -> 在@Measurement 注解生效之前,将变动的name值写入。

    经过大概两天时间的资料查找,发现了可以通过:java反射去解决
    主要需要操作以下两个类的api

    java.lang.reflect.InvocationHandler;
    java.lang.reflect.Proxy;
    

    最终解决方案,通过继承 InfluxDBResultMapper 的 toPOJO 方法得以解决。
    以下贴出代码:

    public class InfluxDBResultMapperHelper extends InfluxDBResultMapper {
    
        public <T> List<T> toPOJO(final QueryResult queryResult, final Class<T> clazz,String name)
                throws InfluxDBMapperException {
            InvocationHandler handler = Proxy.getInvocationHandler(clazz.getAnnotation(Measurement.class));
            Field hField = null;
            try {
                hField = handler.getClass().getDeclaredField(ME_VALUE);
                hField.setAccessible(true);
                Map memberValues = (Map) hField.get(handler);
                memberValues.put(ME_NAME, name);
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            return toPOJO(queryResult, clazz, TimeUnit.MILLISECONDS);
        }
    }
    
  • 相关阅读:
    关于lockkeyword
    关于多层for循环迭代的效率优化问题
    Android 面试精华题目总结
    Linux基础回想(1)——Linux系统概述
    linux源代码编译安装OpenCV
    校赛热身 Problem C. Sometimes Naive (状压dp)
    校赛热身 Problem C. Sometimes Naive (状压dp)
    校赛热身 Problem B. Matrix Fast Power
    校赛热身 Problem B. Matrix Fast Power
    集合的划分(递推)
  • 原文地址:https://www.cnblogs.com/skywp/p/11671947.html
Copyright © 2011-2022 走看看