Creating a message producer

To run this application, we will use the RabbitTemplate.convertAndSend() method to send the message. This method also converts custom Java objects to AMQP messages and is sent to direct exchange. The following BankAccount class is created as a custom class to populate the message properties:

public class BankAccount {

private int accountId;
private String accountType;

public BankAccount(int accountId, String accountType) {
this.accountId = accountId;
this.accountType = accountType;
}

public int getAccountId() {
return accountId;
}

public String getAccountType() {
return accountType;
}

@Override
public String toString() {
return "BankAccount{" +
"Account Id=" + accountId +
", Account Type='" + accountType + ''' +
'}';
}
}

In the following class, we will initialize the preceding class with some proper values and send it to the exchange using RabbitTemplate.convertAndSend():

public class Producer {

private static final Logger LOGGER =
Logger.getLogger(Producer.class);

@SuppressWarnings("resource")
public static void main(String[] args) {
ApplicationContext ctx = new
AnnotationConfigApplication
Context(RabbitMqConfiguration.class);
RabbitTemplate rabbitTemplate =
ctx.getBean(RabbitTemplate.class);
LOGGER.info("Sending bank account information....");
rabbitTemplate.convertAndSend(new BankAccount(100, "Savings
Account"));
rabbitTemplate.convertAndSend(new BankAccount(101, "Current
Account"));

}

}

When we run the preceding code, the producer will send two objects of BankAccount using the convertAndSend() method and the following output will be displayed:

2018-05-13 19:46:58 INFO Producer:17 - Sending bank account information....
2018-05-13 19:46:58 INFO Consumer:17 - Received Message: {"accountId":100,"accountType":"Savings Account"}
2018-05-13 19:46:58 INFO Consumer:17 - Received Message: {"accountId":101,"accountType":"Current Account"}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset