本文介绍了如何在java中使用RabbitMQ实现RPC机制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在java中使用RabbitMQ实现RPC机制(生产者和消费者)?我也访问官方网站但我正在详细了解这些事情。
how to implement RPC Mechanism(both producer and consumer) using RabbitMQ in java?i am also visit official site http://www.rabbitmq.com/api-guide.html#rpc but i am getting detail description about this things.
谢谢
推荐答案
如果没有,您可以下载源代码这里包含示例代码的Java API。
那里有一个示例文件夹 - 下面的代码来自HelloServer .java和HelloClient.java
If not you can download the source for the Java API which includes sample code here. http://www.rabbitmq.com/releases/rabbitmq-java-client/v2.0.0/rabbitmq-java-client-2.0.0.zipThere is an example folder in there - The code below is from HelloServer.java and 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);
}
}
}
这篇关于如何在java中使用RabbitMQ实现RPC机制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!