ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

feign

2021-07-27 15:33:09  阅读:144  来源: 互联网

标签:feign obj String java return new import


feign

org.springframework.cloud
spring-cloud-starter-openfeign
2.0.2.RELEASE

package com.wpg.data.feign;

import feign.Logger;
import feign.codec.Encoder;
import feign.form.spring.SpringFormEncoder;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.cloud.openfeign.support.SpringEncoder;
import org.springframework.context.annotation.Bean;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Map;

/**

  • @author menghm.

  • @description表务统计相关接口

  • @date 2020/4/27.
    */
    @Component
    @FeignClient(name = “dbData”, url = “${wxdb.url}”, configuration = DbFeignClient.FormSupportConfig.class)
    public interface DbFeignClient {

    /**

    • 查询命令状态
    • @param cmdUuid
    • @return
      */
      @GetMapping(value = “/cmds/{cmdUuid}”)
      String querycmdInfo(@PathVariable(“cmdUuid”) String cmdUuid);

    /**

    • 查询设备详情
    • @param deviceId
    • @return
      */
      @GetMapping(value = “/devices/{deviceId}”)
      String queryDeviceInfo(@PathVariable(“deviceId”) String deviceId);

    /**

    • 查询设备历史数据
    • @param deviceId
    • @param date
    • @param limit
    • @param page
    • @return
      */
      @GetMapping(value = “/devices/{deviceId}/data”)
      String queryHistory(@PathVariable(“deviceId”) String deviceId,
      @RequestParam(required = false, value = “date”) String date,
      @RequestParam(required = false, value = “limit”) String limit,
      @RequestParam(required = false, value = “page”) String page

    );

    /**

    • 发送命令
    • @param queryParam
    • @return
      */
      @PostMapping(value = “/cmds”,
      consumes = {MediaType.MULTIPART_FORM_DATA_VALUE},
      produces = {MediaType.APPLICATION_JSON_UTF8_VALUE}
      )
      String cmd(Map<String, ?> queryParam);

    /**

    • 查询设备历史命令
    • @param deviceId
    • @param limit
    • @param page
    • @return
      */
      @GetMapping(value = “/cmds/history/{deviceId}”)
      String queryHistoryCmd(@PathVariable(“deviceId”) String deviceId,
      @RequestParam(required = false, value = “limit”) String limit,
      @RequestParam(required = false, value = “page”) String page

    );

    class FormSupportConfig {
    @Autowired
    private ObjectFactory messageConverters;

     // new一个form编码器,实现支持form表单提交
     @Bean
     public Encoder feignFormEncoder() {
         return new SpringFormEncoder(new SpringEncoder(messageConverters));
     }
     // 开启Feign的日志
    
     @Bean
     public Logger.Level logger() {
         return Logger.Level.FULL;
     }
    

    }

}

objectutil obj转map

package com.wpg.data.utils;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.stream.Stream;

/**

  • @author menghm.

  • @description

  • @date 2019/11/22.
    */
    public class ObjectUtil {
    public ObjectUtil() {
    }

    public static Boolean isEmpty(Object obj) {
    if(obj == null) {
    return Boolean.valueOf(true);
    } else if(obj instanceof CharSequence) {
    return Boolean.valueOf(((CharSequence)obj).length() == 0);
    } else if(obj instanceof Collection) {
    return Boolean.valueOf(((Collection)obj).isEmpty());
    } else if(obj instanceof Map) {
    return Boolean.valueOf(((Map)obj).isEmpty());
    } else if(!(obj instanceof Object[])) {
    return Boolean.valueOf(false);
    } else {
    Object[] object = (Object[])((Object[])obj);
    if(object.length == 0) {
    return Boolean.valueOf(true);
    } else {
    boolean empty = true;

             for(int i = 0; i < object.length; ++i) {
                 if(!isEmpty(object[i]).booleanValue()) {
                     empty = false;
                     break;
                 }
             }
    
             return Boolean.valueOf(empty);
         }
     }
    

    }

    public static boolean nonEmpty(Object obj) {
    return !isEmpty(obj).booleanValue();
    }

    public static Map<String, Object> transBeanToMap(Object obj) {
    if(obj == null) {
    return null;
    } else if(obj instanceof Map) {
    return (Map)obj;
    } else {
    HashMap map = new HashMap();

         try {
             BeanInfo e = Introspector.getBeanInfo(obj.getClass());
             PropertyDescriptor[] propertyDescriptors = e.getPropertyDescriptors();
             PropertyDescriptor[] var4 = propertyDescriptors;
             int var5 = propertyDescriptors.length;
    
             for(int var6 = 0; var6 < var5; ++var6) {
                 PropertyDescriptor property = var4[var6];
                 String key = property.getName();
                 if(!key.equals("class")) {
                     Method getter = property.getReadMethod();
                     if(getter != null) {
                         Object value = getter.invoke(obj, new Object[0]);
                         if(value != null) {
                             map.put(key, value);
                         }
                     }
                 }
             }
         } catch (Exception var11) {
             System.out.println("transBean2Map Error " + var11);
         }
    
         return map;
     }
    

    }

    public static T nvl(T t, T d) {
    return Optional.ofNullable(t).orElse(d);
    }

    public static T nvl(T t, Supplier<? extends T> supplier) {
    return Optional.ofNullable(t).orElseGet(supplier);
    }

    public static Boolean anyEmpty(T… ts) {
    return Boolean.valueOf(Stream.of(ts).anyMatch(ObjectUtil::isEmpty));
    }

    public static List stringToList(String data, Class t) {
    return (List)(new Gson()).fromJson(data, TypeToken.getParameterized(ArrayList.class, new Type[]{t}).getType());
    }
    }

