Created
November 10, 2021 06:45
-
-
Save gbzarelli/e2f6d5632126295a75429a2135f62208 to your computer and use it in GitHub Desktop.
Sample client rabbitmq with test containers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import com.rabbitmq.client.Channel; | |
import com.rabbitmq.client.Connection; | |
import com.rabbitmq.client.ConnectionFactory; | |
import java.io.IOException; | |
import java.util.concurrent.TimeoutException; | |
import org.testcontainers.containers.RabbitMQContainer; | |
public class RabbitMQClient { | |
public static void sendMessage(final RabbitMQContainer rabbitMQContainer, final String queue, | |
final byte[] message) throws IOException, TimeoutException { | |
try (Connection connection = getConnection(rabbitMQContainer)) { | |
try (Channel channel = connection.createChannel()) { | |
channel.basicPublish("", queue, null, message); | |
} | |
} | |
} | |
public static void purgeQueue(final RabbitMQContainer rabbitMQContainer, final String queue) | |
throws IOException, TimeoutException { | |
try (Connection connection = getConnection(rabbitMQContainer)) { | |
try (Channel channel = connection.createChannel()) { | |
channel.queuePurge(queue); | |
} | |
} | |
} | |
private static Connection getConnection(final RabbitMQContainer rabbitMQContainer) | |
throws IOException, TimeoutException { | |
final var factory = new ConnectionFactory(); | |
factory.setHost(rabbitMQContainer.getHost()); | |
factory.setPort(rabbitMQContainer.getMappedPort(5672)); | |
factory.setUsername(rabbitMQContainer.getAdminUsername()); | |
factory.setPassword(rabbitMQContainer.getAdminPassword()); | |
return factory.newConnection(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment