Browse Source

1、动态指令缓存;

2、项目图片压缩;
3、定时请求天气优化出现偶尔调用不到数据;
4、假如多线程处理解析数据报文;
dev
mh 7 months ago
parent
commit
9c90ceb1ef
  1. 7
      common/pom.xml
  2. 50
      common/src/main/java/com/mh/common/utils/FileUtils.java
  3. 5
      user-service/pom.xml
  4. 3
      user-service/src/main/java/com/mh/user/annotation/ApplicationListener.java
  5. 20
      user-service/src/main/java/com/mh/user/annotation/CacheChanges.java
  6. 75
      user-service/src/main/java/com/mh/user/aspect/CacheChangesAsp.java
  7. 12
      user-service/src/main/java/com/mh/user/aspect/DaoAspect.java
  8. 4
      user-service/src/main/java/com/mh/user/controller/MeterManageController.java
  9. 4
      user-service/src/main/java/com/mh/user/controller/SysDictController.java
  10. 6
      user-service/src/main/java/com/mh/user/entity/MeterManageEntity.java
  11. 123
      user-service/src/main/java/com/mh/user/job/CollectionLoopRunner.java
  12. 8
      user-service/src/main/java/com/mh/user/job/DealDataJob.java
  13. 3
      user-service/src/main/java/com/mh/user/mapper/DeviceCodeParamMapper.java
  14. 11
      user-service/src/main/java/com/mh/user/netty/EchoServerHandler.java
  15. 6
      user-service/src/main/java/com/mh/user/service/DeviceCodeParamService.java
  16. 147
      user-service/src/main/java/com/mh/user/service/impl/DeviceCodeParamServiceImpl.java
  17. 4
      user-service/src/main/java/com/mh/user/service/impl/ProjectInfoServiceImpl.java
  18. 2
      user-service/src/main/java/com/mh/user/service/impl/SysDictServiceImpl.java
  19. 20
      user-service/src/main/java/com/mh/user/utils/SimpleWeather.java
  20. 76
      user-service/src/test/java/com/mh/user/socket/BIOServer.java

7
common/pom.xml

@ -82,5 +82,12 @@
<artifactId>poi-ooxml</artifactId>
<version>4.0.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/net.coobird/thumbnailator -->
<dependency>
<groupId>net.coobird</groupId>
<artifactId>thumbnailator</artifactId>
<version>0.4.20</version>
</dependency>
</dependencies>
</project>

50
common/src/main/java/com/mh/common/utils/FileUtils.java

