redis中key过期监听

/**
 * redis中key过期监听(床垫不在床时间 channelRedisService的2号database)
 */
// @Component
@Transactional(rollbackFor = RuntimeException.class)
public class RedisKeyExpiredNotOnBedMinutesListener {

    private final Logger LOGGER = LoggerFactory.getLogger(RedisKeyExpiredNotOnBedMinutesListener.class);

    private final String PATTERN = "__keyevent@2__:expired";

    @DubboReference(interfaceName = "channelRedisService", group = "sys-redis", version = "0.0.1", timeout = 6000)
    private ChannelRedisService channelRedisService;

    //预警值
    @DubboReference(group = "sys-cms", interfaceName = "warningValueService", version = "0.0.1")
    private WarningValueService warningValueService;
    //工单
    @DubboReference(group = "sys-proc", interfaceName = "procWorkOrderService", version = "0.0.1")
    private ProcWorkOrderService procWorkOrderService;
    //判断是否报警并推送
    @DubboReference(group = "sys-iot-cust", interfaceName = "warningResultService", version = "0.0.1")
    private WarningResultService warningResultService;
    //pad端用户是否冻结
    @DubboReference(group = "sys-iot-cust", interfaceName = "custUserService", version = "0.0.1")
    private CustUserService custUserService;
    //设备
    @DubboReference(group = "sys-ims", interfaceName = "equipRelDeviceService", version = "0.0.1")
    private EquipRelDeviceService equipRelDeviceService;


    @PostConstruct
    public void listener() {

        ThreadFactory slaveReportListener = new ThreadFactoryBuilder()
                .setNameFormat("netty-key-expired-listener-thread").build();
        ExecutorService singleThreadPool = new ThreadPoolExecutor(1, 1,
                0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<>(1024), slaveReportListener, new ThreadPoolExecutor.AbortPolicy());

        singleThreadPool.execute(() -> {
            JedisConnection connection = channelRedisService.channelConnection();

            JedisPool pool = new JedisPool(new JedisPoolConfig(),
                    connection.getHostName(),
                    connection.getPort(),
                    connection.getTimeout(),
                    connection.getPassword());

            Jedis jedis = pool.getResource();

            jedis.psubscribe(new Listener(), PATTERN);

        });
    }

    class Listener extends JedisPubSub {
        @Override
        public void onPSubscribe(String pattern, int subscribedChannels) {
            System.out.println(System.currentTimeMillis() + " onPSubscribe " + pattern + " " + subscribedChannels);
        }

        @Override
        public void onPMessage(String pattern, String channel, String userId) {
            LOGGER.info(System.currentTimeMillis() + " --> " + "开始处理:" + userId + "的不在床时间预警");

            //声明用到的数据
            Date nowTime = new Date();
            String workOrderAlarmType = WorkOrderAlarmTypeEnum.SLEEP_ALARM.getCode();
            String tmplIden = TmplIdentificationEnum.NOT_ON_BED_MINUTES.getCode();

            /**
             * 用户不可用
             * 不处理
             */
            IotUser user = custUserService.selectById(userId);
            if(user==null){
                LOGGER.info("用户不存在 userId:{}",userId);
                return;
            }
            boolean isEnabled = EnabledFlagEnum.ENABLEDFLAG_TRUE.getValue().equals(user.getEnabledFlag());
            if(!isEnabled){
                LOGGER.info("用户不可用 userId:{},user:{}",userId,user);
                return;
            }

            /**
             * 未开启预警
             * 不处理
             */
            WarningValue<OneNumJsonBean> warningValue = warningValueService.selectOneByTmplIdenAndIotUserId(TmplIdentificationEnum.NOT_ON_BED_MINUTES.getCode(),userId);
            boolean isEnableWarn = WarningValueStatusEnum.WARNING_VALUE_ENABLED.getCode().equals(warningValue.getWarningValueStatus());
            if(!isEnableWarn){
                LOGGER.info("Pad端用户未开启离床时间预警 warningValue:{}",warningValue);
                return;
            }

            /**
             * 不在预警时间段内
             * 不处理
             */
            WarningValue<SleepIntervalJsonBean> sleepIntervalWarningValue = warningValueService.selectOneByTmplIdenAndIotUserId(TmplIdentificationEnum.SLEEP_INTERVAL.getCode(),userId);
            LOGGER.info("sleepIntervalWarningValue:{}",sleepIntervalWarningValue);
            SleepIntervalJsonBean sleepIntervalJsonBean = sleepIntervalWarningValue.getData();
            boolean isInCheckTimeInterval = sleepIntervalJsonBean.isInCheckTimeInterval(nowTime);
            if(!isInCheckTimeInterval){
                LOGGER.info("监测时间不在Pad端用户睡眠预警时间段内 nowTime:{},sleepIntervalWarningValue:{}",nowTime,sleepIntervalWarningValue);
                return;
            }

            /**
             * 工单未处理完
             * 不处理
             */
            List<ProcWorkOrder> procWorkOrderList = procWorkOrderService.selectByWorkOrderUserIdAndWorkOrderAlarmTypeAndWorkOrderAlarmModelType(userId,workOrderAlarmType,tmplIden);
            LOGGER.info("procWorkOrderList:{}",procWorkOrderList);
            boolean isWorkOrderDone;
            if(procWorkOrderList==null || procWorkOrderList.size()==0){
                isWorkOrderDone = true;
            }else{
                isWorkOrderDone = false;
            }
            if(!isWorkOrderDone){
                LOGGER.info("工单未处理完 procWorkOrderList:{}",procWorkOrderList);
                return;
            }

            /**
             * 开启预警且在预警时间段且工单处理完
             * 才推Pad端通知和生成工单
             */
            List<String> equipIdenList = Arrays.asList(EquipmentIdenEnum.DEV_SLEEP_YJ_WIFI_01.getCode(),
                    EquipmentIdenEnum.DEV_SLEEP_YJ_SIM_01.getCode(),
                    EquipmentIdenEnum.DEV_SLEEP_ZC_01.getCode());
            List<EquipRelDevice> deviceList = equipRelDeviceService.queryByCustUserIdListAndEquipIdenList(Arrays.asList(userId),equipIdenList);
            String equipmentId = deviceList.get(0).getEquipmentId();
            IsWarnDto isWarnDto = IsWarnDto.builder().withTmplIdentification(TmplIdentificationEnum.NOT_ON_BED_MINUTES.getCode()).withUserId(userId).withAlarmType(WorkOrderAlarmTypeEnum.SLEEP_ALARM.getCode()).withEquipmentId(equipmentId).withDataType("2").withCreateTime(new Date()).build();
            WarnDto warnDto = new WarnDto(isWarnDto,WorkOrderTypeEnum.HEALTH_ALARM_WORK_ORDER.getCode(),JpushType.By_Tag,JpushSource.From_Health,null,null,new Date());
            Boolean warnBoolean = warningResultService.warn(warnDto);
            if(!warnBoolean){
                LOGGER.info("工单未处理完 procWorkOrderList:{}",procWorkOrderList);
                return;
            }else{
                LOGGER.info("离床处理完成 procWorkOrderList:{}",procWorkOrderList);
                return;
            }
        }
    }

}

猜你喜欢

转载自blog.csdn.net/xx897115293/article/details/107976198