rabbitmq

rabbitmq - ACCESS_REFUSED 에러

coffee. 2024. 1. 25. 16:14
import java.io.IOException;
import java.nio.charset.StandardCharsets;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

public class Send {
	private final static String QUEUE_NAME = "hello";
	public static void main(String[] args) 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+"'");
		}
	}
}

rabbitmq 공식 문서의 hello world 예제를 하던중 다음과 같은 에러를 만났습니다.

 

더보기

rabbitmq의 username과 password를 설정해 주지 않아 생기는 오류입니다.

다음과 같이 코드에 username과 password를 설정해 줍시다.

import java.io.IOException;
import java.nio.charset.StandardCharsets;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

public class Send {
	private final static String QUEUE_NAME = "hello";
	public static void main(String[] args) throws Exception {
		ConnectionFactory factory = new ConnectionFactory();
		factory.setUsername("username");
		factory.setPassword("password");
		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+"'");
		}
	}
}