how to implement RPC Mechanism(both producer and consumer) using RabbitMQ in java?i am also visit off开发者_高级运维icial site http://www.rabbitmq.com/api-guide.html#rpc but i am getting detail description about this things.
Thanks
http://www.rabbitmq.com/api-guide.html#rpc
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.zip There is an example folder in there - The code below is from HelloServer.java and HelloClient.java
Server
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);
}
}
}
Client
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);
}
}
}
精彩评论