rpc 双队列

需求分析:客户需要请求时候使用一个队列,响应的时候的使用一个队列

客户端:

package rabbitmq;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Envelope;
import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeoutException;

public class RPCClient {

  private Connection connection;
  private Channel channel;
  private String requestQueueName = "req_queue";
  private String responseQueueName = "res_queue";
  public RPCClient() throws IOException, TimeoutException {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("192.168.71.127");
    factory.setUsername("wang");
    factory.setPassword("wang");
    connection = factory.newConnection();
    channel = connection.createChannel();
    channel.queueDeclare(requestQueueName, false, false, false, null);
    channel.queueDeclare(responseQueueName, false, false, false, null);   
  }

  public String call(String message) throws IOException, InterruptedException {
    String corrId = UUID.randomUUID().toString();

    //将corrId、replyQueueName打包发送给consumer  
    /*传输一条消息,AMQP协议预定义了14个属性,下面几个是使用比较频繁的几个属性:
    deliveryMode:配置一个消息是否持久化。(2表示持久化)这个在第二章中有说明。
    contentType :用来描述编码的MIME类型。与html的MIME类型类似,例如,经常使用JSON编码是将此属性设置为一个很好的做法:application/json。
    replyTo : 回调队列的名称。
    correlationId:RPC响应请求的相关编号。*/
    AMQP.BasicProperties props = new AMQP.BasicProperties
            .Builder()
            .correlationId(corrId)
            .replyTo(requestQueueName)
            .build();

    //消息推送
    channel.basicPublish("", requestQueueName, props, message.getBytes("UTF-8"));
     //队列阻塞 等待客户端响应 因为只等待一个响应结果所以是1
    final BlockingQueue<String> response = new ArrayBlockingQueue<String>(1);
    DefaultConsumer consumer=   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 message = new String(body, "UTF-8");
            int  n=  Integer.parseInt(message);
            System.out.println(n);
            System.out.println(" [x] Received '" + message + "'");
        }
      };
      channel.basicConsume(responseQueueName, true,consumer );
    return response.take();
  }

  public void close() throws IOException {
    connection.close();
  }

  public static void main(String[] argv) {
    RPCClient fibonacciRpc = null;
    String response = null;
    try {
      fibonacciRpc = new RPCClient();
      System.out.println(" [x] Requesting fib(30)");
      response = fibonacciRpc.call("30");
      System.out.println(" [.] Got '" + response + "'");
    }
    catch  (IOException | TimeoutException | InterruptedException e) {
      e.printStackTrace();
    }
    finally {
      if (fibonacciRpc!= null) {
        try {
          fibonacciRpc.close();
        }
        catch (IOException _ignore) {}
      }
    }
  }
}

服务端:

package rabbitmq;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Envelope;

import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeoutException;

public class RPCClient {

  private Connection connection;
  private Channel channel;
  private String requestQueueName = "req_queue";
  private String responseQueueName = "res_queue";
  public RPCClient() throws IOException, TimeoutException {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("192.168.71.127");
    factory.setUsername("wang");
    factory.setPassword("wang");
    connection = factory.newConnection();
    channel = connection.createChannel();
    channel.queueDeclare(requestQueueName, false, false, false, null);
    channel.queueDeclare(responseQueueName, false, false, false, null);   
  }

  public String call(String message) throws IOException, InterruptedException {
    String corrId = UUID.randomUUID().toString();

    //将corrId、replyQueueName打包发送给consumer  
    /*传输一条消息,AMQP协议预定义了14个属性,下面几个是使用比较频繁的几个属性:
    deliveryMode:配置一个消息是否持久化。(2表示持久化)这个在第二章中有说明。
    contentType :用来描述编码的MIME类型。与html的MIME类型类似,例如,经常使用JSON编码是将此属性设置为一个很好的做法:application/json。
    replyTo : 回调队列的名称。
    correlationId:RPC响应请求的相关编号。*/
    AMQP.BasicProperties props = new AMQP.BasicProperties
            .Builder()
            .correlationId(corrId)
            .replyTo(requestQueueName)
            .build();

    //消息推送
    channel.basicPublish("", requestQueueName, props, message.getBytes("UTF-8"));
     //队列阻塞 等待客户端响应 因为只等待一个响应结果所以是1
    final BlockingQueue<String> response = new ArrayBlockingQueue<String>(1);
    DefaultConsumer consumer=   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 message = new String(body, "UTF-8");
            int  n=  Integer.parseInt(message);
            System.out.println(n);
            System.out.println(" [x] Received '" + message + "'");
        }
      };
      channel.basicConsume(responseQueueName, true,consumer );
    return response.take();
  }

  public void close() throws IOException {
    connection.close();
  }

  public static void main(String[] argv) {
    RPCClient fibonacciRpc = null;
    String response = null;
    try {
      fibonacciRpc = new RPCClient();
      System.out.println(" [x] Requesting fib(30)");
      response = fibonacciRpc.call("30");
      System.out.println(" [.] Got '" + response + "'");
    }
    catch  (IOException | TimeoutException | InterruptedException e) {
      e.printStackTrace();
    }
    finally {
      if (fibonacciRpc!= null) {
        try {
          fibonacciRpc.close();
        }
        catch (IOException _ignore) {}
      }
    }
  }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值