参考文章:
http://www.rabbitmq.com/install-rpm.html
https://www.cnblogs.com/uptothesky/p/6094357.html
主要步骤:
1.安装GoLang依赖
http://www.rabbitmq.com/install-rpm.html#install-zero-dependency-rpm
2.rabbitmq-serverrpm安装
http://www.rabbitmq.com/install-rpm.html#with-rpm
3.启动管理UI插件
rabbitmq-pluginsenable rabbitmq_management
4.修改配置,允许非localhost远程访问
vi/etc/rabbitmq/rabbitmq.config
[{rabbit,[{loopback_users,[]}]}].
5.启动服务
servicerabbitmq-server start
6.查看服务状态
servicerabbitmq-server status
7.访问管理UI端口
8.java helloworld
http://www.rabbitmq.com/java-client.html
8.1发布消息
importcom.rabbitmq.client.Connection;
importcom.rabbitmq.client.Channel;
importcom.rabbitmq.client.ConnectionFactory;
importjava.io.IOException;
importjava.util.concurrent.TimeoutException;
public classPublisher {
public static void main(String[] args) throws IOException,TimeoutException {
ConnectionFactory factory = new ConnectionFactory();
factory.setUsername("guest");
factory.setPassword("guest");
factory.setVirtualHost("/");
factory.setHost("10.62.156.211");
factory.setPort(5672);
Connection conn = factory.newConnection();
System.out.println(conn);
Channel channel = conn.createChannel();
String exchangeName = "madixinExchange";
String queueName = "madixinQueueName";
String routingKey = "madixinRoutingKey";
channel.exchangeDeclare(exchangeName,"direct",true);
channel.queueDeclare(queueName,true,false,null);
channel.queueBind(queueName,exchangeName,routingKey);
byte[] messageBodyBytes = "44".getBytes();
channel.basicpublish(exchangeName,routingKey,null,messageBodyBytes);
channel.close();
conn.close();
}
}
8.2订阅消息
importcom.rabbitmq.client.*;
importjava.io.IOException;
importjava.util.concurrent.TimeoutException;
public classSubscribe {
public static void main(String[] args) throws IOException,TimeoutException {
ConnectionFactory factory = new ConnectionFactory();
factory.setUsername("guest");
factory.setPassword("guest");
factory.setVirtualHost("/");
factory.setHost("10.62.156.211");
factory.setPort(5672);
Connection conn = factory.newConnection();
System.out.println(conn);
final Channel channel = conn.createChannel();
String queueName = "madixinQueueName";
boolean autoAck = false;
channel.basicConsume(queueName,autoAck,"myConsumerTag",
new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag,
Envelope envelope,
AMQP.BasicProperties properties,
byte[] body)
throws IOException
{
String routingKey = envelope.getRoutingKey();
String contentType = properties.getContentType();
long deliveryTag = envelope.getDeliveryTag();
String s= new String(body);
// (process the message components here ...)
System.out.println(s);
channel.basicAck(deliveryTag,false);
}
});
try {
Thread.sleep(50000);
System.out.println("over");
} catch (InterruptedException e) {
e.printStackTrace();
}
channel.close();
conn.close();
}
}
Github代码参考