/**
* 开始定时统计RTU设备数据
*/
public void getRTUData() {
//获取需要采集的RTU设备
List deviceRtuList = deviceRtuMapper.getDevice();
if (CollectionUtil.isNotEmpty(deviceRtuList)) {
//调接口查询数据
for (DeviceRtu deviceRtu : deviceRtuList) {
String deviceId = deviceRtu.getDeviceId();
String date = this.getCurrentDay();
DbHistoryDTO dbHistoryDTO = new DbHistoryDTO(deviceId, date, “”, “”);
String result = “”;
try {
result = dbFeignClient.queryHistory(dbHistoryDTO.getDeviceId(), dbHistoryDTO.getDate(),
dbHistoryDTO.getLimit(), dbHistoryDTO.getPage()
);
log.debug("======" + result);
if (StringUtils.isEmpty(result)) {
continue;
}
DbResultVO resultVO = JSONObject.parseObject(result,
new TypeReference<DbResultVO>() {
});
if (ObjectUtil.isEmpty(resultVO)) {
continue;
}
if (!resultVO.getStat()) {
continue;
}
HistoryResultVO deviceInfoVO = resultVO.getData();
if (ObjectUtil.isEmpty(deviceInfoVO)) {
continue;
}
List list = deviceInfoVO.getItems();
if (CollectionUtil.isEmpty(list)) {
continue;
}
//组装数据
List serviceList = new ArrayList<>();
List mqList = new ArrayList<>();
for (HistoryInfoVO historyInfoVO : list) {
String addressId = historyInfoVO.getDeviceId();
if (com.xiaoleilu.hutool.util.ObjectUtil.isNotNull(historyInfoVO.getUploadTime())) {
historyInfoVO.setDate(
ftf.format(LocalDateTime.ofInstant(
Instant.ofEpochMilli(historyInfoVO.getUploadTime() * 1000),
ZoneId.systemDefault())));
}
String timeStamp = historyInfoVO.getDate();
String sumFlow = historyInfoVO.getSumFlow();
String pipePressure = historyInfoVO.getPipePressure();
Integer valve = historyInfoVO.getValveStatus();
//累计流量
ServiceValueDTO cumulativeFlow = new ServiceValueDTO(
addressId, addressId + “\” + “CumulativeFlow”,
“CumulativeFlow”, timeStamp
, sumFlow
);
serviceList.add(cumulativeFlow);
//水压1 管网压力
ServiceValueDTO pressureOne = new ServiceValueDTO(
addressId, addressId + “\” + “PipePressure”,
“PipePressure”, timeStamp, pipePressure
);
serviceList.add(pressureOne);
//阀门状态
ServiceValueDTO valveStatus = new ServiceValueDTO(
addressId, addressId + “\” + “ValveState”,
“ValveState”, timeStamp, valve == 0 ? “true” : “false”
);
serviceList.add(valveStatus);

                    //入mq
                    SortedMap<String, String> values = new TreeMap<>();
                    values.put("CumulativeFlow", sumFlow);
                    values.put("PipePressure", pipePressure);
                    values.put("ValveState", String.valueOf(valve));
                    MqttInfoDTO mqttInfoDTO = new MqttInfoDTO(addressId, timeStamp, values);
                    mqList.add(mqttInfoDTO);

                }
                //入库
                this.insertDeviceValue(serviceList);
                //入mq
                this.sendMqtt(mqList);

            } catch (Exception e) {
                log.error("调用接口失败");
            }
        }

    }
}  feign
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-openfeign</artifactId>
        <version>2.0.2.RELEASE</version>
    </dependency>

