Commit 943c3a45 by levphon

新e盾gps基站消费服务

0 parents
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>glsx-ne-shield</artifactId>
<groupId>com.glsx</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<packaging>war</packaging>
<artifactId>ne-shield-kafkaconsumer-gpsbs</artifactId>
<dependencies>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-alliance</artifactId>
</dependency>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-mybatis</artifactId>
</dependency>
<!--kafak-->
<dependency>
<groupId>org.apache.kafka</groupId>
<artifactId>kafka_2.10</artifactId>
<version>0.8.1.1</version>
<exclusions>
<exclusion>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.16</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>glsx-ne-shield-api</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>glsx-ne-shield-common</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<!-- protocol buf -->
<dependency>
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-java</artifactId>
<version>2.6.1</version>
</dependency>
<!-- 新E盾标准接口-->
<dependency>
<groupId>com.glsx</groupId>
<artifactId>ne-shield-standard-interfaces-api</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-deploy-plugin</artifactId>
<configuration>
<skip>true</skip>
</configuration>
</plugin>
</plugins>
</build>
</project>
\ No newline at end of file
package cn.com.glsx;
import com.glsx.plat.context.EnableRestAdmin;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.ConfigurationPropertiesScan;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.EnableMBeanExport;
import org.springframework.jmx.support.RegistrationPolicy;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.annotation.PostConstruct;
import java.util.TimeZone;
import static java.time.ZoneId.of;
import static java.util.TimeZone.getTimeZone;
/**
* @author fengzhi
* @funtion 启动类
*/
@EnableRestAdmin
@EnableDiscoveryClient
@EnableFeignClients(basePackages = {"cn.com.glsx.*.api"})
@EnableTransactionManagement
@ConfigurationPropertiesScan
@EnableMBeanExport(registration = RegistrationPolicy.IGNORE_EXISTING)
@SpringBootApplication(scanBasePackages = {"cn.com.glsx.*"})
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@PostConstruct
void started() {
TimeZone.setDefault(getTimeZone(of("Asia/Shanghai")));
}
}
package cn.com.glsx.kafka.config;
import cn.com.glsx.kafka.constant.KafkaConstant;
import kafka.consumer.ConsumerConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.Properties;
/**
* @author fengzhi
* @time 2020/12/4
* @function kafka的公共配置
*/
@Configuration
@EnableConfigurationProperties(KafkaNacosProperties.class)
public class KafkaConfig {
@Autowired
private KafkaNacosProperties ddboxKafkaProperties;
@Autowired
private KafkaNacosGpsProperties gpsKafkaProperties;
@Bean(name = "ddboxConsumerConfig")
public ConsumerConfig ddboxConsumerConfig() {
return new ConsumerConfig(ddboxGetProperties());
}
@Bean(name = "gpsConsumerConfig")
public ConsumerConfig gpsConsumerConfig() {
return new ConsumerConfig(gpsGetProperties());
}
@Bean
public PropertiesFactoryBean ddboxConsumerProperties() {
PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
propertiesFactoryBean.setProperties(ddboxGetProperties());
return propertiesFactoryBean;
}
@Bean
public PropertiesFactoryBean consumerProperties() {
PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
propertiesFactoryBean.setProperties(gpsGetProperties());
return propertiesFactoryBean;
}
/**
* nacos属性封装Properties
*
* @return
*/
public Properties ddboxGetProperties() {
Properties properties = new Properties();
properties.setProperty(KafkaConstant.ZOOKEEPER_CONNECT, ddboxKafkaProperties.getConnect());
properties.setProperty(KafkaConstant.ZOOKEEPER_CONNECT_TIMEOUT, ddboxKafkaProperties.getConnectTimeout());
properties.setProperty(KafkaConstant.ZOOKEEPER_SESSION_TIMEOUT, ddboxKafkaProperties.getSessionTimeout());
properties.setProperty(KafkaConstant.GROUP_ID, ddboxKafkaProperties.getGroupID());
properties.setProperty(KafkaConstant.AUTO_COMMIT_INTERVAL, ddboxKafkaProperties.getAutoCommitInterval());
properties.setProperty(KafkaConstant.AUTO_OFFSET_RESET, ddboxKafkaProperties.getAutoOffsetReset());
properties.setProperty(KafkaConstant.REBLANCE_BACKOFF, ddboxKafkaProperties.getRebalanceBackoff());
properties.setProperty(KafkaConstant.REBLANCE_MAX_RETRIES, ddboxKafkaProperties.getRebalanceMaxRetries());
return properties;
}
/**
* nacos属性封装Properties
*
* @return
*/
public Properties gpsGetProperties() {
Properties properties = new Properties();
properties.setProperty(KafkaConstant.ZOOKEEPER_CONNECT, gpsKafkaProperties.getConnect());
properties.setProperty(KafkaConstant.ZOOKEEPER_CONNECT_TIMEOUT, gpsKafkaProperties.getConnectTimeout());
properties.setProperty(KafkaConstant.ZOOKEEPER_SESSION_TIMEOUT, gpsKafkaProperties.getSessionTimeout());
properties.setProperty(KafkaConstant.GROUP_ID, gpsKafkaProperties.getGroupID());
properties.setProperty(KafkaConstant.AUTO_COMMIT_INTERVAL, gpsKafkaProperties.getAutoCommitInterval());
properties.setProperty(KafkaConstant.AUTO_OFFSET_RESET, gpsKafkaProperties.getAutoOffsetReset());
properties.setProperty(KafkaConstant.REBLANCE_BACKOFF, gpsKafkaProperties.getRebalanceBackoff());
properties.setProperty(KafkaConstant.REBLANCE_MAX_RETRIES, gpsKafkaProperties.getRebalanceMaxRetries());
return properties;
}
}
package cn.com.glsx.kafka.config;
import cn.com.glsx.kafka.queue.consumer.BaseStationConsumer;
import cn.com.glsx.kafka.queue.consumer.GpsAndBsConsumer;
import cn.com.glsx.kafka.queue.consumer.GpsConsumer;
import kafka.consumer.ConsumerConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.annotation.Resource;
/**
* @author fengzhi
* @time 2020/12/9
* @function kafka的消费者配置
*/
@Configuration
public class KafkaConsumerConfig {
@Resource(name = "ddboxConsumerConfig")
private ConsumerConfig ddboxConsumerConfig;
@Resource(name = "gpsConsumerConfig")
private ConsumerConfig gpsConsumerConfig;
@Value("${consumer.nThreads}")
private Integer nThreads;
@Bean(initMethod = "init", destroyMethod = "destroy")
BaseStationConsumer baseStationConsumer(@Value("${mq.kafka.device.bs.topic}") String topic) {
BaseStationConsumer baseStationConsumer = new BaseStationConsumer();
baseStationConsumer.setnThreads(nThreads);
baseStationConsumer.setConsumerConfig(gpsConsumerConfig);
baseStationConsumer.setTopic(topic);
return baseStationConsumer;
}
@Bean(initMethod = "init", destroyMethod = "destroy")
GpsAndBsConsumer gpsAndBsConsumer(@Value("${mq.kafka.device.gpsandbs.topic}") String topic) {
GpsAndBsConsumer gpsAndBsConsumer = new GpsAndBsConsumer();
gpsAndBsConsumer.setnThreads(nThreads);
gpsAndBsConsumer.setConsumerConfig(gpsConsumerConfig);
gpsAndBsConsumer.setTopic(topic);
return gpsAndBsConsumer;
}
@Bean(initMethod = "init", destroyMethod = "destroy")
GpsConsumer channelRiskConsumer(@Value("${mq.kafka.device.gps.topic}") String topic) {
GpsConsumer gpsConsumer = new GpsConsumer();
gpsConsumer.setnThreads(nThreads);
gpsConsumer.setConsumerConfig(gpsConsumerConfig);
gpsConsumer.setTopic(topic);
return gpsConsumer;
}
}
package cn.com.glsx.kafka.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
/**
* @author fengzhi
* @time 2020/12/4
* @function kafka的nacos配置属性
*/
@Data
@ConfigurationProperties(prefix = "kafka.gps.config")
public class KafkaNacosGpsProperties {
//从nacos获取属性
private String connect;
private String connectTimeout;
private String sessionTimeout;
private String groupID;
private String autoCommitInterval;
private String autoOffsetReset;
private String rebalanceBackoff;
private String rebalanceMaxRetries;
}
package cn.com.glsx.kafka.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
/**
* @author fengzhi
* @time 2020/12/4
* @function kafka的nacos配置属性
*/
@Data
@ConfigurationProperties(prefix = "kafka.config")
public class KafkaNacosProperties {
//从nacos获取属性
private String connect;
private String connectTimeout;
private String sessionTimeout;
private String groupID;
private String autoCommitInterval;
private String autoOffsetReset;
private String rebalanceBackoff;
private String rebalanceMaxRetries;
}
package cn.com.glsx.kafka.config;
import kafka.javaapi.producer.Producer;
import kafka.producer.ProducerConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.Properties;
/**
* 设备上点中转kafak
*
* @author yll
*/
@Configuration
public class KafkaProducerConfig {
@Autowired
private MqConfig mqConfig;
@Bean("producer")
public Producer getProducer() {
return new Producer(new ProducerConfig(initProperties()));
}
private Properties initProperties() {
Properties properties = new Properties();
properties.setProperty("serializer.class", "kafka.serializer.DefaultEncoder");
properties.setProperty("key.serializer.class", "kafka.serializer.DefaultEncoder");
properties.setProperty("metadata.broker.list", mqConfig.getProducerServers());
properties.setProperty("producer.type", "async");
return properties;
}
}
package cn.com.glsx.kafka.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
/**
* @author wangxw
* @version 1.0.0
* @ClassName KafkaProductorConfig.java
* @description: ${description}
* @createTime 2020年10月20日 10:21:00
*/
@Data
@Configuration
@ConfigurationProperties("mq.kafka.gpsbs")
public class MqConfig {
/**
* kafka 生产者服务端地址
*/
private String producerServers;
/**
* 围栏规则数据发送 topic
*/
private String eFenceTopic;
}
package cn.com.glsx.kafka.constant;
/**
* 常量类
*
* @author Yanglinlong
* @date 2021/12/17 17:27
*/
public class Constants {
/**
* 有效轨迹
**/
public static final String GPS_IS = "A";
}
package cn.com.glsx.kafka.constant;
/**
* 全局变量
*/
public class KafkaConstant {
/***** kafka消费者配置属性 *****/
//zookeeper地址
public static final String ZOOKEEPER_CONNECT = "zookeeper.connect";
//连接超时
public static final String ZOOKEEPER_CONNECT_TIMEOUT = "zookeeper.connection.timeout.ms";
//session超时
public static final String ZOOKEEPER_SESSION_TIMEOUT = "zookeeper.session.timeout.ms";
//指定默认消费者group id
public static final String GROUP_ID = "group.id";
//如果'enable.auto.commit'为true,则消费者偏移自动提交给Kafka的频率(以毫秒为单位),默认值为5000
public static final String AUTO_COMMIT_INTERVAL = "auto.commit.interval.ms";
//smallest和largest才有效,如果smallest重新0开始读取,如果是largest从logfile的offset读取。一般情况下我们都是设置smallest
public static final String AUTO_OFFSET_RESET = "auto.offset.reset";
public static final String REBLANCE_BACKOFF = "rebalance.backoff.ms";
public static final String REBLANCE_MAX_RETRIES = "rebalance.max.retries";
}
This diff could not be displayed because it is too large.
package cn.com.glsx.kafka.queue.base;
import kafka.consumer.Consumer;
import kafka.consumer.ConsumerConfig;
import kafka.consumer.ConsumerIterator;
import kafka.consumer.KafkaStream;
import kafka.message.MessageAndMetadata;
import lombok.extern.slf4j.Slf4j;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* 消费基类
*/
@Slf4j
public abstract class MessageReceiver {
protected ConsumerConfig consumerConfig;
protected String topic;
protected Integer nThreads;
protected kafka.javaapi.consumer.ConsumerConnector connector;
protected Map<String, Integer> topicCountMap = new HashMap<>();
public abstract void processMessage(String topic, byte[] message) throws Exception;
protected void init() {
connector = Consumer.createJavaConsumerConnector(consumerConfig);
int threadCnt = 1;
if (null != nThreads && nThreads > 0) {
threadCnt = nThreads;
}
String[] topics = topic.split(",");
for (int i = 0; i < topics.length; i++) {
topicCountMap.put(topics[i], threadCnt);
}
Map<String, List<KafkaStream<byte[], byte[]>>> streams = connector.createMessageStreams(topicCountMap);
List<KafkaStream<byte[], byte[]>> list = new ArrayList<>();
for (String ss : topics) {
list.addAll(streams.get(ss));
}
final ExecutorService executor = Executors.newFixedThreadPool(threadCnt * topics.length);
for (final KafkaStream<byte[], byte[]> kafkaStream : list) {
executor.submit(() -> {
ConsumerIterator<byte[], byte[]> it = kafkaStream.iterator();
while (it.hasNext()) {
MessageAndMetadata<byte[], byte[]> item = it.next();
byte[] message = item.message();
try {
processMessage(item.topic(), message);
} catch (Exception e) {
e.printStackTrace();
log.error(e.getMessage());
}
}
});
}
Runtime.getRuntime().addShutdownHook(new Thread(executor::shutdown));
}
public void destroy() {
if (null != connector)
connector.shutdown();
}
public ConsumerConfig getConsumerConfig() {
return consumerConfig;
}
public void setConsumerConfig(ConsumerConfig consumerConfig) {
this.consumerConfig = consumerConfig;
}
public String getTopic() {
return topic;
}
public void setTopic(String topic) {
this.topic = topic.trim().replaceAll(" ", "");
}
public Integer getnThreads() {
return nThreads;
}
public void setnThreads(Integer nThreads) {
this.nThreads = nThreads;
}
}
package cn.com.glsx.kafka.queue.consumer;
import cn.com.glsx.kafka.protocol.kafkaSvr;
import cn.com.glsx.kafka.queue.base.MessageReceiver;
import cn.com.glsx.kafka.service.BloomFilterService;
import cn.com.glsx.kafka.service.TransitHandleService;
import cn.com.glsx.stdinterface.dto.DeviceLocationDto;
import cn.hutool.core.util.ObjectUtil;
import com.glsx.plat.redis.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.Calendar;
import java.util.Date;
/**
* 基站数据消费
* topic:gps_basestation
*
* @author yll
*/
@Slf4j
public class BaseStationConsumer extends MessageReceiver {
@Autowired
private RedisUtils redisUtils;
@Autowired
private BloomFilterService bloomFilterService;
@Autowired
private TransitHandleService transitHandleService;
@Override
public void processMessage(String topic, byte[] message) {
try {
kafkaSvr.BaseStReq baseStReq = kafkaSvr.BaseStReq.parseFrom(message);
// 判断是否是新E盾的设备号 如果不是则过滤掉
if (!bloomFilterService.isExits(baseStReq.getDevicesn())) {
return;
}
DeviceLocationDto deviceLocationDto = setBsData(baseStReq);
if (ObjectUtil.isNull(deviceLocationDto)) {
return;
}
// 写入redis 并且比较 gps和基站时间的先后
transitHandleService.handleGpsAndBsData(deviceLocationDto);
} catch (Exception e) {
e.printStackTrace();
}
}
private DeviceLocationDto setBsData(kafkaSvr.BaseStReq baseStReq) {
Date bsTime = new Date(baseStReq.getTime() * 1000L);
//当前时间如果大于今日,过滤
Calendar c = Calendar.getInstance();
Date now = new Date(c.get(Calendar.YEAR), c.get(Calendar.MONTH) + 1, c.get(Calendar.DAY_OF_MONTH));
if (bsTime.after(now)) {
return null;
}
// 封装数据
DeviceLocationDto deviceLocationDto = new DeviceLocationDto();
deviceLocationDto.setSn(baseStReq.getDevicesn());
deviceLocationDto.setLastBsTime(bsTime);
return deviceLocationDto;
}
}
package cn.com.glsx.kafka.queue.consumer;
import cn.com.glsx.kafka.constant.Constants;
import cn.com.glsx.kafka.protocol.kafkaSvr;
import cn.com.glsx.kafka.queue.base.MessageReceiver;
import cn.com.glsx.kafka.service.BloomFilterService;
import cn.com.glsx.kafka.service.TransitHandleService;
import cn.com.glsx.stdinterface.dto.DeviceLocationDto;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.glsx.plat.redis.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
/**
* GPS和基站数据消费
* topic : gps_gpsandbs
*
* @author yll
*/
@Slf4j
public class GpsAndBsConsumer extends MessageReceiver {
@Autowired
private RedisUtils redisUtils;
@Autowired
private BloomFilterService bloomFilterService;
@Autowired
private TransitHandleService transitHandleService;
@Override
public void processMessage(String topic, byte[] message) {
try {
kafkaSvr.GPSAndBSReq gpsAndBsReq = kafkaSvr.GPSAndBSReq.parseFrom(message);
// 判断是否是新E盾的设备号 如果不是则过滤掉
if (!bloomFilterService.isExits(gpsAndBsReq.getDevicesn())) {
return;
}
DeviceLocationDto deviceLocationDto = setGpsAndBsData(gpsAndBsReq);
if (ObjectUtil.isNull(deviceLocationDto)) {
return;
}
// 写入redis 并且比较 gps和基站时间的先后
transitHandleService.handleGpsAndBsData(deviceLocationDto);
} catch (Exception e) {
e.printStackTrace();
}
}
private DeviceLocationDto setGpsAndBsData(kafkaSvr.GPSAndBSReq gpsAndBsReq) {
kafkaSvr.GPSDATA gpsData = gpsAndBsReq.getGpsdata();
if (null == gpsData) {
return null;
}
Date time = new Date(gpsData.getTime() * 1000L);
//当前时间如果大于今日,过滤
Calendar c = Calendar.getInstance();
Date now = new Date(c.get(Calendar.YEAR), c.get(Calendar.MONTH) + 1, c.get(Calendar.DAY_OF_MONTH));
if (time.after(now)) {
return null;
}
DeviceLocationDto deviceLocationDto = new DeviceLocationDto();
deviceLocationDto.setSn(gpsAndBsReq.getDevicesn());
if (gpsData.getValid().equals(Constants.GPS_IS)) {
//gps有效定位 封装Gps数据
deviceLocationDto.setLastGpsTime(time);
}
List<kafkaSvr.BASESTDATA> bsDataList = gpsAndBsReq.getBstdataList();
if (CollectionUtil.isNotEmpty(bsDataList)) {
// 封装基站数据
deviceLocationDto.setLastBsTime(time);
}
// 如果最后GPS时间和最后基站时间都为 null,则过滤掉数据
if (ObjectUtil.isNull(deviceLocationDto.getLastGpsTime()) && ObjectUtil.isNull(deviceLocationDto.getLastBsTime())) {
return null;
}
return deviceLocationDto;
}
}
package cn.com.glsx.kafka.queue.consumer;
import cn.com.glsx.kafka.constant.Constants;
import cn.com.glsx.kafka.protocol.kafkaSvr;
import cn.com.glsx.kafka.queue.base.MessageReceiver;
import cn.com.glsx.kafka.service.BloomFilterService;
import cn.com.glsx.kafka.service.TransitHandleService;
import cn.com.glsx.stdinterface.dto.DeviceLocationDto;
import cn.hutool.core.util.ObjectUtil;
import com.glsx.plat.redis.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
/**
* GPS数据消费
* topic:gps_gpsdata
*/
@Slf4j
public class GpsConsumer extends MessageReceiver {
@Autowired
private RedisUtils redisUtils;
@Autowired
private BloomFilterService bloomFilterService;
@Autowired
private TransitHandleService transitHandleService;
@Override
public void processMessage(String topic, byte[] message) {
try {
kafkaSvr.TrackDataReq trackDataReq = kafkaSvr.TrackDataReq.parseFrom(message);
// 判断是否是新E盾的设备号 如果不是则过滤掉
if (!bloomFilterService.isExits(trackDataReq.getDevicesn())) {
return ;
}
DeviceLocationDto deviceLocationDto = setGpsData(trackDataReq);
if (ObjectUtil.isNull(deviceLocationDto)) {
return;
}
// 写入redis 并且比较 gps和基站时间的先后
transitHandleService.handleGpsAndBsData(deviceLocationDto);
} catch (Exception e) {
e.printStackTrace();
}
}
private DeviceLocationDto setGpsData(kafkaSvr.TrackDataReq trackDataReq) {
List<kafkaSvr.GPSDATA> gpsDataList = trackDataReq.getGpsdataList();
if (CollectionUtils.isNotEmpty(gpsDataList)) {
kafkaSvr.GPSDATA gpsData = gpsDataList.get(0);
if (null != gpsData) {
Date gpsTime = new Date(gpsData.getTime() * 1000L);
//当前时间如果大于今日,过滤
Calendar c = Calendar.getInstance();
Date now = new Date(c.get(Calendar.YEAR), c.get(Calendar.MONTH) + 1, c.get(Calendar.DAY_OF_MONTH));
if (gpsTime.after(now)) {
return null;
}
if (gpsData.getValid().equals(Constants.GPS_IS)) {
//定位状态有效 封装Gps数据
DeviceLocationDto deviceLocationDto = new DeviceLocationDto();
deviceLocationDto.setSn(trackDataReq.getDevicesn());
deviceLocationDto.setLastGpsTime(gpsTime);
return deviceLocationDto;
}
}
}
return null;
}
}
package cn.com.glsx.kafka.queue.remote;
import cn.com.glsx.stdinterface.api.DeviceLocationClient;
import cn.com.glsx.stdinterface.dto.DeviceLocationDto;
import cn.hutool.core.collection.CollectionUtil;
import com.glsx.plat.core.web.R;
import com.google.common.collect.Lists;
import com.google.gson.reflect.TypeToken;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Collection;
import java.util.List;
/**
* 设备上点 feign 处理服务层
*
* @author Yanglinlong
* @date 2021/12/17 15:32
*/
@Slf4j
@Service
public class RemoteDeviceLocationService {
@Autowired
private DeviceLocationClient deviceLocationClient;
/**
* 获取E盾中的所有设备号集合
*/
public List<String> getAllSnInNewEshield() {
R<List<String>> allSnsR = deviceLocationClient.getAllSnInNewEshield();
List<String> allSns = allSnsR.getDataList(new TypeToken<List<String>>() {
}.getType());
if (CollectionUtil.isEmpty(allSns)) {
allSns = Lists.newArrayList();
}
return allSns;
}
/**
* 修改设备上点数据
*
* @param deviceLocationDtos 设备上点数据集合
*/
public void saveOrUpdateDeviceLocationData(Collection<DeviceLocationDto> deviceLocationDtos) {
deviceLocationClient.saveOrUpdateDeviceLocationData(deviceLocationDtos);
}
}
package cn.com.glsx.kafka.service;
import cn.com.glsx.kafka.queue.remote.RemoteDeviceLocationService;
import com.google.common.hash.BloomFilter;
import com.google.common.hash.Funnels;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import java.nio.charset.Charset;
import java.util.List;
/**
* 布隆过滤器的业务处理层
*
* @author Yanglinlong
* @date 2021/12/17 20:19
*/
@Slf4j
@Service
public class BloomFilterService {
@Autowired
private RemoteDeviceLocationService remoteDeviceLocationService;
/**
* 预计要插入多少数据
*/
private static int size = 1000000;
/**
* 期望的误判率
*/
private static double fpp = 0.01;
/**
* 布隆过滤器
*/
private static BloomFilter<String> bloomFilter = BloomFilter.create(Funnels.stringFunnel(Charset.defaultCharset()), size, fpp);
/**
* 初始化的时候 将新E盾中的所有设备号写入布隆过滤器中
*/
@PostConstruct
public void init() {
List<String> allSns = remoteDeviceLocationService.getAllSnInNewEshield();
allSns.forEach(this::putData);
}
public Boolean isExits(String sn) {
return bloomFilter.mightContain(sn);
}
/**
* 向布隆过滤器中加入设备号
*
* @param sn 设备号
*/
public void putData(String sn) {
boolean flag = bloomFilter.put(sn);
if (flag) {
log.info("向布隆过滤器中加入设备号===" + sn + "成功");
} else {
log.info("向布隆过滤器中加入设备号===" + sn + "失败");
}
}
}
package cn.com.glsx.kafka.service;
import cn.com.glsx.kafka.queue.remote.RemoteDeviceLocationService;
import cn.com.glsx.stdinterface.dto.DeviceLocationDto;
import cn.hutool.core.util.ObjectUtil;
import com.glsx.plat.redis.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.concurrent.ConcurrentHashMap;
/**
* Gps和基站数据处理Service
*
* @author Yanglinlong
* @date 2021/12/17 19:43
*/
@Slf4j
@Service
public class TransitHandleService {
@Autowired
private RedisUtils redisUtils;
@Autowired
private RemoteDeviceLocationService remoteDeviceLocationService;
/**
* 缓存 map
*/
private static ConcurrentHashMap<String, DeviceLocationDto> deviceLocationMap = new ConcurrentHashMap<>();
/**
* 缓存数据入库时间差
*/
private static long tempTime = System.currentTimeMillis();
/**
* 间隔时间
*/
private static final int STEP = 5000;
/**
* 处理GPS和基站的数据
*
* @param deviceLocationDto Gps和基站的数据
*/
public void handleGpsAndBsData(DeviceLocationDto deviceLocationDto) {
DeviceLocationDto deviceLocationCache = (DeviceLocationDto) redisUtils.get(setKey(deviceLocationDto.getSn()));
if (ObjectUtil.isEmpty(deviceLocationCache)) {
redisUtils.set(setKey(deviceLocationDto.getSn()), deviceLocationDto);
deviceLocationMap.put(deviceLocationDto.getSn(), deviceLocationDto);
}
// gps时间比缓存中Gps的时间大就更新缓存的时间
Date lastGpsTime = deviceLocationDto.getLastGpsTime();
Date lastGpsTimeCache = deviceLocationCache.getLastGpsTime();
if (judgeDate(lastGpsTime, lastGpsTimeCache) && lastGpsTime.after(lastGpsTimeCache)) {
deviceLocationCache.setLastGpsTime(lastGpsTime);
}
//基站时间比缓存中基站的时间大就更新缓存的时间
Date lastBsTime = deviceLocationDto.getLastBsTime();
Date lastBsTimeCache = deviceLocationCache.getLastBsTime();
if (judgeDate(lastBsTime, lastBsTimeCache) && lastBsTime.after(lastBsTimeCache)) {
deviceLocationCache.setLastGpsTime(lastBsTime);
}
// 重新设置回缓存
redisUtils.set(setKey(deviceLocationDto.getSn()), deviceLocationCache);
deviceLocationMap.put(deviceLocationDto.getSn(), deviceLocationCache);
// 当数据大小为200个的时候 保存一次
if (deviceLocationMap.size() == 100 || System.currentTimeMillis() >= tempTime + STEP) {
log.info("开始插入或者更新Gps和基站的数据大小===" + deviceLocationMap.size());
remoteDeviceLocationService.saveOrUpdateDeviceLocationData(deviceLocationMap.values());
// 清空缓存map
deviceLocationMap.clear();
// 临时时间设置为此次插入数据库的时间
tempTime = System.currentTimeMillis();
}
}
/**
* 判断两个时间是否都不为null
*
* @param dateOne time
* @param dateTwo time
* @return
*/
private Boolean judgeDate(Date dateOne, Date dateTwo) {
return !ObjectUtil.isNull(dateOne) && !ObjectUtil.isNull(dateTwo);
}
/**
* 设置key值
*
* @param key key
* @return
*/
private String setKey(String key) {
return "gpsbs_" + key;
}
}
#\u9879\u76EE\u540D\u79F0
spring.application.name=ne-shield-kafkaconsumer-gpsbs
#spring.boot.admin.client.instance.service-base-url=
#\u65E5\u5FD7\u8DEF\u5F84\uFF08logback-spring.xml\u8BFB\u53D6\uFF0C\u4E0D\u8981\u52A0\u5165\u914D\u7F6E\u4E2D\u5FC3\uFF09
logging.path=/data/java_log/jetty/${spring.application.name}/${spring.application.name}.log
#nacos\u914D\u7F6E\u4E2D\u5FC3
spring.cloud.nacos.config.server-addr=192.168.3.206:8848
#\u8054\u8C03\u6D4B\u8BD5\u7684\u65F6\u5019\u4F7F\u7528
#spring.cloud.nacos.config.server-addr=192.168.0.63:8848
#nacos\u914D\u7F6Eid\uFF0C\u5B8C\u6574dataId=${spring.cloud.nacos.config.prefix}-${spring.profiles.active}.${file-extension\uFF08\u7531\u65B0\u589E\u914D\u7F6E\u65F6\u9009\u7684\u6587\u4EF6\u7C7B\u578B\u51B3\u5B9A\uFF09}
#\u793A\u4F8B\uFF1Ahttp://192.168.0.63:8848/nacos/v1/cs/configs?dataId=glsx-rest-admin.properties&group=DEV_GROUP
spring.cloud.nacos.config.group=NESHIELD_DEV_GROUP
#\u914D\u7F6Eprefix\uFF0C\u9ED8\u8BA4\u503C\u540C${spring.application.name}
spring.cloud.nacos.config.prefix=${spring.application.name}
#\u914D\u7F6E\u5F00\u53D1\u73AF\u5883
spring.profiles.active=dev
#\u914D\u7F6E\u683C\u5F0F
spring.cloud.nacos.config.file-extension=properties
#\u5FAE\u670D\u52A1sentinel\u3001zipkin\u3001actuator\u7B49\u516C\u5171\u914D\u7F6E
spring.cloud.nacos.config.shared-configs[0].data-id=glsx-rest-microservice-share.properties
spring.cloud.nacos.config.shared-configs[0].group=DEV_GROUP
spring.cloud.nacos.config.shared-configs[0].refresh=true
#\u6570\u636E\u5E93\u3001redis\u7B49\u516C\u5171\u914D\u7F6E
spring.cloud.nacos.config.shared-configs[1].group=NESHIELD_DEV_GROUP
spring.cloud.nacos.config.shared-configs[1].data-id=glsx-ne-shield-share-dev.properties
spring.cloud.nacos.config.shared-configs[1].refresh=true
spring.main.allow-bean-definition-overriding=true
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE generatorConfiguration PUBLIC
"-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<!-- 配置生成器 -->
<generatorConfiguration>
<!--classPathEntry:数据库的JDBC驱动,换成你自己的驱动位置 可选 -->
<!-- <classPathEntry location="F://jdbc//mysql-connector-java-8.0.18.jar"/>-->
<!-- 一个数据库一个context -->
<context id="DB2Tables" targetRuntime="Mybatis3">
<!-- 自动识别数据库关键字,默认false,如果设置为true,根据SqlReservedWords中定义的关键字列表;一般保留默认值,遇到数据库关键字(Java关键字),使用columnOverride覆盖 -->
<property name="autoDelimitKeywords" value="true"/>
<!-- 生成的Java文件的编码 -->
<property name="javaFileEncoding" value="utf-8"/>
<!-- beginningDelimiter和endingDelimiter:指明数据库的用于标记数据库对象名的符号,比如ORACLE就是双引号,MYSQL默认是`反引号; -->
<property name="beginningDelimiter" value="`"/>
<property name="endingDelimiter" value="`"/>
<!-- 格式化java代码 -->
<property name="javaFormatter" value="org.mybatis.generator.api.dom.DefaultJavaFormatter"/>
<!-- 格式化XML代码 -->
<property name="xmlFormatter" value="org.mybatis.generator.api.dom.DefaultXmlFormatter"/>
<plugin type="org.mybatis.generator.plugins.SerializablePlugin"/>
<plugin type="org.mybatis.generator.plugins.ToStringPlugin"/>
<!-- 配置 tk.mybatis 插件 -->
<plugin type="tk.mybatis.mapper.generator.MapperPlugin">
<property name="mappers" value="com.glsx.plat.mybatis.mapper.CommonBaseMapper"/>
</plugin>
<!--配置生成注释信息,最多配置一个 -->
<commentGenerator>
<!-- 阻止生成注释包含时间戳 默认为false -->
<property name="suppressDate" value="true"/>
<!-- 注释是否添加数据库表的备注信息 默认为false -->
<property name="addRemarkComments" value="true"/>
</commentGenerator>
<!-- jdbc连接-->
<jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
connectionURL="jdbc:mysql://192.168.3.222:3307/neshield?serverTimeZone=Asia/Shanghai&amp;useUnicode=true&amp;characterEncoding=utf8&amp;useSSL=false&amp;allowPublicKeyRetrieval=true"
userId="biz_neshield"
password="9USarBaG">
<!--防止生成其他库同名表-->
<property name="nullCatalogMeansCurrent" value="true"/>
</jdbcConnection>
<!-- 类型转换 -->
<javaTypeResolver>
<!-- 是否使用bigDecimal, false可自动转化以下类型(Long, Integer, Short, etc.) -->
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
<!-- 生成实体类地址 -->
<javaModelGenerator targetPackage="cn.com.glsx.kafka.entity" targetProject="src/main/java">
<!-- 是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="true"/>
<!-- 从数据库返回的值去掉前后空格 -->
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<!-- 生成mapper.xml文件存放地址 -->
<sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources">
<property name="enableSubPackages" value="true"/>
</sqlMapGenerator>
<!-- 生成接口dao type="ANNOTATEDMAPPER",生成Java Model 和基于注解的Mapper对象 type="MIXEDMAPPER",生成基于注解的Java Model 和相应的Mapper对象 type="XMLMAPPER",生成SQLMap XML文件和独立的Mapper接口 -->
<javaClientGenerator targetPackage="cn.com.glsx.kafka.mapper" targetProject="src/main/java" type="XMLMAPPER">
<property name="enableSubPackages" value="false"/>
</javaClientGenerator>
<!-- table可以有多个,每个数据库中的表都可以写一个table,tableName表示要匹配的数据库表,也可以在tableName属性中通过使用%通配符来匹配所有数据库表,只有匹配的表才会自动生成文件 enableSelectByPrimaryKey相应的配置表示是否生成相应的接口 -->
<table tableName="t_channel_risk_data" domainObjectName="ChannelRiskData" enableCountByExample="false"
enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false"
selectByExampleQueryId="false"/>
</context>
</generatorConfiguration>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8" ?>
<!--
说明:
1. 文件的命名和加载顺序有关
logback.xml早于application.yml加载,logback-spring.xml晚于application.yml加载
如果logback配置需要使用application.yml中的属性,需要命名为logback-spring.xml
2. logback使用application.yml中的属性
使用springProperty才可使用application.yml中的值 可以设置默认值
如果非要用yaml文件,那么只能使用绝对路径,例如:
logback-spring.xml引入文件:
<property file="${HOME}/configuration/application.yaml"/>
-->
<configuration scan="true" scanPeriod="60 seconds" debug="false">
<include resource="org/springframework/boot/logging/logback/defaults.xml"/>
<property resource="bootstrap.properties"/>
<property name="APP_NAME" value="${spring.application.name}"/>
<!-- 生成日志文件目录 -->
<property name="LOG_FILE" value="${logging.path}"/>
<contextName>${APP_NAME}</contextName>
<turboFilter class="com.glsx.plat.common.loggin.BootTurboFilter">
<Marker>${APP_NAME}</Marker>
</turboFilter>
<!-- 彩色日志 -->
<!-- 彩色日志依赖的渲染类 -->
<!-- <conversionRule conversionWord="clr" converterClass="org.springframework.boot.logging.logback.ColorConverter" />-->
<!-- <conversionRule conversionWord="wex" converterClass="org.springframework.boot.logging.logback.WhitespaceThrowableProxyConverter" />-->
<!-- <conversionRule conversionWord="wEx" converterClass="org.springframework.boot.logging.logback.ExtendedWhitespaceThrowableProxyConverter" />-->
<!-- 配置日志输出参数,彩色日志格式 -->
<property name="CONSOLE_LOG_PATTERN"
value="%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) %clr(${PID:- }){magenta} %clr(---){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}"/>
<!-- 控制台打印日志 -->
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<!-- Minimum logging level to be presented in the console logs-->
<level>INFO</level>
</filter>
<encoder>
<pattern>${CONSOLE_LOG_PATTERN}</pattern>
<charset>utf8</charset>
</encoder>
</appender>
<!-- 日志定时生成压缩文件 -->​
<appender name="flatfile" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${LOG_FILE}</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${LOG_FILE}.%d{yyyy-MM-dd}.gz</fileNamePattern>
<maxHistory>7</maxHistory>
</rollingPolicy>
<encoder>
<pattern>${CONSOLE_LOG_PATTERN}</pattern>
<charset>utf8</charset>
</encoder>
</appender>
<!-- 日志进行格式化 -->
<!-- <appender name="logstash" class="ch.qos.logback.core.rolling.RollingFileAppender">-->
<!-- <file>${LOG_FILE}.json</file>-->
<!-- <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">-->
<!-- <fileNamePattern>${LOG_FILE}.json.%d{yyyy-MM-dd}.gz</fileNamePattern>-->
<!-- <maxHistory>7</maxHistory>-->
<!-- </rollingPolicy>-->
<!-- <encoder class="net.logstash.logback.encoder.LoggingEventCompositeJsonEncoder">-->
<!-- <providers>-->
<!-- <timestamp>-->
<!-- <timeZone>UTC</timeZone>-->
<!-- </timestamp>-->
<!-- <pattern>-->
<!-- <pattern>-->
<!-- {-->
<!-- "severity": "%level",-->
<!-- "service": "${APP_NAME:-}",-->
<!-- "trace": "%X{X-B3-TraceId:-}",-->
<!-- "span": "%X{X-B3-SpanId:-}",-->
<!-- "parent": "%X{X-B3-ParentSpanId:-}",-->
<!-- "exportable": "%X{X-Span-Export:-}",-->
<!-- "pid": "${PID:-}",-->
<!-- "thread": "%thread",-->
<!-- "class": "%logger{40}",-->
<!-- "rest": "%message"-->
<!-- }-->
<!-- </pattern>-->
<!-- </pattern>-->
<!-- </providers>-->
<!-- </encoder>-->
<!-- </appender>-->
​
<root level="INFO">
<appender-ref ref="console"/>
<appender-ref ref="flatfile"/>
<!-- uncomment this to have also JSON logs -->
<!-- <appender-ref ref="logstash"/>-->
</root>
</configuration>
\ No newline at end of file
#!/bin/bash
cd `dirname $0`
./stop.sh
if [ ! $? -eq 2 ];then
./start.sh
fi
\ No newline at end of file
#!/bin/bash
cd `dirname $0`
if [ "$1" = "start" ]; then
ENV=$2
if [ -z "$ENV" ]; then
echo "ERROR:PLEASE SPEC ENV ARGS,SUCH AS dev,test,beta,release.. "
echo "app exit"
exit 1
fi
./start.sh $ENV
else
if [ "$1" = "stop" ]; then
./stop.sh
else
if [ "$1" = "debug" ]; then
ENV=$2
if [ -z "$ENV" ]; then
echo "ERROR:PLEASE SPEC ENV ARGS,SUCH AS dev,test,beta,release.. "
echo "app exit"
exit 1
fi
./start.sh $ENV debug
else
if [ "$1" = "restart" ]; then
ENV=$2
if [ -z "$ENV" ]; then
echo "ERROR:PLEASE SPEC ENV ARGS,SUCH AS dev,test,beta,release.. "
echo "app exit"
exit 1
fi
./restart.sh $ENV
else
if [ "$1" = "dump" ]; then
./dump.sh
else
echo "ERROR: Please input argument: start or stop or debug or restart or dump"
exit 1
fi
fi
fi
fi
fi
#!/bin/bash
####################################
# #
# General shell v1.0.0.1 #
# #
# #
####################################
###########init variable#############
JAVA_HOME="/app/soft/jdk1.8.0_144"
SERVER_PORT="8883"
DUBBO_PORT=""
JMX_ARG="-Xmx1024m -Xms512m -Xmn256m"
MAIN="cn.com.glsx.Application"
SERVER_NAME="ne-shield-kafkaconsumer"
###########end#######################
PID_DIR="/app/soft/java_project/pids"
cd `dirname $0`
BIN_DIR=`pwd`
cd ..
if [ -d "classes" ];then
CONF_DIR="$(pwd)/classes"
LIB_DIR="$(pwd)/lib"
elif [ -d "conf" ];then
CONF_DIR="$(pwd)/conf"
LIB_DIR="$(pwd)/lib"
fi
LIB_JARS=`ls $LIB_DIR|grep .jar|awk '{print "'$LIB_DIR'/"$0}'|tr "\n" ":"`
export CLASSPATH=$CONF_DIR:$LIB_JARS
if [ -z "$CONF_DIR" ];then
echo "Configure dir not found"
exit 1
fi
PIDS=`ps --no-heading -C java -f --width 1000 | grep "$CONF_DIR" |awk '{print $2}'`
if [ -n "$PIDS" ]; then
echo "ERROR: The app is already started!"
echo "PID: $PIDS"
exit 1
fi
if [ ! -d "$PID_DIR" ];then
mkdir -p $PID_DIR
fi
CHECK_PORT=$2
if [ -n "$SERVER_PORT" ];then
SERVER_PORT_COUNT=`netstat -tln | grep -w $SERVER_PORT | wc -l`
if [ $SERVER_PORT_COUNT -gt 0 ]; then
echo "ERROR: The port $SERVER_PORT is already used!"
exit 1
fi
fi
if [ -n "$DUBBO_PORT" ];then
DUBBO_PORT_COUNT=`netstat -tln | grep -w $DUBBO_PORT | wc -l`
if [ $DUBBO_PORT_COUNT -gt 0 ]; then
echo "ERROR: The port $DUBBO_PORT already used!"
exit 1
fi
fi
if [[ -z "$SERVER_PORT" && -z "$DUBBO_PORT" ]];then
CHECK_PORT="skip"
fi
LOG_FILE="/data/java_log/jetty/${SERVER_NAME}/${SERVER_NAME}.log"
LOG_DIR=`dirname $LOG_FILE`
if [ ! -d $LOG_DIR ];then
mkdir -p $LOG_DIR
fi
############java args #######
#JAVA_OPTS="$PINPOINT -Djava.awt.headless=true -Djava.net.preferIPv4Stack=true -Ddubbo.registry.file=/home/jdkapp/.dubbo/${SERVER_NAME}.cache"
JAVA_OPTS="$PINPOINT -Djava.awt.headless=true -Djava.net.preferIPv4Stack=true"
#JAVA_OPTS=" -Djava.awt.headless=true -Djava.net.preferIPv4Stack=true"
JAVA_DEBUG_OPTS=""
if [ "$2" = "debug" ]; then
JAVA_DEBUG_OPTS=" -Xdebug -Xnoagent -Djava.compiler=NONE -Xrunjdwp:transport=dt_socket,address=8000,server=y,suspend=n "
fi
JAVA_JMX_OPTS=""
if [ "$2" = "jmx" ]; then
JAVA_JMX_OPTS=" -Dcom.sun.management.jmxremote.port=1099 -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.authenticate=false "
fi
BITS=`file $JAVA_HOME/bin/java | grep 64-bit`
if [ -n "$BITS" ]; then
if [ -n "$JMX_ARG" ];then
JAVA_MEM_OPTS="-server $JMX_ARG -XX:PermSize=128m -Xss256k -XX:+DisableExplicitGC -XX:+UseConcMarkSweepGC -XX:+CMSParallelRemarkEnabled -XX:+UseCMSCompactAtFullCollection -XX:LargePageSizeInBytes=128m -XX:+UseFastAccessorMethods -XX:+UseCMSInitiatingOccupancyOnly -XX:CMSInitiatingOccupancyFraction=70"
else
JAVA_MEM_OPTS=" -server -Xmx1g -Xms1g -Xmn256m -XX:PermSize=128m -Xss256k -XX:+DisableExplicitGC -XX:+UseConcMarkSweepGC -XX:+CMSParallelRemarkEnabled -XX:+UseCMSCompactAtFullCollection -XX:LargePageSizeInBytes=128m -XX:+UseFastAccessorMethods -XX:+UseCMSInitiatingOccupancyOnly -XX:CMSInitiatingOccupancyFraction=70 "
fi
else
JAVA_MEM_OPTS=" -server -Xms1024m -Xmx1024m -XX:PermSize=128m -XX:SurvivorRatio=2 -XX:+UseParallelGC "
fi
echo -e "Starting $SERVER_NAME \c"
nohup $JAVA_HOME/bin/java $JAVA_OPTS $JAVA_MEM_OPTS $JAVA_DEBUG_OPTS $JAVA_JMX_OPTS -DCLASS_DIR=$CONF_DIR:$LIB_DIR $MAIN > /dev/null 2>&1 &
PIDS=$!
if [ "$CHECK_PORT" != "skip" ];then
COUNT=0
ERROR=0
TIME_OUT=60
ctime=`date +"%s"`
while [ $COUNT -lt 1 ]; do
ctime2=`date +"%s"`
echo -e ".\c"
sleep 1
#PIDS=`ps --no-heading -C java -f --width 1000 | grep "$CONF_DIR" | awk '{print $2}'`
RESULT=`ps --no-heading -p $PIDS`
if [ -n "$RESULT" ];then
if [ -n "$DUBBO_PORT" ]; then
#COUNT=`echo status | nc 127.0.0.1 $DUBBO_PORT -i 1 | grep -c OK`
COUNT=`/usr/sbin/ss -lpn | grep "${DUBBO_PORT}.*$PIDS" | wc -l`
else
if [ -n "$SERVER_PORT" ]; then
#COUNT=`netstat -ntl | grep -w $SERVER_PORT | wc -l`
COUNT=`/usr/sbin/ss -lpn | grep "${SERVER_PORT}.*$PIDS" | wc -l`
fi
fi
if [ $COUNT -gt 0 ]; then
echo $PIDS > $PID_DIR/${SERVER_NAME}.pid
break
fi
dtime=$((ctime2 - ctime))
if [ "$dtime" -ge "$TIME_OUT" ];then
echo $PIDS > $PID_DIR/${SERVER_NAME}.pid
echo -e "\ncheck port status timeout"
exit 1
fi
else
ERROR=$((ERROR + 1))
if [ "$ERROR" -gt 3 ];then
echo -e "\nProgram startup failed"
exit 2
fi
fi
done
fi
#服务检测与注册
if [[ "x$SERVER_PORT" != "x" && -f ./bin/check.sh ]]
then
./bin/check.sh $SERVER_NAME $SERVER_PORT $PIDS &
fi
echo "PID: $PIDS"
echo "LOGFILE: $LOG_FILE"
\ No newline at end of file
#!/bin/bash
####################################
# #
# General shell v1.0.0.1 #
# #
# #
####################################
SERVER_NAME="ne-shield-kafkaconsumer"
PID_DIR="/app/soft/java_project/pids"
cd `dirname $0`
BIN_DIR=`pwd`
cd ..
if [ -d "classes" ];then
CONF_DIR="$(pwd)/classes"
elif [ -d "conf" ];then
CONF_DIR="$(pwd)/conf"
fi
#if [ -f "$PID_DIR/${SERVER_NAME}.pid" ];then
# PID=`cat $PID_DIR/${SERVER_NAME}.pid`
#else
PID=`ps --no-heading -C java -f --width 1000 | grep "$CONF_DIR" |awk '{print $2}'`
#fi
if [ -z "$PID" ];then
echo "The program is not running"
exit 1
fi
pcount=`ps --no-heading -p $PID | wc -l`
if [ "$pcount" -ne 1 ];then
echo "ERROR: $SERVER_NAME does not started!"
exit 1
fi
echo -e "Stopping $SERVER_NAME ...\c"
kill $PID > /dev/null 2>&1
COUNT=0
ctime=`date +"%s"`
while [ $COUNT -lt 1 ]; do
echo -e ".\c"
sleep 1
COUNT=1
PID_EXIST=`ps --no-heading -p $PID`
if [ -n "$PID_EXIST" ]; then
ctime2=`date +"%s"`
dtime=$((ctime2 - ctime))
if [ "$dtime" -ge 10 ];then
echo -e "\nstop program timeout, use kill -9 $PID"
kill -9 $PID >/dev/null 2>&1
if [ ! $? -eq 0 ];then
echo "No permissions"
exit 2
else
rm -rf $PID_DIR/${SERVER_NAME}.pid
fi
fi
COUNT=0
continue
fi
done
echo "OK!"
rm -rf $PID_DIR/${SERVER_NAME}.pid
\ No newline at end of file
package cn.com.glsx.kafka.queue.remote;
import cn.com.glsx.Application;
import cn.com.glsx.stdinterface.dto.DeviceLocationDto;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.Collection;
import java.util.Date;
import java.util.List;
@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class RemoteDeviceLocationServiceTest {
@Autowired
private RemoteDeviceLocationService remoteDeviceLocationService;
@Test
public void getAllSnInNewEshield() {
List<String> allSns = remoteDeviceLocationService.getAllSnInNewEshield();
System.out.println("allSns = " + JSON.toJSONString(allSns));
}
@Test
public void saveOrUpdateDeviceLocationData() {
Collection<DeviceLocationDto> deviceLocationDtos = Lists.newArrayList();
DeviceLocationDto deviceLocationDto = new DeviceLocationDto();
deviceLocationDto.setSn("123456789");
deviceLocationDto.setLastGpsTime(new Date());
deviceLocationDto.setLastBsTime(new Date());
deviceLocationDtos.add(deviceLocationDto);
remoteDeviceLocationService.saveOrUpdateDeviceLocationData(deviceLocationDtos);
System.out.println("更新成功===");
}
}
\ 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!