1:生产者
package org.jeecg.modules.test.rabbitmq.controller;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.MessageProperties;
public class Producer {
public static void producer(){
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("。。。。。");
factory.setPort(。。。。。);
factory.setUsername("。。。。。");
factory.setPassword("。。。。。");
try{
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.exchangeDeclare("exchange", "fanout", true, true, true, null);
channel.queueDeclare("hello", true, true, true, null);
channel.queueBind("hello", "exchange", "", null);
channel.basicPublish("exchange", "hello", MessageProperties.PERSISTENT_TEXT_PLAIN, "hello rabbitMQ".getBytes());
channel.close();
connection.close();
}catch (Exception e){
e.printStackTrace();
}
}
}
2:消费者
package org.jeecg.modules.test.rabbitmq.controller;
import com.rabbitmq.client.*;
import java.io.IOException;
public class Consumer {
public static void consumer() {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("。。。。。");
factory.setPort(。。。。。);
factory.setUsername("。。。。。");
factory.setPassword("。。。。。");
try{
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.queueDeclare("hello", true, true, true, null);
channel.basicConsume("hello", true, new DefaultConsumer(channel){
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
System.err.println("取出消息:" + new String(body));
}
});
}catch (Exception e){
e.printStackTrace();
}
}
}
3:mian方法测试
public static void main(String[] args) {
-----;
}