blob: 9ef40b9d26bd5eeec099040fcb9276b36dcb48e1 [file] [log] [blame]
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--
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.
-->
<html>
<head>
<link href="http://activemq.apache.org/styles/site.css" rel="stylesheet" type="text/css"/>
<link href="http://activemq.apache.org/styles/type-settings.css" rel="stylesheet" type="text/css"/>
<script src="http://activemq.apache.org/styles/prototype.js" type="text/javascript"></script>
<script src="http://activemq.apache.org/styles/rico.js" type="text/javascript"></script>
<script src="http://activemq.apache.org/styles/site.js" type="text/javascript"></script>
<style type="text/css">
.maincontent { overflow:hidden; }
</style>
<!--[if IE]>
<style type="text/css">
.maincontent { width:100%; }
</style>
<![endif]-->
<link href='http://activemq.apache.org/styles/highlighter/styles/shCore.css' rel='stylesheet' type='text/css' />
<link href='http://activemq.apache.org/styles/highlighter/styles/shThemeEclipse.css' rel='stylesheet' type='text/css' />
<script src='http://activemq.apache.org/styles/highlighter/scripts/shCore.js' type='text/javascript'></script>
<script src='http://activemq.apache.org/styles/highlighter/scripts/shBrushJava.js' type='text/javascript'></script>
<script type="text/javascript">
SyntaxHighlighter.defaults['toolbar'] = false;
SyntaxHighlighter.all();
</script>
<title>
Apache ActiveMQ &#8482; -- Example
</title>
</head>
<body>
<div class="white_box">
<div class="header">
<div class="header_l">
<div class="header_r">
</div>
</div>
</div>
<div class="content">
<div class="content_l">
<div class="content_r">
<div>
<!-- Banner -->
<p>
</p><div id="asf_logo">
<div id="activemq_logo">
<a shape="rect" style="float:left; width:280px;display:block;text-indent:-5000px;text-decoration:none;line-height:60px; margin-top:10px; margin-left:100px;" href="http://activemq.apache.org/">ActiveMQ</a>
<a shape="rect" style="float:right; width:210px;display:block;text-indent:-5000px;text-decoration:none;line-height:60px; margin-top:15px; margin-right:10px;" href="http://www.apache.org">ASF</a>
</div>
</div>
<p></p>
<div class="top_red_bar">
<div id="site-breadcrumbs">
<a href="index.html">Index</a>&nbsp;&gt;&nbsp;<a href="example.html">Example</a>
</div>
<div id="site-quicklinks">
<p><a shape="rect" href="download.html">Download</a> | <a shape="rect" href="api.html">API</a> | <a shape="rect" href="source.html">Source</a> | <a shape="rect" class="external-link" href="http://activemq.apache.org/discussion-forums.html">Forums</a> | <a shape="rect" href="support.html">Support</a></p>
</div>
</div>
<table border="0">
<tbody>
<tr>
<td valign="top" width="100%">
<div class="wiki-content maincontent"><h2 id="Example-ActiveMQ-CPPinAction">ActiveMQ-CPP in Action</h2>
<p>In the example below we create two classes <strong>HolloWorldConsumer</strong> and <strong>HelloWorldProducer</strong> each of which runs in its own thread. The Producer sends TextMessage objects via a <strong>MessageProducer</strong> instance to the ActiveMQ broker. The Consumer receives messages asynchronously from the broker on the same Topic or Queue as the Producer looking for a set number of TextMessages to arrive. </p>
<p>The following example is taken from the source code and shows a basic usage scenario of ActiveMQ-CPP, you can find other examples in the examples folder that ships with the source distribution of ActiveMQ-CPP:</p>
<div class="code panel pdl" style="border-width: 1px;"><div class="codeHeader panelHeader pdl" style="border-bottom-width: 1px;"><b>main.cpp</b></div><div class="codeContent panelContent pdl">
<pre class="brush: java; gutter: false; theme: Default" style="font-size:12px;">
/*
* 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.
*/
// START SNIPPET: demo
#include &lt;activemq/library/ActiveMQCPP.h&gt;
#include &lt;decaf/lang/Thread.h&gt;
#include &lt;decaf/lang/Runnable.h&gt;
#include &lt;decaf/util/concurrent/CountDownLatch.h&gt;
#include &lt;decaf/lang/Integer.h&gt;
#include &lt;decaf/lang/Long.h&gt;
#include &lt;decaf/lang/System.h&gt;
#include &lt;activemq/core/ActiveMQConnectionFactory.h&gt;
#include &lt;activemq/util/Config.h&gt;
#include &lt;cms/Connection.h&gt;
#include &lt;cms/Session.h&gt;
#include &lt;cms/TextMessage.h&gt;
#include &lt;cms/BytesMessage.h&gt;
#include &lt;cms/MapMessage.h&gt;
#include &lt;cms/ExceptionListener.h&gt;
#include &lt;cms/MessageListener.h&gt;
#include &lt;stdlib.h&gt;
#include &lt;stdio.h&gt;
#include &lt;iostream&gt;
#include &lt;memory&gt;
using namespace activemq::core;
using namespace decaf::util::concurrent;
using namespace decaf::util;
using namespace decaf::lang;
using namespace cms;
using namespace std;
class HelloWorldProducer : public Runnable {
private:
Connection* connection;
Session* session;
Destination* destination;
MessageProducer* producer;
int numMessages;
bool useTopic;
bool sessionTransacted;
std::string brokerURI;
private:
HelloWorldProducer(const HelloWorldProducer&amp;);
HelloWorldProducer&amp; operator=(const HelloWorldProducer&amp;);
public:
HelloWorldProducer(const std::string&amp; brokerURI, int numMessages, bool useTopic = false, bool sessionTransacted = false) :
connection(NULL),
session(NULL),
destination(NULL),
producer(NULL),
numMessages(numMessages),
useTopic(useTopic),
sessionTransacted(sessionTransacted),
brokerURI(brokerURI) {
}
virtual ~HelloWorldProducer(){
cleanup();
}
void close() {
this-&gt;cleanup();
}
virtual void run() {
try {
// Create a ConnectionFactory
auto_ptr&lt;ConnectionFactory&gt; connectionFactory(
ConnectionFactory::createCMSConnectionFactory(brokerURI));
// Create a Connection
connection = connectionFactory-&gt;createConnection();
connection-&gt;start();
// Create a Session
if (this-&gt;sessionTransacted) {
session = connection-&gt;createSession(Session::SESSION_TRANSACTED);
} else {
session = connection-&gt;createSession(Session::AUTO_ACKNOWLEDGE);
}
// Create the destination (Topic or Queue)
if (useTopic) {
destination = session-&gt;createTopic("TEST.FOO");
} else {
destination = session-&gt;createQueue("TEST.FOO");
}
// Create a MessageProducer from the Session to the Topic or Queue
producer = session-&gt;createProducer(destination);
producer-&gt;setDeliveryMode(DeliveryMode::NON_PERSISTENT);
// Create the Thread Id String
string threadIdStr = Long::toString(Thread::currentThread()-&gt;getId());
// Create a messages
string text = (string) "Hello world! from thread " + threadIdStr;
for (int ix = 0; ix &lt; numMessages; ++ix) {
std::auto_ptr&lt;TextMessage&gt; message(session-&gt;createTextMessage(text));
message-&gt;setIntProperty("Integer", ix);
printf("Sent message #%d from thread %s\n", ix + 1, threadIdStr.c_str());
producer-&gt;send(message.get());
}
} catch (CMSException&amp; e) {
e.printStackTrace();
}
}
private:
void cleanup() {
if (connection != NULL) {
try {
connection-&gt;close();
} catch (cms::CMSException&amp; ex) {
ex.printStackTrace();
}
}
// Destroy resources.
try {
delete destination;
destination = NULL;
delete producer;
producer = NULL;
delete session;
session = NULL;
delete connection;
connection = NULL;
} catch (CMSException&amp; e) {
e.printStackTrace();
}
}
};
class HelloWorldConsumer : public ExceptionListener,
public MessageListener,
public Runnable {
private:
CountDownLatch latch;
CountDownLatch doneLatch;
Connection* connection;
Session* session;
Destination* destination;
MessageConsumer* consumer;
long waitMillis;
bool useTopic;
bool sessionTransacted;
std::string brokerURI;
private:
HelloWorldConsumer(const HelloWorldConsumer&amp;);
HelloWorldConsumer&amp; operator=(const HelloWorldConsumer&amp;);
public:
HelloWorldConsumer(const std::string&amp; brokerURI, int numMessages, bool useTopic = false, bool sessionTransacted = false, int waitMillis = 30000) :
latch(1),
doneLatch(numMessages),
connection(NULL),
session(NULL),
destination(NULL),
consumer(NULL),
waitMillis(waitMillis),
useTopic(useTopic),
sessionTransacted(sessionTransacted),
brokerURI(brokerURI) {
}
virtual ~HelloWorldConsumer() {
cleanup();
}
void close() {
this-&gt;cleanup();
}
void waitUntilReady() {
latch.await();
}
virtual void run() {
try {
// Create a ConnectionFactory
auto_ptr&lt;ConnectionFactory&gt; connectionFactory(
ConnectionFactory::createCMSConnectionFactory(brokerURI));
// Create a Connection
connection = connectionFactory-&gt;createConnection();
connection-&gt;start();
connection-&gt;setExceptionListener(this);
// Create a Session
if (this-&gt;sessionTransacted == true) {
session = connection-&gt;createSession(Session::SESSION_TRANSACTED);
} else {
session = connection-&gt;createSession(Session::AUTO_ACKNOWLEDGE);
}
// Create the destination (Topic or Queue)
if (useTopic) {
destination = session-&gt;createTopic("TEST.FOO");
} else {
destination = session-&gt;createQueue("TEST.FOO");
}
// Create a MessageConsumer from the Session to the Topic or Queue
consumer = session-&gt;createConsumer(destination);
consumer-&gt;setMessageListener(this);
std::cout.flush();
std::cerr.flush();
// Indicate we are ready for messages.
latch.countDown();
// Wait while asynchronous messages come in.
doneLatch.await(waitMillis);
} catch (CMSException&amp; e) {
// Indicate we are ready for messages.
latch.countDown();
e.printStackTrace();
}
}
// Called from the consumer since this class is a registered MessageListener.
virtual void onMessage(const Message* message) {
static int count = 0;
try {
count++;
const TextMessage* textMessage = dynamic_cast&lt;const TextMessage*&gt; (message);
string text = "";
if (textMessage != NULL) {
text = textMessage-&gt;getText();
} else {
text = "NOT A TEXTMESSAGE!";
}
printf("Message #%d Received: %s\n", count, text.c_str());
} catch (CMSException&amp; e) {
e.printStackTrace();
}
// Commit all messages.
if (this-&gt;sessionTransacted) {
session-&gt;commit();
}
// No matter what, tag the count down latch until done.
doneLatch.countDown();
}
// 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&amp; ex AMQCPP_UNUSED) {
printf("CMS Exception occurred. Shutting down client.\n");
ex.printStackTrace();
exit(1);
}
private:
void cleanup() {
if (connection != NULL) {
try {
connection-&gt;close();
} catch (cms::CMSException&amp; ex) {
ex.printStackTrace();
}
}
// Destroy resources.
try {
delete destination;
destination = NULL;
delete consumer;
consumer = NULL;
delete session;
session = NULL;
delete connection;
connection = NULL;
} catch (CMSException&amp; e) {
e.printStackTrace();
}
}
};
int main(int argc AMQCPP_UNUSED, char* argv[] AMQCPP_UNUSED) {
activemq::library::ActiveMQCPP::initializeLibrary();
{
std::cout &lt;&lt; "=====================================================\n";
std::cout &lt;&lt; "Starting the example:" &lt;&lt; std::endl;
std::cout &lt;&lt; "-----------------------------------------------------\n";
// Set the URI to point to the IP Address 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:61613?wireFormat=stomp use stomp instead
//
// SSL:
// =========================
// To use SSL you need to specify the location of the trusted Root CA or the
// certificate for the broker you want to connect to. Using the Root CA allows
// you to use failover with multiple servers all using certificates signed by
// the trusted root. If using client authentication you also need to specify
// the location of the client Certificate.
//
// System::setProperty( "decaf.net.ssl.keyStore", "&lt;path&gt;/client.pem" );
// System::setProperty( "decaf.net.ssl.keyStorePassword", "password" );
// System::setProperty( "decaf.net.ssl.trustStore", "&lt;path&gt;/rootCA.pem" );
//
// The you just specify the ssl transport in the URI, for example:
//
// ssl://localhost:61617
//
std::string brokerURI =
"failover:(tcp://localhost:61616)";
//============================================================
// set to true to use topics instead of queues
// Note in the code above that this causes createTopic or
// createQueue to be used in both consumer an producer.
//============================================================
bool useTopics = true;
bool sessionTransacted = false;
int numMessages = 2000;
long long startTime = System::currentTimeMillis();
HelloWorldProducer producer(brokerURI, numMessages, useTopics);
HelloWorldConsumer consumer(brokerURI, numMessages, useTopics, sessionTransacted);
// Start the consumer thread.
Thread consumerThread(&amp;consumer);
consumerThread.start();
// Wait for the consumer to indicate that its ready to go.
consumer.waitUntilReady();
// Start the producer thread.
Thread producerThread(&amp;producer);
producerThread.start();
// Wait for the threads to complete.
producerThread.join();
consumerThread.join();
long long endTime = System::currentTimeMillis();
double totalTime = (double)(endTime - startTime) / 1000.0;
consumer.close();
producer.close();
std::cout &lt;&lt; "Time to completion = " &lt;&lt; totalTime &lt;&lt; " seconds." &lt;&lt; std::endl;
std::cout &lt;&lt; "-----------------------------------------------------\n";
std::cout &lt;&lt; "Finished with the example." &lt;&lt; std::endl;
std::cout &lt;&lt; "=====================================================\n";
}
activemq::library::ActiveMQCPP::shutdownLibrary();
}
// END SNIPPET: demo
</pre>
</div></div></div>
</td>
<td valign="top">
<div class="navigation">
<div class="navigation_top">
<div class="navigation_bottom">
<h3 id="Navigation-Overview"><a shape="rect" href="index.html">Overview</a></h3>
<ul class="alternate"><li><a shape="rect" href="index.html">Index</a></li><li><a shape="rect" href="news.html">News</a></li><li><a shape="rect" href="getting-started.html">Getting Started</a></li><li><a shape="rect" href="tutorials.html">Tutorials</a></li><li><a shape="rect" href="api.html">API</a></li><li><a shape="rect" href="faq.html">FAQ</a></li><li><a shape="rect" href="download.html">Download</a></li></ul>
<h3 id="Navigation-Connectivityhttps://cwiki.apache.org/confluence/pages/viewpage.action?pageId=51964"><a shape="rect" href="connectivity.html">Connectivity</a></h3>
<ul class="alternate"><li><a shape="rect" href="stomp-support.html">Stomp</a></li><li><a shape="rect" href="openwire-support.html">OpenWire</a></li></ul>
<h3 id="Navigation-UsingActiveMQ-CPPhttps://cwiki.apache.org/confluence/pages/viewpage.action?pageId=51968"><a shape="rect" href="using-activemq-cpp.html">Using ActiveMQ-CPP</a></h3>
<ul class="alternate"><li><a shape="rect" href="getting-started.html">Getting Started</a></li><li><a shape="rect" href="cms-api-overview.html">CMS API Overview</a></li><li><a shape="rect" href="example.html">Example</a></li><li><a shape="rect" href="configuring.html">Configuring</a></li></ul>
<h3 id="Navigation-Search">Search</h3>
<p></p><p>
</p><div>
<form enctype="application/x-www-form-urlencoded" method="get" action="http://www.google.com/search" style="font-size: 10px;">
<input type="hidden" name="ie" value="UTF-8">
<input type="hidden" name="oe" value="UTF-8">
<input maxlength="255" type="text" name="q" size="15" value="value"><br clear="none">
<input type="submit" name="btnG" value="Search">
<input type="hidden" name="domains" value="activemq.apache.org">
<input type="hidden" name="sitesearch" value="activemq.apache.org">
</form>
</div>
<p></p>
<h3 id="Navigation-Communityhttps://cwiki.apache.org/confluence/pages/viewpage.action?pageId=45948"><a shape="rect" href="community.html">Community</a></h3>
<ul class="alternate"><li><a shape="rect" href="support.html">Support</a></li><li><a shape="rect" class="external-link" href="http://activemq.apache.org/contributing.html">Contributing</a></li><li><a shape="rect" class="external-link" href="http://activemq.apache.org/discussion-forums.html">Discussion Forums</a></li><li><a shape="rect" class="external-link" href="http://activemq.apache.org/mailing-lists.html">Mailing Lists</a></li><li><a shape="rect" class="external-link" href="irc://irc.codehaus.org/activemq" rel="nofollow">IRC</a></li><li><a shape="rect" class="external-link" href="http://servlet.uwyn.com/drone/log/hausbot/activemq" rel="nofollow">IRC Log</a></li><li><a shape="rect" href="site.html">Site</a></li><li><a shape="rect" class="external-link" href="http://activemq.apache.org/team.html">Team</a></li></ul>
<h3 id="Navigation-Developershttps://cwiki.apache.org/confluence/pages/viewpage.action?pageId=45950"><a shape="rect" href="developers.html">Developers</a></h3>
<ul class="alternate"><li><a shape="rect" href="source.html">Source</a></li><li><a shape="rect" href="building.html">Building</a></li><li><a shape="rect" href="creating-distributions.html">Creating Distributions</a></li></ul>
</div>
</div>
</div>
</td>
</tr>
</tbody>
</table>
<div class="bottom_red_bar"></div>
</div>
</div>
</div>
</div>
<div class="black_box">
<div class="footer">
<div class="footer_l">
<div class="footer_r">
<div>
<a href="http://activemq.apache.org/privacy-policy.html">Privacy Policy</a> -
(<a href="https://cwiki.apache.org/confluence/pages/editpage.action?pageId=51931">edit this page</a>)
</div>
</div>
</div>
</div>
</div>
</div>
<div class="design_attribution">
&copy; 2004-2011 The Apache Software Foundation.
<br/>
Apache ActiveMQ, ActiveMQ, Apache, the Apache feather logo, and the Apache ActiveMQ project logo are trademarks of The Apache Software Foundation. All other marks mentioned may be trademarks or registered trademarks of their respective owners.
<br/>
<a href="http://hiramchirino.com">Graphic Design By Hiram</a>
</div>
<!-- delay the loading of large javascript files to the end so that they don't interfere with the loading of page content -->
<span style="display: none">
<script type="text/javascript">
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
var pageTracker = _gat._getTracker("UA-1347593-1");
pageTracker._initData();
pageTracker._trackPageview();
</script>
</span>
</body>
</html>