Home  >  Article  >  Java  >  How to apply ApplicationEvent based on SpringBoot

How to apply ApplicationEvent based on SpringBoot

王林
王林forward
2023-05-14 22:01:041626browse

1. Case scenario

1. Initiate a restful request and publish different events according to the request parameters.

2. Event listener, after listening to the event, perform scheduled operations.

3. This example is an event synchronous processing mechanism, that is, after the event is released, the event will be monitored synchronously.

2. Use the class

org.springframework.context.ApplicationEvent, spring’s event object.

org.springframework.context.ApplicationListener, event listener interface.

org.springframework.context.ApplicationEventPublisher, event publisher interface.

3. Code

1. Event object

The event object implements ApplicationEvent.

1.1 ExampleApplicationEvent

ExampleApplicationEvent, an abstract class. Inherit ApplicationEvent and customize and expand some properties required in microservices.

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 is the implementation class of the abstract class ExampleApplicationEvent, where you can expand properties as needed.

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

EventTypeEnum, custom event type enumeration, expanded on demand.

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. Event listener

Event listeners include interfaces and abstract classes.

2.1 IEventListener

IEventListener, an interface, inherits the ApplicationListener interface.

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

AbstractEventListener, an abstract class, implements the IEventListener interface. And provide abstract methods to facilitate class extension and code decoupling.

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, implements the AbstractEventListener abstract class. It is a business class to listen to events and process them.

@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. Event publisher

Event listeners include interfaces and implementation classes.

3.1 IEventPublisher

IEventPublisher, a custom event publishing interface, facilitates extended functions and properties.

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

LocalEventPublisher, event publishing implementation class, this class uses @Component, spring's IOC container will load this class. This class calls the publishEvent of ApplicationEventPublisher to publish events.

@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 request triggers event

Use Restful request to trigger event.

4.1 EventController

EventController, receives Restful requests.

@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 object, is passed in the event object.

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

ResultObj, restful returns a common object.

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

5. Test

5.1 Request information

URL request: http://127.0.0.1:8080/server/event/f1

Enter Parameter:

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

Return value:

{
    "code": "200",
    "message": "成功"
}
5.2 Log

Output log:

How to apply ApplicationEvent based on SpringBoot

The above is the detailed content of How to apply ApplicationEvent based on SpringBoot. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete