Commit c47d2af9 by 111-PC\111

[+]pulsar消费服务

1 parent 917528d7
...@@ -7,4 +7,6 @@ package cn.com.glsx.consumer.common; ...@@ -7,4 +7,6 @@ package cn.com.glsx.consumer.common;
public class Contants { public class Contants {
public static final int STATUS_APPEAR=4; public static final int STATUS_APPEAR=4;
public static final int SCENE_CONDITION_ALL=2;
public static final int SCENE_CONDITION_ANY=1;
} }
package cn.com.glsx.consumer.common;
/**
* @author fengzhi
* @date 2021/3/9 17:05
* @description 工作日,节假日类型枚举
*/
public enum EDay {
WORKDAY {
@Override
public Integer getCode() {
return 0;
}
@Override
public Integer getValue() {
return 2;
}
@Override
public String getName(){
return "工作日";
}
},
HOLIDAY {
@Override
public Integer getCode() {
return 1;
}
@Override
public Integer getValue() {
return 3;
}
@Override
public String getName(){
return "节假日";
}
},
WEEKDAY {
@Override
public Integer getCode() {
return 2;
}
@Override
public Integer getValue() {
return 3;
}
@Override
public String getName(){
return "双休日";
}
},
LEAVE_OFF_DAY {
@Override
public Integer getCode() {
return 3;
}
@Override
public Integer getValue() {
return 2;
}
@Override
public String getName(){
return "调休日";
}
},;
public static Integer getValueByCode(Integer code) {
for (EDay day : EDay.values()) {
if (day.getCode().equals(code)) {
return day.getValue();
}
}
return null;
}
public static String getNameByCode(Integer code) {
for (EDay day : EDay.values()) {
if (day.getCode().equals(code)) {
return day.getName();
}
}
return null;
}
/* 0表示工作日、为1、节假日,为2双休日、3为调休日(上班)*/
public abstract Integer getCode();
// 依据接口整合为平台定义的值,1每天 2工作日 3法定节假日
public abstract Integer getValue();
public abstract String getName();
}
package cn.com.glsx.consumer.common;
/**
* @author fengzhi
* @date 2021/3/19 17:40
* @description 枚举,触发条件的逻辑判断
*/
public enum ELogic {
LESS_THAN {
@Override
public Integer getCode() {
return 3;
}
@Override
public boolean getValue(String deviceOrderValue,String deviceOrderValueReal) {
return Double.parseDouble(deviceOrderValueReal) < Double.parseDouble(deviceOrderValue);
}
@Override
public String getName(){
return "小于";
}
},
GREATER_THAN {
@Override
public Integer getCode() {
return 2;
}
@Override
public boolean getValue(String deviceOrderValue,String deviceOrderValueReal) {
return Double.parseDouble(deviceOrderValueReal) > Double.parseDouble(deviceOrderValue);
}
@Override
public String getName(){
return "大于";
}
},
EQUALS {
@Override
public Integer getCode() {
return 1;
}
@Override
public boolean getValue(String deviceOrderValue,String deviceOrderValueReal) {
return deviceOrderValueReal.equals(deviceOrderValue);
}
@Override
public String getName(){
return "等于";
}
},;
public static boolean getValueByCode(Integer code,String deviceOrderValue,String deviceOrderValueReal) {
for (ELogic day : ELogic.values()) {
if (day.getCode().equals(code)) {
return day.getValue(deviceOrderValue,deviceOrderValueReal);
}
}
return false;
}
public static String getNameByCode(Integer code) {
for (ELogic day : ELogic.values()) {
if (day.getCode().equals(code)) {
return day.getName();
}
}
return null;
}
/* 逻辑(1:<,2:>,3:=)*/
public abstract Integer getCode();
//deviceOrderValue:触发条件中的设备状态值,deviceOrderValueReal:数据库中的设备状态值
public abstract boolean getValue(String deviceOrderValue,String deviceOrderValueReal);
public abstract String getName();
}
package cn.com.glsx.consumer.entity;
import lombok.Data;
import lombok.experimental.Accessors;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import java.io.Serializable;
@Accessors(chain = true)
@Data
@Entity
@Table(name = "smart_date")
public class DayInfo implements Serializable {
@Id
@Column(
name = "id",
unique = true,
nullable = false
)
@GeneratedValue(
strategy = GenerationType.IDENTITY,
generator = "SELECT LAST_INSERT_ID()"
)
private Long id;
/**
* 当前阳历日期,如:2019-10-01
*/
private String date;
/**
* 日期类型,为0表示工作日、为1节假日、为2双休日、3为调休日(上班)
*/
private Integer daycode;
/**
* 节假日名称,如:国庆节
*/
private String name;
/**
* 放假提示,如:10月1日至7日放假调休,共7天......
*/
private String tip;
}
\ No newline at end of file \ No newline at end of file
package cn.com.glsx.consumer.entity;
import lombok.Data;
@Data
public class ScenseParamValue {
//第一列下拉选项值
private String select;
//输入值
private String value;
//指令
private String order;
//指令条件
private String orderCondition;
//指令值
private String orderVal;
//指令值类型
private String valType;
//红外线远程id
private String remoteId;
//推送消息
private String msg;
//推送消息
private String date;
}
package cn.com.glsx.consumer.entity;
import java.io.Serializable;
import javax.persistence.*;
@Table(name = "smart_scene_data")
public class SmartSceneData implements Serializable {
/**
* 标识ID
*/
@Id
private Long id;
/**
* 场景ID 关联smart_scene中id
*/
@Column(name = "scene_id")
private Long sceneId;
/**
* 类型 1触发条件 2执行内容
*/
private Byte type;
/**
* 排序
*/
private Byte sort;
/**
* 参数key
*/
@Column(name = "param_key")
private String paramKey;
/**
* 设备id,取自param_value中select
*/
@Column(name = "device_id")
private String deviceId;
/**
* 参数值 数组对象
*/
@Column(name = "param_value")
private String paramValue;
@Transient
private Integer conditionRule;
@Transient
private Integer executeCycle;
private static final long serialVersionUID = 1L;
/**
* 获取标识ID
*
* @return id - 标识ID
*/
public Long getId() {
return id;
}
/**
* 设置标识ID
*
* @param id 标识ID
*/
public void setId(Long id) {
this.id = id;
}
/**
* 获取场景ID 关联smart_scene中id
*
* @return scene_id - 场景ID 关联smart_scene中id
*/
public Long getSceneId() {
return sceneId;
}
/**
* 设置场景ID 关联smart_scene中id
*
* @param sceneId 场景ID 关联smart_scene中id
*/
public void setSceneId(Long sceneId) {
this.sceneId = sceneId;
}
/**
* 获取类型 1触发条件 2执行内容
*
* @return type - 类型 1触发条件 2执行内容
*/
public Byte getType() {
return type;
}
/**
* 设置类型 1触发条件 2执行内容
*
* @param type 类型 1触发条件 2执行内容
*/
public void setType(Byte type) {
this.type = type;
}
/**
* 获取排序
*
* @return sort - 排序
*/
public Byte getSort() {
return sort;
}
/**
* 设置排序
*
* @param sort 排序
*/
public void setSort(Byte sort) {
this.sort = sort;
}
/**
* 获取参数key
*
* @return param_key - 参数key
*/
public String getParamKey() {
return paramKey;
}
/**
* 设置参数key
*
* @param paramKey 参数key
*/
public void setParamKey(String paramKey) {
this.paramKey = paramKey == null ? null : paramKey.trim();
}
/**
* 获取设备id,取自param_value中select
*
* @return device_id - 设备id,取自param_value中select
*/
public String getDeviceId() {
return deviceId;
}
/**
* 设置设备id,取自param_value中select
*
* @param deviceId 设备id,取自param_value中select
*/
public void setDeviceId(String deviceId) {
this.deviceId = deviceId == null ? null : deviceId.trim();
}
/**
* 获取参数值 数组对象
*
* @return param_value - 参数值 数组对象
*/
public String getParamValue() {
return paramValue;
}
/**
* 设置参数值 数组对象
*
* @param paramValue 参数值 数组对象
*/
public void setParamValue(String paramValue) {
this.paramValue = paramValue == null ? null : paramValue.trim();
}
public Integer getConditionRule() {
return conditionRule;
}
public void setConditionRule(Integer conditionRule) {
this.conditionRule = conditionRule;
}
public Integer getExecuteCycle() {
return executeCycle;
}
public void setExecuteCycle(Integer executeCycle) {
this.executeCycle = executeCycle;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", sceneId=").append(sceneId);
sb.append(", type=").append(type);
sb.append(", sort=").append(sort);
sb.append(", paramKey=").append(paramKey);
sb.append(", deviceId=").append(deviceId);
sb.append(", paramValue=").append(paramValue);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
}
\ No newline at end of file \ No newline at end of file
package cn.com.glsx.consumer.mapper;
import cn.com.glsx.consumer.entity.DayInfo;
import com.glsx.plat.mybatis.mapper.CommonBaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
@Mapper
public interface DayInfoMapper extends CommonBaseMapper<DayInfo> {
int updateDayInsert(@Param("daysYear") List<DayInfo> daysYear);
DayInfo getDayCodeByDate(String date);
}
\ No newline at end of file \ No newline at end of file
package cn.com.glsx.consumer.mapper;
import cn.com.glsx.consumer.entity.SmartSceneData;
import com.glsx.plat.mybatis.mapper.CommonBaseMapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface SmartSceneDataMapper extends CommonBaseMapper<SmartSceneData> {
List<SmartSceneData> findSceneDataByDeviceId(@Param("deviceId") String deviceId);
List<SmartSceneData> findBySceneId(Long sceneId);
}
\ No newline at end of file \ No newline at end of file
package cn.com.glsx.consumer.service;
import cn.com.glsx.consumer.entity.SmartSceneData;
import java.util.List;
import java.util.function.Predicate;
/**
* @author fengzhi
* @date 2021/3/9 17:05
* @description 平台统一对外接口
*/
public interface ConditionStrategy {
boolean isTrigger(List<SmartSceneData> dataList,Integer executeCycle,Predicate<SmartSceneData> predicate);
}
package cn.com.glsx.consumer.service;
import cn.com.glsx.consumer.common.Contants;
import cn.com.glsx.consumer.entity.SmartSceneData;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.function.Predicate;
/**
* @author zhouhaibao
* @date 2021/4/10 15:44
*/
@Service
public class ConditionStrategyImpl implements ConditionStrategy {
@Override
public boolean isTrigger(List<SmartSceneData> dataList,Integer executeCycle,Predicate<SmartSceneData> predicate) {
if(executeCycle.equals(Contants.SCENE_CONDITION_ALL)) {
return dataList.stream().allMatch(predicate);
}else{
return dataList.stream().anyMatch(predicate);
}
}
}
package cn.com.glsx.consumer.service; package cn.com.glsx.consumer.service;
import cn.com.glsx.consumer.common.EDay;
import cn.com.glsx.consumer.common.ELogic;
import cn.com.glsx.consumer.entity.DayInfo;
import cn.com.glsx.consumer.entity.DeviceStatus; import cn.com.glsx.consumer.entity.DeviceStatus;
import cn.com.glsx.consumer.entity.DeviceStatusDetail; import cn.com.glsx.consumer.entity.DeviceStatusDetail;
import cn.com.glsx.consumer.entity.ScenseParamValue;
import cn.com.glsx.consumer.entity.SmartDevideStatus; import cn.com.glsx.consumer.entity.SmartDevideStatus;
import cn.com.glsx.consumer.entity.SmartSceneData;
import cn.com.glsx.consumer.mapper.DayInfoMapper;
import cn.com.glsx.consumer.mapper.SmartDevideStatusMapper; import cn.com.glsx.consumer.mapper.SmartDevideStatusMapper;
import cn.com.glsx.consumer.mapper.SmartSceneDataMapper;
import cn.com.glsx.consumer.utils.DateUtils;
import cn.com.glsx.consumer.utils.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Date; import java.util.Date;
import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.stream.Collectors; import java.util.stream.Collectors;
/** /**
...@@ -26,6 +40,18 @@ public class TuyaConmsumerService { ...@@ -26,6 +40,18 @@ public class TuyaConmsumerService {
@Autowired @Autowired
private SmartDevideStatusMapper smartDevideStatusMapper; private SmartDevideStatusMapper smartDevideStatusMapper;
@Autowired
private SmartSceneDataMapper smartSceneDataMapper;
@Autowired
private DayInfoMapper dayInfoMapper;
@Autowired
private ConditionStrategy conditionStrategy;
@Value("${issueOrderUrl}")
private String issueOrderUrl;
/** /**
* 处理消息 * 处理消息
* *
...@@ -34,14 +60,43 @@ public class TuyaConmsumerService { ...@@ -34,14 +60,43 @@ public class TuyaConmsumerService {
public void processMessage(String data) { public void processMessage(String data) {
DeviceStatus deviceStatus = JSONObject.parseObject(data, DeviceStatus.class); DeviceStatus deviceStatus = JSONObject.parseObject(data, DeviceStatus.class);
List<SmartDevideStatus> list = buildParams(deviceStatus); List<SmartDevideStatus> list = buildParams(deviceStatus);
if(CollectionUtils.isNotEmpty(list)){ if (CollectionUtils.isNotEmpty(list)) {
list.forEach(index->{ list.forEach(index -> {
if(index.getId()==null){ if (index.getId() == null) {
smartDevideStatusMapper.insert(index); smartDevideStatusMapper.insert(index);
}else { } else {
smartDevideStatusMapper.updateByPrimaryKeySelective(index); smartDevideStatusMapper.updateByPrimaryKeySelective(index);
} }
}); });
// 判断该设备是否在用户场景里面
List<SmartSceneData> smartSceneDataList = smartSceneDataMapper.findSceneDataByDeviceId(list.get(0).getDeviceId());
if(CollectionUtils.isEmpty(smartSceneDataList)){
return;
}
smartSceneDataList.forEach(index -> {
Integer executeCycle = index.getExecuteCycle();
// 判断场景是否触发
List<SmartSceneData> sceneDataList=smartSceneDataMapper.findBySceneId(index.getSceneId());
// 判断场景条件是否配置了时间并且是全部条件满足执行的
List<SmartSceneData> scene_condition_time = sceneDataList.stream().filter(inx -> inx.getParamKey().equals("scene_condition_status")).collect(Collectors.toList());
if(list.size()!=scene_condition_time.size()&&executeCycle.equals("1")){
return;
}
boolean isTrigger = conditionStrategy.isTrigger(sceneDataList, executeCycle,
(SmartSceneData condition) -> getTriggerResult(condition));
if (isTrigger) {
// 下发场景
Map<String, String> requestMap = new HashMap<>();
requestMap.put("id", index.getSceneId() + "");
try {
String responseBody = HttpUtil.sendPost(issueOrderUrl, JSONObject.toJSONString(requestMap), new HashMap<>());
log.info("场景id{}下发结果{}", index.getSceneId(), responseBody);
} catch (Exception e) {
e.printStackTrace();
log.info("场景id{}下发指令异常,{}", index.getSceneId(), e);
}
}
});
} }
} }
...@@ -50,9 +105,9 @@ public class TuyaConmsumerService { ...@@ -50,9 +105,9 @@ public class TuyaConmsumerService {
List<DeviceStatusDetail> status = deviceStatus.getStatus(); List<DeviceStatusDetail> status = deviceStatus.getStatus();
if (CollectionUtils.isNotEmpty(status)) { if (CollectionUtils.isNotEmpty(status)) {
list = status.stream().map(index -> { list = status.stream().map(index -> {
SmartDevideStatus smartDevideStatus=smartDevideStatusMapper.findDevStatusByIdAndCode(deviceStatus.getDevId(),index.getCode()); SmartDevideStatus smartDevideStatus = smartDevideStatusMapper.findDevStatusByIdAndCode(deviceStatus.getDevId(), index.getCode());
if(smartDevideStatus==null) { if (smartDevideStatus == null) {
smartDevideStatus=new SmartDevideStatus(); smartDevideStatus = new SmartDevideStatus();
smartDevideStatus.setDeviceId(deviceStatus.getDevId()); smartDevideStatus.setDeviceId(deviceStatus.getDevId());
smartDevideStatus.setProductKey(deviceStatus.getProductKey()); smartDevideStatus.setProductKey(deviceStatus.getProductKey());
smartDevideStatus.setCreatetime(new Date(index.getT())); smartDevideStatus.setCreatetime(new Date(index.getT()));
...@@ -66,4 +121,57 @@ public class TuyaConmsumerService { ...@@ -66,4 +121,57 @@ public class TuyaConmsumerService {
} }
return list; return list;
} }
//根据当前时间对应的执行周期类型
private Integer getExecuteCycle() {
//判断当天的日类型
String date = DateUtils.getTodayDate();
//0表示工作日、为1节假日、为2双休日、3为调休日(上班)
DayInfo dayInfo = dayInfoMapper.getDayCodeByDate(date);
//转换为对应的执行周期
return EDay.getValueByCode(null == dayInfo ? -1 : dayInfo.getDaycode());
}
//触发条件判断
private boolean getTriggerResult(SmartSceneData condition) {
if (condition.getExecuteCycle()!=1&&!getExecuteCycle().equals(condition.getExecuteCycle())) {
log.info("当前时间不是触发周期:" + condition.getId());
return false;
}
String value = condition.getParamValue();
if (StringUtils.isEmpty(value)) {
log.info("触发条件的value不存在===id:" + condition.getId());
return false;
}
ScenseParamValue paramValue = null;
try {
paramValue = JSON.parseObject(JSON.parse(value).toString(), ScenseParamValue.class);
} catch (Exception e) {
log.info("JSON解析异常:ScenseParamValue====" + e.getMessage() + "===conditionId:" + condition.getId());
return false;
}
//参数一,设备id
String deviceId = paramValue.getSelect();
//参数二,设备指令
String deviceOrderCode = paramValue.getOrder();
//参数三,逻辑(1:<,2:>,3:=)
int logic = Integer.parseInt(paramValue.getOrderCondition());
//参数四,值
SmartDevideStatus smartDevideStatus = smartDevideStatusMapper.findDevStatusByIdAndCode(deviceId, deviceOrderCode);
if (smartDevideStatus == null) {
return false;
}
//触发状态值,如果value没有值,则取ordervalue
String Value = paramValue.getValue();
if (StringUtils.isEmpty(Value)) {
Value = paramValue.getOrderVal();
if (StringUtils.isEmpty(Value)) {
log.info("设备触发状态值不存在===deviceId:" + deviceId + "===deviceOrderCode:" + deviceOrderCode);
return false;
}
}
//根据logic逻辑码,判断触发条件与数据库中实际的值,判断是否满足
return ELogic.getValueByCode(logic, Value, smartDevideStatus.getDeviceOrderValue()==null?"":smartDevideStatus.getDeviceOrderValue());
}
} }
package cn.com.glsx.consumer.utils;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.NoHttpResponseException;
import org.apache.http.ParseException;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.client.utils.HttpClientUtils;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.config.SocketConfig;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.LayeredConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLHandshakeException;
import javax.xml.ws.http.HTTPException;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.UnknownHostException;
import java.nio.charset.Charset;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class HttpUtil {
private static final Log logger = LogFactory.getLog(HttpUtil.class);
final static int CONNECTION_TIMEOUT = 10000; // 设置请求超时 10 秒钟 根据业务调整
final static int SOCKET_TIMEOUT = 180000; // 数据传输时间 3 分钟
final static int SEARCH_CONNECTION_TIMEOUT = 500; // 连接不够用的时候等待超时时间,不设置默认等于 CONNECTION_TIMEOUT
public final static ContentType JSON_UTF8 = ContentType.create("application/json", "utf-8");
static PoolingHttpClientConnectionManager httpClientConnectionManager = null;
static {
LayeredConnectionSocketFactory sslsf = null;
try {
sslsf = new SSLConnectionSocketFactory(SSLContext.getDefault());
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register("https", sslsf)
.register("http", new PlainConnectionSocketFactory()).build();
httpClientConnectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
httpClientConnectionManager.setMaxTotal(200); // 总的连接池的大小
httpClientConnectionManager.setDefaultMaxPerRoute(20); // 对每个主机的最大连接大小,每个主机最大20 个连接,总共 200 个连接,支持 10 台主机
}
public static CloseableHttpClient getHttpClient() {
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECTION_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT)
.setConnectionRequestTimeout(SEARCH_CONNECTION_TIMEOUT).build();
SocketConfig socketConfig = SocketConfig.custom()
.setSoKeepAlive(true)
.setTcpNoDelay(true).build();
// 请求重试处理
HttpRequestRetryHandler httpRequestRetryHandler = new HttpRequestRetryHandler() {
@Override
public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
if (executionCount >= 3) {// 如果已经重试了 3 次,就放弃
return false;
}
if (exception instanceof NoHttpResponseException) {// 如果服务器丢掉了连接,那么就重试
return true;
}
if (exception instanceof SSLHandshakeException) {// 不要重试SSL握手异常
return false;
}
if (exception instanceof InterruptedIOException) {// 超时
return false;
}
if (exception instanceof UnknownHostException) {// 目标服务器不可达
return false;
}
if (exception instanceof ConnectTimeoutException) {// 连接被拒绝
return false;
}
if (exception instanceof SSLException) {// SSL握手异常
return false;
}
HttpClientContext clientContext = HttpClientContext.adapt(context);
HttpRequest request = clientContext.getRequest();
// 如果请求是幂等的,就再次尝试
if (!(request instanceof HttpEntityEnclosingRequest)) {
return true;
}
return false;
}
};
CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(httpClientConnectionManager)
.setDefaultRequestConfig(requestConfig)
.setRetryHandler(httpRequestRetryHandler)
.setDefaultSocketConfig(socketConfig).build();
return httpClient;
}
/**
* 作者:sanri <br/>
* 时间:2017-7-26下午3:47:02<br/>
* 功能:将 map 型 的参数转换为NameValuePair 类型 <br/>
*
* @param params 注:日期将会转格式为 yyyy-MM-dd
* @return
*/
public static List<NameValuePair> transferParam(Map<String, ? extends Object> params) {
return transferParam(params, "yyyy-MM-dd");
}
public static List<NameValuePair> transferParam(Map<String, ? extends Object> params, String dateFormat) {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
if (params != null && !params.isEmpty()) {
Set<?> entrySet = params.entrySet();
Iterator<?> paramIterator = entrySet.iterator();
while (paramIterator.hasNext()) {
Map.Entry<String, ? extends Object> param = (Map.Entry<String, ? extends Object>) paramIterator.next();
Object value = param.getValue();
if (value == null) {
nameValuePairs.add(new BasicNameValuePair(param.getKey(), null));
} else {
if (value instanceof Date) {
Date date = (Date) value;
String dateString = "";
if (StringUtils.isBlank(dateFormat)) {
dateString = date.toString();
} else {
dateString = DateFormatUtils.format(date, dateFormat);
}
nameValuePairs.add(new BasicNameValuePair(param.getKey(), dateString));
continue;
}
nameValuePairs.add(new BasicNameValuePair(param.getKey(), ObjectUtils.toString(value)));
}
}
}
return nameValuePairs;
}
/**
* http发送post请求
*
* @param url
* @return
* @throws IOException
*/
public static String sendPost(String url, String json, Map<String, String> headerParams) throws IOException {
String formData = postData(url, json, headerParams);
return formData;
}
/**
* 作者:sanri <br/>
* 时间:2017-10-19下午2:25:40<br/>
* 功能:向指定 url 提交数据 <br/>
*
* @param url
* @param data
* @return
* @throws IOException
*/
public static String postData(String url, String data, Map<String, String> headerParams) throws IOException, HTTPException {
HttpClient httpClient = getHttpClient();
//请求头,请求体数据封装
HttpPost postMethod = new HttpPost(url);
postMethod.addHeader("Content-Type", "application/json");
if (!headerParams.isEmpty()) {
headerParams.forEach((key, value) -> {
postMethod.addHeader(key, value);
});
}
postMethod.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:56.0) Gecko/20100101 Firefox/56.0");
StringEntity dataEntity = new StringEntity(data, JSON_UTF8);
postMethod.setEntity(dataEntity);
HttpResponse response = null;
try {
//开始请求,记录请求数据和请求时间
response = httpClient.execute(postMethod);
//获取响应
HttpEntity entity = response.getEntity();
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode != 200) {
HTTPException exception = new HTTPException(statusCode);
logger.error("请求地址" + url + "出错,http 状态码为:" + statusCode, exception);
throw exception;
}
String retData = EntityUtils.toString(entity, JSON_UTF8.getCharset());
return retData;
} catch (ClientProtocolException e) {
throw new IllegalArgumentException("客户端协议错误 ,检查 url 配置 url: " + url, e);
} finally {
HttpClientUtils.closeQuietly(response);
}
}
/**
* 作者:sanri <br/>
* 时间:2017-10-19下午2:25:40<br/>
* 功能:向指定 url 提交数据 <br/>
*
* @param url
* @param data
* @return
* @throws IOException
*/
public static String putData(String url, String data, Map<String, String> headerParams) throws IOException, HTTPException {
HttpClient httpClient = getHttpClient();
//请求头,请求体数据封装
HttpPut postMethod = new HttpPut(url);
postMethod.addHeader("Content-Type", "application/json");
if (!headerParams.isEmpty()) {
headerParams.forEach((key, value) -> {
postMethod.addHeader(key, value);
});
}
postMethod.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:56.0) Gecko/20100101 Firefox/56.0");
StringEntity dataEntity = new StringEntity(data, JSON_UTF8);
postMethod.setEntity(dataEntity);
HttpResponse response = null;
try {
//开始请求,记录请求数据和请求时间
response = httpClient.execute(postMethod);
//获取响应
HttpEntity entity = response.getEntity();
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode != 200) {
HTTPException exception = new HTTPException(statusCode);
logger.error("请求地址" + url + "出错,http 状态码为:" + statusCode, exception);
throw exception;
}
String retData = EntityUtils.toString(entity, JSON_UTF8.getCharset());
return retData;
} catch (ClientProtocolException e) {
throw new IllegalArgumentException("客户端协议错误 ,检查 url 配置 url: " + url, e);
} finally {
HttpClientUtils.closeQuietly(response);
}
}
/**
* 作者:sanri <br/>
* 时间:2017-10-19下午2:25:40<br/>
* 功能:向指定 url 提交数据 <br/>
*
* @param url
* @return
* @throws IOException
*/
public static String deleteData(String url, Map<String, String> headerParams) throws IOException, HTTPException {
HttpClient httpClient = getHttpClient();
//请求头,请求体数据封装
HttpDelete httpDelete = new HttpDelete(url);
httpDelete.addHeader("Content-Type", "application/json");
if (!headerParams.isEmpty()) {
headerParams.forEach((key, value) -> {
httpDelete.addHeader(key, value);
});
}
httpDelete.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:56.0) Gecko/20100101 Firefox/56.0");
HttpResponse response = null;
try {
//开始请求,记录请求数据和请求时间
response = httpClient.execute(httpDelete);
//获取响应
HttpEntity entity = response.getEntity();
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode != 200) {
HTTPException exception = new HTTPException(statusCode);
logger.error("请求地址" + url + "出错,http 状态码为:" + statusCode, exception);
throw exception;
}
String retData = EntityUtils.toString(entity, JSON_UTF8.getCharset());
return retData;
} catch (ClientProtocolException e) {
throw new IllegalArgumentException("客户端协议错误 ,检查 url 配置 url: " + url, e);
} finally {
HttpClientUtils.closeQuietly(response);
}
}
/**
* 作者:sanri <br/>
* 时间:2018-3-28下午8:57:50<br/>
* 功能: 请求地址获取数据<br/>
*
* @param url
* @param urlEncoded
* @return
* @throws IOException
* @throws ParseException
*/
public static String getData(final String url, final String urlEncoded, Map<String, String> headerParams) throws IOException {
HttpClient httpClient = getHttpClient();
String queryUrl = url;
if (StringUtils.isNotBlank(urlEncoded)) {
queryUrl += "?" + urlEncoded;
}
HttpGet httpGet = new HttpGet(queryUrl);
if (!headerParams.isEmpty()) {
headerParams.forEach((key, value) -> {
httpGet.addHeader(key, value);
});
}
httpGet.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:56.0) Gecko/20100101 Firefox/56.0");
HttpResponse response = null;
try {
response = httpClient.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode != 200) {
HTTPException exception = new HTTPException(statusCode);
logger.error("请求地址" + url + "出错,http 状态码为:" + statusCode, exception);
throw exception;
}
HttpEntity msgEntity = response.getEntity();
String message = EntityUtils.toString(msgEntity);
return message;
} catch (ClientProtocolException e) {
throw new IllegalArgumentException("客户端协议错误 ,检查 url 配置 url: " + url, e);
} finally {
HttpClientUtils.closeQuietly(response);
}
}
/**
* 作者:sanri <br/>
* 时间:2017-7-26下午3:36:40<br/>
* 功能:兼容以前的功能,传入路径和参数,返回字符串的返回结果 <br/>
*
* @param url
* @param params
* @return
* @throws IOException
*/
public static String getData(String url, Map<String, String> params, Charset charset, Map<String, String> headerParams) throws IOException {
List<NameValuePair> nameValuePairs = transferParam(params);
HttpEntity urlEncodedFormEntity = new UrlEncodedFormEntity(nameValuePairs, charset);
String urlEncoded = EntityUtils.toString(urlEncodedFormEntity, charset);
String data = getData(url, urlEncoded, headerParams);
return data;
}
/**
* http发送get请求
*
* @param url
* @param params
* @param headerParams
* @return
* @throws IOException
*/
public static JSONObject sendGet(String url, Map<String, String> params, Map<String, String> headerParams) throws IOException {
String retData = getData(url, params, Consts.UTF_8, headerParams);
if (StringUtils.isNotBlank(retData)) {
return JSONObject.parseObject(retData);
}
return new JSONObject();
}
/**
* http的put方法
*
* @param url 请求url
* @param json 请求body
* @param headerParams 请求参数
* @return
* @throws IOException
*/
public static JSONObject sendPut(String url, String json, Map<String, String> headerParams) throws IOException {
String formData = putData(url, json, headerParams);
if (StringUtils.isNotBlank(formData)) {
return JSONObject.parseObject(formData);
}
return new JSONObject();
}
/**
* http发送delete请求
*
* @param url url
* @param headerParams 请求参数
* @return
* @throws IOException
*/
public static JSONObject sendDelete(String url,Map<String, String> headerParams) throws IOException {
String retData = deleteData(url,headerParams);
if (StringUtils.isNotBlank(retData)) {
return JSONObject.parseObject(retData);
}
return new JSONObject();
}
}
\ No newline at end of file \ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.com.glsx.consumer.mapper.DayInfoMapper">
<resultMap id="BaseResultMap" type="cn.com.glsx.consumer.entity.DayInfo">
<!--
WARNING - @mbg.generated
-->
<id column="id" jdbcType="INTEGER" property="id" />
<result column="date" jdbcType="VARCHAR" property="date" />
<result column="daycode" jdbcType="INTEGER" property="daycode" />
<result column="name" jdbcType="VARCHAR" property="name" />
<result column="tip" jdbcType="VARCHAR" property="tip" />
</resultMap>
<sql id="Base_Column_List">
<!--
WARNING - @mbg.generated
-->
id, `date`, daycode, `name`, tip
</sql>
<select id="getDayCodeByDate" resultMap="BaseResultMap">
select `daycode` from smart_date where date = #{date}
</select>
</mapper>
\ No newline at end of file \ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.com.glsx.consumer.mapper.SmartSceneDataMapper">
<resultMap id="BaseResultMap" type="cn.com.glsx.consumer.entity.SmartSceneData">
<!--
WARNING - @mbg.generated
-->
<id column="id" jdbcType="BIGINT" property="id" />
<result column="scene_id" jdbcType="BIGINT" property="sceneId" />
<result column="type" jdbcType="TINYINT" property="type" />
<result column="sort" jdbcType="TINYINT" property="sort" />
<result column="param_key" jdbcType="VARCHAR" property="paramKey" />
<result column="device_id" jdbcType="VARCHAR" property="deviceId" />
<result column="param_value" jdbcType="VARCHAR" property="paramValue" />
<result column="condition_rule" jdbcType="TINYINT" property="conditionRule" />
<result column="execute_cycle" jdbcType="TINYINT" property="executeCycle" />
</resultMap>
<sql id="Base_Column_List">
<!--
WARNING - @mbg.generated
-->
id, scene_id, `type`, sort, param_key, device_id, param_value
</sql>
<select id="findSceneDataByDeviceId" resultMap="BaseResultMap">
select t1.*,t2.condition_rule,t2.execute_cycle from smart_scene_data t1 left join smart_scene t2 on t1.scene_id=t2.id
where device_id=#{deviceId} and param_key='scene_condition_status'
</select>
<select id="findBySceneId" resultType="cn.com.glsx.consumer.entity.SmartSceneData">
select t1.*,t2.condition_rule,t2.execute_cycle from smart_scene_data t1 left join smart_scene t2 on t1.scene_id=t2.id
where scene_id=#{sceneId} and (param_key='scene_condition_status' or param_key='scene_condition_time')
</select>
</mapper>
\ No newline at end of file \ No newline at end of file
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!