Commit c3499af5246b869160d8e81b89e5f713584b2789
1 parent
33fed798
reactor:【IoT 物联网】消息处理时,异步进行时间相关的记录
Showing
13 changed files
with
105 additions
and
257 deletions
yudao-module-iot/yudao-module-iot-biz/src/main/java/cn/iocoder/yudao/module/iot/dal/redis/RedisKeyConstants.java
| @@ -22,7 +22,7 @@ public interface RedisKeyConstants { | @@ -22,7 +22,7 @@ public interface RedisKeyConstants { | ||
| 22 | /** | 22 | /** |
| 23 | * 设备的最后上报时间,采用 ZSET 结构 | 23 | * 设备的最后上报时间,采用 ZSET 结构 |
| 24 | * | 24 | * |
| 25 | - * KEY 格式:{productKey},${deviceName} | 25 | + * KEY 格式:{deviceId} |
| 26 | * SCORE:上报时间 | 26 | * SCORE:上报时间 |
| 27 | */ | 27 | */ |
| 28 | String DEVICE_REPORT_TIMES = "iot:device_report_times"; | 28 | String DEVICE_REPORT_TIMES = "iot:device_report_times"; |
| @@ -39,7 +39,7 @@ public interface RedisKeyConstants { | @@ -39,7 +39,7 @@ public interface RedisKeyConstants { | ||
| 39 | /** | 39 | /** |
| 40 | * 设备信息的数据缓存,使用 Spring Cache 操作(忽略租户) | 40 | * 设备信息的数据缓存,使用 Spring Cache 操作(忽略租户) |
| 41 | * | 41 | * |
| 42 | - * KEY 格式 1:device_${id} | 42 | + * KEY 格式 1:device_${deviceId} |
| 43 | * KEY 格式 2:device_${productKey}_${deviceName} | 43 | * KEY 格式 2:device_${productKey}_${deviceName} |
| 44 | * VALUE 数据类型:String(JSON) | 44 | * VALUE 数据类型:String(JSON) |
| 45 | */ | 45 | */ |
| @@ -48,7 +48,7 @@ public interface RedisKeyConstants { | @@ -48,7 +48,7 @@ public interface RedisKeyConstants { | ||
| 48 | /** | 48 | /** |
| 49 | * 产品信息的数据缓存,使用 Spring Cache 操作(忽略租户) | 49 | * 产品信息的数据缓存,使用 Spring Cache 操作(忽略租户) |
| 50 | * | 50 | * |
| 51 | - * KEY 格式:product_${id} | 51 | + * KEY 格式:product_${productId} |
| 52 | * VALUE 数据类型:String(JSON) | 52 | * VALUE 数据类型:String(JSON) |
| 53 | */ | 53 | */ |
| 54 | String PRODUCT = "iot:product"; | 54 | String PRODUCT = "iot:product"; |
yudao-module-iot/yudao-module-iot-biz/src/main/java/cn/iocoder/yudao/module/iot/dal/redis/device/DeviceReportTimeRedisDAO.java
| 1 | package cn.iocoder.yudao.module.iot.dal.redis.device; | 1 | package cn.iocoder.yudao.module.iot.dal.redis.device; |
| 2 | 2 | ||
| 3 | import cn.hutool.core.date.LocalDateTimeUtil; | 3 | import cn.hutool.core.date.LocalDateTimeUtil; |
| 4 | -import cn.hutool.core.util.StrUtil; | ||
| 5 | -import cn.iocoder.yudao.framework.common.util.collection.CollectionUtils; | ||
| 6 | import cn.iocoder.yudao.module.iot.dal.redis.RedisKeyConstants; | 4 | import cn.iocoder.yudao.module.iot.dal.redis.RedisKeyConstants; |
| 7 | import jakarta.annotation.Resource; | 5 | import jakarta.annotation.Resource; |
| 8 | import org.springframework.data.redis.core.StringRedisTemplate; | 6 | import org.springframework.data.redis.core.StringRedisTemplate; |
| @@ -11,6 +9,8 @@ import org.springframework.stereotype.Repository; | @@ -11,6 +9,8 @@ import org.springframework.stereotype.Repository; | ||
| 11 | import java.time.LocalDateTime; | 9 | import java.time.LocalDateTime; |
| 12 | import java.util.Set; | 10 | import java.util.Set; |
| 13 | 11 | ||
| 12 | +import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertSet; | ||
| 13 | + | ||
| 14 | /** | 14 | /** |
| 15 | * 设备的最后上报时间的 Redis DAO | 15 | * 设备的最后上报时间的 Redis DAO |
| 16 | * | 16 | * |
| @@ -22,17 +22,15 @@ public class DeviceReportTimeRedisDAO { | @@ -22,17 +22,15 @@ public class DeviceReportTimeRedisDAO { | ||
| 22 | @Resource | 22 | @Resource |
| 23 | private StringRedisTemplate stringRedisTemplate; | 23 | private StringRedisTemplate stringRedisTemplate; |
| 24 | 24 | ||
| 25 | - public void update(String productKey, String deviceName, LocalDateTime reportTime) { | ||
| 26 | - String value = productKey + StrUtil.COMMA + deviceName; // 使用 , 分隔 | ||
| 27 | - stringRedisTemplate.opsForZSet().add(RedisKeyConstants.DEVICE_REPORT_TIMES, value, | 25 | + public void update(Long deviceId, LocalDateTime reportTime) { |
| 26 | + stringRedisTemplate.opsForZSet().add(RedisKeyConstants.DEVICE_REPORT_TIMES, String.valueOf(deviceId), | ||
| 28 | LocalDateTimeUtil.toEpochMilli(reportTime)); | 27 | LocalDateTimeUtil.toEpochMilli(reportTime)); |
| 29 | } | 28 | } |
| 30 | 29 | ||
| 31 | - public Set<String[]> range(LocalDateTime maxReportTime) { | ||
| 32 | - Set<String> values = stringRedisTemplate.opsForZSet().rangeByScore(RedisKeyConstants.DEVICE_REPORT_TIMES, 0, | ||
| 33 | - LocalDateTimeUtil.toEpochMilli(maxReportTime)); | ||
| 34 | - return CollectionUtils.convertSet(values, | ||
| 35 | - value -> value.split(StrUtil.COMMA)); // 使用, 分隔 | 30 | + public Set<Long> range(LocalDateTime maxReportTime) { |
| 31 | + Set<String> values = stringRedisTemplate.opsForZSet().rangeByScore(RedisKeyConstants.DEVICE_REPORT_TIMES, | ||
| 32 | + 0, LocalDateTimeUtil.toEpochMilli(maxReportTime)); | ||
| 33 | + return convertSet(values, Long::parseLong); | ||
| 36 | } | 34 | } |
| 37 | 35 | ||
| 38 | } | 36 | } |
yudao-module-iot/yudao-module-iot-biz/src/main/java/cn/iocoder/yudao/module/iot/dal/redis/device/DeviceServerIdRedisDAO.java
| 1 | package cn.iocoder.yudao.module.iot.dal.redis.device; | 1 | package cn.iocoder.yudao.module.iot.dal.redis.device; |
| 2 | 2 | ||
| 3 | -import cn.hutool.core.util.StrUtil; | ||
| 4 | import cn.iocoder.yudao.module.iot.dal.redis.RedisKeyConstants; | 3 | import cn.iocoder.yudao.module.iot.dal.redis.RedisKeyConstants; |
| 5 | import jakarta.annotation.Resource; | 4 | import jakarta.annotation.Resource; |
| 6 | import org.springframework.data.redis.core.StringRedisTemplate; | 5 | import org.springframework.data.redis.core.StringRedisTemplate; |
| @@ -17,40 +16,15 @@ public class DeviceServerIdRedisDAO { | @@ -17,40 +16,15 @@ public class DeviceServerIdRedisDAO { | ||
| 17 | @Resource | 16 | @Resource |
| 18 | private StringRedisTemplate stringRedisTemplate; | 17 | private StringRedisTemplate stringRedisTemplate; |
| 19 | 18 | ||
| 20 | - /** | ||
| 21 | - * 更新设备关联的网关 serverId | ||
| 22 | - * | ||
| 23 | - * @param productKey 产品标识 | ||
| 24 | - * @param deviceName 设备名称 | ||
| 25 | - * @param serverId 网关 serverId | ||
| 26 | - */ | ||
| 27 | - public void update(String productKey, String deviceName, String serverId) { | ||
| 28 | - String hashKey = buildHashKey(productKey, deviceName); | ||
| 29 | - stringRedisTemplate.opsForHash().put(RedisKeyConstants.DEVICE_SERVER_ID, hashKey, serverId); | 19 | + public void update(Long deviceId, String serverId) { |
| 20 | + stringRedisTemplate.opsForHash().put(RedisKeyConstants.DEVICE_SERVER_ID, | ||
| 21 | + String.valueOf(deviceId), serverId); | ||
| 30 | } | 22 | } |
| 31 | 23 | ||
| 32 | - /** | ||
| 33 | - * 获得设备关联的网关 serverId | ||
| 34 | - * | ||
| 35 | - * @param productKey 产品标识 | ||
| 36 | - * @param deviceName 设备名称 | ||
| 37 | - * @return 网关 serverId | ||
| 38 | - */ | ||
| 39 | - public String get(String productKey, String deviceName) { | ||
| 40 | - String hashKey = buildHashKey(productKey, deviceName); | ||
| 41 | - Object value = stringRedisTemplate.opsForHash().get(RedisKeyConstants.DEVICE_SERVER_ID, hashKey); | 24 | + public String get(Long deviceId) { |
| 25 | + Object value = stringRedisTemplate.opsForHash().get(RedisKeyConstants.DEVICE_SERVER_ID, | ||
| 26 | + String.valueOf(deviceId)); | ||
| 42 | return value != null ? (String) value : null; | 27 | return value != null ? (String) value : null; |
| 43 | } | 28 | } |
| 44 | 29 | ||
| 45 | - /** | ||
| 46 | - * 构建 HASH KEY | ||
| 47 | - * | ||
| 48 | - * @param productKey 产品标识 | ||
| 49 | - * @param deviceName 设备名称 | ||
| 50 | - * @return HASH KEY | ||
| 51 | - */ | ||
| 52 | - private String buildHashKey(String productKey, String deviceName) { | ||
| 53 | - return productKey + StrUtil.COMMA + deviceName; | ||
| 54 | - } | ||
| 55 | - | ||
| 56 | } | 30 | } |
| 57 | \ No newline at end of file | 31 | \ No newline at end of file |
yudao-module-iot/yudao-module-iot-biz/src/main/java/cn/iocoder/yudao/module/iot/job/device/IotDeviceOfflineCheckJob.java
| 1 | package cn.iocoder.yudao.module.iot.job.device; | 1 | package cn.iocoder.yudao.module.iot.job.device; |
| 2 | 2 | ||
| 3 | import cn.hutool.core.collection.CollUtil; | 3 | import cn.hutool.core.collection.CollUtil; |
| 4 | -import cn.hutool.core.util.StrUtil; | ||
| 5 | import cn.iocoder.yudao.framework.common.util.json.JsonUtils; | 4 | import cn.iocoder.yudao.framework.common.util.json.JsonUtils; |
| 6 | import cn.iocoder.yudao.framework.quartz.core.handler.JobHandler; | 5 | import cn.iocoder.yudao.framework.quartz.core.handler.JobHandler; |
| 7 | import cn.iocoder.yudao.framework.tenant.core.job.TenantJob; | 6 | import cn.iocoder.yudao.framework.tenant.core.job.TenantJob; |
| @@ -20,8 +19,6 @@ import java.util.Collections; | @@ -20,8 +19,6 @@ import java.util.Collections; | ||
| 20 | import java.util.List; | 19 | import java.util.List; |
| 21 | import java.util.Set; | 20 | import java.util.Set; |
| 22 | 21 | ||
| 23 | -import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertSet; | ||
| 24 | - | ||
| 25 | /** | 22 | /** |
| 26 | * IoT 设备离线检查 Job | 23 | * IoT 设备离线检查 Job |
| 27 | * | 24 | * |
| @@ -46,7 +43,6 @@ public class IotDeviceOfflineCheckJob implements JobHandler { | @@ -46,7 +43,6 @@ public class IotDeviceOfflineCheckJob implements JobHandler { | ||
| 46 | @Resource | 43 | @Resource |
| 47 | private IotDeviceMessageService deviceMessageService; | 44 | private IotDeviceMessageService deviceMessageService; |
| 48 | 45 | ||
| 49 | - // TODO @芋艿:需要重构下; | ||
| 50 | @Override | 46 | @Override |
| 51 | @TenantJob | 47 | @TenantJob |
| 52 | public String execute(String param) { | 48 | public String execute(String param) { |
| @@ -56,22 +52,20 @@ public class IotDeviceOfflineCheckJob implements JobHandler { | @@ -56,22 +52,20 @@ public class IotDeviceOfflineCheckJob implements JobHandler { | ||
| 56 | return JsonUtils.toJsonString(Collections.emptyList()); | 52 | return JsonUtils.toJsonString(Collections.emptyList()); |
| 57 | } | 53 | } |
| 58 | // 1.2 获取超时的设备集合 | 54 | // 1.2 获取超时的设备集合 |
| 59 | - Set<String[]> timeoutDevices = devicePropertyService.getProductKeyDeviceNameListByReportTime( | 55 | + Set<Long> timeoutDeviceIds = devicePropertyService.getDeviceIdListByReportTime( |
| 60 | LocalDateTime.now().minus(OFFLINE_TIMEOUT)); | 56 | LocalDateTime.now().minus(OFFLINE_TIMEOUT)); |
| 61 | - Set<String> timeoutDevices2 = convertSet(timeoutDevices, item -> item[0] + StrUtil.COMMA + item[1]); | ||
| 62 | 57 | ||
| 63 | // 2. 下线设备 | 58 | // 2. 下线设备 |
| 64 | - List<String[]> offlineDeviceKeys = CollUtil.newArrayList(); | 59 | + List<String[]> offlineDevices = CollUtil.newArrayList(); |
| 65 | for (IotDeviceDO device : devices) { | 60 | for (IotDeviceDO device : devices) { |
| 66 | - String timeoutDeviceKey = device.getProductKey() + StrUtil.COMMA + device.getDeviceName(); | ||
| 67 | - if (!timeoutDevices2.contains(timeoutDeviceKey)) { | 61 | + if (!timeoutDeviceIds.contains(device.getId())) { |
| 68 | continue; | 62 | continue; |
| 69 | } | 63 | } |
| 70 | - offlineDeviceKeys.add(new String[]{device.getProductKey(), device.getDeviceName()}); | 64 | + offlineDevices.add(new String[]{device.getProductKey(), device.getDeviceName()}); |
| 71 | // 为什么不直接更新状态呢?因为通过 IotDeviceMessage 可以经过一系列的处理,例如说记录日志等等 | 65 | // 为什么不直接更新状态呢?因为通过 IotDeviceMessage 可以经过一系列的处理,例如说记录日志等等 |
| 72 | deviceMessageService.sendDeviceMessage(IotDeviceMessage.buildStateOffline().setDeviceId(device.getId())); | 66 | deviceMessageService.sendDeviceMessage(IotDeviceMessage.buildStateOffline().setDeviceId(device.getId())); |
| 73 | } | 67 | } |
| 74 | - return JsonUtils.toJsonString(offlineDeviceKeys); | 68 | + return JsonUtils.toJsonString(offlineDevices); |
| 75 | } | 69 | } |
| 76 | 70 | ||
| 77 | } | 71 | } |
yudao-module-iot/yudao-module-iot-biz/src/main/java/cn/iocoder/yudao/module/iot/mq/consumer/device/IotDeviceMessageSubscriber.java
| @@ -65,9 +65,9 @@ public class IotDeviceMessageSubscriber implements IotMessageSubscriber<IotDevic | @@ -65,9 +65,9 @@ public class IotDeviceMessageSubscriber implements IotMessageSubscriber<IotDevic | ||
| 65 | TenantUtils.execute(message.getTenantId(), () -> { | 65 | TenantUtils.execute(message.getTenantId(), () -> { |
| 66 | // 1.1 更新设备的最后时间 | 66 | // 1.1 更新设备的最后时间 |
| 67 | IotDeviceDO device = deviceService.validateDeviceExistsFromCache(message.getDeviceId()); | 67 | IotDeviceDO device = deviceService.validateDeviceExistsFromCache(message.getDeviceId()); |
| 68 | - devicePropertyService.updateDeviceReportTime(device.getProductKey(), device.getDeviceName(), LocalDateTime.now()); | 68 | + devicePropertyService.updateDeviceReportTimeAsync(device.getId(), LocalDateTime.now()); |
| 69 | // 1.2 更新设备的连接 server | 69 | // 1.2 更新设备的连接 server |
| 70 | - devicePropertyService.updateDeviceServerId(device.getProductKey(), device.getDeviceName(), message.getServerId()); | 70 | + devicePropertyService.updateDeviceServerIdAsync(device.getId(), message.getServerId()); |
| 71 | 71 | ||
| 72 | // 2. 未上线的设备,强制上线 | 72 | // 2. 未上线的设备,强制上线 |
| 73 | forceDeviceOnline(message, device); | 73 | forceDeviceOnline(message, device); |
yudao-module-iot/yudao-module-iot-biz/src/main/java/cn/iocoder/yudao/module/iot/service/device/message/IotDeviceMessageServiceImpl.java
| 1 | package cn.iocoder.yudao.module.iot.service.device.message; | 1 | package cn.iocoder.yudao.module.iot.service.device.message; |
| 2 | 2 | ||
| 3 | import cn.hutool.core.util.StrUtil; | 3 | import cn.hutool.core.util.StrUtil; |
| 4 | +import cn.hutool.extra.spring.SpringUtil; | ||
| 4 | import cn.iocoder.yudao.framework.common.exception.ServiceException; | 5 | import cn.iocoder.yudao.framework.common.exception.ServiceException; |
| 6 | +import cn.iocoder.yudao.framework.common.util.json.JsonUtils; | ||
| 5 | import cn.iocoder.yudao.framework.common.util.object.BeanUtils; | 7 | import cn.iocoder.yudao.framework.common.util.object.BeanUtils; |
| 6 | import cn.iocoder.yudao.module.iot.core.enums.IotDeviceMessageMethodEnum; | 8 | import cn.iocoder.yudao.module.iot.core.enums.IotDeviceMessageMethodEnum; |
| 7 | import cn.iocoder.yudao.module.iot.core.enums.IotDeviceStateEnum; | 9 | import cn.iocoder.yudao.module.iot.core.enums.IotDeviceStateEnum; |
| @@ -16,6 +18,7 @@ import cn.iocoder.yudao.module.iot.service.device.property.IotDevicePropertyServ | @@ -16,6 +18,7 @@ import cn.iocoder.yudao.module.iot.service.device.property.IotDevicePropertyServ | ||
| 16 | import com.google.common.base.Objects; | 18 | import com.google.common.base.Objects; |
| 17 | import jakarta.annotation.Resource; | 19 | import jakarta.annotation.Resource; |
| 18 | import lombok.extern.slf4j.Slf4j; | 20 | import lombok.extern.slf4j.Slf4j; |
| 21 | +import org.springframework.scheduling.annotation.Async; | ||
| 19 | import org.springframework.stereotype.Service; | 22 | import org.springframework.stereotype.Service; |
| 20 | import org.springframework.validation.annotation.Validated; | 23 | import org.springframework.validation.annotation.Validated; |
| 21 | 24 | ||
| @@ -56,10 +59,16 @@ public class IotDeviceMessageServiceImpl implements IotDeviceMessageService { | @@ -56,10 +59,16 @@ public class IotDeviceMessageServiceImpl implements IotDeviceMessageService { | ||
| 56 | log.info("[defineDeviceMessageStable][设备消息超级表不存在,创建成功]"); | 59 | log.info("[defineDeviceMessageStable][设备消息超级表不存在,创建成功]"); |
| 57 | } | 60 | } |
| 58 | 61 | ||
| 59 | - // TODO @芋艿:要不要异步记录; | ||
| 60 | - private void createDeviceLog(IotDeviceMessage message) { | 62 | + @Async |
| 63 | + void createDeviceLogAsync(IotDeviceMessage message) { | ||
| 61 | IotDeviceMessageDO messageDO = BeanUtils.toBean(message, IotDeviceMessageDO.class) | 64 | IotDeviceMessageDO messageDO = BeanUtils.toBean(message, IotDeviceMessageDO.class) |
| 62 | .setUpstream(IotDeviceMessageUtils.isUpstreamMessage(message)); | 65 | .setUpstream(IotDeviceMessageUtils.isUpstreamMessage(message)); |
| 66 | + if (message.getParams() != null) { | ||
| 67 | + messageDO.setParams(JsonUtils.toJsonString(messageDO.getData())); | ||
| 68 | + } | ||
| 69 | + if (messageDO.getData() != null) { | ||
| 70 | + messageDO.setData(JsonUtils.toJsonString(messageDO.getData())); | ||
| 71 | + } | ||
| 63 | deviceLogMapper.insert(messageDO); | 72 | deviceLogMapper.insert(messageDO); |
| 64 | } | 73 | } |
| 65 | 74 | ||
| @@ -72,6 +81,10 @@ public class IotDeviceMessageServiceImpl implements IotDeviceMessageService { | @@ -72,6 +81,10 @@ public class IotDeviceMessageServiceImpl implements IotDeviceMessageService { | ||
| 72 | // TODO @芋艿:针对连接网关的设备,是不是 productKey、deviceName 需要调整下; | 81 | // TODO @芋艿:针对连接网关的设备,是不是 productKey、deviceName 需要调整下; |
| 73 | @Override | 82 | @Override |
| 74 | public IotDeviceMessage sendDeviceMessage(IotDeviceMessage message, IotDeviceDO device) { | 83 | public IotDeviceMessage sendDeviceMessage(IotDeviceMessage message, IotDeviceDO device) { |
| 84 | + return sendDeviceMessage(message, device, null); | ||
| 85 | + } | ||
| 86 | + | ||
| 87 | + private IotDeviceMessage sendDeviceMessage(IotDeviceMessage message, IotDeviceDO device, String serverId) { | ||
| 75 | // 1. 补充信息 | 88 | // 1. 补充信息 |
| 76 | appendDeviceMessage(message, device); | 89 | appendDeviceMessage(message, device); |
| 77 | 90 | ||
| @@ -84,31 +97,31 @@ public class IotDeviceMessageServiceImpl implements IotDeviceMessageService { | @@ -84,31 +97,31 @@ public class IotDeviceMessageServiceImpl implements IotDeviceMessageService { | ||
| 84 | 97 | ||
| 85 | // 2.2 情况二:发送下行消息 | 98 | // 2.2 情况二:发送下行消息 |
| 86 | // 如果是下行消息,需要校验 serverId 存在 | 99 | // 如果是下行消息,需要校验 serverId 存在 |
| 87 | - String serverId = devicePropertyService.getDeviceServerId(device.getProductKey(), device.getDeviceName()); | ||
| 88 | if (StrUtil.isEmpty(serverId)) { | 100 | if (StrUtil.isEmpty(serverId)) { |
| 89 | - throw exception(DEVICE_DOWNSTREAM_FAILED_SERVER_ID_NULL); | 101 | + serverId = devicePropertyService.getDeviceServerId(device.getId()); |
| 102 | + if (StrUtil.isEmpty(serverId)) { | ||
| 103 | + throw exception(DEVICE_DOWNSTREAM_FAILED_SERVER_ID_NULL); | ||
| 104 | + } | ||
| 90 | } | 105 | } |
| 91 | deviceMessageProducer.sendDeviceMessageToGateway(serverId, message); | 106 | deviceMessageProducer.sendDeviceMessageToGateway(serverId, message); |
| 92 | // 特殊:记录消息日志。原因:上行消息,消费时,已经会记录;下行消息,因为消费在 Gateway 端,所以需要在这里记录 | 107 | // 特殊:记录消息日志。原因:上行消息,消费时,已经会记录;下行消息,因为消费在 Gateway 端,所以需要在这里记录 |
| 93 | - createDeviceLog(message); | 108 | + getSelf().createDeviceLogAsync(message); |
| 94 | return message; | 109 | return message; |
| 95 | } | 110 | } |
| 96 | 111 | ||
| 97 | /** | 112 | /** |
| 98 | * 补充消息的后端字段 | 113 | * 补充消息的后端字段 |
| 99 | * | 114 | * |
| 100 | - * @param message 消息 | ||
| 101 | - * @param device 设备信息 | ||
| 102 | - * @return 消息 | 115 | + * @param message 消息 |
| 116 | + * @param device 设备信息 | ||
| 103 | */ | 117 | */ |
| 104 | - private IotDeviceMessage appendDeviceMessage(IotDeviceMessage message, IotDeviceDO device) { | 118 | + private void appendDeviceMessage(IotDeviceMessage message, IotDeviceDO device) { |
| 105 | message.setId(IotDeviceMessageUtils.generateMessageId()).setReportTime(LocalDateTime.now()) | 119 | message.setId(IotDeviceMessageUtils.generateMessageId()).setReportTime(LocalDateTime.now()) |
| 106 | .setDeviceId(device.getId()).setTenantId(device.getTenantId()); | 120 | .setDeviceId(device.getId()).setTenantId(device.getTenantId()); |
| 107 | // 特殊:如果设备没有指定 requestId,则使用 messageId | 121 | // 特殊:如果设备没有指定 requestId,则使用 messageId |
| 108 | if (StrUtil.isEmpty(message.getRequestId())) { | 122 | if (StrUtil.isEmpty(message.getRequestId())) { |
| 109 | message.setRequestId(message.getId()); | 123 | message.setRequestId(message.getId()); |
| 110 | } | 124 | } |
| 111 | - return message; | ||
| 112 | } | 125 | } |
| 113 | 126 | ||
| 114 | @Override | 127 | @Override |
| @@ -120,26 +133,33 @@ public class IotDeviceMessageServiceImpl implements IotDeviceMessageService { | @@ -120,26 +133,33 @@ public class IotDeviceMessageServiceImpl implements IotDeviceMessageService { | ||
| 120 | replyData = handleUpstreamDeviceMessage0(message, device); | 133 | replyData = handleUpstreamDeviceMessage0(message, device); |
| 121 | } catch (ServiceException ex) { | 134 | } catch (ServiceException ex) { |
| 122 | serviceException = ex; | 135 | serviceException = ex; |
| 123 | - log.warn("[onMessage][message({}) 业务异常]", message, serviceException); | 136 | + log.warn("[handleUpstreamDeviceMessage][message({}) 业务异常]", message, serviceException); |
| 124 | } catch (Exception ex) { | 137 | } catch (Exception ex) { |
| 125 | - log.error("[onMessage][message({}) 发生异常]", message, ex); | 138 | + log.error("[handleUpstreamDeviceMessage][message({}) 发生异常]", message, ex); |
| 126 | throw ex; | 139 | throw ex; |
| 127 | } | 140 | } |
| 128 | 141 | ||
| 129 | // 2. 记录消息 | 142 | // 2. 记录消息 |
| 130 | - createDeviceLog(message); | 143 | + getSelf().createDeviceLogAsync(message); |
| 131 | 144 | ||
| 132 | // 3. 回复消息。前提:非 _reply 消息,并且非禁用回复的消息 | 145 | // 3. 回复消息。前提:非 _reply 消息,并且非禁用回复的消息 |
| 133 | if (IotDeviceMessageUtils.isReplyMessage(message) | 146 | if (IotDeviceMessageUtils.isReplyMessage(message) |
| 134 | - || IotDeviceMessageMethodEnum.isReplyDisabled(message.getMethod())) { | 147 | + || IotDeviceMessageMethodEnum.isReplyDisabled(message.getMethod()) |
| 148 | + || StrUtil.isEmpty(message.getServerId())) { | ||
| 135 | return; | 149 | return; |
| 136 | } | 150 | } |
| 137 | - sendDeviceMessage(IotDeviceMessage.replyOf(message.getRequestId(), message.getMethod(), replyData, | ||
| 138 | - serviceException != null ? serviceException.getCode() : null, | ||
| 139 | - serviceException != null ? serviceException.getMessage() : null)); | 151 | + try { |
| 152 | + IotDeviceMessage replyMessage = IotDeviceMessage.replyOf(message.getRequestId(), message.getMethod(), replyData, | ||
| 153 | + serviceException != null ? serviceException.getCode() : null, | ||
| 154 | + serviceException != null ? serviceException.getMessage() : null); | ||
| 155 | + sendDeviceMessage(replyMessage, device, message.getServerId()); | ||
| 156 | + } catch (Exception ex) { | ||
| 157 | + log.error("[handleUpstreamDeviceMessage][message({}) 回复消息失败]", message, ex); | ||
| 158 | + } | ||
| 140 | } | 159 | } |
| 141 | 160 | ||
| 142 | // TODO @芋艿:可优化:未来逻辑复杂后,可以独立拆除 Processor 处理器 | 161 | // TODO @芋艿:可优化:未来逻辑复杂后,可以独立拆除 Processor 处理器 |
| 162 | + @SuppressWarnings("SameReturnValue") | ||
| 143 | private Object handleUpstreamDeviceMessage0(IotDeviceMessage message, IotDeviceDO device) { | 163 | private Object handleUpstreamDeviceMessage0(IotDeviceMessage message, IotDeviceDO device) { |
| 144 | // 设备上线 | 164 | // 设备上线 |
| 145 | if (Objects.equal(message.getMethod(), IotDeviceMessageMethodEnum.STATE_ONLINE.getMethod())) { | 165 | if (Objects.equal(message.getMethod(), IotDeviceMessageMethodEnum.STATE_ONLINE.getMethod())) { |
| @@ -164,4 +184,8 @@ public class IotDeviceMessageServiceImpl implements IotDeviceMessageService { | @@ -164,4 +184,8 @@ public class IotDeviceMessageServiceImpl implements IotDeviceMessageService { | ||
| 164 | return null; | 184 | return null; |
| 165 | } | 185 | } |
| 166 | 186 | ||
| 187 | + private IotDeviceMessageServiceImpl getSelf() { | ||
| 188 | + return SpringUtil.getBean(getClass()); | ||
| 189 | + } | ||
| 190 | + | ||
| 167 | } | 191 | } |
yudao-module-iot/yudao-module-iot-biz/src/main/java/cn/iocoder/yudao/module/iot/service/device/property/IotDevicePropertyService.java
| @@ -55,38 +55,35 @@ public interface IotDevicePropertyService { | @@ -55,38 +55,35 @@ public interface IotDevicePropertyService { | ||
| 55 | // ========== 设备时间相关操作 ========== | 55 | // ========== 设备时间相关操作 ========== |
| 56 | 56 | ||
| 57 | /** | 57 | /** |
| 58 | - * 获得最后上报时间小于指定时间的设备标识 | 58 | + * 获得最后上报时间小于指定时间的设备编号集合 |
| 59 | * | 59 | * |
| 60 | * @param maxReportTime 最大上报时间 | 60 | * @param maxReportTime 最大上报时间 |
| 61 | - * @return [productKey, deviceName] 列表 | 61 | + * @return 设备编号集合 |
| 62 | */ | 62 | */ |
| 63 | - Set<String[]> getProductKeyDeviceNameListByReportTime(LocalDateTime maxReportTime); | 63 | + Set<Long> getDeviceIdListByReportTime(LocalDateTime maxReportTime); |
| 64 | 64 | ||
| 65 | /** | 65 | /** |
| 66 | * 更新设备上报时间 | 66 | * 更新设备上报时间 |
| 67 | * | 67 | * |
| 68 | - * @param productKey 产品标识 | ||
| 69 | - * @param deviceName 设备名称 | 68 | + * @param id 设备编号 |
| 70 | * @param reportTime 上报时间 | 69 | * @param reportTime 上报时间 |
| 71 | */ | 70 | */ |
| 72 | - void updateDeviceReportTime(String productKey, String deviceName, LocalDateTime reportTime); | 71 | + void updateDeviceReportTimeAsync(Long id, LocalDateTime reportTime); |
| 73 | 72 | ||
| 74 | /** | 73 | /** |
| 75 | - * 更新设备关联的网关 serverId | 74 | + * 更新设备关联的网关服务 serverId |
| 76 | * | 75 | * |
| 77 | - * @param productKey 产品标识 | ||
| 78 | - * @param deviceName 设备名称 | 76 | + * @param id 设备编号 |
| 79 | * @param serverId 网关 serverId | 77 | * @param serverId 网关 serverId |
| 80 | */ | 78 | */ |
| 81 | - void updateDeviceServerId(String productKey, String deviceName, String serverId); | 79 | + void updateDeviceServerIdAsync(Long id, String serverId); |
| 82 | 80 | ||
| 83 | /** | 81 | /** |
| 84 | - * 获得设备关联的网关 serverId | 82 | + * 获得设备关联的网关服务 serverId |
| 85 | * | 83 | * |
| 86 | - * @param productKey 产品标识 | ||
| 87 | - * @param deviceName 设备名称 | 84 | + * @param id 设备编号 |
| 88 | * @return 网关 serverId | 85 | * @return 网关 serverId |
| 89 | */ | 86 | */ |
| 90 | - String getDeviceServerId(String productKey, String deviceName); | 87 | + String getDeviceServerId(Long id); |
| 91 | 88 | ||
| 92 | } | 89 | } |
| 93 | \ No newline at end of file | 90 | \ No newline at end of file |
yudao-module-iot/yudao-module-iot-biz/src/main/java/cn/iocoder/yudao/module/iot/service/device/property/IotDevicePropertyServiceImpl.java
| @@ -27,6 +27,7 @@ import com.baomidou.mybatisplus.core.metadata.IPage; | @@ -27,6 +27,7 @@ import com.baomidou.mybatisplus.core.metadata.IPage; | ||
| 27 | import com.baomidou.mybatisplus.extension.plugins.pagination.Page; | 27 | import com.baomidou.mybatisplus.extension.plugins.pagination.Page; |
| 28 | import jakarta.annotation.Resource; | 28 | import jakarta.annotation.Resource; |
| 29 | import lombok.extern.slf4j.Slf4j; | 29 | import lombok.extern.slf4j.Slf4j; |
| 30 | +import org.springframework.scheduling.annotation.Async; | ||
| 30 | import org.springframework.stereotype.Service; | 31 | import org.springframework.stereotype.Service; |
| 31 | 32 | ||
| 32 | import java.time.LocalDateTime; | 33 | import java.time.LocalDateTime; |
| @@ -183,26 +184,27 @@ public class IotDevicePropertyServiceImpl implements IotDevicePropertyService { | @@ -183,26 +184,27 @@ public class IotDevicePropertyServiceImpl implements IotDevicePropertyService { | ||
| 183 | // ========== 设备时间相关操作 ========== | 184 | // ========== 设备时间相关操作 ========== |
| 184 | 185 | ||
| 185 | @Override | 186 | @Override |
| 186 | - public Set<String[]> getProductKeyDeviceNameListByReportTime(LocalDateTime maxReportTime) { | 187 | + public Set<Long> getDeviceIdListByReportTime(LocalDateTime maxReportTime) { |
| 187 | return deviceReportTimeRedisDAO.range(maxReportTime); | 188 | return deviceReportTimeRedisDAO.range(maxReportTime); |
| 188 | } | 189 | } |
| 189 | 190 | ||
| 190 | @Override | 191 | @Override |
| 191 | - public void updateDeviceReportTime(String productKey, String deviceName, LocalDateTime reportTime) { | ||
| 192 | - deviceReportTimeRedisDAO.update(productKey, deviceName, reportTime); | 192 | + @Async |
| 193 | + public void updateDeviceReportTimeAsync(Long id, LocalDateTime reportTime) { | ||
| 194 | + deviceReportTimeRedisDAO.update(id, reportTime); | ||
| 193 | } | 195 | } |
| 194 | 196 | ||
| 195 | @Override | 197 | @Override |
| 196 | - public void updateDeviceServerId(String productKey, String deviceName, String serverId) { | 198 | + public void updateDeviceServerIdAsync(Long id, String serverId) { |
| 197 | if (StrUtil.isEmpty(serverId)) { | 199 | if (StrUtil.isEmpty(serverId)) { |
| 198 | return; | 200 | return; |
| 199 | } | 201 | } |
| 200 | - deviceServerIdRedisDAO.update(productKey, deviceName, serverId); | 202 | + deviceServerIdRedisDAO.update(id, serverId); |
| 201 | } | 203 | } |
| 202 | 204 | ||
| 203 | @Override | 205 | @Override |
| 204 | - public String getDeviceServerId(String productKey, String deviceName) { | ||
| 205 | - return deviceServerIdRedisDAO.get(productKey, deviceName); | 206 | + public String getDeviceServerId(Long id) { |
| 207 | + return deviceServerIdRedisDAO.get(id); | ||
| 206 | } | 208 | } |
| 207 | 209 | ||
| 208 | } | 210 | } |
| 209 | \ No newline at end of file | 211 | \ No newline at end of file |
yudao-module-iot/yudao-module-iot-biz/src/main/resources/mapper/device/IotDeviceMessageMapper.xml
| @@ -12,11 +12,13 @@ | @@ -12,11 +12,13 @@ | ||
| 12 | tenant_id BIGINT, | 12 | tenant_id BIGINT, |
| 13 | server_id NCHAR(50), | 13 | server_id NCHAR(50), |
| 14 | upstream BOOL, | 14 | upstream BOOL, |
| 15 | + reply BOOL, | ||
| 15 | request_id NCHAR(50), | 16 | request_id NCHAR(50), |
| 16 | method NCHAR(100), | 17 | method NCHAR(100), |
| 17 | params NCHAR(2048), | 18 | params NCHAR(2048), |
| 18 | data NCHAR(2048), | 19 | data NCHAR(2048), |
| 19 | - code INT | 20 | + code INT, |
| 21 | + msg NCHAR(256) | ||
| 20 | ) TAGS ( | 22 | ) TAGS ( |
| 21 | device_id BIGINT | 23 | device_id BIGINT |
| 22 | ) | 24 | ) |
| @@ -29,21 +31,22 @@ | @@ -29,21 +31,22 @@ | ||
| 29 | <insert id="insert"> | 31 | <insert id="insert"> |
| 30 | INSERT INTO device_message_${deviceId} ( | 32 | INSERT INTO device_message_${deviceId} ( |
| 31 | ts, id, report_time, tenant_id, server_id, | 33 | ts, id, report_time, tenant_id, server_id, |
| 32 | - upstream, request_id, method, params, data, | ||
| 33 | - code | 34 | + upstream, reply, request_id, method, params, |
| 35 | + data, code, msg | ||
| 34 | ) | 36 | ) |
| 35 | USING device_message | 37 | USING device_message |
| 36 | TAGS (#{deviceId}) | 38 | TAGS (#{deviceId}) |
| 37 | VALUES ( | 39 | VALUES ( |
| 38 | - #{ts}, #{id}, #{reportTime}, #{tenantId}, #{serverId}, | ||
| 39 | - #{upstream}, #{requestId}, #{method}, #{params}, #{data}, | ||
| 40 | - #{code} | 40 | + NOW, #{id}, #{reportTime}, #{tenantId}, #{serverId}, |
| 41 | + #{upstream}, #{reply}, #{requestId}, #{method}, #{params}, | ||
| 42 | + #{data}, #{code}, #{msg} | ||
| 41 | ) | 43 | ) |
| 42 | </insert> | 44 | </insert> |
| 43 | 45 | ||
| 44 | <select id="selectPage" resultType="cn.iocoder.yudao.module.iot.dal.dataobject.device.IotDeviceMessageDO"> | 46 | <select id="selectPage" resultType="cn.iocoder.yudao.module.iot.dal.dataobject.device.IotDeviceMessageDO"> |
| 45 | - SELECT ts, id, report_time, device_id, tenant_id, server_id, upstream, | ||
| 46 | - request_id, method, params, data, code | 47 | + SELECT ts, id, report_time, tenant_id, server_id, |
| 48 | + upstream, reply, request_id, method, params, | ||
| 49 | + data, code, msg | ||
| 47 | FROM device_message_${reqVO.deviceId} | 50 | FROM device_message_${reqVO.deviceId} |
| 48 | <where> | 51 | <where> |
| 49 | <if test="reqVO.method != null and reqVO.method != ''"> | 52 | <if test="reqVO.method != null and reqVO.method != ''"> |
yudao-module-iot/yudao-module-iot-gateway/src/main/java/cn/iocoder/yudao/module/iot/gateway/protocol/http/IotHttpDownstreamSubscriber.java
| @@ -39,7 +39,7 @@ public class IotHttpDownstreamSubscriber implements IotMessageSubscriber<IotDevi | @@ -39,7 +39,7 @@ public class IotHttpDownstreamSubscriber implements IotMessageSubscriber<IotDevi | ||
| 39 | 39 | ||
| 40 | @Override | 40 | @Override |
| 41 | public void onMessage(IotDeviceMessage message) { | 41 | public void onMessage(IotDeviceMessage message) { |
| 42 | - log.error("[onMessage][IoT 网关 HTTP 协议不支持下行消息,忽略消息:{}]", message); | 42 | + log.info("[onMessage][IoT 网关 HTTP 协议不支持下行消息,忽略消息:{}]", message); |
| 43 | } | 43 | } |
| 44 | 44 | ||
| 45 | } | 45 | } |
yudao-module-iot/yudao-module-iot-gateway/src/main/java/cn/iocoder/yudao/module/iot/gateway/protocol/http/router/IotHttpUpstreamHandler.java
| @@ -6,7 +6,6 @@ import cn.hutool.core.text.StrPool; | @@ -6,7 +6,6 @@ import cn.hutool.core.text.StrPool; | ||
| 6 | import cn.hutool.extra.spring.SpringUtil; | 6 | import cn.hutool.extra.spring.SpringUtil; |
| 7 | import cn.iocoder.yudao.framework.common.pojo.CommonResult; | 7 | import cn.iocoder.yudao.framework.common.pojo.CommonResult; |
| 8 | import cn.iocoder.yudao.module.iot.core.mq.message.IotDeviceMessage; | 8 | import cn.iocoder.yudao.module.iot.core.mq.message.IotDeviceMessage; |
| 9 | -import cn.iocoder.yudao.module.iot.core.mq.producer.IotDeviceMessageProducer; | ||
| 10 | import cn.iocoder.yudao.module.iot.gateway.protocol.http.IotHttpUpstreamProtocol; | 9 | import cn.iocoder.yudao.module.iot.gateway.protocol.http.IotHttpUpstreamProtocol; |
| 11 | import cn.iocoder.yudao.module.iot.gateway.service.device.message.IotDeviceMessageService; | 10 | import cn.iocoder.yudao.module.iot.gateway.service.device.message.IotDeviceMessageService; |
| 12 | import io.vertx.ext.web.RoutingContext; | 11 | import io.vertx.ext.web.RoutingContext; |
| @@ -26,13 +25,10 @@ public class IotHttpUpstreamHandler extends IotHttpAbstractHandler { | @@ -26,13 +25,10 @@ public class IotHttpUpstreamHandler extends IotHttpAbstractHandler { | ||
| 26 | 25 | ||
| 27 | private final IotHttpUpstreamProtocol protocol; | 26 | private final IotHttpUpstreamProtocol protocol; |
| 28 | 27 | ||
| 29 | - private final IotDeviceMessageProducer deviceMessageProducer; | ||
| 30 | - | ||
| 31 | private final IotDeviceMessageService deviceMessageService; | 28 | private final IotDeviceMessageService deviceMessageService; |
| 32 | 29 | ||
| 33 | public IotHttpUpstreamHandler(IotHttpUpstreamProtocol protocol) { | 30 | public IotHttpUpstreamHandler(IotHttpUpstreamProtocol protocol) { |
| 34 | this.protocol = protocol; | 31 | this.protocol = protocol; |
| 35 | - this.deviceMessageProducer = SpringUtil.getBean(IotDeviceMessageProducer.class); | ||
| 36 | this.deviceMessageService = SpringUtil.getBean(IotDeviceMessageService.class); | 32 | this.deviceMessageService = SpringUtil.getBean(IotDeviceMessageService.class); |
| 37 | } | 33 | } |
| 38 | 34 | ||
| @@ -46,10 +42,11 @@ public class IotHttpUpstreamHandler extends IotHttpAbstractHandler { | @@ -46,10 +42,11 @@ public class IotHttpUpstreamHandler extends IotHttpAbstractHandler { | ||
| 46 | // 2.1 解析消息 | 42 | // 2.1 解析消息 |
| 47 | byte[] bytes = context.body().buffer().getBytes(); | 43 | byte[] bytes = context.body().buffer().getBytes(); |
| 48 | IotDeviceMessage message = deviceMessageService.decodeDeviceMessage(bytes, | 44 | IotDeviceMessage message = deviceMessageService.decodeDeviceMessage(bytes, |
| 49 | - productKey, deviceName, protocol.getServerId()); | 45 | + productKey, deviceName); |
| 50 | Assert.equals(method, message.getMethod(), "method 不匹配"); | 46 | Assert.equals(method, message.getMethod(), "method 不匹配"); |
| 51 | // 2.2 发送消息 | 47 | // 2.2 发送消息 |
| 52 | - deviceMessageProducer.sendDeviceMessage(message); | 48 | + deviceMessageService.sendDeviceMessage(message, |
| 49 | + productKey, deviceName, protocol.getServerId()); | ||
| 53 | 50 | ||
| 54 | // 3. 返回结果 | 51 | // 3. 返回结果 |
| 55 | return CommonResult.success(MapUtil.of("messageId", message.getId())); | 52 | return CommonResult.success(MapUtil.of("messageId", message.getId())); |
yudao-module-iot/yudao-module-iot-gateway/src/main/java/cn/iocoder/yudao/module/iot/gateway/service/device/message/IotDeviceMessageServiceImpl.java
| @@ -96,20 +96,18 @@ public class IotDeviceMessageServiceImpl implements IotDeviceMessageService { | @@ -96,20 +96,18 @@ public class IotDeviceMessageServiceImpl implements IotDeviceMessageService { | ||
| 96 | /** | 96 | /** |
| 97 | * 补充消息的后端字段 | 97 | * 补充消息的后端字段 |
| 98 | * | 98 | * |
| 99 | - * @param message 消息 | ||
| 100 | - * @param device 设备信息 | ||
| 101 | - * @param serverId 设备连接的 serverId | ||
| 102 | - * @return 消息 | 99 | + * @param message 消息 |
| 100 | + * @param device 设备信息 | ||
| 101 | + * @param serverId 设备连接的 serverId | ||
| 103 | */ | 102 | */ |
| 104 | - private IotDeviceMessage appendDeviceMessage(IotDeviceMessage message, | ||
| 105 | - IotDeviceRespDTO device, String serverId) { | 103 | + private void appendDeviceMessage(IotDeviceMessage message, |
| 104 | + IotDeviceRespDTO device, String serverId) { | ||
| 106 | message.setId(IotDeviceMessageUtils.generateMessageId()).setReportTime(LocalDateTime.now()) | 105 | message.setId(IotDeviceMessageUtils.generateMessageId()).setReportTime(LocalDateTime.now()) |
| 107 | .setDeviceId(device.getId()).setTenantId(device.getTenantId()).setServerId(serverId); | 106 | .setDeviceId(device.getId()).setTenantId(device.getTenantId()).setServerId(serverId); |
| 108 | // 特殊:如果设备没有指定 requestId,则使用 messageId | 107 | // 特殊:如果设备没有指定 requestId,则使用 messageId |
| 109 | if (StrUtil.isEmpty(message.getRequestId())) { | 108 | if (StrUtil.isEmpty(message.getRequestId())) { |
| 110 | message.setRequestId(message.getId()); | 109 | message.setRequestId(message.getId()); |
| 111 | } | 110 | } |
| 112 | - return message; | ||
| 113 | } | 111 | } |
| 114 | 112 | ||
| 115 | } | 113 | } |
yudao-module-iot/yudao-module-iot-gateway/src/test/java/cn/iocoder/yudao/module/iot/gateway/service/auth/IotDeviceTokenServiceImplTest.java deleted
| 1 | -package cn.iocoder.yudao.module.iot.gateway.service.auth; | ||
| 2 | - | ||
| 3 | -import cn.iocoder.yudao.module.iot.core.util.IotDeviceAuthUtils; | ||
| 4 | -import cn.iocoder.yudao.module.iot.gateway.config.IotGatewayProperties; | ||
| 5 | -import org.junit.jupiter.api.BeforeEach; | ||
| 6 | -import org.junit.jupiter.api.Test; | ||
| 7 | -import org.junit.jupiter.api.extension.ExtendWith; | ||
| 8 | -import org.mockito.InjectMocks; | ||
| 9 | -import org.mockito.Mock; | ||
| 10 | -import org.mockito.junit.jupiter.MockitoExtension; | ||
| 11 | - | ||
| 12 | -import java.time.Duration; | ||
| 13 | - | ||
| 14 | -import static org.junit.jupiter.api.Assertions.*; | ||
| 15 | -import static org.mockito.Mockito.when; | ||
| 16 | - | ||
| 17 | -/** | ||
| 18 | - * {@link IotDeviceTokenServiceImpl} 的单元测试 | ||
| 19 | - * | ||
| 20 | - * @author 芋道源码 | ||
| 21 | - */ | ||
| 22 | -@ExtendWith(MockitoExtension.class) | ||
| 23 | -class IotDeviceTokenServiceImplTest { | ||
| 24 | - | ||
| 25 | - @Mock | ||
| 26 | - private IotGatewayProperties gatewayProperties; | ||
| 27 | - | ||
| 28 | - @InjectMocks | ||
| 29 | - private IotDeviceTokenServiceImpl tokenService; | ||
| 30 | - | ||
| 31 | - private IotGatewayProperties.TokenProperties tokenProperties; | ||
| 32 | - | ||
| 33 | - @BeforeEach | ||
| 34 | - void setUp() { | ||
| 35 | - // 初始化 Token 配置 | ||
| 36 | - tokenProperties = new IotGatewayProperties.TokenProperties(); | ||
| 37 | - tokenProperties.setSecret("1234567890123456789012345678901"); | ||
| 38 | - tokenProperties.setExpiration(Duration.ofDays(7)); | ||
| 39 | - | ||
| 40 | - when(gatewayProperties.getToken()).thenReturn(tokenProperties); | ||
| 41 | - } | ||
| 42 | - | ||
| 43 | - @Test | ||
| 44 | - void testCreateToken_Success() { | ||
| 45 | - // 准备参数 | ||
| 46 | - String productKey = "testProduct"; | ||
| 47 | - String deviceName = "testDevice"; | ||
| 48 | - | ||
| 49 | - // 调用方法 | ||
| 50 | - String token = tokenService.createToken(productKey, deviceName); | ||
| 51 | - | ||
| 52 | - // 验证结果 | ||
| 53 | - assertNotNull(token); | ||
| 54 | - assertFalse(token.isEmpty()); | ||
| 55 | - } | ||
| 56 | - | ||
| 57 | - @Test | ||
| 58 | - void testCreateToken_WithBlankParameters() { | ||
| 59 | - // 测试空白参数 | ||
| 60 | - assertNull(tokenService.createToken("", "deviceName")); | ||
| 61 | - assertNull(tokenService.createToken("productKey", "")); | ||
| 62 | - assertNull(tokenService.createToken(null, "deviceName")); | ||
| 63 | - assertNull(tokenService.createToken("productKey", null)); | ||
| 64 | - } | ||
| 65 | - | ||
| 66 | - @Test | ||
| 67 | - void testCreateToken_WithoutConfig() { | ||
| 68 | - // 模拟配置为空 | ||
| 69 | - when(gatewayProperties.getToken()).thenReturn(null); | ||
| 70 | - | ||
| 71 | - // 调用方法 | ||
| 72 | - String token = tokenService.createToken("productKey", "deviceName"); | ||
| 73 | - | ||
| 74 | - // 验证结果 | ||
| 75 | - assertNull(token); | ||
| 76 | - } | ||
| 77 | - | ||
| 78 | - @Test | ||
| 79 | - void testVerifyToken_Success() { | ||
| 80 | - // 准备参数 | ||
| 81 | - String productKey = "testProduct"; | ||
| 82 | - String deviceName = "testDevice"; | ||
| 83 | - | ||
| 84 | - // 创建 Token | ||
| 85 | - String token = tokenService.createToken(productKey, deviceName); | ||
| 86 | - assertNotNull(token); | ||
| 87 | - | ||
| 88 | - // 验证 Token | ||
| 89 | - IotDeviceAuthUtils.DeviceInfo deviceInfo = tokenService.verifyToken(token); | ||
| 90 | - | ||
| 91 | - // 验证结果 | ||
| 92 | - assertNotNull(deviceInfo); | ||
| 93 | - assertEquals(productKey, deviceInfo.getProductKey()); | ||
| 94 | - assertEquals(deviceName, deviceInfo.getDeviceName()); | ||
| 95 | - } | ||
| 96 | - | ||
| 97 | - @Test | ||
| 98 | - void testVerifyToken_WithBlankToken() { | ||
| 99 | - // 测试空白 Token | ||
| 100 | - assertNull(tokenService.verifyToken("")); | ||
| 101 | - assertNull(tokenService.verifyToken(null)); | ||
| 102 | - } | ||
| 103 | - | ||
| 104 | - @Test | ||
| 105 | - void testVerifyToken_WithInvalidToken() { | ||
| 106 | - // 测试无效 Token | ||
| 107 | - assertNull(tokenService.verifyToken("invalid.token.here")); | ||
| 108 | - } | ||
| 109 | - | ||
| 110 | - @Test | ||
| 111 | - void testVerifyToken_WithoutConfig() { | ||
| 112 | - // 模拟配置为空 | ||
| 113 | - when(gatewayProperties.getToken()).thenReturn(null); | ||
| 114 | - | ||
| 115 | - // 调用方法 | ||
| 116 | - IotDeviceAuthUtils.DeviceInfo deviceInfo = tokenService.verifyToken("any.token.here"); | ||
| 117 | - | ||
| 118 | - // 验证结果 | ||
| 119 | - assertNull(deviceInfo); | ||
| 120 | - } | ||
| 121 | - | ||
| 122 | - @Test | ||
| 123 | - void testTokenRoundTrip() { | ||
| 124 | - // 测试完整的 Token 创建和验证流程 | ||
| 125 | - String productKey = "myProduct"; | ||
| 126 | - String deviceName = "myDevice"; | ||
| 127 | - | ||
| 128 | - // 1. 创建 Token | ||
| 129 | - String token = tokenService.createToken(productKey, deviceName); | ||
| 130 | - assertNotNull(token); | ||
| 131 | - | ||
| 132 | - // 2. 验证 Token | ||
| 133 | - IotDeviceAuthUtils.DeviceInfo deviceInfo = tokenService.verifyToken(token); | ||
| 134 | - assertNotNull(deviceInfo); | ||
| 135 | - assertEquals(productKey, deviceInfo.getProductKey()); | ||
| 136 | - assertEquals(deviceName, deviceInfo.getDeviceName()); | ||
| 137 | - } | ||
| 138 | - | ||
| 139 | -} | ||
| 140 | \ No newline at end of file | 0 | \ No newline at end of file |