package com.wpg.data.feign;

import feign.Logger;
import feign.codec.Encoder;
import feign.form.spring.SpringFormEncoder;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.cloud.openfeign.support.SpringEncoder;
import org.springframework.context.annotation.Bean;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Map;

/**

  • @author menghm.

  • @description表务统计相关接口

  • @date 2020/4/27.
    */
    @Component
    @FeignClient(name = “dbData”, url = “${wxdb.url}”, configuration = DbFeignClient.FormSupportConfig.class)
    public interface DbFeignClient {

    /**

    • 查询命令状态
    • @param cmdUuid
    • @return
      */
      @GetMapping(value = “/cmds/{cmdUuid}”)
      String querycmdInfo(@PathVariable(“cmdUuid”) String cmdUuid);

    /**

    • 查询设备详情
    • @param deviceId
    • @return
      */
      @GetMapping(value = “/devices/{deviceId}”)
      String queryDeviceInfo(@PathVariable(“deviceId”) String deviceId);

    /**

    • 查询设备历史数据
    • @param deviceId
    • @param date
    • @param limit
    • @param page
    • @return
      */
      @GetMapping(value = “/devices/{deviceId}/data”)
      String queryHistory(@PathVariable(“deviceId”) String deviceId,
      @RequestParam(required = false, value = “date”) String date,
      @RequestParam(required = false, value = “limit”) String limit,
      @RequestParam(required = false, value = “page”) String page

    );

    /**

    • 发送命令
    • @param queryParam
    • @return
      */
      @PostMapping(value = “/cmds”,
      consumes = {MediaType.MULTIPART_FORM_DATA_VALUE},
      produces = {MediaType.APPLICATION_JSON_UTF8_VALUE}
      )
      String cmd(Map<String, ?> queryParam);

    /**

    • 查询设备历史命令
    • @param deviceId
    • @param limit
    • @param page
    • @return
      */
      @GetMapping(value = “/cmds/history/{deviceId}”)
      String queryHistoryCmd(@PathVariable(“deviceId”) String deviceId,
      @RequestParam(required = false, value = “limit”) String limit,
      @RequestParam(required = false, value = “page”) String page

    );

    class FormSupportConfig {
    @Autowired
    private ObjectFactory messageConverters;

     // new一个form编码器,实现支持form表单提交
     @Bean
     public Encoder feignFormEncoder() {
         return new SpringFormEncoder(new SpringEncoder(messageConverters));
     }
     // 开启Feign的日志
    
     @Bean
     public Logger.Level logger() {
         return Logger.Level.FULL;
     }
    

    }

}

objectutil obj转map

package com.wpg.data.utils;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.stream.Stream;

/**

  • @author menghm.

  • @description

  • @date 2019/11/22.
    */
    public class ObjectUtil {
    public ObjectUtil() {
    }

    public static Boolean isEmpty(Object obj) {
    if(obj == null) {
    return Boolean.valueOf(true);
    } else if(obj instanceof CharSequence) {
    return Boolean.valueOf(((CharSequence)obj).length() == 0);
    } else if(obj instanceof Collection) {
    return Boolean.valueOf(((Collection)obj).isEmpty());
    } else if(obj instanceof Map) {
    return Boolean.valueOf(((Map)obj).isEmpty());
    } else if(!(obj instanceof Object[])) {
    return Boolean.valueOf(false);
    } else {
    Object[] object = (Object[])((Object[])obj);
    if(object.length == 0) {
    return Boolean.valueOf(true);
    } else {
    boolean empty = true;

             for(int i = 0; i < object.length; ++i) {
                 if(!isEmpty(object[i]).booleanValue()) {
                     empty = false;
                     break;
                 }
             }
    
             return Boolean.valueOf(empty);
         }
     }
    

    }

    public static boolean nonEmpty(Object obj) {
    return !isEmpty(obj).booleanValue();
    }

    public static Map<String, Object> transBeanToMap(Object obj) {
    if(obj == null) {
    return null;
    } else if(obj instanceof Map) {
    return (Map)obj;
    } else {
    HashMap map = new HashMap();

         try {
             BeanInfo e = Introspector.getBeanInfo(obj.getClass());
             PropertyDescriptor[] propertyDescriptors = e.getPropertyDescriptors();
             PropertyDescriptor[] var4 = propertyDescriptors;
             int var5 = propertyDescriptors.length;
    
             for(int var6 = 0; var6 < var5; ++var6) {
                 PropertyDescriptor property = var4[var6];
                 String key = property.getName();
                 if(!key.equals("class")) {
                     Method getter = property.getReadMethod();
                     if(getter != null) {
                         Object value = getter.invoke(obj, new Object[0]);
                         if(value != null) {
                             map.put(key, value);
                         }
                     }
                 }
             }
         } catch (Exception var11) {
             System.out.println("transBean2Map Error " + var11);
         }
    
         return map;
     }
    

    }

    public static T nvl(T t, T d) {
    return Optional.ofNullable(t).orElse(d);
    }

    public static T nvl(T t, Supplier<? extends T> supplier) {
    return Optional.ofNullable(t).orElseGet(supplier);
    }

    public static Boolean anyEmpty(T… ts) {
    return Boolean.valueOf(Stream.of(ts).anyMatch(ObjectUtil::isEmpty));
    }

    public static List stringToList(String data, Class t) {
    return (List)(new Gson()).fromJson(data, TypeToken.getParameterized(ArrayList.class, new Type[]{t}).getType());
    }
    }