@ -1,5 +1,6 @@
package com.mh.common.utils;
import net.coobird.thumbnailator.Thumbnails;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Encoder;
@ -54,4 +55,53 @@ public class FileUtils {
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(data);
}
public static byte[] compressImage(MultipartFile file, long targetSize) throws IOException {
try (InputStream inputStream = file.getInputStream()) {
// 将输入流转换为字节数组
byte[] originalBytes = new byte[inputStream.available()];
inputStream.read(originalBytes);
inputStream.close();
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(originalBytes);
// 初始压缩比例
double compressionRatio = 0.9;
byte[] compressedBytes;
while (true) {
try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
Thumbnails.of(byteArrayInputStream)
.scale(compressionRatio)
.outputQuality(compressionRatio)
.toOutputStream(outputStream);
compressedBytes = outputStream.toByteArray();
if (compressedBytes.length <= targetSize) {
return compressedBytes;
} else {
// 调整压缩比例
compressionRatio -= 0.1;
if (compressionRatio <= 0.1) {
throw new RuntimeException("无法将图像压缩到目标大小");
}
}
}
// 重置输入流
byteArrayInputStream.reset();
}
}
}
public static String reSizeImg(MultipartFile file) {
try {
byte[] bytes = compressImage(file, 512 * 1024);
// 对字节数组进行编码,得到base64编码字符串
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(bytes);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}

5
user-service/pom.xml

@ -34,6 +34,11 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-undertow</artifactId>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.1.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>

3
user-service/src/main/java/com/mh/user/annotation/applicationListener.java → user-service/src/main/java/com/mh/user/annotation/ApplicationListener.java

@ -1,12 +1,11 @@
package com.mh.user.annotation;
import javax.servlet.ServletContextAttributeEvent;
import javax.servlet.ServletContextAttributeListener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
@WebListener
public class applicationListener implements ServletContextListener,ServletContextAttributeListener{
public class ApplicationListener implements ServletContextListener,ServletContextAttributeListener{
@Override
public void contextDestroyed(ServletContextEvent arg0) {

20
user-service/src/main/java/com/mh/user/annotation/CacheChanges.java

@ -0,0 +1,20 @@
package com.mh.user.annotation;
import java.lang.annotation.*;
/**
* @author LJF
* @version 1.0
* @project mh_esi
* @description 缓存变动
* @date 2024-11-19 11:36:47
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface CacheChanges {
// 缓存类型
String value() default "";
}

75
user-service/src/main/java/com/mh/user/aspect/CacheChangesAsp.java

@ -0,0 +1,75 @@
package com.mh.user.aspect;
import com.mh.common.utils.StringUtils;
import com.mh.user.annotation.CacheChanges;
import com.mh.user.entity.MeterManageEntity;
import com.mh.user.service.DeviceCodeParamService;
import com.mh.user.service.SysDictService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
/**
* @author LJF
* @version 1.0
* @project mh_esi
* @description 缓存数据切面
* @date 2024-11-19 11:40:50
*/
@Aspect
@Component
public class CacheChangesAsp {
@Autowired
private SysDictService sysDictService;
@Autowired
private DeviceCodeParamService deviceCodeParamService;
@Pointcut("@annotation(com.mh.user.annotation.CacheChanges)")
public void cachePointCut() {
}
@After("cachePointCut()")
public void afterAdvice(JoinPoint point) throws Throwable {
// 保存日志
updateCacheChanges(point);
}
private void updateCacheChanges(JoinPoint joinPoint) {
// 获取方法签名
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
// 获取方法上的注解
CacheChanges cacheChanges = signature.getMethod().getAnnotation(CacheChanges.class);
// 获取值
String value = "";
if (cacheChanges != null) {
value = cacheChanges.value();
}
// 获取项目id参数
Object[] args = joinPoint.getArgs();
switch (value) {
case "sys_dict":
sysDictService.createDictDataCache();
break;
case "device_code_params":
MeterManageEntity entity = (MeterManageEntity) args[0];
deviceCodeParamService.createCodeParams(entity);
default:
break;
}
}
}

12
user-service/src/main/java/com/mh/user/aspect/DaoAspect.java

@ -72,11 +72,13 @@ public class DaoAspect {
for (Object arg : objects) {
String username = getUserName();
if (username != null) {
if (StringUtils.isBlank(BeanUtils.getProperty(arg, createBy))) {
BeanUtils.setProperty(arg, createBy, username);
}
if (StringUtils.isBlank(BeanUtils.getProperty(arg, createTime))) {
BeanUtils.setProperty(arg, createTime, new Date());
if (arg.equals(createBy) || arg.equals(createTime)) {
if (StringUtils.isBlank(BeanUtils.getProperty(arg, createBy))) {
BeanUtils.setProperty(arg, createBy, username);
}
if (StringUtils.isBlank(BeanUtils.getProperty(arg, createTime))) {
BeanUtils.setProperty(arg, createTime, new Date());
}
}
}
}

4
user-service/src/main/java/com/mh/user/controller/MeterManageController.java

@ -3,6 +3,7 @@ package com.mh.user.controller;
import com.mh.common.http.HttpResult;
import com.mh.common.page.PageRequest;
import com.mh.common.page.PageResult;
import com.mh.user.annotation.CacheChanges;
import com.mh.user.annotation.FieldParam;
import com.mh.user.annotation.SysLogger;
import com.mh.user.annotation.TranslationDict;
@ -37,6 +38,7 @@ public class MeterManageController {
return meterManageService.queryByPage(pageRequest);
}
@CacheChanges(value = "device_code_params")
@SysLogger(value="仪表管理信息",optDesc = "编辑仪表管理信息")
@PostMapping("/update")
public HttpResult updateProInfo(MeterManageEntity entity) {
@ -51,6 +53,7 @@ public class MeterManageController {
return HttpResult.ok(entity);
}
@CacheChanges(value = "device_code_params")
@SysLogger(value="仪表管理信息",optDesc = "添加仪表管理信息")
@PostMapping("/save")
public HttpResult saveGw(MeterManageEntity entity) {
@ -58,6 +61,7 @@ public class MeterManageController {
return HttpResult.ok();
}
@CacheChanges(value = "device_code_params")
@SysLogger(value="仪表管理信息",optDesc = "删除仪表管理信息")
@GetMapping("/deleteById")
public HttpResult deleteProInfo(@RequestParam String id) {

4
user-service/src/main/java/com/mh/user/controller/SysDictController.java

@ -3,6 +3,7 @@ package com.mh.user.controller;
import com.mh.common.http.HttpResult;
import com.mh.common.page.PageRequest;
import com.mh.common.page.PageResult;
import com.mh.user.annotation.CacheChanges;
import com.mh.user.annotation.SysLogger;
import com.mh.user.model.SysDict;
import com.mh.user.service.SysDictService;
@ -29,6 +30,7 @@ public class SysDictController {
return sysDictService.findPage(pageRequest);
}
@CacheChanges(value = "sys_dict")
@SysLogger(value="系统字典管理",optDesc = "编辑系统字典管理")
@PostMapping("/update")
public HttpResult update(SysDict entity) {
@ -43,6 +45,7 @@ public class SysDictController {
return HttpResult.ok(entity);
}
@CacheChanges(value = "sys_dict")
@SysLogger(value="系统字典管理",optDesc = "添加系统字典管理")
@PostMapping("/save")
public HttpResult save(SysDict entity) {
@ -50,6 +53,7 @@ public class SysDictController {
return HttpResult.ok();
}
@CacheChanges(value = "sys_dict")
@SysLogger(value="系统字典管理",optDesc = "删除系统字典管理")
@GetMapping("/deleteById")
public HttpResult delete(@RequestParam Long id) {

6
user-service/src/main/java/com/mh/user/entity/MeterManageEntity.java

@ -193,6 +193,11 @@ public class MeterManageEntity implements Serializable {
*/
private int registerSize;
/**
* 采集点是否启用
*/
private String isUse;
@Override
public String toString() {
return "MeterManageEntity{" +
@ -230,6 +235,7 @@ public class MeterManageEntity implements Serializable {
", projectId=" + projectId +
", communicationType=" + communicationType +
", registerSize=" + registerSize +
", isUse=" + isUse +
'}';
}
}

123
user-service/src/main/java/com/mh/user/job/CollectionLoopRunner.java

@ -1,14 +1,7 @@
package com.mh.user.job;
import com.mh.common.page.PageRequest;
import com.mh.user.entity.*;
import com.mh.user.factory.Protocol;
import com.mh.user.factory.ProtocolFactory;
import com.mh.user.netty.EchoServer;
import com.mh.user.service.*;
import com.mh.user.strategy.ProtocolStrategy;
import com.mh.user.strategy.ProtocolStrategyFactory;
import com.mh.user.utils.GetReadOrder485;
import gnu.io.SerialPort;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
@ -16,8 +9,6 @@ import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
import java.util.*;
/**
* @author ljf
* @title
@ -31,41 +22,27 @@ public class CollectionLoopRunner implements ApplicationRunner {
public static SerialPort serialPort = null;
@Autowired
ProjectInfoService projectInfoService;
@Autowired
private MeterManageService meterManageService;
@Autowired
private DeviceCodeParamService deviceCodeParamService;
@Autowired
private GatewayManageService gatewayManageService;
@Autowired
private DeviceParamsService deviceParamsService;
@Autowired
private SysDictService sysDictService;
@Override
public void run(ApplicationArguments args) throws Exception {
List<ProjectInfoEntity> projectInfoEntities = projectInfoService.queryProjectInfo("1");
if (null != projectInfoEntities && !projectInfoEntities.isEmpty()) {
for (ProjectInfoEntity projectInfoEntity : projectInfoEntities) {
// getReadOrder485.createOrderParam(String.valueOf(projectInfoEntity.getId())); //生成采集参数,1新珠江(6000),2广合科技(6001),3广大科技(6002),6珠江国际,7保利山庄,8东莞迎宾馆
createOrderParamByStrategy(projectInfoEntity.getSystemId(), String.valueOf(projectInfoEntity.getId()));
}
}
public void run(ApplicationArguments args) {
try {
// 生成采集参数
createCodeParams();
// 生成字典缓存
createDictDataCache();
new EchoServer(6001).start(); // 调用服务器的start方法,网关作为客户端,6006新珠江,6001广合科技,6077广大科技 6028(6006)珠江国际,5000保利山庄,6004东莞迎宾馆
} catch (Exception e) {
log.info("6001端口已占用!");
}
}
// 生成字典缓存
createDictDataCache();
private void createCodeParams() {
deviceCodeParamService.createCodeParams(null);
}
public void createDictDataCache() {
@ -73,88 +50,4 @@ public class CollectionLoopRunner implements ApplicationRunner {
sysDictService.createDictDataCache();
}
public void createOrderParamByStrategy(String systemId, String projectId) throws InterruptedException {
int r;
if (projectId != null && !projectId.isEmpty()) {
r = deviceCodeParamService.queryCount(projectId);//查询记录数
} else {
r = deviceCodeParamService.queryCount2();//查询记录数
}
if (r > 0) {
return;
}
List<DeviceCodeParamEntity> deviceCodeParamEntityList = new ArrayList<>();
List<MeterManageEntity> meterManageEntities = Collections.emptyList();
if (projectId != null && !projectId.isEmpty()) {
meterManageEntities = meterManageService.queryBySystemIdAndProjectId(systemId, projectId);
}
DeviceCodeParamEntity deviceCodeParamEntity = new DeviceCodeParamEntity();
// 根据协议进行匹配生成采集报文
for (MeterManageEntity meterManageEntity : meterManageEntities) {
// 重置采集参数
deviceCodeParamEntity.reset();
// 创建设备报文
String protocolType = String.valueOf(meterManageEntity.getProtocolType());
Protocol protocol = ProtocolFactory.matchProtocol(protocolType);
ProtocolStrategy strategy = ProtocolStrategyFactory.matchProtocolStrategy(protocolType);
if (strategy == null) {
continue;
}
protocol.setStrategy(strategy);
String sendStr = protocol.createOrder(meterManageEntity);
log.info("采集指令===> {}", sendStr);
deviceCodeParamEntity.setDeviceAddr(meterManageEntity.getMtCode());
deviceCodeParamEntity.setDeviceName(meterManageEntity.getMtName());
deviceCodeParamEntity.setDeviceType(String.valueOf(meterManageEntity.getMtType()));
deviceCodeParamEntity.setStrData(sendStr);
try {
GatewayManageEntity gatewayManageEntity = gatewayManageService.findById(meterManageEntity.getGatewayId());
if (gatewayManageEntity != null) {
deviceCodeParamEntity.setDataPort(String.valueOf(gatewayManageEntity.getPort()));
}
} catch (Exception e) {
log.error("查询网关信息失败: {}", e.getMessage());
}
try {
DeviceParamsEntity paramsEntity = deviceParamsService.findById(meterManageEntity.getParamId());
if (paramsEntity != null) {
deviceCodeParamEntity.setBaudRate(paramsEntity.getBaudRate());
deviceCodeParamEntity.setParity(paramsEntity.getParity());
}
} catch (Exception e) {
log.error("查询设备参数失败: {}", e.getMessage());
}
deviceCodeParamEntity.setBrand(meterManageEntity.getMtBrand());
deviceCodeParamEntity.setFunCode(meterManageEntity.getFuncCode());
deviceCodeParamEntity.setRegisterAddr(meterManageEntity.getRegisterAddr());
deviceCodeParamEntity.setRegisterName(meterManageEntity.getOtherName());
deviceCodeParamEntity.setDigit(meterManageEntity.getDigits());
deviceCodeParamEntity.setGrade(meterManageEntity.getGrade());
deviceCodeParamEntity.setDataValue(null); // 传入值(目前不需要)
deviceCodeParamEntity.setProjectId(projectId);
deviceCodeParamEntity.setCreateTime(new Date());
deviceCodeParamEntity.setMmId(meterManageEntity.getId());
deviceCodeParamEntity.setDataType(meterManageEntity.getDataType());
deviceCodeParamEntity.setProtocolType(meterManageEntity.getProtocolType());
deviceCodeParamEntityList.add(deviceCodeParamEntity.clone());
}
if (!deviceCodeParamEntityList.isEmpty()) {
deviceCodeParamService.insertDeviceCodeParamList(deviceCodeParamEntityList);
}
}
}

8
user-service/src/main/java/com/mh/user/job/DealDataJob.java

@ -100,10 +100,14 @@ public class DealDataJob {
Date date=new Date();
Map<String, Object> map= SimpleWeather.queryWeather("广州");
String curDate=sdf1.format(date);
if (map.isEmpty()) {
// 重新请求接口
map= SimpleWeather.queryWeather("广州");
}
String temperature=map.get("temperature").toString();
String humidity=map.get("humidity").toString();
dealDataService.saveTempHumidity(curDate,temperature,humidity);
log.info(curDate+","+temperature+"℃,"+humidity+"%");
log.info("{},{}℃,{}%", curDate, temperature, humidity);
} catch (Exception e) {
// e.printStackTrace();
log.error("调用获取环境温湿度接口失败!", e);
@ -129,7 +133,7 @@ public class DealDataJob {
dealDataService.proEnergyDaySum(curDate,projectId);
}
}
log.info("---------中央热水生产概况汇总,每一小时!"+curDate);
log.info("---------中央热水生产概况汇总,每一小时!{}", curDate);
} catch (Exception e) {
log.error("中央热水生产概况定时汇总异常", e);
}

3
user-service/src/main/java/com/mh/user/mapper/DeviceCodeParamMapper.java

@ -118,4 +118,7 @@ public interface DeviceCodeParamMapper extends BaseMapper<DeviceCodeParamEntity>
@Insert("insert into device_code_param(device_addr,device_name,device_type,data_port,baud_rate,parity,brand,create_time,project_id,digit,grade) select device_addr,device_name,device_type,data_port,baud_rate,parity,brand,getDate(),project_id,2,grade from device_code " +
" where (device_type='电表' or device_type='水表') and project_id=#{projectId} ")
void selectInsertDeviceCodeParam(@Param("projectId") String projectId);
@Delete("delete from device_code_param where project_id=#{projectId} ")
void deleteDeviceCodeParam(@Param("projectId") long projectId);
}

11
user-service/src/main/java/com/mh/user/netty/EchoServerHandler.java

@ -198,10 +198,13 @@ public class EchoServerHandler extends ChannelInboundHandlerAdapter {
}
}
private void analysisReceiveData(String receiveStr, DeviceCodeParamEntity deviceCodeParamEntity) {
// 解析采集的报文,并保存到数据库
AnalysisReceiveOrder485 analysisReceiveOrder485 = new AnalysisReceiveOrder485();
analysisReceiveOrder485.analysisReceiveOrder485(receiveStr, deviceCodeParamEntity);
private void analysisReceiveData(final String receiveStr, final DeviceCodeParamEntity deviceCodeParamEntity) {
// 多线程解析数据
ThreadPoolService.getInstance().execute(() -> {
// 解析采集的报文,并保存到数据库
AnalysisReceiveOrder485 analysisReceiveOrder485 = new AnalysisReceiveOrder485();
analysisReceiveOrder485.analysisReceiveOrder485(receiveStr, deviceCodeParamEntity);
});
}
private void whiteGateway(ChannelHandlerContext ctx) throws InterruptedException {

6
user-service/src/main/java/com/mh/user/service/DeviceCodeParamService.java

@ -1,6 +1,7 @@
package com.mh.user.service;
import com.mh.user.entity.DeviceCodeParamEntity;
import com.mh.user.entity.MeterManageEntity;
import org.apache.ibatis.annotations.Param;
@ -34,4 +35,9 @@ public interface DeviceCodeParamService {
//查询插入
void selectInsertDeviceCodeParam(String ProjectID);
/**
* 创建指令参数缓存
*/
void createCodeParams(MeterManageEntity entity);
}

147
user-service/src/main/java/com/mh/user/service/impl/DeviceCodeParamServiceImpl.java

@ -1,21 +1,50 @@
package com.mh.user.service.impl;
import com.mh.user.entity.DeviceCodeParamEntity;
import com.alibaba.fastjson2.JSONObject;
import com.github.benmanes.caffeine.cache.Cache;
import com.mh.user.entity.*;
import com.mh.user.factory.Protocol;
import com.mh.user.factory.ProtocolFactory;
import com.mh.user.mapper.DeviceCodeParamMapper;
import com.mh.user.service.DeviceCodeParamService;
import com.mh.user.model.SysDict;
import com.mh.user.service.*;
import com.mh.user.strategy.ProtocolStrategy;
import com.mh.user.strategy.ProtocolStrategyFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
@Transactional(rollbackFor = Exception.class)
@Service
@Slf4j
public class DeviceCodeParamServiceImpl implements DeviceCodeParamService {
@Autowired
DeviceCodeParamMapper deviceCodeParamMapper;
@Autowired
private ProjectInfoService projectInfoService;
@Autowired
private MeterManageService meterManageService;
@Autowired
private GatewayManageService gatewayManageService;
@Autowired
private DeviceParamsService deviceParamsService;
@Autowired
@Qualifier("caffeineCache")
private Cache caffeineCache;
@Override
public void insertDeviceCodeParam(DeviceCodeParamEntity deviceCodeParamEntity) {
@ -61,4 +90,118 @@ public class DeviceCodeParamServiceImpl implements DeviceCodeParamService {
public void selectInsertDeviceCodeParam(String ProjectID) {
deviceCodeParamMapper.selectInsertDeviceCodeParam(ProjectID);
}
@Override
public void createCodeParams(MeterManageEntity entity) {
if (entity == null) {
List<ProjectInfoEntity> projectInfoEntities = projectInfoService.queryProjectInfo("1");
if (null != projectInfoEntities && !projectInfoEntities.isEmpty()) {
for (ProjectInfoEntity projectInfoEntity : projectInfoEntities) {
// getReadOrder485.createOrderParam(String.valueOf(projectInfoEntity.getId())); //生成采集参数,1新珠江(6000),2广合科技(6001),3广大科技(6002),6珠江国际,7保利山庄,8东莞迎宾馆
createOrderParamByStrategy(projectInfoEntity.getSystemId(), String.valueOf(projectInfoEntity.getId()));
}
}
return;
}
Long projectId = entity.getProjectId();
if (projectId != 0) {
// 删除数据库存储的采集参数
deviceCodeParamMapper.deleteDeviceCodeParam(projectId);
// 删除缓存
caffeineCache.invalidate("code_params_"+projectId);
List<DeviceCodeParamEntity> deviceCodeParamEntityList = createOrderParamByStrategy("1", String.valueOf(projectId));
// 放入缓存中
if (deviceCodeParamEntityList != null) {
caffeineCache.put("code_params_" + projectId, deviceCodeParamEntityList);
}
List<DeviceCodeParamEntity> test = (List<DeviceCodeParamEntity>) caffeineCache.getIfPresent("code_params_"+projectId);
log.info("生成采集参数完毕==>{}", JSONObject.toJSONString(test));
}
}
public List<DeviceCodeParamEntity> createOrderParamByStrategy(String systemId, String projectId) {
int r;
if (projectId != null && !projectId.isEmpty()) {
r = queryCount(projectId);//查询记录数
} else {
r = queryCount2();//查询记录数
}
if (r > 0) {
return null;
}
List<DeviceCodeParamEntity> deviceCodeParamEntityList = new ArrayList<>();
List<MeterManageEntity> meterManageEntities = Collections.emptyList();
if (projectId != null && !projectId.isEmpty()) {
meterManageEntities = meterManageService.queryBySystemIdAndProjectId(systemId, projectId);
}
DeviceCodeParamEntity deviceCodeParamEntity = new DeviceCodeParamEntity();
// 根据协议进行匹配生成采集报文
for (MeterManageEntity meterManageEntity : meterManageEntities) {
// 重置采集参数
deviceCodeParamEntity.reset();
// 创建设备报文
String protocolType = String.valueOf(meterManageEntity.getProtocolType());
Protocol protocol = ProtocolFactory.matchProtocol(protocolType);
ProtocolStrategy strategy = ProtocolStrategyFactory.matchProtocolStrategy(protocolType);
if (strategy == null) {
continue;
}
protocol.setStrategy(strategy);
String sendStr = protocol.createOrder(meterManageEntity);
log.info("采集指令===> {}", sendStr);
deviceCodeParamEntity.setDeviceAddr(meterManageEntity.getMtCode());
deviceCodeParamEntity.setDeviceName(meterManageEntity.getMtName());
deviceCodeParamEntity.setDeviceType(String.valueOf(meterManageEntity.getMtType()));
deviceCodeParamEntity.setStrData(sendStr);
try {
GatewayManageEntity gatewayManageEntity = gatewayManageService.findById(meterManageEntity.getGatewayId());
if (gatewayManageEntity != null) {
deviceCodeParamEntity.setDataPort(String.valueOf(gatewayManageEntity.getPort()));
}
} catch (Exception e) {
log.error("查询网关信息失败: {}", e.getMessage());
}
try {
DeviceParamsEntity paramsEntity = deviceParamsService.findById(meterManageEntity.getParamId());
if (paramsEntity != null) {
deviceCodeParamEntity.setBaudRate(paramsEntity.getBaudRate());
deviceCodeParamEntity.setParity(paramsEntity.getParity());
}
} catch (Exception e) {
log.error("查询设备参数失败: {}", e.getMessage());
}
deviceCodeParamEntity.setBrand(meterManageEntity.getMtBrand());
deviceCodeParamEntity.setFunCode(meterManageEntity.getFuncCode());
deviceCodeParamEntity.setRegisterAddr(meterManageEntity.getRegisterAddr());
deviceCodeParamEntity.setRegisterName(meterManageEntity.getOtherName());
deviceCodeParamEntity.setDigit(meterManageEntity.getDigits());
deviceCodeParamEntity.setGrade(meterManageEntity.getGrade());
deviceCodeParamEntity.setDataValue(null); // 传入值(目前不需要)
deviceCodeParamEntity.setProjectId(projectId);
deviceCodeParamEntity.setCreateTime(new Date());
deviceCodeParamEntity.setMmId(meterManageEntity.getId());
deviceCodeParamEntity.setDataType(meterManageEntity.getDataType());
deviceCodeParamEntity.setProtocolType(meterManageEntity.getProtocolType());
deviceCodeParamEntityList.add(deviceCodeParamEntity.clone());
}
if (!deviceCodeParamEntityList.isEmpty()) {
insertDeviceCodeParamList(deviceCodeParamEntityList);
}
return deviceCodeParamEntityList;
}
}

4
user-service/src/main/java/com/mh/user/service/impl/ProjectInfoServiceImpl.java

@ -52,7 +52,7 @@ public class ProjectInfoServiceImpl implements ProjectInfoService {
@Override
public void update(ProjectInfoEntity projectInfoEntity) {
if (null != projectInfoEntity.getFile()) {
String fileToBase64 = FileUtils.convertFileToBase64(projectInfoEntity.getFile());
String fileToBase64 = FileUtils.reSizeImg(projectInfoEntity.getFile());
projectInfoEntity.setPicContent(fileToBase64);
projectInfoEntity.setPic(projectInfoEntity.getFile().getOriginalFilename());
}
@ -62,7 +62,7 @@ public class ProjectInfoServiceImpl implements ProjectInfoService {
@Override
public void save(ProjectInfoEntity projectInfoEntity) {
if (null != projectInfoEntity.getFile()) {
String fileToBase64 = FileUtils.convertFileToBase64(projectInfoEntity.getFile());
String fileToBase64 = FileUtils.reSizeImg(projectInfoEntity.getFile());
projectInfoEntity.setPicContent(fileToBase64);
projectInfoEntity.setPic(projectInfoEntity.getFile().getOriginalFilename());
}

2
user-service/src/main/java/com/mh/user/service/impl/SysDictServiceImpl.java

@ -106,6 +106,8 @@ public class SysDictServiceImpl implements SysDictService {
@Override
public void createDictDataCache() {
// 删除上次缓存
caffeineCache.invalidate("sys_dict");
List<SysDict> sysDictList = sysDictMapper.selectList(
new QueryWrapper<SysDict>().orderByDesc("create_time"));
// 把项目列表放到缓存中

20
user-service/src/main/java/com/mh/user/utils/SimpleWeather.java

@ -1,6 +1,7 @@
package com.mh.user.utils;
import com.alibaba.fastjson2.JSONObject;
import lombok.extern.slf4j.Slf4j;
import java.io.*;
import java.net.HttpURLConnection;
@ -10,6 +11,7 @@ import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
@Slf4j
public class SimpleWeather {
// 天气情况查询接口地址
public static String API_URL = "http://apis.juhe.cn/simpleWeather/query";
@ -35,16 +37,15 @@ public class SimpleWeather {
JSONObject jsonObject = JSONObject.parseObject(response);
int error_code = jsonObject.getIntValue("error_code");
if (error_code == 0) {
System.out.println("调用接口成功");
JSONObject result = jsonObject.getJSONObject("result");
JSONObject realtime = result.getJSONObject("realtime");
System.out.printf("城市:%s%n", result.getString("city"));
System.out.printf("天气:%s%n", realtime.getString("info"));
System.out.printf("温度:%s%n", realtime.getString("temperature"));
System.out.printf("湿度:%s%n", realtime.getString("humidity"));
System.out.printf("风向:%s%n", realtime.getString("direct"));
System.out.printf("风力:%s%n", realtime.getString("power"));
System.out.printf("空气质量:%s%n", realtime.getString("aqi"));
log.info("城市:{}", result.getString("city"));
log.info("天气:{}", realtime.getString("info"));
log.info("温度:{}", realtime.getString("temperature"));
log.info("湿度:{}", realtime.getString("humidity"));
log.info("风向:{}", realtime.getString("direct"));
log.info("风力:{}", realtime.getString("power"));
log.info("空气质量:{}", realtime.getString("aqi"));
map.put("city", result.getString("city"));// 城市
map.put("info", realtime.getString("info"));// 天气信息
@ -55,10 +56,11 @@ public class SimpleWeather {
map.put("aqi", realtime.getString("aqi"));// 空气质量
} else {
System.out.println("调用接口失败:" + jsonObject.getString("reason"));
log.info("调用接口失败:{}", jsonObject.getString("reason"));
}
} catch (Exception e) {
e.printStackTrace();
log.error("调用天气接口失败:", e);
}
return map;
}

76
user-service/src/test/java/com/mh/user/socket/BIOServer.java

@ -1,11 +1,16 @@
package com.mh.user.socket;
import com.mh.user.utils.SimpleWeather;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
@ -22,65 +27,18 @@ public class BIOServer {
private static ExecutorService threadPool = Executors.newCachedThreadPool();
public static void main(String[] args) throws Exception {
ServerSocket sc = new ServerSocket(9093);
System.out.println("服务器启动成功!");
while (!sc.isClosed()) {
Socket request = sc.accept(); // 阻塞
System.out.println("收到新连接:" + request.toString());
// 引用线程池
threadPool.execute(() -> {
try {
InputStream is = request.getInputStream(); // net+i/o
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"));
String msg;
while ((msg = reader.readLine()) != null) { // 没有数据会阻塞
if (msg.length() == 0) {
break;
}
System.out.println(msg);
}
System.out.println("收到数据,来自:" + request.toString());
// 响应http结果
// 响应结果
OutputStream outputStream = request.getOutputStream();
outputStream.write("HTTP/1.1 200 ok\r\n".getBytes());
outputStream.write("Content-Length: 40\r\n\r\n".getBytes());
outputStream.write("<button type=\\\"button\\\">Click Me!</button>".getBytes());
} catch (Exception e) {
// TODO: handle exception
} finally {
try {
request.close();
} catch (Exception e2) {
// TODO: handle exception
}
}
});
// try {
// InputStream is = request.getInputStream(); // net+i/o
// BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"));
// String msg;
// while ((msg = reader.readLine()) != null) { // 没有数据会阻塞
// if (msg.length() == 0) {
// break;
// }
// System.out.println(msg);
// }
// System.out.println("收到数据,来自:" + request.toString());
// } catch (Exception e) {
// // TODO: handle exception
// } finally {
// try {
// request.close();
// } catch (Exception e2) {
// // TODO: handle exception
// }
// }
try {
SimpleDateFormat sdf1=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date=new Date();
Map<String, Object> map= SimpleWeather.queryWeather("广州");
String curDate=sdf1.format(date);
String temperature=map.get("temperature").toString();
String humidity=map.get("humidity").toString();
System.out.println(curDate+","+temperature+"℃,"+humidity+"%");
} catch (Exception e) {
// e.printStackTrace();
System.out.println("调用获取环境温湿度接口失败!"+ e);
}
}
}
}

Loading…
Cancel
Save