【发布时间】:2021-07-01 03:01:05
【问题描述】:
我的 Spring Boot 应用程序正在通过 RabbitMQ 订阅一个事件。 另一个 Web 应用程序负责将事件发布到我的应用程序正在侦听的队列中。 该事件主要包含机构信息。 主应用程序类实现 CommandLineRunner 并覆盖 run() 方法。 这个 run() 方法调用一个方法来创建管理员用户。
当我的应用程序启动并且队列中已经存在一个事件时,我的应用程序中的侦听器应该更新管理员用户的机构 ID。 但是,看起来 createAdmin() 和 listener() 正在并行执行,并且机构 ID 永远不会更新。帮助我理解控制流。
参见下面的代码 sn-p 和打印语句的顺序。
@SpringBootApplication
public class UserManagementApplication implements CommandLineRunner{
public static void main(String[] args) {
SpringApplication.run(UserManagementApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
createAdmin();
}
private void createAdmin() {
System.out.println("************** createAdmin invoked *********************");
Optional<AppUserEntity> user = appUserService.getUserByUserName("superuser");
if(!user.isPresent()) {
AppUserEntity superuser = new AppUserEntity();
superuser.setUsername("superuser");
superuser.setAppUserRole(AppUserRole.SUPERADMIN);
superuser.setInstId(null); // will be set when Queue receives Institute information
appUserService.saveUser(superuser);
System.out.println("************** superuser creation SUCCESSFUL *********************");
}
}
}
@Component
public class InstituteQueueListener {
@RabbitListener(queues = "institute-queue")
public void updateSuperAdminInstituteId(InstituteEntity institute) {
System.out.println("************** RabbitListener invoked *********************");
Long headInstituteId = institute.getInstId();
Optional<AppUserEntity> user = appUserService.getUserByUserName("superuser");
if(user.isPresent()) {
System.out.println("************* superuser is present *****************");
AppUserEntity superuser = user.get();
superuser.setInstId(headInstituteId);
System.out.println("************* Going to save inst Id = "+headInstituteId);
appUserService.saveUser(superuser);
}
System.out.println("************** superuser is NOT present (inside Q listener)*********************");
}
}
Order of print statements ....
(the queue already has event before running my application)
System.out.println("************** createAdmin invoked *********************");
System.out.println("************** RabbitListener invoked *********************");
System.out.println("************** superuser is NOT present (inside Q listener) *********************");
System.out.println("************** superuser creation SUCCESSFUL *********************");
【问题讨论】:
标签: spring spring-boot rabbitmq