C++ activemqc++;同步客户端

C++ activemqc++;同步客户端,c++,asynchronous,activemq,activemq-cpp,C++,Asynchronous,Activemq,Activemq Cpp,我有以下来自svn的代码。正如您所看到的,这是一个异步客户机。我想要的是一个同步客户机,这样客户机就可以问我的消费者“我能得到一条消息吗”,我的消费者“当然可以,先生,在这里”。所以我不需要一个同步的客户端,但是我找不到一个同步的例子,当我编写代码的时候,我得到的分段总是失败的 若你们看这段代码,有一个叫做onMessage的方法,这是由于listener,我甚至不能在那个里返回消息。无法更改退货类型 问题是,我怎样才能使这个示例类同步,而不会导致分段失败。这个问题很难回答 /* *根据一个或多

我有以下来自svn的代码。正如您所看到的,这是一个异步客户机。我想要的是一个同步客户机,这样客户机就可以问我的消费者“我能得到一条消息吗”,我的消费者“当然可以,先生,在这里”。所以我不需要一个同步的客户端,但是我找不到一个同步的例子,当我编写代码的时候,我得到的分段总是失败的

若你们看这段代码,有一个叫做onMessage的方法,这是由于listener,我甚至不能在那个里返回消息。无法更改退货类型

问题是,我怎样才能使这个示例类同步,而不会导致分段失败。这个问题很难回答

/*
*根据一个或多个许可证颁发给Apache软件基金会(ASF)
*贡献者许可协议。请参阅随附的通知文件
*本作品提供了有关版权所有权的更多信息。
*ASF根据Apache许可证2.0版将此文件许可给您
*(以下简称“许可证”);除非符合以下要求,否则不得使用此文件
*执照。您可以通过以下方式获得许可证副本:
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
*除非适用法律要求或书面同意,软件
*根据许可证进行的分发是按“原样”进行分发的,
*无任何明示或暗示的保证或条件。
*请参阅许可证以了解管理权限和权限的特定语言
*许可证下的限制。
*/
#包括
#包括
#包括
#包括
#包括
#包括
#包括
#包括
#包括
#包括
#包括
#包括
#包括
#包括
#包括
#包括
#包括
#包括
#包括
#包括
使用名称空间activemq;
使用名称空间activemq::core;
使用名称空间activemq::transport;
使用名称空间decf::lang;
使用名称空间decf::util;
使用名称空间decf::util::concurrent;
使用名称空间cms;
使用名称空间std;
////////////////////////////////////////////////////////////////////////////////
类SimpleAsyncConsumer:PublicExceptionListener,
公共信息监听器,
公共默认传输侦听器{
私人:
连接*连接;
会议*会议;
目的地*目的地;
MessageConsumer*消费者;
布尔主题;
std::string brokerURI;
std::字符串destURI;
布尔克利恩塔克;
私人:
SimpleAsyncConsumer(常数SimpleAsyncConsumer&);
SimpleAsyncConsumer&运算符=(常量SimpleAsyncConsumer&);
公众:
SimpleAsyncConsumer(const std::string和brokerURI,
常量std::string和destURI,
bool useTopic=false,
bool clientAck=false):
连接(空),
会话(空),
目的地(空),
消费者(空),
useTopic(useTopic),
brokerURI(brokerURI),
destURI(destURI),
clientAck(clientAck){
}
虚拟~SimpleAsyncConsumer()抛出(){
这个->清理();
}
无效关闭(){
这个->清理();
}
void runConsumer(){
试一试{
//创建连接工厂
ActiveMQConnectionFactory*连接工厂=
新ActiveMQConnectionFactory(brokerURI);
//创建连接
connection=connectionFactory->createConnection();
删除连接工厂;
ActiveMQConnection*amqConnection=dynamic_cast(连接);
if(amqConnection!=NULL){
amqConnection->addTransportListener(此);
}
连接->开始();
connection->setExceptionListener(此);
//创建会话
if(客户端){
会话=连接->创建会话(会话::客户端确认);
}否则{
会话=连接->创建会话(会话::自动确认);
}
//创建目标(主题或队列)
如果(使用主题){
目的地=会话->创建主题(destURI);
}否则{
目的地=会话->创建队列(destURI);
}
//从会话到主题或队列创建MessageConsumer
消费者=会话->创建消费者(目的地);
消费者->设置消息侦听器(此);
}捕获(CMSException&e){
e、 printStackTrace();
}
}
//从使用者调用,因为此类是已注册的MessageListener。
虚拟void onMessage(const Message*Message)throw(){
静态整数计数=0;
尝试
{
计数++;
const TextMessage*TextMessage=
动态广播(消息);
字符串文本=”;
if(textMessage!=NULL){
text=textMessage->getText();
}否则{
text=“不是短信!”;
}
if(客户端){
消息->确认();
}
printf(“收到的消息#%d:%s\n”,计数,text.c#u str());
}捕获(CMSException&e){
e、 printStackTrace();
}
}
//如果发生了什么不好的事情,你可以在这里看到,因为这门课也被取消了
//已注册为连接的ExceptionListener。
虚拟void onException(const CMSException和ex AMQCPP_未使用){
printf(“发生CMS异常。正在关闭客户端。\n”);
出口(1);
}
虚空传输中断(){

std::cout从前面的问题中,我看到您找到了的receive()功能,这是创建同步接收器的方法。但我不确定您为什么会出现分段错误。我可以为此提出几点建议:

尝试设置一个clientID不确定SessionExecutor上的第129行是否是罪魁祸首,但它正在尝试访问consum
 /*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <decaf/lang/Thread.h>
#include <decaf/lang/Runnable.h>
#include <decaf/util/concurrent/CountDownLatch.h>
#include <activemq/core/ActiveMQConnectionFactory.h>
#include <activemq/core/ActiveMQConnection.h>
#include <activemq/transport/DefaultTransportListener.h>
#include <activemq/library/ActiveMQCPP.h>
#include <decaf/lang/Integer.h>
#include <activemq/util/Config.h>
#include <decaf/util/Date.h>
#include <cms/Connection.h>
#include <cms/Session.h>
#include <cms/TextMessage.h>
#include <cms/BytesMessage.h>
#include <cms/MapMessage.h>
#include <cms/ExceptionListener.h>
#include <cms/MessageListener.h>
#include <stdlib.h>
#include <stdio.h>
#include <iostream>

using namespace activemq;
using namespace activemq::core;
using namespace activemq::transport;
using namespace decaf::lang;
using namespace decaf::util;
using namespace decaf::util::concurrent;
using namespace cms;
using namespace std;

////////////////////////////////////////////////////////////////////////////////
class SimpleAsyncConsumer : public ExceptionListener,
                            public MessageListener,
                            public DefaultTransportListener {
private:

    Connection* connection;
    Session* session;
    Destination* destination;
    MessageConsumer* consumer;
    bool useTopic;
    std::string brokerURI;
    std::string destURI;
    bool clientAck;

private:

    SimpleAsyncConsumer( const SimpleAsyncConsumer& );
    SimpleAsyncConsumer& operator= ( const SimpleAsyncConsumer& );

public:

    SimpleAsyncConsumer( const std::string& brokerURI,
                         const std::string& destURI,
                         bool useTopic = false,
                         bool clientAck = false ) :
        connection(NULL),
        session(NULL),
        destination(NULL),
        consumer(NULL),
        useTopic(useTopic),
        brokerURI(brokerURI),
        destURI(destURI),
        clientAck(clientAck) {
    }

    virtual ~SimpleAsyncConsumer() throw() {
        this->cleanup();
    }

    void close() {
        this->cleanup();
    }

    void runConsumer() {

        try {

            // Create a ConnectionFactory
            ActiveMQConnectionFactory* connectionFactory =
                new ActiveMQConnectionFactory( brokerURI );

            // Create a Connection
            connection = connectionFactory->createConnection();
            delete connectionFactory;

            ActiveMQConnection* amqConnection = dynamic_cast<ActiveMQConnection*>( connection );
            if( amqConnection != NULL ) {
                amqConnection->addTransportListener( this );
            }

            connection->start();

            connection->setExceptionListener(this);

            // Create a Session
            if( clientAck ) {
                session = connection->createSession( Session::CLIENT_ACKNOWLEDGE );
            } else {
                session = connection->createSession( Session::AUTO_ACKNOWLEDGE );
            }

            // Create the destination (Topic or Queue)
            if( useTopic ) {
                destination = session->createTopic( destURI );
            } else {
                destination = session->createQueue( destURI );
            }

            // Create a MessageConsumer from the Session to the Topic or Queue
            consumer = session->createConsumer( destination );
            consumer->setMessageListener( this );

        } catch (CMSException& e) {
            e.printStackTrace();
        }
    }

    // Called from the consumer since this class is a registered MessageListener.
    virtual void onMessage( const Message* message ) throw() {

        static int count = 0;

        try
        {
            count++;
            const TextMessage* textMessage =
                dynamic_cast< const TextMessage* >( message );
            string text = "";

            if( textMessage != NULL ) {
                text = textMessage->getText();
            } else {
                text = "NOT A TEXTMESSAGE!";
            }

            if( clientAck ) {
                message->acknowledge();
            }

            printf( "Message #%d Received: %s\n", count, text.c_str() );
        } catch (CMSException& e) {
            e.printStackTrace();
        }
    }

    // If something bad happens you see it here as this class is also been
    // registered as an ExceptionListener with the connection.
    virtual void onException( const CMSException& ex AMQCPP_UNUSED ) {
        printf("CMS Exception occurred.  Shutting down client.\n");
        exit(1);
    }

    virtual void transportInterrupted() {
        std::cout << "The Connection's Transport has been Interrupted." << std::endl;
    }

    virtual void transportResumed() {
        std::cout << "The Connection's Transport has been Restored." << std::endl;
    }

private:

    void cleanup(){

        //*************************************************
        // Always close destination, consumers and producers before
        // you destroy their sessions and connection.
        //*************************************************

        // Destroy resources.
        try{
            if( destination != NULL ) delete destination;
        }catch (CMSException& e) {}
        destination = NULL;

        try{
            if( consumer != NULL ) delete consumer;
        }catch (CMSException& e) {}
        consumer = NULL;

        // Close open resources.
        try{
            if( session != NULL ) session->close();
            if( connection != NULL ) connection->close();
        }catch (CMSException& e) {}

        // Now Destroy them
        try{
            if( session != NULL ) delete session;
        }catch (CMSException& e) {}
        session = NULL;

        try{
            if( connection != NULL ) delete connection;
        }catch (CMSException& e) {}
        connection = NULL;
    }
};

////////////////////////////////////////////////////////////////////////////////
int main(int argc AMQCPP_UNUSED, char* argv[] AMQCPP_UNUSED) {

    activemq::library::ActiveMQCPP::initializeLibrary();

    std::cout << "=====================================================\n";
    std::cout << "Starting the example:" << std::endl;
    std::cout << "-----------------------------------------------------\n";

    // Set the URI to point to the IPAddress of your broker.
    // add any optional params to the url to enable things like
    // tightMarshalling or tcp logging etc.  See the CMS web site for
    // a full list of configuration options.
    //
    //  http://activemq.apache.org/cms/
    //
    // Wire Format Options:
    // =====================
    // Use either stomp or openwire, the default ports are different for each
    //
    // Examples:
    //    tcp://127.0.0.1:61616                      default to openwire
    //    tcp://127.0.0.1:61616?wireFormat=openwire  same as above
    //    tcp://127.0.0.1:61613?wireFormat=stomp     use stomp instead
    //
    std::string brokerURI =
        "failover:(tcp://127.0.0.1:61616"
//        "?wireFormat=openwire"
//        "&connection.useAsyncSend=true"
//        "&transport.commandTracingEnabled=true"
//        "&transport.tcpTracingEnabled=true"
//        "&wireFormat.tightEncodingEnabled=true"
        ")";

    //============================================================
    // This is the Destination Name and URI options.  Use this to
    // customize where the consumer listens, to have the consumer
    // use a topic or queue set the 'useTopics' flag.
    //============================================================
    std::string destURI = "TEST.FOO"; //?consumer.prefetchSize=1";

    //============================================================
    // set to true to use topics instead of queues
    // Note in the code above that this causes createTopic or
    // createQueue to be used in the consumer.
    //============================================================
    bool useTopics = false;

    //============================================================
    // set to true if you want the consumer to use client ack mode
    // instead of the default auto ack mode.
    //============================================================
    bool clientAck = false;

    // Create the consumer
    SimpleAsyncConsumer consumer( brokerURI, destURI, useTopics, clientAck );

    // Start it up and it will listen forever.
    consumer.runConsumer();

    // Wait to exit.
    std::cout << "Press 'q' to quit" << std::endl;
    while( std::cin.get() != 'q') {}

    // All CMS resources should be closed before the library is shutdown.
    consumer.close();

    std::cout << "-----------------------------------------------------\n";
    std::cout << "Finished with the example." << std::endl;
    std::cout << "=====================================================\n";

    activemq::library::ActiveMQCPP::shutdownLibrary();
}
std::string clientID = "someid";
Connection* conn = connectionFactory->createConnection("", "", clientID);