Search code examples
javaspring-bootspring-rabbit

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


I'm new for springboot and rabbitmq. how to make every 5 seconds send a message in rabbitmq. I tried to do it in the code below but I'm not sure. Can you help me? thanks...

Sample code:

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);
     }

}

Solution

  • This may go against the greater goal of your project, but you could remove the post-construct method + separate thread + sleep, and then simply use the Spring @Scheduled annotation with a 'fixed delay' or perhaps even a cron expression. Something like this:

    @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);
    }
    

    Here is a great tutorial on the @Scheduled annotation:

    Don't forget to add the @EnableScheduling to your application as mentioned in the tutorial.