场景
根据第三方系统的事件做出不同动作
优化前
@Slf4j
@RestController
@RequiredArgsConstructor
public class WebHookController {
@PostMapping("/webhook")
public ResponseEntity<Object> webhook(@RequestBody JSONObject body) {
String event = body.getString("event");
if(event == "***"){
log.info("==>***事件")
// do
}else if(event == "***"){
log.info("==>***事件")
// do
}else if(event == "***"){
log.info("==>***事件")
// do
}else if(event == "***"){
log.info("==>***事件")
// do
}else if(event == "***"){
log.info("==>***事件")
// do
}else if(event == "***"){
log.info("==>***事件")
// do
}else if(event == "***"){
log.info("==>***事件")
// do
}
return ResponseEntity.ok().build();
}
}
事件枚举
public enum EventType {
PROJECT_CREATE,
TASK_CREATE,
WORKTIME_CREATE
}
事件处理接口
public interface IEventTemplate{
void process(JSONObject json)
}
抽奖模板
public abstract class AbstractEventTemplate implements IEventTemplate,InitializingBean{
public abstract EventType support();
@Override
public void afterPropertiesSet() throws Exception{
EventType[] eventTypes = EventType.values();
boolean flag = false;
for(EventType eventType : eventTypes){
// support方法调用的是子类返回的对象
EvenType support = support();
if(support == eventType){
flag = true;
break;
}
}
}
if(!flag){
throw new RuntimeException("不支持的事件类型");
}
}
模板实现类
@Component
@Slf4j
public class ProjectCreateTemplate extends AbstractEventTemplate{
@Override
public void process(JSONObject json){
log.info("==> 项目创建")
// do
}
@Override
public TBEventType support() {
return EventType.PROJECT_CREATE;
}
}
上下文
@Component
public class EventContext implements ApplicationContextAware{
private final static Map<EventType,IEventTemplate> eventService = new EnumMap<>(EventType.class);
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeanException{
// 抽象类所有的子类对象 从容器中获取的所有子类对象
Map<String, AbstractEventTemplate> beansOfType = applicationContext.getBeansOfType(AbstractEventTemplate.class); // 从容器中获取所有的子类对象 key=beanName value=bean对象
//循环抽象类的子类
for (AbstractTBEventTemplate value : beansOfType.values()) {
EventType support = value.support();
eventServices.put(support, value);
}
}
public IEventTemplate getEventService(TBEventType eventType) {
return eventServices.get(eventType);
}
}
优化后接口
@Slf4j
@RestController
@RequiredArgsConstructor
public class WebHookController {
@PostMapping("/webhook")
public ResponseEntity<Object> webhook(@RequestBody JSONObject body) {
String event = body.getString("event");
try{
EventType eventType = EventType.valueOf(event);
IEventTemplate eventTemplate = tbEventContext.getEventService(eventType);
eventTemplate.process(body);
}catch (IllegalArgumentException illegalArgumentException) {
log.info("未知事件:{}", body);
} catch (Exception e) {
log.error(e.getMessage());
throw new RuntimeException(e);
}
return ResponseEntity.ok().build();
}
}
标签:info,...,log,EventType,support,public,else,优化,event
From: https://www.cnblogs.com/luyifo/p/18152499