Commit d20727dd authored by zhuangzhuang's avatar zhuangzhuang

3.14--增加checkIn主题监控,修改redis的结构

parent d1e29e6a
...@@ -45,6 +45,8 @@ dependencies { ...@@ -45,6 +45,8 @@ dependencies {
compile('org.apache.commons:commons-compress:1.9') compile('org.apache.commons:commons-compress:1.9')
compile('org.springframework.boot:spring-boot-starter-data-redis') compile('org.springframework.boot:spring-boot-starter-data-redis')
compile ('org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.1.0') compile ('org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.1.0')
compile ('org.influxdb:influxdb-java:2.7')
compile ('com.github.miwurster:spring-data-influxdb:1.6')
} }
jar { jar {
String someString = '' String someString = ''
......
package com.example.tdl.callabletask; package com.example.tdl.callabletask;
import com.example.tdl.config.mqtt.MqttTemlateAsync; import com.example.tdl.config.mqtt.MqttTemlateAsync;
import com.example.tdl.domain.vo.CheckInVo;
import com.example.tdl.domain.vo.ConfigCMDVo;
import com.example.tdl.domain.vo.ConfigVo;
import com.example.tdl.domain.vo.RespVo;
import com.example.tdl.entity.Config;
import com.example.tdl.service.ConfigService;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.JsonObject; import com.google.gson.JsonObject;
import com.google.gson.JsonParser; import com.google.gson.JsonParser;
import com.google.gson.JsonSyntaxException; import com.google.gson.JsonSyntaxException;
import org.eclipse.paho.client.mqttv3.*; import org.eclipse.paho.client.mqttv3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
...@@ -22,6 +31,11 @@ import java.util.concurrent.TimeUnit; ...@@ -22,6 +31,11 @@ import java.util.concurrent.TimeUnit;
**/ **/
public class GWConfigWorker implements Callable<String>, MqttCallback { public class GWConfigWorker implements Callable<String>, MqttCallback {
private Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
private ConfigService configService;
private static final int INIT_DELAY_DEFAULT = 1000; // unit:ms private static final int INIT_DELAY_DEFAULT = 1000; // unit:ms
private static final int SCH_PERIOD_DEFAULT = 10 * INIT_DELAY_DEFAULT; // unit:ms private static final int SCH_PERIOD_DEFAULT = 10 * INIT_DELAY_DEFAULT; // unit:ms
...@@ -32,10 +46,10 @@ public class GWConfigWorker implements Callable<String>, MqttCallback { ...@@ -32,10 +46,10 @@ public class GWConfigWorker implements Callable<String>, MqttCallback {
private String Type; private String Type;
private Boolean NeedResp = false; private Boolean NeedResp = false;
private String Device; private String Device;
private String ConfigCMD; private String ConfigCMD;//发送的数据
private String ConfigTopic; private String ConfigTopic;//发送的主题
private String RespTopic; private String RespTopic;//返回的主题
private String ret_data=null; private String ret_data=null;
...@@ -58,8 +72,7 @@ public class GWConfigWorker implements Callable<String>, MqttCallback { ...@@ -58,8 +72,7 @@ public class GWConfigWorker implements Callable<String>, MqttCallback {
private String clientpwd; private String clientpwd;
public void SetMqttConfig(String url, String port, String user, String password, int qos, public void SetMqttConfig(String url, String port, String user, String password, int qos,
String mcacrt, String mclientkey, String mclientcrt, String mclientpwd) String mcacrt, String mclientkey, String mclientcrt, String mclientpwd) {
{
this.url = url; this.url = url;
this.port = port; this.port = port;
this.username = user; this.username = user;
...@@ -76,7 +89,7 @@ public class GWConfigWorker implements Callable<String>, MqttCallback { ...@@ -76,7 +89,7 @@ public class GWConfigWorker implements Callable<String>, MqttCallback {
this.Type = type; this.Type = type;
this.Device = Type + "_" + SN; this.Device = Type + "_" + SN;
this.ConfigCMD = CMD; this.ConfigCMD = CMD;
this.NeedResp = false; this.NeedResp = flag;
this.ConfigTopic = "GW/" + Type + "/" + SN + PUB_TOPIC; this.ConfigTopic = "GW/" + Type + "/" + SN + PUB_TOPIC;
this.RespTopic = "GW/" + Type + "/" + SN + SUB_TOPIC; this.RespTopic = "GW/" + Type + "/" + SN + SUB_TOPIC;
} }
...@@ -88,20 +101,21 @@ public class GWConfigWorker implements Callable<String>, MqttCallback { ...@@ -88,20 +101,21 @@ public class GWConfigWorker implements Callable<String>, MqttCallback {
Device + "_" + String.valueOf(System.currentTimeMillis()) + "_config"); Device + "_" + String.valueOf(System.currentTimeMillis()) + "_config");
mqttAsyncClient.connect(MqttTemlateAsync.setSSLOptions(this.username, this.password, mqttAsyncClient.connect(MqttTemlateAsync.setSSLOptions(this.username, this.password,
this.cacrt, this.clientcrt, this.clientkey, this.clientpwd), null, this.cacrt, this.clientcrt, this.clientkey, this.clientpwd), null,
new IMqttActionListener() { new IMqttActionListener() {//监听
@Override @Override
public void onSuccess(IMqttToken iMqttToken) { public void onSuccess(IMqttToken iMqttToken) {
System.out.println("connection successfull "); System.out.println("connection successfull ");
try { try {
if(NeedResp) if(NeedResp){
mqttAsyncClient.subscribe(RespTopic, qos); mqttAsyncClient.subscribe(RespTopic, qos);//订阅主题
}
MqttMessage msg = new MqttMessage(); //获取数据
msg.setQos(1); ConfigVo configVo = configService.getConfig(SN,Type);
msg.setRetained(true); ConfigCMD = configVo.getMessage();
msg.setPayload(ConfigCMD.getBytes()); //发送数据
mqttAsyncClient.publish(ConfigTopic,msg); publish(ConfigCMD,ConfigTopic);
} catch (MqttException e) { } catch (MqttException e){
e.printStackTrace();
System.out.println("Error: " + e.getMessage()); System.out.println("Error: " + e.getMessage());
} }
} }
...@@ -113,16 +127,16 @@ public class GWConfigWorker implements Callable<String>, MqttCallback { ...@@ -113,16 +127,16 @@ public class GWConfigWorker implements Callable<String>, MqttCallback {
this.mqttAsyncClient.setCallback(this); this.mqttAsyncClient.setCallback(this);
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
logger.info(e.toString());
} }
return ret_data; return ret_data;
} }
private void clientReconnect() { private void clientReconnect(){
if (mReconnectScheduler != null) { if (mReconnectScheduler != null) {
// mReconnectScheduler is running. // mReconnectScheduler is running.
return; return;
} }
mReconnectScheduler = Executors.newSingleThreadScheduledExecutor(); mReconnectScheduler = Executors.newSingleThreadScheduledExecutor();
mReconnectScheduler.scheduleAtFixedRate(new Runnable() { mReconnectScheduler.scheduleAtFixedRate(new Runnable() {
@Override @Override
...@@ -134,9 +148,11 @@ public class GWConfigWorker implements Callable<String>, MqttCallback { ...@@ -134,9 +148,11 @@ public class GWConfigWorker implements Callable<String>, MqttCallback {
} catch (MqttSecurityException e) { } catch (MqttSecurityException e) {
// TODO: handle exception // TODO: handle exception
e.printStackTrace(); e.printStackTrace();
logger.info(e.toString());
} catch (MqttException e) { } catch (MqttException e) {
// TODO: handle exception // TODO: handle exception
e.printStackTrace(); e.printStackTrace();
logger.info(e.toString());
} }
} else { } else {
mReconnectScheduler.shutdown(); mReconnectScheduler.shutdown();
...@@ -157,21 +173,45 @@ public class GWConfigWorker implements Callable<String>, MqttCallback { ...@@ -157,21 +173,45 @@ public class GWConfigWorker implements Callable<String>, MqttCallback {
String Message = mqttMessage.toString(); String Message = mqttMessage.toString();
try { try {
this.ret_data = Message; this.ret_data = Message;
//解析Message消息
mqttAsyncClient.unsubscribe(RespTopic); RespVo respVo = new Gson().fromJson(Message,RespVo.class);
if(respVo.getResponse().equals("config")){
//配置回复
configService.bindiSuccess(SN,Type,respVo.getStatus());
}else{
//解绑回复
if(respVo.getStatus() ==0 || respVo.getStatus() == 1){
configService.delConfig(SN,Type);
}
}
if(NeedResp){
mqttAsyncClient.unsubscribe(RespTopic);//不监听回复主题
}
mqttAsyncClient.disconnect(); mqttAsyncClient.disconnect();
} catch (JsonSyntaxException e) { } catch (JsonSyntaxException e){
e.printStackTrace();
System.out.println("mqttAsyncClient: message " + Message + " received syntax error."); System.out.println("mqttAsyncClient: message " + Message + " received syntax error.");
} catch (IllegalStateException e) { } catch (IllegalStateException e){
e.printStackTrace();
System.out.println("mqttAsyncClient: " + e); System.out.println("mqttAsyncClient: " + e);
} catch (Exception e) { } catch (Exception e){
e.printStackTrace(); e.printStackTrace();
logger.info(e.toString());
} }
} }
@Override @Override
public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) { public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
}
//发送数据的接口
public void publish(String ConfigCMD,String ConfigTopic) throws MqttException {
//发送数据
MqttMessage msg = new MqttMessage();
msg.setQos(1);
msg.setRetained(true);
msg.setPayload(ConfigCMD.getBytes());
mqttAsyncClient.publish(ConfigTopic,msg);
} }
} }
package com.example.tdl.config;
import org.influxdb.InfluxDB;
import org.influxdb.InfluxDBFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@ConfigurationProperties(prefix = "witium.influxdb")
public class Influxdbconfig {
private String user;
private String password;
private String host;
private String database;
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public String getDatabase() {
return database;
}
public void setDatabase(String database) {
this.database = database;
}
@Bean
public InfluxDB influxDB() {
return InfluxDBFactory.connect(host, user, password);
}
}
...@@ -4,6 +4,7 @@ import com.fasterxml.jackson.annotation.JsonAutoDetect; ...@@ -4,6 +4,7 @@ import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor; import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cache.CacheManager; import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport; import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching; import org.springframework.cache.annotation.EnableCaching;
...@@ -26,18 +27,92 @@ import java.util.Map; ...@@ -26,18 +27,92 @@ import java.util.Map;
@Configuration @Configuration
@EnableCaching @EnableCaching
@PropertySource(value = "classpath:/application.properties") @ConfigurationProperties(prefix = "tdl.redis")
public class RedisConfig extends CachingConfigurerSupport { public class RedisConfig extends CachingConfigurerSupport{
@Value("${spring.redis.host}")
private String host; private String host;
// @Value("${spring.redis.password}") private String password;
// private String password;
@Value("${spring.redis.port}")
private int port; private int port;
@Value("${spring.redis.timeout}")
private int timeout; private int timeout;
private int index;
private int poolmaxactive;
private int poolmaxwait;
private int poolmaxidle;
private int poolminidle;
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
public int getPoolmaxactive() {
return poolmaxactive;
}
public void setPoolmaxactive(int poolmaxactive) {
this.poolmaxactive = poolmaxactive;
}
public int getPoolmaxwait() {
return poolmaxwait;
}
public void setPoolmaxwait(int poolmaxwait) {
this.poolmaxwait = poolmaxwait;
}
public int getPoolmaxidle() {
return poolmaxidle;
}
public void setPoolmaxidle(int poolmaxidle) {
this.poolmaxidle = poolmaxidle;
}
public int getPoolminidle() {
return poolminidle;
}
public void setPoolminidle(int poolminidle) {
this.poolminidle = poolminidle;
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public int getTimeout() {
return timeout;
}
public void setTimeout(int timeout) {
this.timeout = timeout;
}
/** /**
* 生产key的策略 * 生产key的策略
* *
...@@ -66,9 +141,8 @@ public class RedisConfig extends CachingConfigurerSupport { ...@@ -66,9 +141,8 @@ public class RedisConfig extends CachingConfigurerSupport {
* @param redisTemplate * @param redisTemplate
* @return * @return
*/ */
@SuppressWarnings("rawtypes")
@Bean @Bean
public CacheManager CacheManager(RedisTemplate redisTemplate) { public CacheManager CacheManager(RedisTemplate<?, ?> redisTemplate) {
RedisCacheManager rcm = new RedisCacheManager(redisTemplate); RedisCacheManager rcm = new RedisCacheManager(redisTemplate);
// 设置cache过期时间,时间单位是秒 // 设置cache过期时间,时间单位是秒
rcm.setDefaultExpiration(60); rcm.setDefaultExpiration(60);
...@@ -83,13 +157,12 @@ public class RedisConfig extends CachingConfigurerSupport { ...@@ -83,13 +157,12 @@ public class RedisConfig extends CachingConfigurerSupport {
* *
* @return * @return
*/ */
@Bean public RedisConnectionFactory redisConnectionFactory(int dbIndex) {
public JedisConnectionFactory tokenConnectionFactory() {
JedisConnectionFactory factory = new JedisConnectionFactory(); JedisConnectionFactory factory = new JedisConnectionFactory();
setIndex(dbIndex);
factory.setHostName(host); factory.setHostName(host);
// factory.setPassword(password); factory.setPort(Integer.valueOf(port));
factory.setPort( Integer.valueOf(port)); factory.setDatabase(index);
factory.setDatabase(0);
factory.setTimeout(10000); // 设置连接超时时间 factory.setTimeout(10000); // 设置连接超时时间
factory.setPoolConfig(poolConfig()); factory.setPoolConfig(poolConfig());
factory.afterPropertiesSet(); factory.afterPropertiesSet();
...@@ -97,32 +170,50 @@ public class RedisConfig extends CachingConfigurerSupport { ...@@ -97,32 +170,50 @@ public class RedisConfig extends CachingConfigurerSupport {
} }
public JedisPoolConfig poolConfig() { public JedisPoolConfig poolConfig() {
JedisPoolConfig poolConfig = new JedisPoolConfig(); JedisPoolConfig poolCofig = new JedisPoolConfig();
poolConfig.setMaxIdle(8); poolCofig.setMaxIdle(poolmaxidle);
poolConfig.setMaxTotal(8); poolCofig.setMaxTotal(poolmaxactive);
poolConfig.setMaxWaitMillis(-1); poolCofig.setMaxWaitMillis(poolmaxwait);
poolConfig.setTestOnBorrow(false); poolCofig.setTestOnBorrow(false);
return poolConfig; return poolCofig;
} }
/** /**
* redisTemplate配置 * redisSerializer
*
* @param tokenConnectionFactory
* @return
*/ */
@SuppressWarnings({"rawtypes", "unchecked"}) private void JsonRedisSerializer(StringRedisTemplate template, boolean isHash) {
@Bean Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer =
public RedisTemplate<String, String> tokenRedisTemplate(RedisConnectionFactory tokenConnectionFactory) { new Jackson2JsonRedisSerializer<Object>(Object.class);
StringRedisTemplate template = new StringRedisTemplate(tokenConnectionFactory);
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper(); ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om); jackson2JsonRedisSerializer.setObjectMapper(om);
template.setValueSerializer(jackson2JsonRedisSerializer); template.setValueSerializer(jackson2JsonRedisSerializer);
if (isHash) {
template.setHashValueSerializer(jackson2JsonRedisSerializer);
template.setHashKeySerializer(jackson2JsonRedisSerializer);
}
template.afterPropertiesSet(); template.afterPropertiesSet();
}
/**
* redisTemplate配置
*
* @param
* @return
*/
//@SuppressWarnings({"rawtypes", "unchecked"})
@Bean
public RedisTemplate<String, String> tokenRedisTemplate() {
StringRedisTemplate template = new StringRedisTemplate(redisConnectionFactory(15));
JsonRedisSerializer(template, false);
return template;
}
@Bean
public RedisTemplate<String, String> redisTemplate() {
StringRedisTemplate template = new StringRedisTemplate(redisConnectionFactory(1));
JsonRedisSerializer(template, true);
return template; return template;
} }
} }
......
...@@ -34,6 +34,7 @@ public class MqttTemlateAsync extends MqttAsyncClient { ...@@ -34,6 +34,7 @@ public class MqttTemlateAsync extends MqttAsyncClient {
super(serverURL, clientId, new MemoryPersistence()); // set default MqttClientPersistence as MemoryPersistence super(serverURL, clientId, new MemoryPersistence()); // set default MqttClientPersistence as MemoryPersistence
} }
private static String getPem(String path) throws Exception{ private static String getPem(String path) throws Exception{
FileInputStream fin = new FileInputStream(path); FileInputStream fin = new FileInputStream(path);
BufferedReader br = new BufferedReader(new InputStreamReader(fin)); BufferedReader br = new BufferedReader(new InputStreamReader(fin));
...@@ -51,6 +52,7 @@ public class MqttTemlateAsync extends MqttAsyncClient { ...@@ -51,6 +52,7 @@ public class MqttTemlateAsync extends MqttAsyncClient {
return sb.toString(); return sb.toString();
} }
public static PrivateKey getPrivateKey(String path) throws Exception{ public static PrivateKey getPrivateKey(String path) throws Exception{
byte[] buffer = new Base64().decode(getPem(path)); byte[] buffer = new Base64().decode(getPem(path));
...@@ -59,6 +61,7 @@ public class MqttTemlateAsync extends MqttAsyncClient { ...@@ -59,6 +61,7 @@ public class MqttTemlateAsync extends MqttAsyncClient {
return (RSAPrivateKey) keyFactory.generatePrivate(keySpec); return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
} }
private static SSLSocketFactory getSSLSocketFactory(String caPath, String crtPath, String keyPath, private static SSLSocketFactory getSSLSocketFactory(String caPath, String crtPath, String keyPath,
String password) throws Exception { String password) throws Exception {
// CA certificate is used to authenticate server // CA certificate is used to authenticate server
...@@ -96,6 +99,7 @@ public class MqttTemlateAsync extends MqttAsyncClient { ...@@ -96,6 +99,7 @@ public class MqttTemlateAsync extends MqttAsyncClient {
return context.getSocketFactory(); return context.getSocketFactory();
} }
@SuppressWarnings("unused") @SuppressWarnings("unused")
private static Properties getSSLProperties() { private static Properties getSSLProperties() {
Properties props = null; Properties props = null;
...@@ -120,6 +124,7 @@ public class MqttTemlateAsync extends MqttAsyncClient { ...@@ -120,6 +124,7 @@ public class MqttTemlateAsync extends MqttAsyncClient {
return props; return props;
} }
public static MqttConnectOptions defaultOptions(){ public static MqttConnectOptions defaultOptions(){
String str = "witium"; String str = "witium";
char[] bm; char[] bm;
...@@ -130,6 +135,8 @@ public class MqttTemlateAsync extends MqttAsyncClient { ...@@ -130,6 +135,8 @@ public class MqttTemlateAsync extends MqttAsyncClient {
mqttConnectOptions.setPassword(bm); mqttConnectOptions.setPassword(bm);
return mqttConnectOptions; return mqttConnectOptions;
} }
/* For raw tcp only */ /* For raw tcp only */
public static MqttConnectOptions setOptions(String username, String pwd){ public static MqttConnectOptions setOptions(String username, String pwd){
MqttConnectOptions mqttConnectOptions = new MqttConnectOptions(); MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
...@@ -140,6 +147,7 @@ public class MqttTemlateAsync extends MqttAsyncClient { ...@@ -140,6 +147,7 @@ public class MqttTemlateAsync extends MqttAsyncClient {
return mqttConnectOptions; return mqttConnectOptions;
} }
public static MqttConnectOptions setSSLOptions(String username, String pwd, public static MqttConnectOptions setSSLOptions(String username, String pwd,
String cacrt, String clientcrt, String clientkey, String clientpwd){ String cacrt, String clientcrt, String clientkey, String clientpwd){
MqttConnectOptions mqttConnectOptions = new MqttConnectOptions(); MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
......
package com.example.tdl.domain.vo;
public class AddAlarmLogVo {
private String routeNumber;
private String routeName;
private String description;
private Float data;
private Long alarmTime;
public AddAlarmLogVo() {
}
public AddAlarmLogVo(String routeNumber, String routeName, String description, Float data, Long alarmTime) {
this.routeNumber = routeNumber;
this.routeName = routeName;
this.description = description;
this.data = data;
this.alarmTime = alarmTime;
}
public String getRouteNumber() {
return routeNumber;
}
public void setRouteNumber(String routeNumber) {
this.routeNumber = routeNumber;
}
public String getRouteName() {
return routeName;
}
public void setRouteName(String routeName) {
this.routeName = routeName;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Float getData() {
return data;
}
public void setData(Float data) {
this.data = data;
}
public Long getAlarmTime() {
return alarmTime;
}
public void setAlarmTime(Long alarmTime) {
this.alarmTime = alarmTime;
}
}
package com.example.tdl.domain.vo;
public class AlarmLogVo {
private String routeName;
private String description;
private Float data;
private Long alarmTime;
public String getRouteName() {
return routeName;
}
public void setRouteName(String routeName) {
this.routeName = routeName;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Float getData() {
return data;
}
public void setData(Float data) {
this.data = data;
}
public Long getAlarmTime() {
return alarmTime;
}
public void setAlarmTime(Long alarmTime) {
this.alarmTime = alarmTime;
}
}
package com.example.tdl.domain.vo;
import java.util.List;
public class CheckInVo {
private String action;
private String ccid;
private Integer battery;
private String version;
private String bleVersion;
private Boolean first;
private Integer gpsPeriod;
private Integer gprsPeriod;
private Integer mode;
private List<String> devList;
public String getAction() {
return action;
}
public void setAction(String action) {
this.action = action;
}
public String getCcid() {
return ccid;
}
public void setCcid(String ccid) {
this.ccid = ccid;
}
public Integer getBattery() {
return battery;
}
public void setBattery(Integer battery) {
this.battery = battery;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getBleVersion() {
return bleVersion;
}
public void setBleVersion(String bleVersion) {
this.bleVersion = bleVersion;
}
public Boolean getFirst() {
return first;
}
public void setFirst(Boolean first) {
this.first = first;
}
public Integer getGpsPeriod() {
return gpsPeriod;
}
public void setGpsPeriod(Integer gpsPeriod) {
this.gpsPeriod = gpsPeriod;
}
public Integer getGprsPeriod() {
return gprsPeriod;
}
public void setGprsPeriod(Integer gprsPeriod) {
this.gprsPeriod = gprsPeriod;
}
public Integer getMode() {
return mode;
}
public void setMode(Integer mode) {
this.mode = mode;
}
public List<String> getDevList() {
return devList;
}
public void setDevList(List<String> devList) {
this.devList = devList;
}
}
package com.example.tdl.domain.vo;
import java.util.List;
public class ConfigCMDVo {
private String action;
private Integer gpsPeriod;
private Integer gprsPeriod;
private List<String> devList;
private Integer mode; //1为运输,2位仓储
private Long t;//配置时的时间戳
public String getAction() {
return action;
}
public void setAction(String action) {
this.action = action;
}
public Integer getGpsPeriod() {
return gpsPeriod;
}
public void setGpsPeriod(Integer gpsPeriod) {
this.gpsPeriod = gpsPeriod;
}
public Integer getGprsPeriod() {
return gprsPeriod;
}
public void setGprsPeriod(Integer gprsPeriod) {
this.gprsPeriod = gprsPeriod;
}
public List<String> getDevList() {
return devList;
}
public void setDevList(List<String> devList) {
this.devList = devList;
}
public Integer getMode() {
return mode;
}
public void setMode(Integer mode) {
this.mode = mode;
}
public Long getT() {
return t;
}
public void setT(Long t) {
this.t = t;
}
}
package com.example.tdl.domain.vo;
public class ConfigVo {
private String gSN;
private String gType;
private String message;
private Boolean flag;
private Integer resp;
private Integer state;
private Boolean untie;
public String getgSN() {
return gSN;
}
public void setgSN(String gSN) {
this.gSN = gSN;
}
public String getgType() {
return gType;
}
public void setgType(String gType) {
this.gType = gType;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Boolean getFlag() {
return flag;
}
public void setFlag(Boolean flag) {
this.flag = flag;
}
public Integer getResp() {
return resp;
}
public void setResp(Integer resp) {
this.resp = resp;
}
public Integer getState() {
return state;
}
public void setState(Integer state) {
this.state = state;
}
public Boolean getUntie() {
return untie;
}
public void setUntie(Boolean untie) {
this.untie = untie;
}
}
package com.example.tdl.domain.vo;
import java.util.List;
public class HomePageDataVo {
private Integer sum;//总线路
private Integer onRoute;//在途数量
private Integer complted;//已完成
private Integer alarmed;//报警线路
private List<ResultRouteVo> routeVoList;//线路列表
//报警列表
private List<AlarmLogVo> alarmLogVoList;
//报警原因分析
public Integer getSum() {
return sum;
}
public void setSum(Integer sum) {
this.sum = sum;
}
public Integer getOnRoute() {
return onRoute;
}
public void setOnRoute(Integer onRoute) {
this.onRoute = onRoute;
}
public Integer getComplted() {
return complted;
}
public void setComplted(Integer complted) {
this.complted = complted;
}
public Integer getAlarmed() {
return alarmed;
}
public void setAlarmed(Integer alarmed) {
this.alarmed = alarmed;
}
public List<ResultRouteVo> getRouteVoList() {
return routeVoList;
}
public void setRouteVoList(List<ResultRouteVo> routeVoList) {
this.routeVoList = routeVoList;
}
public List<AlarmLogVo> getAlarmLogVoList() {
return alarmLogVoList;
}
public void setAlarmLogVoList(List<AlarmLogVo> alarmLogVoList) {
this.alarmLogVoList = alarmLogVoList;
}
}
package com.example.tdl.domain.vo;
import java.util.List;
public class RespVo {
private String response;
private Integer status;
private List<String> devList;
public String getResponse() {
return response;
}
public void setResponse(String response) {
this.response = response;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public List<String> getDevList() {
return devList;
}
public void setDevList(List<String> devList) {
this.devList = devList;
}
}
package com.example.tdl.domain.vo;
public class TermVo {
private String time;
private String evaluation;
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getEvaluation() {
return evaluation;
}
public void setEvaluation(String evaluation) {
this.evaluation = evaluation;
}
}
package com.example.tdl.entity;
public class AlarmLog {
private Integer id;
private String routeNumber;
private String routeName;
private String description;
private Float data;
private Long alarmTime;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getRouteNumber() {
return routeNumber;
}
public void setRouteNumber(String routeNumber) {
this.routeNumber = routeNumber;
}
public String getRouteName() {
return routeName;
}
public void setRouteName(String routeName) {
this.routeName = routeName;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Float getData() {
return data;
}
public void setData(Float data) {
this.data = data;
}
public Long getAlarmTime() {
return alarmTime;
}
public void setAlarmTime(Long alarmTime) {
this.alarmTime = alarmTime;
}
}
package com.example.tdl.entity;
public class Config {
private Integer id;
private String gSN;
private String gType;
private String message;
private Boolean flag;
private Integer resp;
private Integer state;
private Boolean untie;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getgSN() {
return gSN;
}
public void setgSN(String gSN) {
this.gSN = gSN;
}
public String getgType() {
return gType;
}
public void setgType(String gType) {
this.gType = gType;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Boolean getFlag() {
return flag;
}
public void setFlag(Boolean flag) {
this.flag = flag;
}
public Integer getResp() {
return resp;
}
public void setResp(Integer resp) {
this.resp = resp;
}
public Integer getState() {
return state;
}
public void setState(Integer state) {
this.state = state;
}
public Boolean getUntie() {
return untie;
}
public void setUntie(Boolean untie) {
this.untie = untie;
}
}
package com.example.tdl.interceptor; package com.example.tdl.interceptor;
import com.example.tdl.service.TokenRedisService;
import com.example.tdl.service.redis.TokenRedisService;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
...@@ -41,7 +42,7 @@ public class LoginInterceptor implements HandlerInterceptor { ...@@ -41,7 +42,7 @@ public class LoginInterceptor implements HandlerInterceptor {
ps.write("{\"code\":2,\"message\":\"用户登录过期,请重新登录\"}".getBytes("UTF-8")); ps.write("{\"code\":2,\"message\":\"用户登录过期,请重新登录\"}".getBytes("UTF-8"));
return false; return false;
} }
redisService.expire("TOKEN_" +token,60 * 30); redisService.refeshTimeOut("TOKEN_" +token,60 * 30);
return true; return true;
} }
......
...@@ -2,7 +2,7 @@ package com.example.tdl.interceptor; ...@@ -2,7 +2,7 @@ package com.example.tdl.interceptor;
import com.example.tdl.domain.vo.UserVo; import com.example.tdl.domain.vo.UserVo;
import com.example.tdl.service.RoleService; import com.example.tdl.service.RoleService;
import com.example.tdl.service.TokenRedisService; import com.example.tdl.service.redis.TokenRedisService;
import com.google.gson.Gson; import com.google.gson.Gson;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
......
package com.example.tdl.mapper;
import com.example.tdl.domain.vo.AddAlarmLogVo;
import com.example.tdl.domain.vo.AlarmLogVo;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
@Mapper
public interface AlarmLogMapper {
//获取所有的数据
List<AlarmLogVo> getAll();
//根据条件获取报警数据
List<AlarmLogVo> getAlarmLog(String time);
//新增报警数据
int addAlarmLog(AddAlarmLogVo addAlarmLogVo);
}
package com.example.tdl.mapper;
import com.example.tdl.domain.vo.ConfigVo;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
@Mapper
public interface ConfigMapper {
int addConfig(ConfigVo configVo);
ConfigVo getConfig(@Param("gSN") String gSN, @Param("gType") String gType);
int delConfig(@Param("gSN") String gSN,@Param("gType") String gType);
int bindiSuccess(@Param("gSN") String gSN,@Param("gType") String gType,@Param("resp") Integer resp);
int updateConfig(@Param("gSN") String gSN,@Param("gType") String gType,@Param("untie") Boolean untie);
}
...@@ -14,6 +14,8 @@ public interface RouteMapper { ...@@ -14,6 +14,8 @@ public interface RouteMapper {
List<ResultRouteVo> getAll(); List<ResultRouteVo> getAll();
List<ResultRouteVo> getAllRoute(String time);
List<ResultRouteVo> getRouteByTerm(RouteTermVo routeTermVo); List<ResultRouteVo> getRouteByTerm(RouteTermVo routeTermVo);
int addRoute(Route route); int addRoute(Route route);
......
...@@ -3,11 +3,17 @@ package com.example.tdl.mqtt; ...@@ -3,11 +3,17 @@ package com.example.tdl.mqtt;
import com.example.tdl.callabletask.GWConfigWorker; import com.example.tdl.callabletask.GWConfigWorker;
import com.example.tdl.config.mqtt.MqttConfig; import com.example.tdl.config.mqtt.MqttConfig;
import com.example.tdl.config.mqtt.MqttTemlateAsync; import com.example.tdl.config.mqtt.MqttTemlateAsync;
import com.example.tdl.domain.vo.CheckInVo;
import com.example.tdl.domain.vo.ConfigCMDVo;
import com.example.tdl.domain.vo.ConfigVo;
import com.example.tdl.service.ConfigService;
import com.google.gson.Gson;
import com.google.gson.JsonObject; import com.google.gson.JsonObject;
import com.google.gson.JsonParser; import com.google.gson.JsonParser;
import com.google.gson.JsonSyntaxException; import com.google.gson.JsonSyntaxException;
import org.eclipse.paho.client.mqttv3.*; import org.eclipse.paho.client.mqttv3.*;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.expression.spel.ast.NullLiteral;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
...@@ -39,6 +45,9 @@ public class MqttListener implements MqttCallback { ...@@ -39,6 +45,9 @@ public class MqttListener implements MqttCallback {
@Autowired @Autowired
ThreadPoolTaskExecutor configthreadPool; ThreadPoolTaskExecutor configthreadPool;
@Autowired
private ConfigService configService;
Map<String,Future<String>> futureMap = new HashMap<String,Future<String>>(); Map<String,Future<String>> futureMap = new HashMap<String,Future<String>>();
private ScheduledExecutorService mReconnectScheduler; private ScheduledExecutorService mReconnectScheduler;
...@@ -51,24 +60,24 @@ public class MqttListener implements MqttCallback { ...@@ -51,24 +60,24 @@ public class MqttListener implements MqttCallback {
try { try {
mqttAsyncClient = new MqttTemlateAsync(mqttconfig.getUrl() + ":" + mqttconfig.getPort(), mqttAsyncClient = new MqttTemlateAsync(mqttconfig.getUrl() + ":" + mqttconfig.getPort(),
"TDL_CheckIn" + "_" + String.valueOf(System.currentTimeMillis()) + "_sub"); "TDL_CheckIn" + "_" + String.valueOf(System.currentTimeMillis()) + "_sub");
mqttAsyncClient.connect(MqttTemlateAsync.setSSLOptions(mqttconfig.getUsername(), mqttconfig.getPassword(), mqttAsyncClient.connect(MqttTemlateAsync.setSSLOptions(mqttconfig.getUsername(), mqttconfig.getPassword(),
mqttconfig.getCacrt(), mqttconfig.getClientcrt(),mqttconfig.getClientkey(), mqttconfig.getClientpwd()), null, mqttconfig.getCacrt(), mqttconfig.getClientcrt(),mqttconfig.getClientkey(), mqttconfig.getClientpwd()), null,
new IMqttActionListener() { new IMqttActionListener() {
@Override @Override
public void onSuccess(IMqttToken iMqttToken) { public void onSuccess(IMqttToken iMqttToken) {
System.out.println("connection successfull "); System.out.println("connection successfull ");
try { try {
mqttAsyncClient.subscribe(listener_topic, mqttconfig.getQos()); mqttAsyncClient.subscribe(listener_topic, mqttconfig.getQos());
} catch (MqttException e) { } catch (MqttException e) {
System.out.println("Error: " + e.getMessage()); System.out.println("Error: " + e.getMessage());
}
} }
}
@Override @Override
public void onFailure(IMqttToken iMqttToken, Throwable throwable) { public void onFailure(IMqttToken iMqttToken, Throwable throwable) {
System.out.println("connection fail with client id"); System.out.println("connection fail with client id");
} }
}); });
this.mqttAsyncClient.setCallback(this); this.mqttAsyncClient.setCallback(this);
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
...@@ -118,30 +127,47 @@ public class MqttListener implements MqttCallback { ...@@ -118,30 +127,47 @@ public class MqttListener implements MqttCallback {
String[] tmparray = topic.split("/"); String[] tmparray = topic.split("/");
String Type = tmparray[1]; String Type = tmparray[1];
String SN = tmparray[2]; String SN = tmparray[2];
Integer flag = parseData(Message,SN,Type);
String ConfigData ="{\"action\":\"config\"}"; String ConfigData;
Future<String> result = null; Future<String> result = null;
GWConfigWorker gcconfig = new GWConfigWorker(Type,SN,ConfigData, true); GWConfigWorker gcconfig = null;
if(flag == 0){
ConfigCMDVo configCMDVo = new ConfigCMDVo();
configCMDVo.setAction("sleep");
configCMDVo.setT(System.currentTimeMillis()/1000l);
ConfigData = new Gson().toJson(configCMDVo);
gcconfig = new GWConfigWorker(Type,SN,ConfigData, false);
}else if(flag == 2){
ConfigCMDVo configCMDVo = new ConfigCMDVo();
configCMDVo.setAction("end");
configCMDVo.setT(System.currentTimeMillis()/1000l);
ConfigData = new Gson().toJson(configCMDVo);
gcconfig = new GWConfigWorker(Type,SN,ConfigData, true);
}else if(flag == 1){
ConfigData = configService.getConfig(SN,Type).getMessage();
gcconfig = new GWConfigWorker(Type,SN,ConfigData, true);
}
// String ConfigData ="{\"action\":\"config\"}";
gcconfig.SetMqttConfig(mqttconfig.getUrl(),mqttconfig.getPort(), gcconfig.SetMqttConfig(mqttconfig.getUrl(),mqttconfig.getPort(),
mqttconfig.getUsername(), mqttconfig.getPassword(),mqttconfig.getQos(), mqttconfig.getUsername(), mqttconfig.getPassword(),mqttconfig.getQos(),
mqttconfig.getCacrt(),mqttconfig.getClientkey(), mqttconfig.getClientcrt(),mqttconfig.getClientpwd()); mqttconfig.getCacrt(),mqttconfig.getClientkey(), mqttconfig.getClientcrt(),mqttconfig.getClientpwd());
result = configthreadPool.submit(gcconfig); result = configthreadPool.submit(gcconfig);
while (result.isDone()) // while (result.isDone())
{ // {
String respcmd = result.get(); // String respcmd = result.get();
} // }
// futureMap.put(timestamp.toString(),result);
// futureMap.put(timestamp.toString(),result);
} catch (JsonSyntaxException e) { } catch (JsonSyntaxException e) {
e.printStackTrace();
System.out.println("mqttAsyncClient: message " + Message + " received syntax error."); System.out.println("mqttAsyncClient: message " + Message + " received syntax error.");
} catch (IllegalStateException e) { } catch (IllegalStateException e) {
e.printStackTrace();
System.out.println("mqttAsyncClient: " + e); System.out.println("mqttAsyncClient: " + e);
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
System.out.println(e.toString());
} }
} }
...@@ -149,4 +175,31 @@ public class MqttListener implements MqttCallback { ...@@ -149,4 +175,31 @@ public class MqttListener implements MqttCallback {
public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) { public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
} }
//checkIn数据解析,true即发送休眠信息;false发送config信息
public Integer parseData(String message,String SN,String Type){
CheckInVo checkInVo = new Gson().fromJson(message,CheckInVo.class);
if(checkInVo.getDevList().size() == 0){
return 1;//重发
}
//有设备信息
ConfigVo configVo = configService.getConfig(SN,Type);
ConfigCMDVo configCMDVo = new Gson().fromJson(configVo.getMessage(),ConfigCMDVo.class);
if(configVo.getUntie()){
//解绑状态
return 2;//解绑
}
//判断两者的devList是否一致
if (configCMDVo.getDevList().containsAll(checkInVo.getDevList())
&& checkInVo.getDevList().containsAll(configCMDVo.getDevList())
&& checkInVo.getGprsPeriod().equals(configCMDVo.getGprsPeriod())
&& checkInVo.getGpsPeriod().equals(configCMDVo.getGpsPeriod())
&& checkInVo.getMode().equals(configCMDVo.getMode())) {
//一致
return 0;//发送休眠信息
} else {
//不一致
return 1;//重发
}
}
} }
package com.example.tdl.service;
import com.example.tdl.domain.vo.AddAlarmLogVo;
import com.example.tdl.domain.vo.AlarmLogVo;
import com.example.tdl.mapper.AlarmLogMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class AlarmLogServcie {
@Autowired
private AlarmLogMapper alarmLogMapper;
public List<AlarmLogVo> getAll(){
return alarmLogMapper.getAll();
}
public List<AlarmLogVo> getAlarmLog(String time){
return alarmLogMapper.getAlarmLog(time);
}
public int addAlarmLog(AddAlarmLogVo addAlarmLogVo){
return alarmLogMapper.addAlarmLog(addAlarmLogVo);
}
}
package com.example.tdl.service;
import com.example.tdl.domain.vo.ConfigVo;
import com.example.tdl.mapper.ConfigMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class ConfigService {
@Autowired
private ConfigMapper configMapper;
//绑定getway和tdl
public int addConfig(ConfigVo configVo){
return configMapper.addConfig(configVo);
}
//获取绑定的数据信息
public ConfigVo getConfig(String gSN,String gType){
return configMapper.getConfig(gSN,gType);
}
//绑定成功
public int bindiSuccess(String gSN,String gType,Integer resp){
return configMapper.bindiSuccess(gSN,gType,resp);
}
//解绑getWay和tdl
public int updateConfig(String gSN,String gType,Boolean untie ){
return configMapper.updateConfig(gSN,gType,untie);
}
//解绑成功
public int delConfig(String gSN,String gType){
return configMapper.delConfig(gSN,gType);
}
}
package com.example.tdl.service;
import com.example.tdl.config.Influxdbconfig;
import org.influxdb.InfluxDB;
import org.influxdb.dto.BatchPoints;
import org.influxdb.dto.Point;
import org.influxdb.dto.Query;
import org.influxdb.dto.QueryResult;
import org.influxdb.dto.QueryResult.Result;
import org.influxdb.dto.QueryResult.Series;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
@Service("influxdbService")
public class InfluxDBService {
@Autowired
Influxdbconfig influxdbconfig;
@Autowired
private InfluxDB influxDB;
public final static String DEFAULT_DATABASE = "original";
public final static String DEFAULT_POLICY = "witium_policy";
private final static String DEFAULT_DURATION = "0d";
private final static String DEFAULT_SHARD_DURATION = "90d";
private String mPolicyName = DEFAULT_POLICY;
private String mDBName = DEFAULT_DATABASE;
public void connectDatabase(String dbname) {
if(!dbname.isEmpty() && dbname != null)
{
useDatabase(dbname);
useRetentionPolicy(mPolicyName);
}
}
/* Create the database if it is not exist. */
private void createDatabase(String database) {
if (database != null && !database.isEmpty()) {
if (!influxDB.databaseExists(database)) {
influxDB.createDatabase(database);
}
}
}
public void useDatabase(String database) {
if (!influxDB.databaseExists(database)) {
createDatabase(database);
}
influxdbconfig.setDatabase(database);
mDBName = database;
}
public List<String> showRetentionPolicys() {
String command = String.format("SHOW RETENTION POLICIES ON \"%s\"",
mDBName);
QueryResult results = this.query(command);
List<String> policys = new ArrayList<String>();
for (Result result : results.getResults()) {
List<Series> series = result.getSeries();
for (Series serie : series) {
List<List<Object>> values = serie.getValues();
for (List<Object> value : values) {
policys.add(0, (String)value.get(0));
}
}
}
return policys;
}
/* Judge whether policy is exist. */
public boolean isRetentionPolicyExist(String policyname) {
boolean isExist = false;
List<String> policys;
policys = showRetentionPolicys();
for (String policy : policys) {
if (policy.equals(policyname)) {
isExist = true;
break;
}
}
return isExist;
}
public void useRetentionPolicy(String policy) {
mPolicyName = policy;
if (!isRetentionPolicyExist(policy)) {
createRetentionPolicy(DEFAULT_DURATION, DEFAULT_SHARD_DURATION, 1, true);
}
}
/**
* 创建保存策略 <br/>
* CREATE RETENTION POLICY "default" ON "database" DURATION 30d REPLICATION 1 DEFAULT
*
* @param duration 存放时间
* @param replicationNum 备份数量
*/
public void createRetentionPolicy(String duration, Integer replicationNum, Boolean isDefault) {
if (mPolicyName != null && !mPolicyName.isEmpty()
&& mDBName != null && !mDBName.isEmpty()) {
String command = String.format("CREATE RETENTION POLICY \"%s\" ON \"%s\" DURATION %s REPLICATION %s %s",
mPolicyName, mDBName, duration, replicationNum, isDefault ? "DEFAULT" : "");
this.query(command);
}
}
/**
* 创建保存策略 <br/>
* CREATE RETENTION POLICY "default" ON "database" DURATION 30d SHARD DURATION %s REPLICATION 1 DEFAULT
*
* @param duration 存放时间
* @param shardGroupDuration 存放快速读取组时间
* @param replicationNum 备份数量
*/
public void createRetentionPolicy(String duration, String shardGroupDuration, Integer replicationNum,
Boolean isDefault) {
if (mPolicyName != null && !mPolicyName.isEmpty()
&& mDBName != null && !mDBName.isEmpty()) {
String command = String.format("CREATE RETENTION POLICY \"%s\" ON \"%s\" DURATION %s SHARD DURATION %s REPLICATION %s %s",
mPolicyName, mDBName, duration, shardGroupDuration, replicationNum, isDefault ? "DEFAULT" : "");
this.query(command);
}
}
/**
* 插入数据
*
* @param measurement a Point in a fluent manner
* @param tagsToAdd the Map of tags to add
* @param fields the fields to add
*/
public void insert(String measurement, Long timestamp, Map<String, String> tagsToAdd, Map<String, Object> fields) {
if (measurement != null && !measurement.isEmpty()
&& tagsToAdd != null && !tagsToAdd.isEmpty()
&& fields != null && !fields.isEmpty()) {
Point.Builder builder = Point.measurement(measurement)
.time(timestamp, TimeUnit.MILLISECONDS)
.tag(tagsToAdd)
.fields(fields);
try {
influxDB.write(mDBName, mPolicyName, builder.build());
} catch (RuntimeException e) {
// TODO: handle exception
e.printStackTrace();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
public void insertBatchWithMultiTags(String dbname, String measurement, Long[] timestamp,
List<Map<String, String>> tagsToAdd, List<Map<String, Object>> fields)
{
if (measurement != null && !measurement.isEmpty()
&& tagsToAdd != null && !tagsToAdd.isEmpty()
&& fields != null && !fields.isEmpty()) {
BatchPoints batchPoints = BatchPoints.database(dbname)
.retentionPolicy(mPolicyName)
.consistency(InfluxDB.ConsistencyLevel.ALL)
.build();
for (int i = 0; i < tagsToAdd.size(); i++)
{
Point pointdata = Point.measurement(measurement)
.time(timestamp[i], TimeUnit.MILLISECONDS)
.tag(tagsToAdd.get(i))
.fields(fields.get(i))
.build();
batchPoints.point(pointdata);
}
try {
influxDB.write(batchPoints);
} catch (RuntimeException e) {
// TODO: handle exception
e.printStackTrace();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
public void insertBatchWithSameTags(String dbname, String measurement, Long[] timestamp,
Map<String, String> tagsToAdd, List<Map<String, Object>> fields)
{
if (measurement != null && !measurement.isEmpty()
&& tagsToAdd != null && !tagsToAdd.isEmpty()
&& fields != null && !fields.isEmpty()) {
BatchPoints batchPoints = BatchPoints.database(dbname)
.retentionPolicy(mPolicyName)
.consistency(InfluxDB.ConsistencyLevel.ALL)
.build();
for (int i = 0; i < fields.size(); i++)
{
Point pointdata = Point.measurement(measurement)
.time(timestamp[i], TimeUnit.MILLISECONDS)
.tag(tagsToAdd)
.fields(fields.get(i))
.build();
if(pointdata != null)
{
batchPoints.point(pointdata);
}
}
try {
influxDB.write(batchPoints);
} catch (RuntimeException e) {
// TODO: handle exception
e.printStackTrace();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
/**
* 查询数据
*
* @param command
* @return QueryResult
*/
public QueryResult query(String command) {
return influxDB.query(new Query(command, mDBName));
}
}
...@@ -21,6 +21,10 @@ public class RouteService { ...@@ -21,6 +21,10 @@ public class RouteService {
return routeMapper.getAll(); return routeMapper.getAll();
} }
public List<ResultRouteVo> getAllRoute(String time){
return routeMapper.getAllRoute(time);
}
public List<ResultRouteVo> getRouteByTerm(RouteTermVo routeTermVo){ public List<ResultRouteVo> getRouteByTerm(RouteTermVo routeTermVo){
return routeMapper.getRouteByTerm(routeTermVo); return routeMapper.getRouteByTerm(routeTermVo);
} }
......
package com.example.tdl.service;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.*;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import java.io.Serializable;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
@Service
public class TokenRedisService {
private static Logger logger = Logger.getLogger(TokenRedisService.class);
@Autowired
private RedisTemplate tokenRedisTemplate;
/**
* 批量删除对应的value
*
* @param keys
*/
public void remove(final String... keys) {
for (String key : keys) {
remove(key);
}
}
/**
* 哈希 添加
*
* @param key
* @param hashKey
* @param value
*/
public void hmSet(String key, Object hashKey, Object value) {
HashOperations<String, Object, Object> hash = tokenRedisTemplate.opsForHash();
hash.put(key, hashKey, value);
}
/**
* 哈希获取数据
*
* @param key
* @param hashKey
* @return
*/
public Object hmGet(String key,Object hashKey) {
try {
HashOperations<Serializable,Object,Object> hash = tokenRedisTemplate.opsForHash();
return hash.get(key,hashKey);
}catch (Exception e){
e.printStackTrace();
return null;
}
}
/**
* 列表添加
*
* @param k
* @param v
*/
public void Push(String k, Object v) {
ListOperations<String, Object> list = tokenRedisTemplate.opsForList();
list.rightPush(k, v);
}
/**
* 列表获取
*
* @param k
* @param l
* @param l1
* @return
*/
public List<Object> Range(String k, long l, long l1) {
ListOperations<String, Object> list = tokenRedisTemplate.opsForList();
return list.range(k, l, l1);
}
public Set<Object> rangeByScore(String key, double scoure, double scoure1) {
ZSetOperations<String, Object> zset = tokenRedisTemplate.opsForZSet();
return zset.rangeByScore(key, scoure, scoure1);
}
//删除hash中的key
public void delHashKey(String key, String Hashkey) {
HashOperations<Serializable, Object, Object> hash = tokenRedisTemplate.opsForHash();
hash.delete(key,Hashkey);
}
public Object getHashKeys(String key) {
String ret="{error}";
Object result = ret;
try {
HashOperations<Serializable, Object, Object> hash = tokenRedisTemplate.opsForHash();
result = hash.keys(key);
return result;
}catch (Exception e){
e.printStackTrace();
}
return result;
}
public String get(final String key) {
String result = null;
try {
ValueOperations<Serializable, String> operations = tokenRedisTemplate.opsForValue();
result = operations.get(key);
return result;
}catch (Exception e){
e.printStackTrace();
}
return result;
}
public void expire(final String key,final Integer seconds) {
try {
tokenRedisTemplate.expire(key,seconds, TimeUnit.SECONDS);
}catch (Exception e){
e.printStackTrace();
}
}
public void set(final String key,final String value,final Integer seconds){
try{
ValueOperations<Serializable, String> operations = tokenRedisTemplate.opsForValue();
operations.set(key,value,seconds,TimeUnit.SECONDS);
}catch (Exception e){
e.printStackTrace();
logger.info(e.toString());
}
}
public void delKey(final String... key){
if(key!=null && key.length > 0){
if(key.length == 1){
tokenRedisTemplate.delete(key[0]);
}else{
tokenRedisTemplate.delete(CollectionUtils.arrayToList(key));
}
}
}
}
...@@ -2,6 +2,7 @@ package com.example.tdl.service; ...@@ -2,6 +2,7 @@ package com.example.tdl.service;
import com.example.tdl.domain.vo.*; import com.example.tdl.domain.vo.*;
import com.example.tdl.mapper.UserMapper; import com.example.tdl.mapper.UserMapper;
import com.example.tdl.service.redis.TokenRedisService;
import com.google.gson.Gson; import com.google.gson.Gson;
import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.codec.digest.DigestUtils;
......
package com.example.tdl.service.redis;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.CollectionUtils;
import java.io.Serializable;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
public class RedisService {
final static Logger logger = LoggerFactory.getLogger(RedisService.class);
protected RedisTemplate redisTemplate;
public RedisService(RedisTemplate redisTemplate) {
this.redisTemplate = redisTemplate;
}
@SuppressWarnings({ "unchecked", "rawtypes" })
public boolean setHash(String key, Map map, long expireTime) {
boolean result = false;
try {
HashOperations<Serializable, Object, Object> hash = redisTemplate.opsForHash();
hash.putAll(key, map);
redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
result = true;
} catch (Exception e) {
e.printStackTrace();
logger.error("redis插入hash值发生错误", this);
}
return result;
}
public boolean setHash(String key, String hashKey, String value, long expireTime) {
boolean result = false;
try {
HashOperations<Serializable, Object, Object> hash = redisTemplate.opsForHash();
hash.put(key, hashKey, value);
redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
result = true;
} catch (Exception e) {
e.printStackTrace();
logger.error("redis插入hash值发生错误", this);
}
return result;
}
public boolean setHashs(String key, Map<? extends String, ? extends Object> map, long expireTime) {
boolean result = false;
try {
HashOperations<Serializable, Object, Object> hash = redisTemplate.opsForHash();
hash.putAll(key, map);
redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
public Object getHash(String key, Object mapKey) {
Object result = null;
try {
HashOperations<Serializable, Object, Object> hash = redisTemplate.opsForHash();
result = hash.get(key, mapKey);
}catch (Exception e){
e.printStackTrace();
logger.error("redis获取hash值发生错误", this);
}
return result;
}
public Object getHashKeys(String key) {
Object result = null;
try {
HashOperations<Serializable, Object, Object> hash = redisTemplate.opsForHash();
result = hash.keys(key);
} catch (Exception e) {
e.printStackTrace();
logger.error("redis获取hash 所有key发生错误", this);
}
return result;
}
public Map<Object, Object> getHashAll(String key) {
Map<Object, Object> result = null;
try {
HashOperations<Serializable, Object, Object> hash = redisTemplate.opsForHash();
result = hash.entries(key);
} catch (Exception e) {
e.printStackTrace();
logger.error("redis获取hash 所有key value发生错误", this);
}
return result;
}
public boolean hasHashKey(String key, String Hashkey) {
boolean result = false;
try {
HashOperations<Serializable, Object, Object> hash = redisTemplate.opsForHash();
result = hash.hasKey(key, Hashkey);
}catch (Exception e){
e.printStackTrace();
logger.error("判断key值是否存在", this);
}
return result;
}
public long delHashKey(String key, String Hashkey) {
long result = 0;
try {
HashOperations<Serializable, Object, Object> hash = redisTemplate.opsForHash();
result = hash.delete(key, Hashkey);
}catch (Exception e){
e.printStackTrace();
logger.error("删除指定key值", this);
}
return result;
}
/**
* 获取此数据库所有的Keys表
* @return
*/
public Object getAllKeys() {
Object ret = null;
try {
ret = redisTemplate.keys("*");
} catch (Exception e) {
e.printStackTrace();
}
return ret;
}
/**
* 批量删除对应的value
*
* @param keys
*/
public void remove(final String... keys) {
for (String key : keys) {
remove(key);
}
}
/**
* 批量删除key
*
* @param pattern
*/
public void removePattern(final String pattern) {
Set<Serializable> keys = redisTemplate.keys(pattern);
if (keys.size() > 0)
redisTemplate.delete(keys);
}
/**
* 删除对应的value
*
* @param key
*/
public void remove(final String key) {
if (exists(key)) {
redisTemplate.delete(key);
}
}
/**
* 判断缓存中是否有对应的value
*
* @param key
* @return
*/
public boolean exists(final String key) {
return redisTemplate.hasKey(key);
}
/**
* 读取缓存
*
* @param key
* @return
*/
public String get(final String key) {
String result = null;
try {
ValueOperations<Serializable, String> operations = redisTemplate.opsForValue();
result = operations.get(key);
return result;
}catch (Exception e){
e.printStackTrace();
}
return result;
}
/**
* 写入缓存
*
* @param key
* @param value
* @return
*/
public boolean set(final String key, Object value) {
boolean result = false;
try {
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
operations.set(key, value);
result = true;
} catch (Exception e) {
e.printStackTrace();
logger.error("redis插入String失败", this);
}
return result;
}
/**
* 写入缓存
*
* @param key
* @param value
* @return
*/
public boolean set(final String key, Object value, long expireTime) {
boolean result = false;
try {
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
operations.set(key, value);
//logger.info("[key:" + key + "],[value:" + value + "]");
redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
result = true;
} catch (Exception e) {
e.printStackTrace();
logger.error("redis插入String失败", this);
}
return result;
}
/**
* 更新过期时间
*
* @param key
* @return
*/
public boolean refeshTimeOut(String key, long expireTime) {
boolean f = false;
try {
redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
f = true;
} catch (Exception e) {
e.printStackTrace();
logger.error("redis更新过期时间失败", this);
}
return f;
}
//删除key
public void delKey(final String... key){
if(key!=null && key.length > 0){
if(key.length == 1){
redisTemplate.delete(key[0]);
}else{
redisTemplate.delete(CollectionUtils.arrayToList(key));
}
}
}
}
package com.example.tdl.service.redis;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
@Service
public class TokenRedisService extends RedisService {
@SuppressWarnings({ "unchecked", "rawtypes" })
@Autowired
public TokenRedisService(RedisTemplate tokenRedisTemplate) {
super(tokenRedisTemplate);
}
}
...@@ -6,22 +6,21 @@ import com.example.tdl.domain.dto.CommFeedback; ...@@ -6,22 +6,21 @@ import com.example.tdl.domain.dto.CommFeedback;
import com.example.tdl.domain.vo.AddAlarmVo; import com.example.tdl.domain.vo.AddAlarmVo;
import com.example.tdl.domain.vo.DelAlarmVo; import com.example.tdl.domain.vo.DelAlarmVo;
import com.example.tdl.domain.vo.UpdateAlarmVo; import com.example.tdl.domain.vo.UpdateAlarmVo;
import com.example.tdl.domain.vo.UserVo;
import com.example.tdl.service.AlarmService; import com.example.tdl.service.AlarmService;
import com.example.tdl.service.TokenRedisService;
import com.example.tdl.service.WarehouseService; import com.example.tdl.service.WarehouseService;
import com.example.tdl.service.redis.TokenRedisService;
import com.google.gson.Gson; import com.google.gson.Gson;
import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
@RestController @RestController
@RequestMapping("/alarm") @RequestMapping("/alarm")
......
package com.example.tdl.web;
import com.example.tdl.domain.dto.CommFeedback;
import com.example.tdl.domain.vo.AddAlarmLogVo;
import com.example.tdl.service.AlarmLogServcie;
import com.google.gson.Gson;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/alarmLog")
public class AlarmLogController {
private Logger logger= LoggerFactory.getLogger(AlarmLogController.class);
Gson gson= new Gson();
CommFeedback fb=new CommFeedback();
@Autowired
private AlarmLogServcie alarmLogServcie;
//获取所有的报警数据
@GetMapping("/getAll")
@ApiImplicitParams({
@ApiImplicitParam(paramType="header", name = "Account_token", value = "token", required = true, dataType = "String"),
})
public Object getAll(){
return alarmLogServcie.getAll();
}
//新增报警消息
@PostMapping("/addAlarmLog")
@ApiImplicitParams({
@ApiImplicitParam(paramType="header", name = "Account_token", value = "token", required = true, dataType = "String"),
})
public Object addAlarmLog(@RequestBody AddAlarmLogVo addAlarmLogVo){
if(StringUtils.isEmpty(addAlarmLogVo.getRouteNumber())){
fb.setCode(0);
fb.setMessage("路由编号不能为空");
return gson.toJson(fb);
}
if(StringUtils.isEmpty(addAlarmLogVo.getRouteName())){
fb.setCode(0);
fb.setMessage("路由名称不能为空");
return gson.toJson(fb);
}
if(StringUtils.isEmpty(addAlarmLogVo.getDescription())){
fb.setCode(0);
fb.setMessage("报警描述不能为空");
return gson.toJson(fb);
}
if(addAlarmLogVo.getData() == null){
fb.setCode(0);
fb.setMessage("报警数据不能为空");
return gson.toJson(fb);
}
if(addAlarmLogVo.getAlarmTime() == null){
fb.setCode(0);
fb.setMessage("报警时间不能为空");
return gson.toJson(fb);
}
//获取报警的线路信息
int i= alarmLogServcie.addAlarmLog(addAlarmLogVo);
if(i == 0){
fb.setCode(0);
fb.setMessage("添加成功");
}else{
fb.setCode(0);
fb.setMessage("添加失败");
}
return gson.toJson(fb);
}
}
package com.example.tdl.web;
import com.example.tdl.domain.dto.CommFeedback;
import com.example.tdl.service.GatewayService;
import com.example.tdl.service.InfluxDBService;
import com.example.tdl.service.redis.RedisService;
import com.google.gson.Gson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class DataController {
private Logger logger = LoggerFactory.getLogger(DataController.class);
Gson gson = new Gson();
CommFeedback fb = new CommFeedback();
@Autowired
private GatewayService gatewayService;
@Autowired
private RedisService redisService;
@Autowired
private InfluxDBService influxDBService;
}
...@@ -5,8 +5,6 @@ import com.example.tdl.domain.dto.CommFeedback; ...@@ -5,8 +5,6 @@ import com.example.tdl.domain.dto.CommFeedback;
import com.example.tdl.domain.vo.*; import com.example.tdl.domain.vo.*;
import com.example.tdl.service.GatewayService; import com.example.tdl.service.GatewayService;
import com.example.tdl.service.ModelService; import com.example.tdl.service.ModelService;
import com.example.tdl.service.RoleService;
import com.example.tdl.service.TokenRedisService;
import com.google.gson.Gson; import com.google.gson.Gson;
import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiImplicitParams;
...@@ -20,7 +18,6 @@ import org.springframework.web.bind.annotation.RequestMapping; ...@@ -20,7 +18,6 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
......
package com.example.tdl.web;
import com.example.tdl.domain.dto.CommFeedback;
import com.example.tdl.domain.vo.AlarmLogVo;
import com.example.tdl.domain.vo.HomePageDataVo;
import com.example.tdl.domain.vo.ResultRouteVo;
import com.example.tdl.domain.vo.TermVo;
import com.example.tdl.service.AlarmLogServcie;
import com.example.tdl.service.RouteService;
import com.google.gson.Gson;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/homePage")
public class HomePageController {
private Logger logger = LoggerFactory.getLogger(HomePageController.class);
Gson gson = new Gson();
CommFeedback fb = new CommFeedback();
@Autowired
private RouteService routeService;
@Autowired
private AlarmLogServcie alarmLogServcie;
//获取当天所有的设备数据
@ApiOperation(value = "获取所有的运输数据",notes = "获取运输设备数据:" +
"sum:总数量" +
"onRoute:在途数量" +
"complted:已完成数量" +
"alarmed: 报警数量" +
"routeVoList: " +
"routeNumber:路由编号(R+TyyyyMMdd+运输方式+四位随机数)"+
"routeName:路由名称(出发地-启运地)"+
"abbreviation:名称缩写(出发地-启运地-运输方式)"+
"startLongitude:启运经度"+
"startLatitude:启运纬度"+
"startCounrty:启运国"+
"startProvince:启运省"+
"startCity:启运市"+
"startAddress:启运地址"+
"endLongitude:目的经度"+
"endLatitude:目的纬度"+
"endCounrty:目的国"+
"endProvince:目的省"+
"endCity:目的市"+
"endAddress:目的地址"+
"transport:运输方式(T铁路,G汽运,H海运,K空运,D快递)"+
"transportRemark:运输方式备注"+
"remark:备注" +
"alarmLogVoList :"+
"routeName:线路名称"+
"description:报警描述" +
"data:数据"+
"alarmTime:报警时间")
@GetMapping("/getAll")
@ApiImplicitParams({
@ApiImplicitParam(paramType="header", name = "Account_token", value = "token", required = true, dataType = "String"),
})
public Object getAll(){
HomePageDataVo dataVo = new HomePageDataVo();
//获取所有的路线
List<ResultRouteVo> routeVos = routeService.getAll();//所有的路线
//List<ResultRouteVo> routeVoList = routeService.getAllRoute();//当天的数量
//获取所有的报警
List<AlarmLogVo> alarmLogVos = alarmLogServcie.getAll();
// 获取所有的路线数量
dataVo.setRouteVoList(routeVos);//路线列表
dataVo.setAlarmLogVoList(alarmLogVos);//报警列表
dataVo.setSum(routeVos.size());//总数量
dataVo.setOnRoute(0);//在途数量
dataVo.setComplted(0);//已完成数量
dataVo.setAlarmed(0);//报警数量
return gson.toJson(dataVo);
}
//根据条件获取路线数据(所有的)
@PostMapping("/getByTerm")
@ApiImplicitParams({
@ApiImplicitParam(paramType="header", name = "Account_token", value = "token", required = true, dataType = "String"),
})
public Object getByTerm(@RequestBody TermVo termVo){
HomePageDataVo dataVo = new HomePageDataVo();
List<ResultRouteVo> routeVos = routeService.getAll();//所有的路线
List<ResultRouteVo> routeVoList = routeService.getAllRoute(termVo.getTime());//根据条件获取数据
List<AlarmLogVo> alarmLogVos = alarmLogServcie.getAlarmLog(termVo.getTime());
dataVo.setRouteVoList(routeVos);//路线列表
dataVo.setAlarmLogVoList(alarmLogVos);//报警列表
dataVo.setSum(routeVos.size());//总数量
dataVo.setOnRoute(0);//在途数量
dataVo.setComplted(0);//已完成数量
dataVo.setAlarmed(0);//报警数量
return gson.toJson(dataVo);
}
}
...@@ -6,8 +6,8 @@ import com.example.tdl.domain.vo.UserRedisVo; ...@@ -6,8 +6,8 @@ import com.example.tdl.domain.vo.UserRedisVo;
import com.example.tdl.domain.vo.UserVo; import com.example.tdl.domain.vo.UserVo;
import com.example.tdl.entity.LoginLog; import com.example.tdl.entity.LoginLog;
import com.example.tdl.service.LoginLogService; import com.example.tdl.service.LoginLogService;
import com.example.tdl.service.TokenRedisService;
import com.example.tdl.service.UserService; import com.example.tdl.service.UserService;
import com.example.tdl.service.redis.TokenRedisService;
import com.example.tdl.util.CookieUtils; import com.example.tdl.util.CookieUtils;
import com.google.gson.Gson; import com.google.gson.Gson;
import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParam;
......
...@@ -3,15 +3,13 @@ package com.example.tdl.web; ...@@ -3,15 +3,13 @@ package com.example.tdl.web;
import com.example.tdl.domain.dto.CommFeedback; import com.example.tdl.domain.dto.CommFeedback;
import com.example.tdl.domain.vo.LoginLogTermVo; import com.example.tdl.domain.vo.LoginLogTermVo;
import com.example.tdl.domain.vo.UserVo;
import com.example.tdl.service.LoginLogService; import com.example.tdl.service.LoginLogService;
import com.example.tdl.service.TokenRedisService; import com.example.tdl.service.redis.TokenRedisService;
import com.google.gson.Gson; import com.google.gson.Gson;
import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
...@@ -20,8 +18,6 @@ import org.springframework.web.bind.annotation.RequestMapping; ...@@ -20,8 +18,6 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
@RestController @RestController
@RequestMapping("/loginLog") @RequestMapping("/loginLog")
public class LoginLogController { public class LoginLogController {
......
...@@ -2,15 +2,14 @@ package com.example.tdl.web; ...@@ -2,15 +2,14 @@ package com.example.tdl.web;
import com.example.tdl.domain.dto.CommFeedback; import com.example.tdl.domain.dto.CommFeedback;
import com.example.tdl.domain.vo.UserVo;
import com.example.tdl.service.PermissionService; import com.example.tdl.service.PermissionService;
import com.example.tdl.service.RoleService; import com.example.tdl.service.redis.TokenRedisService;
import com.example.tdl.service.TokenRedisService;
import com.google.gson.Gson; import com.google.gson.Gson;
import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
...@@ -18,7 +17,6 @@ import org.springframework.web.bind.annotation.RequestMapping; ...@@ -18,7 +17,6 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
@RestController @RestController
@RequestMapping("/permission") @RequestMapping("/permission")
......
...@@ -6,7 +6,7 @@ import com.example.tdl.domain.dto.CommFeedback; ...@@ -6,7 +6,7 @@ import com.example.tdl.domain.dto.CommFeedback;
import com.example.tdl.domain.vo.AddProbesModelVo; import com.example.tdl.domain.vo.AddProbesModelVo;
import com.example.tdl.domain.vo.UpdateProbesModelVo; import com.example.tdl.domain.vo.UpdateProbesModelVo;
import com.example.tdl.service.ProbesModelService; import com.example.tdl.service.ProbesModelService;
import com.example.tdl.service.TokenRedisService; import com.example.tdl.service.redis.TokenRedisService;
import com.google.gson.Gson; import com.google.gson.Gson;
import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiImplicitParams;
......
...@@ -2,26 +2,23 @@ package com.example.tdl.web; ...@@ -2,26 +2,23 @@ package com.example.tdl.web;
import com.example.tdl.domain.dto.CommFeedback; import com.example.tdl.domain.dto.CommFeedback;
import com.example.tdl.domain.vo.UserVo;
import com.example.tdl.service.RoleService; import com.example.tdl.service.RoleService;
import com.example.tdl.service.TokenRedisService; import com.example.tdl.service.redis.TokenRedisService;
import com.google.gson.Gson; import com.google.gson.Gson;
import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
@RestController @RestController
@RequestMapping("/role") @RequestMapping("/role")
......
...@@ -3,14 +3,14 @@ package com.example.tdl.web; ...@@ -3,14 +3,14 @@ package com.example.tdl.web;
import com.example.tdl.domain.dto.CommFeedback; import com.example.tdl.domain.dto.CommFeedback;
import com.example.tdl.domain.vo.UserRedisVo; import com.example.tdl.domain.vo.UserRedisVo;
import com.example.tdl.domain.vo.UserVo;
import com.example.tdl.service.RoleHasPermissionService; import com.example.tdl.service.RoleHasPermissionService;
import com.example.tdl.service.TokenRedisService;
import com.example.tdl.service.redis.TokenRedisService;
import com.google.gson.Gson; import com.google.gson.Gson;
import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
......
...@@ -9,7 +9,8 @@ import com.example.tdl.domain.vo.RouteTermVo; ...@@ -9,7 +9,8 @@ import com.example.tdl.domain.vo.RouteTermVo;
import com.example.tdl.domain.vo.UpdateRouteVo; import com.example.tdl.domain.vo.UpdateRouteVo;
import com.example.tdl.entity.Route; import com.example.tdl.entity.Route;
import com.example.tdl.service.RouteService; import com.example.tdl.service.RouteService;
import com.example.tdl.service.TokenRedisService;
import com.example.tdl.service.redis.TokenRedisService;
import com.google.gson.Gson; import com.google.gson.Gson;
import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiImplicitParams;
......
...@@ -8,7 +8,7 @@ import com.example.tdl.domain.vo.*; ...@@ -8,7 +8,7 @@ import com.example.tdl.domain.vo.*;
import com.example.tdl.entity.Route; import com.example.tdl.entity.Route;
import com.example.tdl.service.RouteService; import com.example.tdl.service.RouteService;
import com.example.tdl.service.TDLDeviceService; import com.example.tdl.service.TDLDeviceService;
import com.example.tdl.service.TokenRedisService; import com.example.tdl.service.redis.TokenRedisService;
import com.google.gson.Gson; import com.google.gson.Gson;
import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiImplicitParams;
......
...@@ -5,8 +5,9 @@ import com.alibaba.fastjson.JSONObject; ...@@ -5,8 +5,9 @@ import com.alibaba.fastjson.JSONObject;
import com.example.tdl.domain.dto.CommFeedback; import com.example.tdl.domain.dto.CommFeedback;
import com.example.tdl.domain.vo.AddTopicModelVo; import com.example.tdl.domain.vo.AddTopicModelVo;
import com.example.tdl.domain.vo.UpdateTopicModelVo; import com.example.tdl.domain.vo.UpdateTopicModelVo;
import com.example.tdl.service.TokenRedisService;
import com.example.tdl.service.TopicModelService; import com.example.tdl.service.TopicModelService;
import com.example.tdl.service.redis.TokenRedisService;
import com.google.gson.Gson; import com.google.gson.Gson;
import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiImplicitParams;
......
...@@ -7,9 +7,10 @@ import com.example.tdl.domain.dto.CommFeedback; ...@@ -7,9 +7,10 @@ import com.example.tdl.domain.dto.CommFeedback;
import com.example.tdl.domain.vo.AddTopicModelInfoVo; import com.example.tdl.domain.vo.AddTopicModelInfoVo;
import com.example.tdl.domain.vo.DelTopicModelInfoVo; import com.example.tdl.domain.vo.DelTopicModelInfoVo;
import com.example.tdl.domain.vo.UpdateTopicModelInfoVo; import com.example.tdl.domain.vo.UpdateTopicModelInfoVo;
import com.example.tdl.service.TokenRedisService;
import com.example.tdl.service.TopicModelInfoService; import com.example.tdl.service.TopicModelInfoService;
import com.example.tdl.service.TopicModelService; import com.example.tdl.service.TopicModelService;
import com.example.tdl.service.redis.TokenRedisService;
import com.google.gson.Gson; import com.google.gson.Gson;
import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiImplicitParams;
......
...@@ -7,8 +7,9 @@ import com.example.tdl.domain.dto.CommFeedback; ...@@ -7,8 +7,9 @@ import com.example.tdl.domain.dto.CommFeedback;
import com.example.tdl.domain.vo.*; import com.example.tdl.domain.vo.*;
import com.example.tdl.service.RoleHasPermissionService; import com.example.tdl.service.RoleHasPermissionService;
import com.example.tdl.service.RoleService; import com.example.tdl.service.RoleService;
import com.example.tdl.service.TokenRedisService;
import com.example.tdl.service.UserService; import com.example.tdl.service.UserService;
import com.example.tdl.service.redis.TokenRedisService;
import com.google.gson.Gson; import com.google.gson.Gson;
import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiImplicitParams;
......
...@@ -7,8 +7,8 @@ import com.example.tdl.domain.dto.CommFeedback; ...@@ -7,8 +7,8 @@ import com.example.tdl.domain.dto.CommFeedback;
import com.example.tdl.domain.vo.*; import com.example.tdl.domain.vo.*;
import com.example.tdl.entity.Warehouse; import com.example.tdl.entity.Warehouse;
import com.example.tdl.service.RoleService; import com.example.tdl.service.RoleService;
import com.example.tdl.service.TokenRedisService;
import com.example.tdl.service.WarehouseService; import com.example.tdl.service.WarehouseService;
import com.example.tdl.service.redis.TokenRedisService;
import com.google.gson.Gson; import com.google.gson.Gson;
import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiImplicitParams;
......
...@@ -15,24 +15,23 @@ mybatis.config-location=classpath:mybatis-config.xml ...@@ -15,24 +15,23 @@ mybatis.config-location=classpath:mybatis-config.xml
# Redis服务器地址 # Redis服务器地址
spring.redis.host=127.0.0.1 tdl.redis.host=127.0.0.1
#spring.redis.host=120.27.235.39
# Redis数据库索引(默认为0) # Redis数据库索引(默认为0)
spring.redis.database=0 tdl.redis.index=0
# Redis服务器连接端口 # Redis服务器连接端口
spring.redis.port=6379 tdl.redis.port=6379
# Redis服务器连接密码(默认为空) # Redis服务器连接密码(默认为空)
spring.redis.password= tdl.redis.password=
# 连接池最大连接数(使用负值表示没有限制) # 连接池最大连接数(使用负值表示没有限制)
spring.redis.pool.max-active=8 tdl.redis.poolmaxactive=8
# 连接池最大阻塞等待时间(使用负值表示没有限制) # 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.pool.max-wait=-1 tdl.redis.poolmaxwait=-1
# 连接池中的最大空闲连接 # 连接池中的最大空闲连接
spring.redis.pool.max-idle=8 tdl.redis.poolmaxidle=8
# 连接池中的最小空闲连接 # 连接池中的最小空闲连接
spring.redis.pool.min-idle=0 tdl.redis.poolminidle=0
# 连接超时时间(毫秒) # 连接超时时间(毫秒)
spring.redis.timeout=0 tdl.redis.timeout=0
# Logging # Logging
......
<?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="com.example.tdl.mapper.AlarmLogMapper">
<!--获取所有的报警数据-->
<select id="getAll" resultType="com.example.tdl.domain.vo.AlarmLogVo">
select routeName,description,data,alarmTime from alarm_log order by alarmTime desc limit 10;
</select>
<!--根据条件获取报警数据-->
<select id="getAlarmLog" resultType="com.example.tdl.domain.vo.AlarmLogVo">
select routeName,description,data,alarmTime
from alarm_log
where DATE_SUB(CURDATE(), INTERVAL #{time,jdbcType=VARCHAR} DAY) &lt;= date(FROM_UNIXTIME(alarmTime/1000,'%Y-%m-%d %H:%i:%s'))
order by alarmTime desc limit 10;
</select>
<insert id="addAlarmLog" parameterType="com.example.tdl.domain.vo.AddAlarmLogVo">
insert into alarm_log
values(
null,
#{routeNumber,jdbcType=VARCHAR},
#{routeName,jdbcType=VARCHAR},
#{description,jdbcType=VARCHAR},
#{data,jdbcType=FLOAT},
#{alarmTime,jdbcType=INTEGER}
)
</insert>
</mapper>
\ 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="com.example.tdl.mapper.ConfigMapper">
<!--绑定getway和tdl-->
<insert id="addConfig" parameterType="com.example.tdl.domain.vo.ConfigVo">
insert into config
values(
null,
#{gSN,jdbcType=VARCHAR},
#{gType,jdbcType=VARCHAR},
#{message,jdbcType=VARCHAR},
#{flag,jdbcType=INTEGER},
#{resp,jdbcType=INTEGER},
#{state,jdbcType=INTEGER},
#{untie,jdbcType=INTEGER}
)
</insert>
<!--获取绑定消息-->
<select id="getConfig" parameterType="String" resultType="com.example.tdl.domain.vo.ConfigVo">
select gSN,gType,message,flag,resp,state,untie from config where gSN= #{gSN,jdbcType=VARCHAR} and gType=#{gType,jdbcType=VARCHAR} and state = 1;
</select>
<!-- 绑定回复-->
<update id="bindiSuccess" parameterType="String">
update config set resp=#{resp,jdbcTpye=INTEGER},flag=true
where gSN= #{gSN,jdbcType=VARCHAR}
and gType=#{gType,jdbcType=VARCHAR}
and state = 1;
</update>
<update id="updateConfig">
update config set untie=#{untie,jdbcTpye=INTEGER}
where gSN= #{gSN,jdbcType=VARCHAR}
and gType=#{gType,jdbcType=VARCHAR}
and state = 1;
</update>
<update id="delConfig" parameterType="String">
update config set state = 0 where gSN= #{gSN,jdbcType=VARCHAR} and gType=#{gType,jdbcType=VARCHAR} and state = 1;
</update>
</mapper>
\ No newline at end of file
...@@ -88,4 +88,11 @@ ...@@ -88,4 +88,11 @@
<select id="getByRouteNumber" resultType="java.lang.Integer" parameterType="String"> <select id="getByRouteNumber" resultType="java.lang.Integer" parameterType="String">
SELECT COUNT(routeNumber) FROM route WHERE routeNumber=#{routeNumber,jdbcType=VARCHAR} SELECT COUNT(routeNumber) FROM route WHERE routeNumber=#{routeNumber,jdbcType=VARCHAR}
</select> </select>
<select id="getAllRoute" resultType="com.example.tdl.domain.vo.ResultRouteVo">
SELECT routeNumber,routeName,abbreviation,startLongitude,startLatitude,startCountry,startProvince,startCity,startAddress,
endLongitude,endLatitude,endCountry,endProvince,endCity,endAddress,transport,transportRemark,remark FROM route
where DATE_SUB(CURDATE(), INTERVAL #{time,jdbcType=VARCHAR} DAY) &lt;= date(FROM_UNIXTIME(createTime/1000,'%Y-%m-%d %H:%i:%s'))
order by createTime desc limit 10;
</select>
</mapper> </mapper>
\ No newline at end of file
...@@ -41,6 +41,8 @@ ...@@ -41,6 +41,8 @@
<mapper resource="mapper/ProbesModelInfoMapper.xml"/> <mapper resource="mapper/ProbesModelInfoMapper.xml"/>
<mapper resource="mapper/ModelMapper.xml"/> <mapper resource="mapper/ModelMapper.xml"/>
<mapper resource="mapper/ModelInfoMapper.xml"/> <mapper resource="mapper/ModelInfoMapper.xml"/>
<mapper resource="mapper/AlarmLogMapper.xml"/>
<mapper resource="mapper/ConfigMapper.xml"/>
<mapper resource="mapper/ProbesMapper.xml"/> <mapper resource="mapper/ProbesMapper.xml"/>
<mapper resource="mapper/TopicMapper.xml"/> <mapper resource="mapper/TopicMapper.xml"/>
<mapper resource="mapper/TopicConfigMapper.xml"/> <mapper resource="mapper/TopicConfigMapper.xml"/>
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment