Architecture 出版及;订阅模式与主题交换

Architecture 出版及;订阅模式与主题交换,architecture,rabbitmq,message-queue,rpc,publish-subscribe,Architecture,Rabbitmq,Message Queue,Rpc,Publish Subscribe,我正在使用事件驱动体系结构开发缓存服务器,其工作原理如下: 我希望将发送到所有副本(扇出交换(?)的操作设置为并将获取操作设置为单个副本(默认交换(?) 我已经阅读了该模式,并且能够使用fanoutexchange使所有服务器响应。我读过关于这个模型的文章,能够做出任意的服务器响应。但我无法将这些方法统一到一个体系结构中。请帮忙 问题: 组织MQ以实现此行为的最佳方式是什么 我应该将两个队列绑定到一个交换机中吗 我想用correlationId从服务器响应到客户端。我应该重用现有队列/交换还是

我正在使用事件驱动体系结构开发缓存服务器,其工作原理如下:

我希望
将发送到所有副本(扇出交换(?)的操作设置为
并将
获取操作设置为单个副本(默认交换(?)

我已经阅读了该模式,并且能够使用
fanoutexchange
使所有服务器响应。我读过关于这个模型的文章,能够做出任意的服务器响应。但我无法将这些方法统一到一个体系结构中。请帮忙

问题:

  • 组织MQ以实现此行为的最佳方式是什么
  • 我应该将两个队列绑定到一个交换机中吗
  • 我想用
    correlationId
    从服务器响应到客户端。我应该重用现有队列/交换还是创建新的队列/交换

  • 您需要设置操作的队列。通过这种方式,N个客户端可以接收/响应消息。

    在浏览了您的问题域之后,我了解到的是-在运行时,多个客户端将向RabbitMQ发送“set”“get”消息,每个“set”消息都将由此时处于活动状态的每个服务器缓存处理。而“get”消息需要由任何一个服务器缓存处理,并且需要将响应消息发送回发送“get”消息的客户端

    如果我错了,请纠正我

    在这种情况下,可以公平地假设客户端将有单独的触发点来生成/发布“get”/“set”消息。因此,逻辑上,“获取”消息生产者和“设置”消息发布者将是两个独立的程序/类

    因此,您对发布/订阅和RPC模型的选择看起来是合乎逻辑的。您需要做的唯一一件事是将“set”“get”消息处理和服务器缓存结合起来,这可以很容易地使用两个单独的通道(在同一连接中)来完成服务器缓存上的设置获取消息各一个。请参阅下面附加的我的代码。我使用了相同示例的java代码(来自rabbitmq站点)这是您在问题中提到的。进行了一些小的修改,而且非常简单。在python中也不难做到这一点

    现在来问你一些问题-

    组织MQ以实现此行为的最佳方式是什么

    您对发布/订阅和RPC模型的选择看起来合乎逻辑。 客户端将向exchange发布“set”消息(键入扇出,例如name“set_ex”),每个服务器缓存实例将侦听其绑定到exchange的临时队列(“set_ex”
    )。 客户端将向exchange生成“get”消息(键入Direct,例如name“get_ex”),队列“get_q”将与其队列名绑定到此exchange。每个服务器缓存都将侦听此get_q“。服务器缓存将结果消息发送到随“get”消息一起传递的临时队列名。一旦客户端收到响应消息,连接即关闭,临时队列即被删除(注意-在下面的示例代码中,我已将“get_q”绑定到默认exchange中,就像rabbitmq站点上的示例一样。但将“get_q”绑定到单独的exchange(直接键入)以提高可管理性并不困难。)

    我应该将两个队列绑定到一个交换机中吗

    我认为这不是一个正确的选择,因为对于发布/订阅场景,您将明确需要一个扇出交换,并且发送到扇出交换的每个消息都会复制到绑定到交换的每个队列。而且我们不希望将get消息推送到所有服务器缓存中

    我想使用correlationId从服务器响应到客户端。 我应该重用现有队列/交换还是创建新的队列/交换

    您所需要做的就是将响应消息从服务器发送到tempQueueName,该消息与原始“get”消息一起传递,正如rabbitmq提供的示例中所使用的那样

    用于发布“设置”消息的客户端代码。

    public class Client {
    
        private static final String EXCHANGE_NAME_SET = "set_ex";
    
        public static void main(String[] args) throws IOException, TimeoutException {
    
            ConnectionFactory factory = new ConnectionFactory();
            factory.setHost("localhost");
            Connection connection = factory.newConnection();
            Channel channel = connection.createChannel();
    
            channel.exchangeDeclare(EXCHANGE_NAME_SET, BuiltinExchangeType.FANOUT);
    
            String message = getMessage(args);
    
            channel.basicPublish(EXCHANGE_NAME_SET, "", null, message.getBytes("UTF-8"));
            System.out.println("Sent '" + message + "'");
    
    
            channel.close();
            connection.close();
    
        }
    
        private static String getMessage(String[] strings) {
            if (strings.length < 1)
                return "info: Hello World!";
            return joinStrings(strings, " ");
        }
    
        private static String joinStrings(String[] strings, String delimiter) {
            int length = strings.length;
            if (length == 0)
                return "";
            StringBuilder words = new StringBuilder(strings[0]);
            for (int i = 1; i < length; i++) {
                words.append(delimiter).append(strings[i]);
            }
            return words.toString();
        }
    
    
    }
    
    public class RPCClient {
    
        private static final String EXCHANGE_NAME_GET = "get_ex";
        private Connection connection;
          private Channel channel;
          private String requestQueueName = "get_q";
          private String replyQueueName;
    
        public RPCClient() throws IOException, TimeoutException {
            ConnectionFactory factory = new ConnectionFactory();
            factory.setHost("localhost");
    
            connection = factory.newConnection();
            channel = connection.createChannel();
    
            replyQueueName = channel.queueDeclare().getQueue();
          }
    
        public String call(String message) throws IOException, InterruptedException {
            String corrId = UUID.randomUUID().toString();
    
            AMQP.BasicProperties props = new AMQP.BasicProperties
                    .Builder()
                    .correlationId(corrId)
                    .replyTo(replyQueueName)
                    .build();
    
            //channel.basicPublish("", requestQueueName, props, message.getBytes("UTF-8"));
            channel.basicPublish("", requestQueueName, props, message.getBytes("UTF-8"));
    
            final BlockingQueue<String> response = new ArrayBlockingQueue<String>(1);
    
            channel.basicConsume(replyQueueName, true, 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"));
                }
              }
            });
    
            return response.take();
          }
    
         public void close() throws IOException {
                connection.close();
              }
    
    
        public static void main(String[] args) throws IOException, TimeoutException {
    
            RPCClient rpcClient = null;
            String response = null;
            try {
                rpcClient = new RPCClient();
    
              System.out.println(" sending get message");
              response = rpcClient.call("30");
              System.out.println(" Got '" + response + "'");
            }
            catch  (IOException | TimeoutException | InterruptedException e) {
              e.printStackTrace();
            }
            finally {
              if (rpcClient!= null) {
                try {
                    rpcClient.close();
                }
                catch (IOException _ignore) {}
              }
            }
    
        }
    
    
    }
    
    public class ServerCache1 {
    
        private static final String EXCHANGE_NAME_SET = "set_ex";
        private static final String EXCHANGE_NAME_GET = "get_ex";
        private static final String RPC_GET_QUEUE_NAME = "get_q";
        private static final String s = UUID.randomUUID().toString();
    
        public static void main(String[] args) throws IOException, TimeoutException {
    
            System.out.println("Server Id " + s);
    
            ConnectionFactory factory = new ConnectionFactory();
            factory.setHost("localhost");
            Connection connection = factory.newConnection();
    
            // set server to receive and process set messages
            Channel channelSet = connection.createChannel();
            channelSet.exchangeDeclare(EXCHANGE_NAME_SET, BuiltinExchangeType.FANOUT);
    
            String queueName = channelSet.queueDeclare().getQueue();
            channelSet.queueBind(queueName, EXCHANGE_NAME_SET, "");
    
            System.out.println("waiting for set message");
    
            Consumer consumerSet = new DefaultConsumer(channelSet) {
                  @Override
                  public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body)
                      throws IOException {
                    String message = new String(body, "UTF-8");
                    System.out.println("Received '" + message + "'");
                  }
            };
    
            channelSet.basicConsume(queueName, true, consumerSet);
    
            // here onwards following code is to set up Get message processing at Server cache
    
            Channel channelGet = connection.createChannel();
            channelGet.queueDeclare(RPC_GET_QUEUE_NAME, false, false, false, null);
    
            channelGet.basicQos(1);
    
            System.out.println("waiting for get message");
    
            Consumer consumerGet = new DefaultConsumer(channelGet) {
                @Override
                public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
    
                    AMQP.BasicProperties replyProps = new AMQP.BasicProperties
                            .Builder()
                            .correlationId(properties.getCorrelationId())
                            .build();
    
                    System.out.println("received get message");
                    String response = "get response from server " + s;
    
                    channelGet.basicPublish( "", properties.getReplyTo(), replyProps, response.getBytes("UTF-8"));
                    channelGet.basicAck(envelope.getDeliveryTag(), false);
                    // RabbitMq consumer worker thread notifies the RPC server owner thread 
                    synchronized(this) {
                        this.notify();
                    }
                }
            };
    
            channelGet.basicConsume(RPC_GET_QUEUE_NAME, false, consumerGet);
         // Wait and be prepared to consume the message from RPC client.
            while (true) {
                synchronized(consumerGet) {
                    try {
                        consumerGet.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();            
                    }
                }
            }
    
        }
    
    }
    

    希望这有帮助。

    据我所知,您正在使用RabbitMQ作为负载平衡器/服务发现机制。因此,您的客户机和缓存不需要了解彼此以及彼此的体系结构。您是否考虑过在缓存集群前面安装负载平衡器,它会更快,而且不会涉及:路由、队列、代理设置、相关ID等。