Sangil's blog

https://github.com/ChoiSangIl Admin

java rabbitMq 메세지 전송 DEV / PROGRAMING

2020-04-16 posted by sang12


Java에서 RabbitMQ 메세지 전송 하는 방법을 알아보겠습니다.

-maven dependency

<!-- https://mvnrepository.com/artifact/com.rabbitmq/amqp-client -->
<dependency>
	<groupId>com.rabbitmq</groupId>
	<artifactId>amqp-client</artifactId>
	<version>4.11.3</version>
</dependency>

<dependency>

<groupId>com.googlecode.json-simple</groupId>
	<artifactId>json-simple</artifactId>
	<version>1.1.1</version>
</dependency>

-RabbitMq.java

public class RabbitMq {
	ConnectionFactory factory = new ConnectionFactory();
	
	public RabbitMq(String id, String password, String host, int port, int timeout){
		//config
		factory.setUsername(id);
		factory.setPassword(password);
		factory.setHost(host);
		factory.setPort(port);
		factory.setRequestedHeartbeat(timeout); //timeout 10초
	}
	
	private Connection getConnection() throws Exception{
		return factory.newConnection();
	}
	
	/**
	 * 설명 : rabbitMq queue에 데이터를 넣는다.
	 * @author : 최상일
	 * @since : 2020. 4. 16.
	 * @param queueName
	 * @param jsonMessage
	 * @throws Exception
	 */
	public void sendMessage(String queueName, JSONObject jsonMessage) throws Exception{
		Connection conn = getConnection();
		Channel channel = conn.createChannel();
		channel.queueDeclare(queueName, true, false, false, null);
		String message = jsonMessage.toJSONString();
		channel.basicPublish("", queueName, MessageProperties.PERSISTENT_TEXT_PLAIN, message.getBytes());
	    channel.close();
	    conn.close();
	}
}

-rabbitMqTest.java


import org.json.simple.JSONObject;

public class RabbitMqClassTest {
	public static void main(String[] args) {
		RabbitMq rabbit = new RabbitMq("test", "test", "172.0.0.1", 5672, 10);
		JSONObject orderInfoJson = new JSONObject();
		orderInfoJson.put("test1", "123");
		orderInfoJson.put("test2", "234");
		
		try {
			rabbit.sendMessage("test_queue", orderInfoJson);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
#Java RabbitMq #java rabbitMq send
REPLY