fix(): 处理事件监听器执行异常问题

dev.entOperation
xinzirun 2024-10-07 19:29:12 +08:00
parent 222b2ad30f
commit 20977536e3
2 changed files with 16 additions and 4 deletions

View File

@ -1,5 +1,6 @@
package com.muyu.event.process.basic; package com.muyu.event.process.basic;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener; import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
@ -10,6 +11,7 @@ import java.util.List;
* @Date 2024/9/30 15:37 * @Date 2024/9/30 15:37
* @Description * @Description
*/ */
@Slf4j
@Component @Component
public class BasicEventHandler<T> implements ApplicationListener<BasicEvent<T>> { public class BasicEventHandler<T> implements ApplicationListener<BasicEvent<T>> {
@ -34,6 +36,12 @@ public class BasicEventHandler<T> implements ApplicationListener<BasicEvent<T>>
*/ */
@Override @Override
public void onApplicationEvent(BasicEvent<T> event) { public void onApplicationEvent(BasicEvent<T> event) {
listeners.forEach(l -> l.onEvent(event)); listeners.forEach(l -> {
try {
l.onEvent(event);
} catch (Exception e) {
log.error("{}监听器处理事件时发生异常:{}", l, e.getMessage());
}
});
} }
} }

View File

@ -1,6 +1,7 @@
package com.muyu.event.process.listener; package com.muyu.event.process.listener;
import com.alibaba.fastjson2.JSONObject; import com.alibaba.fastjson2.JSONObject;
import com.muyu.common.core.exception.ServiceException;
import com.muyu.enterprise.domain.FaultRule; import com.muyu.enterprise.domain.FaultRule;
import com.muyu.event.process.basic.BasicEvent; import com.muyu.event.process.basic.BasicEvent;
import com.muyu.event.process.basic.BasicEventListener; import com.muyu.event.process.basic.BasicEventListener;
@ -11,6 +12,7 @@ import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import java.util.Map; import java.util.Map;
import java.util.Optional;
/** /**
* @Author: zi run * @Author: zi run
@ -31,8 +33,10 @@ public class IdentifyingFailuresEventListener implements BasicEventListener<Stri
public void onEvent(BasicEvent<String> event) { public void onEvent(BasicEvent<String> event) {
log.info("触发识别故障时间监听器……"); log.info("触发识别故障时间监听器……");
JSONObject data = JSONObject.parseObject(event.getData()); JSONObject data = JSONObject.parseObject(event.getData());
Map<String, Object> dataMap = (Map<String, Object>) cacheUtil.get((String) data.get("vin")); Optional<Map<String, Object>> optionalDataMap =
FaultRule faultRule = (FaultRule) dataMap.get(CacheHandlerConstants.FAULT_RULE_KEY); Optional.ofNullable((Map<String, Object>) cacheUtil.get((String) data.get("vin")));
optionalDataMap
.map(dataMap -> (FaultRule) dataMap.get(CacheHandlerConstants.FAULT_RULE_KEY))
.orElseThrow(() -> new ServiceException("故障规则未找到"));
} }
} }