首先commend
创建工具类 sendCommend:
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.Channel;
public class SendCommend {
public static void sendCommend(String ip,String queue_name,String message) throws Exception{
//创建工厂
ConnectionFactory factory = new ConnectionFactory();
//设置RabbitMQ相关信息
factory.setHost(ip);//本地主机
//创建连接
Connection con = factory.newConnection();
//使用连接创建通道
Channel channel = con.createChannel();
//交换机名
channel.exchangeDeclare(queue_name, "topic",true);
//发布消息
channel.basicPublish(queue_name,"",null,message.getBytes("UTF-8"));
System.out.printf("[x]已发送消息");
channel.close();
con.close();
}
}
调用就更简单了 几句话 当然我这里处理的是他的message的值 根据传的数据不同 灵活拼接就是了:
JSONObject jsonObject = new JSONObject();
jsonObject.put("key", value);
JSONObject obj = new JSONObject();
obj.put("key", "value");
obj.put("key", jsonObject);
String message = obj.toString();
SendCommend.sendCommend("服务器ip地址", "发送的交换机", message);
下面介绍RPC模式:
rpc相比较commend模式呢 多了一个返回值 ,怎么说呢 就是它既是生产者 也是消费者 其实咱们的消息队列可以看成一个在线的数据库 就比较好理解了 废话不多说 直接看代码
import java.io.IOException;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;
public class SendRpc {
public static String sendRpc(String ip,String queue_name,String message) throws Exception{
ConnectionFactory factory = new ConnectionFactory();
//设置RabbitMQ相关信息
factory.setHost(ip);//本地主机
//创建连接
Connection con = factory.newConnection();
//使用连接创建通道
Channel channel = con.createChannel();
String callBack = call(message, channel, queue_name);
return callBack;
}
public static String call(String message,Channel channel,String queue_name) throws IOException, InterruptedException {
final String corrId = UUID.randomUUID().toString();
String replyQueueName = channel.queueDeclare().getQueue();
AMQP.BasicProperties props = new AMQP.BasicProperties
.Builder()
.correlationId(corrId)
.replyTo(replyQueueName)
.build();
channel.basicPublish("", queue_name, props, message.getBytes("UTF-8"));
final BlockingQueue<String> response = new ArrayBlockingQueue<String>(1);
String ctag = channel.basicConsume(replyQueueName, true, new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
if (properties.getCorrelationId().equals(corrId)) {
response.offer(new String(body, "UTF-8"));
}
}
});
String result = response.take();
channel.basicCancel(ctag);
return result;
}
}
调用:
String s = SendRpc.sendRpc("ip", "交换机名", message);
具体返回的json数据还需要自己去解析
学习的话 官网上有现成的代码demo 讲的也挺不错 可以看下官网:http://www.rabbitmq.com/