如何让每 5 秒发送消息到 rabbitmq 中的队列?

how to make every 5 seconds send message to queue in rabbitmq?

我是 springboot 和 rabbitmq 的新手。 如何让每 5 秒在 rabbitmq 中发送一条消息。 我试图在下面的代码中做到这一点,但我不确定。你能帮助我吗?谢谢...

示例代码:

package com.aysenur.sr.producer;


@Service
public class NotificationProducer {

@Value("${sr.rabbit.routing.name}")
private String routingName;

@Value("${sr.rabbit.exchange.name}")
private String exchangeName;


@PostConstruct
public void init() {
    Notification notification = new Notification();
    notification.setNotificationId(UUID.randomUUID().toString());
    notification.setCreatedAt(new Date());
    notification.setMessage("WELCOME TO RABBITMQ");
    notification.setSeen(Boolean.FALSE);

    try {
        Thread t=new Thread();
        t.start();
        sendToQueue(notification);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

}

@Autowired
private RabbitTemplate rabbitTemplate;

public void sendToQueue(Notification notification) throws InterruptedException  {
    System.out.println("Notification Sent ID : " + notification.getNotificationId());
    rabbitTemplate.convertAndSend(exchangeName, routingName, notification);
    Thread.sleep(5000);
     }

}

您的代码仅在实例化 service bean 时被调用一次。在这种情况下,添加创建新威胁的调用实际上不会执行任何操作,因为您没有安排针对该威胁的任何工作。

使用 spring 完成此操作的最简单方法是使用 (Scheduled)[https://www.baeldung.com/spring-scheduled-tasks]annotation 在 NotificationProducer 方法中使用注释方法。这将告诉 spring 安排调用该方法,而无需您做任何额外的工作。


@Scheduled(fixedRate=5000)
public void deliverScheduledMessage(){

    Notification notification = new Notification();
    notification.setNotificationId(UUID.randomUUID().toString());
    notification.setCreatedAt(new Date());
    notification.setMessage("WELCOME TO RABBITMQ");
    notification.setSeen(Boolean.FALSE);

   sendToQueue(notification);
}

这可能会违背您项目的更大目标,但您可以删除 post-construct 方法 + 单独的线程 + 睡眠,然后简单地使用 Spring @Scheduled 注释'fixed delay' 或者甚至是 cron 表达式。像这样:

@Value("${sr.rabbit.routing.name}")
private String routingName;

@Value("${sr.rabbit.exchange.name}")
private String exchangeName;


@Scheduled(fixedDelay = 5000, initialDelay = 5000)
public void runSomething() {

    Notification notification = new Notification();
    notification.setNotificationId(UUID.randomUUID().toString());
    notification.setCreatedAt(new Date());
    notification.setMessage("WELCOME TO RABBITMQ");
    notification.setSeen(Boolean.FALSE);

    try {
        sendToQueue(notification);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

@Autowired
private RabbitTemplate rabbitTemplate;

public void sendToQueue(Notification notification) throws InterruptedException  {
    System.out.println("Notification Sent ID : " + notification.getNotificationId());
    rabbitTemplate.convertAndSend(exchangeName, routingName, notification);
}

这是关于 @Scheduled 注释的精彩教程:

不要忘记按照教程中的说明将@EnableScheduling 添加到您的应用程序。