/**
* 开始定时统计RTU设备数据
*/
public void getRTUData() {
//获取需要采集的RTU设备
List deviceRtuList = deviceRtuMapper.getDevice();
if (CollectionUtil.isNotEmpty(deviceRtuList)) {
//调接口查询数据
for (DeviceRtu deviceRtu : deviceRtuList) {
String deviceId = deviceRtu.getDeviceId();
String date = this.getCurrentDay();
DbHistoryDTO dbHistoryDTO = new DbHistoryDTO(deviceId, date, “”, “”);
String result = “”;
try {
result = dbFeignClient.queryHistory(dbHistoryDTO.getDeviceId(), dbHistoryDTO.getDate(),
dbHistoryDTO.getLimit(), dbHistoryDTO.getPage()
);
log.debug("======" + result);
if (StringUtils.isEmpty(result)) {
continue;
}
DbResultVO resultVO = JSONObject.parseObject(result,
new TypeReference<DbResultVO>() {
});
if (ObjectUtil.isEmpty(resultVO)) {
continue;
}
if (!resultVO.getStat()) {
continue;
}
HistoryResultVO deviceInfoVO = resultVO.getData();
if (ObjectUtil.isEmpty(deviceInfoVO)) {
continue;
}
List list = deviceInfoVO.getItems();
if (CollectionUtil.isEmpty(list)) {
continue;
}
//组装数据
List serviceList = new ArrayList<>();
List mqList = new ArrayList<>();
for (HistoryInfoVO historyInfoVO : list) {
String addressId = historyInfoVO.getDeviceId();
if (com.xiaoleilu.hutool.util.ObjectUtil.isNotNull(historyInfoVO.getUploadTime())) {
historyInfoVO.setDate(
ftf.format(LocalDateTime.ofInstant(
Instant.ofEpochMilli(historyInfoVO.getUploadTime() * 1000),
ZoneId.systemDefault())));
}
String timeStamp = historyInfoVO.getDate();
String sumFlow = historyInfoVO.getSumFlow();
String pipePressure = historyInfoVO.getPipePressure();
Integer valve = historyInfoVO.getValveStatus();
//累计流量
ServiceValueDTO cumulativeFlow = new ServiceValueDTO(
addressId, addressId + “\” + “CumulativeFlow”,
“CumulativeFlow”, timeStamp
, sumFlow
);
serviceList.add(cumulativeFlow);
//水压1 管网压力
ServiceValueDTO pressureOne = new ServiceValueDTO(
addressId, addressId + “\” + “PipePressure”,
“PipePressure”, timeStamp, pipePressure
);
serviceList.add(pressureOne);
//阀门状态
ServiceValueDTO valveStatus = new ServiceValueDTO(
addressId, addressId + “\” + “ValveState”,
“ValveState”, timeStamp, valve == 0 ? “true” : “false”
);
serviceList.add(valveStatus);

                    //入mq
                    SortedMap<String, String> values = new TreeMap<>();
                    values.put("CumulativeFlow", sumFlow);
                    values.put("PipePressure", pipePressure);
                    values.put("ValveState", String.valueOf(valve));
                    MqttInfoDTO mqttInfoDTO = new MqttInfoDTO(addressId, timeStamp, values);
                    mqList.add(mqttInfoDTO);

                }
                //入库
                this.insertDeviceValue(serviceList);
                //入mq
                this.sendMqtt(mqList);

            } catch (Exception e) {
                log.error("调用接口失败");
            }
        }

    }
}

标签:feign,obj,String,java,return,new,import
来源: https://blog.csdn.net/weixin_53200945/article/details/119144733

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有