개발 공부
RabbitMQ Sendding Java
king yun bell
2023. 6. 13. 13:34
먼저 Send class를 설정하고, Queue 이름을 설정한다.
public class Send {
private final static String QUEUE_NAME = "hello";
}
이후, 서버에 대한 연결을 해준다.
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
try (Connection connection = factory.newConnection();
Channel channel = connection.createChannel()) {
}
지금은 localhost에 연결을 하지만 다른 ip나 호스트 주소를 추가하여 넣을 수 있다.
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
String message = "Hello World!";
channel.basicPublish("", QUEUE_NAME, null, message.getBytes(StandardCharsets.UTF_8));
System.out.println(" [x] Sent '" + message + "'");
데이터는 byte배열 임으로 원하는 데이터를 넣을 수 있다.
지금은 Hello World! 라는 String 데이터를 전송해 보자.
package send;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import java.nio.charset.StandardCharsets;
public class Send {
private final static String QUEUE_NAME = "hello";
public static void main(String[] argv) throws Exception {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
try (Connection connection = factory.newConnection();
Channel channel = connection.createChannel()) {
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
String message = "Hello World!";
channel.basicPublish("", QUEUE_NAME, null, message.getBytes(StandardCharsets.UTF_8));
System.out.println(" [x] Sent '" + message + "'");
}
}
}