如何在java中使用RabbitMQ实现RPC机制(生产者和消费者)?我也访问官方网站http://www.rabbitmq.com/api-guide.html#rpc但是我正在详细描述这些事情。
由于
答案 0 :(得分:8)
http://www.rabbitmq.com/api-guide.html#rpc
如果没有,您可以在此处下载包含示例代码的Java API源代码。 http://www.rabbitmq.com/releases/rabbitmq-java-client/v2.0.0/rabbitmq-java-client-2.0.0.zip 那里有一个示例文件夹 - 下面的代码来自HelloServer.java和HelloClient.java
服务器强>
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.StringRpcServer;
public class HelloServer {
public static void main(String[] args) {
try {
String hostName = (args.length > 0) ? args[0] : "localhost";
int portNumber = (args.length > 1) ? Integer.parseInt(args[1]) : AMQP.PROTOCOL.PORT;
ConnectionFactory connFactory = new ConnectionFactory();
connFactory.setHost(hostName);
connFactory.setPort(portNumber);
Connection conn = connFactory.newConnection();
final Channel ch = conn.createChannel();
ch.queueDeclare("Hello", false, false, false, null);
StringRpcServer server = new StringRpcServer(ch, "Hello") {
public String handleStringCall(String request) {
System.out.println("Got request: " + request);
return "Hello, " + request + "!";
}
};
server.mainloop();
} catch (Exception ex) {
System.err.println("Main thread caught exception: " + ex);
ex.printStackTrace();
System.exit(1);
}
}
}
<强>客户端强>
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.RpcClient;
public class HelloClient {
public static void main(String[] args) {
try {
String request = (args.length > 0) ? args[0] : "Rabbit";
String hostName = (args.length > 1) ? args[1] : "localhost";
int portNumber = (args.length > 2) ? Integer.parseInt(args[2]) : AMQP.PROTOCOL.PORT;
ConnectionFactory cfconn = new ConnectionFactory();
cfconn.setHost(hostName);
cfconn.setPort(portNumber);
Connection conn = cfconn.newConnection();
Channel ch = conn.createChannel();
RpcClient service = new RpcClient(ch, "", "Hello");
System.out.println(service.stringCall(request));
conn.close();
} catch (Exception e) {
System.err.println("Main thread caught exception: " + e);
e.printStackTrace();
System.exit(1);
}
}
}