设备分享

This commit is contained in:
2025-09-06 16:19:12 +08:00
parent b945420446
commit 64a4485ced
6 changed files with 119 additions and 14 deletions

View File

@ -1,5 +1,9 @@
package com.fuyuanshen.global.mqtt.listener;
import cn.hutool.core.thread.ThreadUtil;
import com.baomidou.lock.LockInfo;
import com.baomidou.lock.LockTemplate;
import com.baomidou.lock.executor.RedissonLockExecutor;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.fuyuanshen.common.core.constant.GlobalConstants;
import com.fuyuanshen.common.redis.utils.RedisUtils;
@ -32,6 +36,9 @@ public class RedisKeyExpirationListener implements MessageListener {
@Autowired
private DeviceMapper deviceMapper;
@Autowired
private LockTemplate lockTemplate;
@Override
public void onMessage(Message message, byte[] pattern) {
String expiredKey = new String(message.getBody());
@ -40,16 +47,43 @@ public class RedisKeyExpirationListener implements MessageListener {
String element = expiredKey.substring(FUNCTION_ACCESS_KEY.length());
handleFunctionAccessExpired(element);
}
if(expiredKey.endsWith(DEVICE_ONLINE_STATUS_KEY_PREFIX)){
if(expiredKey.endsWith(DEVICE_ONLINE_STATUS_KEY_PREFIX)) {
// threadPoolTaskExecutor.execute(() -> {
// log.info("设备离线:{}", expiredKey);
// String element = expiredKey.substring(GlobalConstants.GLOBAL_REDIS_KEY.length() + DEVICE_KEY_PREFIX.length(), expiredKey.length() - DEVICE_ONLINE_STATUS_KEY_PREFIX.length());
// UpdateWrapper<Device> deviceUpdateWrapper = new UpdateWrapper<>();
// deviceUpdateWrapper.eq("device_imei", element);
// deviceUpdateWrapper.set("online_status", 0);
// deviceMapper.update(deviceUpdateWrapper);
// });
threadPoolTaskExecutor.execute(() -> {
log.info("设备离线:{}", expiredKey);
String element = expiredKey.substring(GlobalConstants.GLOBAL_REDIS_KEY.length() + DEVICE_KEY_PREFIX.length(), expiredKey.length() - DEVICE_ONLINE_STATUS_KEY_PREFIX.length());
UpdateWrapper<Device> deviceUpdateWrapper = new UpdateWrapper<>();
deviceUpdateWrapper.eq("device_imei", element);
deviceUpdateWrapper.set("online_status", 0);
deviceMapper.update(deviceUpdateWrapper);
// 构造设备锁键
String deviceLockKey = GlobalConstants.GLOBAL_REDIS_KEY + ":device_lock:" + element;
// 尝试获取Redis锁
LockInfo lockInfo = lockTemplate.lock(deviceLockKey, 30000L, 5000L, RedissonLockExecutor.class); // 30秒过期
if (lockInfo != null) {
try {
UpdateWrapper<Device> deviceUpdateWrapper = new UpdateWrapper<>();
deviceUpdateWrapper.eq("device_imei", element);
deviceUpdateWrapper.set("online_status", 0);
deviceMapper.update(deviceUpdateWrapper);
} finally {
//释放锁
lockTemplate.releaseLock(lockInfo);
}
} else {
log.warn("无法获取设备锁,跳过设备离线处理: {}", element);
}
});
}
}
/**
* 访问key过期事件