提问人:YMG 提问时间:5/5/2023 更新时间:5/5/2023 访问量:228
如果我想在Spring Boot的不同事件中传递相同的对象怎么办
What if I want to pass same object in different events in Spring Boot
问:
我正在研究事件驱动的东西和Spring Boot应用程序事件。我有 2 个问题。
所以我创建了一些基本类,例如(基本酒店预订应用程序)
模型类
public class HotelBookRequest {
private String userID;
private String hotelID;
public String getUserID() {
return userID;
}
public void setUserID(String userID) {
this.userID = userID;
}
public String getHotelID() {
return hotelID;
}
public void setHotelID(String hotelID) {
this.hotelID = hotelID;
}
@Override
public String toString() {
return "HotelBookRequest{" +
"userID='" + userID + '\'' +
", hotelID='" + hotelID + '\'' +
'}';
}
应用程序接口
@RestController
@RequestMapping("/book")
public class BookingApi {
@Autowired
ReservationService reservationService;
@PostMapping
public void bookHotel(@RequestBody HotelBookRequest hotelBookRequest){
System.out.println("Request Processing...");
reservationService.publishReservationEvent(hotelBookRequest);
reservationService.publishMsgEvent(hotelBookRequest);
}
}
服务
@Service
public class ReservationService {
@Autowired
private ApplicationEventPublisher applicationEventPublisher;
public void publishReservationEvent(HotelBookRequest hotelBookRequest){
applicationEventPublisher.publishEvent(hotelBookRequest);
}
public void publishMsgEvent(HotelBookRequest hotelBookRequest){
applicationEventPublisher.publishEvent(hotelBookRequest);
}
}
和事件侦听器
@Component
public class ReservationEventListener {
@Autowired
ReservationService service;
@Async
@EventListener
public void reservationEventHandler(HotelBookRequest hotelBookRequest) throws InterruptedException {
System.out.println("1st Event");
}
@Async
@EventListener
public void msgEventHandler(HotelBookRequest hotelBookRequest){
System.out.println("2nd Event");
}
}
所以,如您所见,我在 Service 类中有 2 个事件,在 Event Listener 类中有 2 个事件侦听器。
如果我将 HotelBookRequest 对象提供给 Service 函数之一,它会调用 2 个事件侦听器。我的意思是,如果我调用它会触发 2 个事件侦听器并给我输出,例如reservationService.publishReservationEvent(hotelBookRequest);
1st Event
2nd Event
如果我调用它,它也会给我相同的输出。我能理解为什么它会这样。reservationService.publishMsgEvent(hotelBookRequest);
但是,我的主要问题是,如果我想用 完全相同的对象没有重复的输出?逻辑是什么 关于它?
第二个问题是,当我想触发 来自其他事件的事件?它是否会产生对它的依赖性?触发嵌套事件的最有效方法是什么?
答:
0赞
mslowiak
5/5/2023
#1
关于 1. 是否要发出两个并发 API 请求? 在这种情况下,为确保酒店仅预订一次,您应该查看乐观/悲观锁定。
关于 2. 这实际上取决于将发出嵌套事件的逻辑是什么。 当然,如果要确保操作是事务性的并且最终一致,则可以查看发件箱模式
评论
0赞
YMG
5/8/2023
实际上,举个简单的例子,我想发布 2 个事件,其中 1 个打印出参数(仅供参考),另一个打印出时间。但是,当我发布 2 个事件时,2 个事件侦听器分别调用了 2 次。预计每次 1 次
评论