首頁  >  文章  >  Java  >  基於SpringBoot怎麼應用ApplicationEvent

基於SpringBoot怎麼應用ApplicationEvent

王林
王林轉載
2023-05-14 22:01:041622瀏覽

一、案例場景

1.發起restful請求,根據請求參數發布不同的事件。

2.事件監聽者,監聽到事件後,做預定操作。

3.本例是事件同步處理機制,即發布事件後,會同步監聽事件。

二、使用類別

org.springframework.context.ApplicationEvent,spring的事件物件。

org.springframework.context.ApplicationListener,事件監聽者介面。

org.springframework.context.ApplicationEventPublisher,事件發布者介面。

三、程式碼

1.事件物件

事件物件實作ApplicationEvent。

1.1 ExampleApplicationEvent

ExampleApplicationEvent,一個抽象類別。繼承ApplicationEvent,自訂拓展微服務中需求的一些屬性。

public abstract class ExampleApplicationEvent extends ApplicationEvent {
  private static final String eventSource = "Example";
  private String eventType = null;
  private Object eventData = null;
  public ExampleApplicationEvent(Object eventData) {
      super(eventSource);
      this.eventData = eventData;
  }
  public ExampleApplicationEvent(Object eventData, String eventType) {
      super(eventSource);
      this.eventData = eventData;
      this.eventType = eventType;
  }
  public String getEventType() {
      return eventType;
  }
  public Object getEventData() {
      return eventData;
  }
}
1.2 ExampleLocalApplicationEvent

ExampleLocalApplicationEvent,是抽象類別ExampleApplicationEvent的實作類,在此按需拓展屬性。

public class ExampleLocalApplicationEvent extends ExampleApplicationEvent {
  public ExampleLocalApplicationEvent(Object eventData) {
      super(eventData);
  }
  public ExampleLocalApplicationEvent(Object eventData, String eventType) {
      super(eventData, eventType);
  }
}
1.3 EventTypeEnum

EventTypeEnum,自訂事件類型枚舉,按需擴展。

public enum EventTypeEnum {
  CHANGE("change", "变更事件"),
  ADD("add", "新增事件");
  private String id;
  private String name;
  public String getId() {
   return id;
  }
  public String getName() {
   return name;
  }
  EventTypeEnum(String id, String name) {
   this.id = id;
   this.name = name;
  }
  public static EventTypeEnum getEventTypeEnum(String id) {
   for (EventTypeEnum var : EventTypeEnum.values()) {
       if (var.getId().equalsIgnoreCase(id)) {
           return var;
       }
   }
   return null;
  }
}

2.事件監聽者

事件監聽者包含介面和抽象類別。

2.1 IEventListener

IEventListener,一個接口,繼承ApplicationListener介面。

@SuppressWarnings("rawtypes")
public interface IEventListener extends ApplicationListener {
}
2.2 AbstractEventListener

AbstractEventListener,一個抽象類,實作IEventListener介面。並提供抽象方法方便實作類別擴展和程式碼解耦。

public abstract  class AbstractEventListener implements IEventListener {
 @Override
 public void onApplicationEvent(ApplicationEvent event){
  if(!(event instanceof ExampleApplicationEvent)){
    return;
  }
  ExampleApplicationEvent exEvent = (ExampleApplicationEvent) event;
  try{
    onExampleApplicationEvent(exEvent);
  }catch (Exception e){
    e.printStackTrace();
  }
 }
 protected abstract void onExampleApplicationEvent(ExampleApplicationEvent event);
}
2.3 OrderEventListener

OrderEventListener,實作類別AbstractEventListener抽象類別。監聽事件,並對事件做處理,是一個業務類別。

@Slf4j
@Component
public class OrderEventListener extends AbstractEventListener {
  @Override
  protected void onExampleApplicationEvent(ExampleApplicationEvent event) {
   log.info("OrderEventListener->onSpApplicationEvent,监听事件.");
   Object eventData = event.getEventData();
   log.info("事件类型: " + EventTypeEnum.getEventTypeEnum(event.getEventType()));
   log.info("事件数据: " + eventData.toString());
  }
}

3.事件發布者

事件監聽者包含介面和實作類別。

3.1 IEventPublisher

IEventPublisher,自訂事件發布接口,方便擴展功能和屬性。

public interface IEventPublisher {
    boolean publish(ExampleApplicationEvent event);
}
3.2 LocalEventPublisher

LocalEventPublisher,事件發布實作類,此類使用@Component,spring的IOC容器會載入此類。此類別呼叫ApplicationEventPublisher的publishEvent發布事件。

@Slf4j
@Component("localEventPublisher")
public class LocalEventPublisher implements IEventPublisher {
  @Override
  public boolean publish(ExampleApplicationEvent event) {
    try{
      log.info("LocalEventPublisher->publish,发布事件.");
      log.info("事件类型: " + EventTypeEnum.getEventTypeEnum(event.getEventType()));
      log.info("事件数据: " + event.getEventData().toString());
      SpringUtil.getApplicationContext().publishEvent(event);
    }catch (Exception e){
      log.info("事件发布异常.");
      e.printStackTrace();
      return false;
    }
    return true;
  }
}

4.Restful請求觸發事件

使用Restful請求觸發事件發生。

4.1 EventController

EventController,接收Restful請求。

@Slf4j
@RestController
@RequestMapping("/event")
public class EventController {
  @Autowired
  private LocalEventPublisher eventPublisher;
  @PostMapping("/f1")
  public Object f1(@RequestBody Object obj) {
   log.info("EventController->f1,接收参数,obj = " + obj.toString());
   Map objMap = (Map) obj;
   OrderInfo orderInfo = new OrderInfo();
   orderInfo.setUserName((String) objMap.get("userName"));
   orderInfo.setTradeName((String) objMap.get("tradeName"));
   orderInfo.setReceiveTime(DateUtil.format(new Date(),
           "yyyy-MM-dd HH:mm:ss"));
   String flag = (String) objMap.get("flag");
   if (StringUtils.equals("change", flag)) {
       eventPublisher.publish(new ExampleLocalApplicationEvent(orderInfo,
               EventTypeEnum.CHANGE.getId()));
   } else if (StringUtils.equals("add", flag)) {
       eventPublisher.publish(new ExampleLocalApplicationEvent(orderInfo,
               EventTypeEnum.ADD.getId()));
   } else {
       eventPublisher.publish(new ExampleLocalApplicationEvent(orderInfo));
   }
   log.info("EventController->f1,返回.");
   return ResultObj.builder().code("200").message("成功").build();
  }
}
4.2 OrderInfo

OrderInfo,資料對象,放入事件對象傳遞。

@Data
@NoArgsConstructor
public class OrderInfo {
  private String userName;
  private String tradeName;
  private String receiveTime;
}
4.3 ResultObj

ResultObj,restful傳回通用物件。

@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class ResultObj {
    private String code;
    private String message;
}

5.測試

5.1 要求資訊

URL要求:http://127.0.0.1:8080/server/event/f1

入參:

{
    "userName": "HangZhou",
    "tradeName": "Vue进阶教程",
    "flag": "add"
}

傳回值:

{
    "code": "200",
    "message": "成功"
}
5.2 日誌

輸出日誌:

基於SpringBoot怎麼應用ApplicationEvent

以上是基於SpringBoot怎麼應用ApplicationEvent的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:yisu.com。如有侵權,請聯絡admin@php.cn刪除