依赖包
compile 'com.rabbitmq:amqp-client:5.5.0'
发送消息
RabbitMQUtils2.setupConnectionFactory();
RabbitMQUtils2.basicPublish();
接收消息
RabbitMQUtils2.setupConnectionFactory();
RabbitMQUtils2.basicConsume();
RabbitMQUtils相关方法
public class RabbitMQUtils2 {
private static String userName = "Admin";
private static String passWord = "123456";
private static String hostName = "192.168.130.64";
private static int portNum = 5672;
private static String exchangeName = "你设置的exchange的名字";
private static ConnectionFactory factory = new ConnectionFactory();
private static final String routingKey = "你设置的routingKey ";
/**
* Rabbit配置
*/
public static void setupConnectionFactory() {
factory.setUsername(userName);
factory.setPassword(passWord);
factory.setHost(hostName);
factory.setPort(portNum);
}
/**
* 发消息
*/
public static void basicPublish() {
new Thread(){
@Override
public void run() {
super.run();
try {
//连接
Connection connection = factory.newConnection();
//通道
Channel channel = connection.createChannel();
//消息发布
byte[] msg = "hello friend!".getBytes();
//rountingKey 自己任意填写
channel.basicPublish(exchangeName, routingKey, null, msg);
} catch (IOException e) {
e.printStackTrace();
} catch (TimeoutException e) {
e.printStackTrace();
}
}
}.start();
}
/**
* 收消息
*/
public static void basicConsume() {
new Thread(){
@Override
public void run() {
super.run();
try {
//连接
Connection connection = factory.newConnection();
//通道
final Channel channel = connection.createChannel();
//声明了一个交换和一个服务器命名的队列,然后将它们绑定在一起。
channel.exchangeDeclare(exchangeName, "fanout", true);
// String queueName = channel.queueDeclare().getQueue();
String queueName = "你配置的exchange名字.你设置的routingKey";
Log.e("TAG", queueName + " :queueName");
channel.queueBind(queueName, exchangeName, routingKey);
//实现Consumer的最简单方法是将便捷类DefaultConsumer子类化。可以在basicConsume 调用上传递此子类的对象以设置订阅:
channel.basicConsume(queueName, false, "administrator", new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
super.handleDelivery(consumerTag, envelope, properties, body);
//路由密钥
String rountingKey = envelope.getRoutingKey();
//contentType字段,如果尚未设置字段,则为null。
String contentType = properties.getContentType();
//接收到的消息
String msg = new String(body, "UTF-8");
//交付标记
long deliveryTag = envelope.getDeliveryTag();
channel.basicAck(deliveryTag, false);
}
});
} catch (IOException e) {
e.printStackTrace();
} catch (TimeoutException e) {
e.printStackTrace();
}
}
}.start();
}
}
exchange配置
在rabbitMQ管理界面添加exchangge,配置你想配置的exchange名字,(如图红色部分就是你配置的名字)
三种类型交换器
可参考https://blog.youkuaiyun.com/message_lx/article/details/77584771