RabbitMQ RPC java实现

2025-07-22 15:17:57

1、搭建RabbitMQ 服务,设置相关参数,本文总线服务已提前安装,再次不在赘述相关步骤。

RabbitMQ RPC java实现RabbitMQ RPC java实现

3、客户端代码:RPCClient.javapackagecom.cn.trap.test.rpc;importcom.rabbitmq.艘早祓胂client.ConnectionFactory;importcom.rabbitmq.client.Connection;importcom.rabbitmq.client.Channel;importcom.rabbitmq.client.QueueingConsumer;importcom.rabbitmq.client.AMQP.BasicProperties;importjava.util.UUID;publicclassRPCClient{privateConnectionconnection;privateChannelchannel;privateStringrequestQueueName="rpc_queue";privateStringreplyQueueName;privateQueueingConsumerconsumer;publicRPCClient()throwsException{ConnectionFactoryfactory=newConnectionFactory();factory.setHost("192.168.100.17"); //RabbitMQ 服务地址factory.setPassword("admin");factory.setUsername("admin");factory.setPort(5677);connection=factory.newConnection();channel=connection.createChannel();replyQueueName=channel.queueDeclare().getQueue();consumer=newQueueingConsumer(channel);channel.basicConsume(replyQueueName,true,consumer);}publicStringcall(Stringmessage)throwsException{Stringresponse=null;StringcorrId=UUID.randomUUID().toString();BasicPropertiesprops=newBasicProperties.Builder().correlationId(corrId).replyTo(replyQueueName).build();channel.basicPublish("",requestQueueName,props,message.getBytes("UTF-8"));while(true){QueueingConsumer.Deliverydelivery=consumer.nextDelivery();if(delivery.getProperties().getCorrelationId().equals(corrId)){response=newString(delivery.getBody(),"UTF-8");break;}}returnresponse;}publicvoidclose()throwsException{connection.close();}publicstaticvoidmain(String[]argv){RPCClientfibonacciRpc=null;Stringresponse=null;try{fibonacciRpc=newRPCClient();System.out.println("[x]Requestingfib(30)");response=fibonacciRpc.call("30");System.out.println("[.]Got'"+response+"'");}catch(Exceptione){e.printStackTrace();}finally{if(fibonacciRpc!=null){try{fibonacciRpc.close();}catch(Exceptionignore){}}}}}

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
相关推荐
  • 阅读量:24
  • 阅读量:66
  • 阅读量:53
  • 阅读量:90
  • 阅读量:64
  • 猜你喜欢