Нужен пример запроса (Java)-Reply(C++) в утешении.

import com.solacesystems.jcsmp.BytesXMLMessage;
import com.solacesystems.jcsmp.JCSMPException;
import com.solacesystems.jcsmp.JCSMPFactory;
import com.solacesystems.jcsmp.JCSMPProperties;
import com.solacesystems.jcsmp.JCSMPRequestTimeoutException;
import com.solacesystems.jcsmp.JCSMPSession;
import com.solacesystems.jcsmp.JCSMPStreamingPublishEventHandler;
import com.solacesystems.jcsmp.Requestor;
import com.solacesystems.jcsmp.TextMessage;
import com.solacesystems.jcsmp.Topic;
import com.solacesystems.jcsmp.XMLMessageConsumer;
import com.solacesystems.jcsmp.XMLMessageListener;
import com.solacesystems.jcsmp.XMLMessageProducer;

public class REquestor {

public static void main(String... args) throws JCSMPException {
    // Check command line arguments
    String host="tcp://52.76.233.76:55555";
    String username="ccs_jcsmp_user_ccs3";
    String pwd="password";
    String vpn="default";

    System.out.println("BasicRequestor initializing...");

    // Create a JCSMP Session
    final JCSMPProperties properties = new JCSMPProperties();
    properties.setProperty(JCSMPProperties.HOST, host);     // host:port
    properties.setProperty(JCSMPProperties.USERNAME, username); // client-username
    properties.setProperty(JCSMPProperties.PASSWORD, pwd); // client-password
    properties.setProperty(JCSMPProperties.VPN_NAME,  vpn); // message-vpn
    final JCSMPSession session =  JCSMPFactory.onlyInstance().createSession(properties);
    session.connect();

    //This will have the session create the producer and consumer required
    //by the Requestor used below.

    /** Anonymous inner-class for handling publishing events */
    @SuppressWarnings("unused")
    XMLMessageProducer producer = session.getMessageProducer(new JCSMPStreamingPublishEventHandler() {

        public void responseReceived(String messageID) {
            System.out.println("Producer received response for msg: " + messageID);
        }

        public void handleError(String messageID, JCSMPException e, long timestamp) {
            System.out.printf("Producer received error for msg: %s@%s - %s%n",
                    messageID,timestamp,e);
        }
    });

    XMLMessageConsumer consumer = session.getMessageConsumer((XMLMessageListener)null);
//        final XMLMessageConsumer consumer = session.getMessageConsumer(new     XMLMessageListener() {
//
//            public void onReceive(BytesXMLMessage reply) {
//
//                System.out.printf("TextMessage reply received: '%s'%n",((TextMessage)reply).getText());
//
//            }
//
//            public void onException(JCSMPException e) {
//                System.out.printf("Consumer received exception: %s%n", e);
//            }
//        });
//        consumer.
    consumer.start();

    final Topic topic = JCSMPFactory.onlyInstance().createTopic("topicAnkit");

    //Time to wait for a reply before timing out
    final int timeoutMs = 100000;
    TextMessage request = JCSMPFactory.onlyInstance().createMessage(TextMessage.class);
    final String text = "Sample Request from Java!";
    request.setText(text);

    try {
        Requestor requestor = session.createRequestor();
        System.out.printf("Connected. About to send request message '%s' to topic '%s'...%n",text,topic.getName());
        BytesXMLMessage reply = requestor.request(request, timeoutMs, topic);

        // Process the reply
        if (reply instanceof TextMessage) {
            System.out.printf("TextMessage response received: '%s'%n",
                    ((TextMessage)reply).getText());
        }
        System.out.printf("Response Message Dump:%n%s%n",reply.dump());
    } catch (JCSMPRequestTimeoutException e) {
        System.out.println("Failed to receive a reply in " + timeoutMs + " msecs");
    }

    System.out.println("Exiting...");
    session.closeSession();
}
}

Поэтому мое требование - я собираюсь отправить сообщение в "TopicAnkit" и прослушать ответ в какой-либо теме / очереди "topicResponse". Как этого добиться? Я вижу в своем ответчике C++, я получаю запрос и отправляю ответ этой программе, но этот Java-реквестер не слушает никаких тем. Я вижу, что временная тема создана в поле sendTo для запрашивающей стороны, и отправка прошла успешно, но запрашивающая сторона не получает ответ. Пожалуйста, совет 1. Как получить ответ в Java запрашивающей стороне из этой временной темы 2. Как указать тему для прослушивания, чтобы C++ мог отправить ответ на эту тему.

Спасибо Анкит

2 ответа

Похоже, вы явно не устанавливаете тему ответа, которую хотите использовать.

Это может быть установлено в сообщении или сеансе, см. https://docs.solace.com/API-Developer-Online-Ref-Documentation/java/com/solacesystems/jcsmp/Requestor.html

добавлять

final Topic responseTopic = JCSMPFactory.onlyInstance().createTopic("responseTopic");

request.setReplyTo(responseTopic);

перед отправкой сообщения

Проверьте сообщения CorrelationId и ReplyTo.

Согласно документации по утешению API, не забывайте про "#":

Запрашивающая сторона использует значения CorrelationId, начинающиеся с '#', которые зарезервированы для внутреннего использования, такого как запрос / ответ двух сторон. Если для получения ответа требуются другие приложения, укажите CorrelationId приложения.

Другие вопросы по тегам