ActiveMQ--HelloWorld

下载windows版本ActiveMQ,apache-activemq-5.15.3\bin\win64\activemq.bat 启动mq,ActiveMQ内置jetty,默认端口8161,默认用户名密码admin、admin,在apache-activemq-5.15.3\conf\jetty-realm.properties 可修改登录用户密码。

访问控制台:http://localhost:8161/  

java连接ActiveMQ代码

maven依赖:

<dependency>
        <groupId>org.apache.activemq</groupId>
        <artifactId>activemq-all</artifactId>
        <version>5.15.3</version>
    </dependency>

消息发送者:

package com.lhy.mq.helloworld;

import java.util.concurrent.TimeUnit;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnectionFactory;

public class Receiver {

    public static void main(String[] args) throws Exception {
        //第一步:建立ConnectionFactory工厂对象。需要填入用户名、密码、连接地址,均使用默认即可,默认端口为"tcp://localhost:61616"
                ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(
                        ActiveMQConnectionFactory.DEFAULT_USER, 
                        ActiveMQConnectionFactory.DEFAULT_PASSWORD,
                        "tcp://localhost:61616");
                
                //第二步:通过ConnectionFactory工厂对象,创建Connection连接,并调用Connection的start方法开启连接,Connection默认是关闭的
                Connection connection = connectionFactory.createConnection();
                connection.start();
                
                //第三步:通过Connection对象创建Session会话(上下文环境对象),用于接收消息,参数配置1 为是否启用事物,参数配置2为签收模式,一般设置自动签收
                Session session = connection.createSession(Boolean.FALSE, Session.AUTO_ACKNOWLEDGE);
                
                //第四步:通过Session创建Destination对象,指的是一个客户端用来指定生产消息目标和消费消息来源的对象,
                //在PTP模式中,Destination被称作Queue即队列;在Pub/Sub模式,Destination被称作Topic即主题。
                //在程序中可以使用多个Queue和Topic
                Destination destination = session.createQueue("NB-Java");
                
                //第五步:通过Session对象创建MessageConsumer
                MessageConsumer consumer = session.createConsumer(destination);
                
                while(true){
                    //阻塞状态
                    TextMessage message = (TextMessage) consumer.receive();
                    System.err.println("消费数据:"+message.getText());
                }
    }
}

消息接收者:

package com.lhy.mq.helloworld;

import java.util.concurrent.TimeUnit;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnectionFactory;

public class Sender {
    
    public static void main(String[] args) throws Exception {
        
        //第一步:建立ConnectionFactory工厂对象。需要填入用户名、密码、连接地址,均使用默认即可,默认端口为"tcp://localhost:61616"
        ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(
                ActiveMQConnectionFactory.DEFAULT_USER, 
                ActiveMQConnectionFactory.DEFAULT_PASSWORD,
                "tcp://127.0.0.1:61616");
        
        //第二步:通过ConnectionFactory工厂对象,创建Connection连接,并调用Connection的start方法开启连接,Connection默认是关闭的
        Connection connection = connectionFactory.createConnection();
        connection.start();
        
        //第三步:通过Connection对象创建Session会话(上下文环境对象),用于接收消息,参数配置1 为是否启用事物,参数配置2为签收模式,一般设置自动签收
        Session session = connection.createSession(Boolean.FALSE, Session.AUTO_ACKNOWLEDGE);
        
        //第四步:通过Session创建Destination对象,指的是一个客户端用来指定生产消息目标和消费消息来源的对象,
        //在PTP模式中,Destination被称作Queue即队列;在Pub/Sub模式,Destination被称作Topic即主题。
        //在程序中可以使用多个Queue和Topic
        Destination destination = session.createQueue("NB-Java"); //队列名称
        
        //第五步:需要通过Session对象创建消息的发送和接收对象(生产者和消费者) MessageProducer/MessageConsumer
        //可以在创建生产者时指定 Destination目的地,这样发送的消息就都发到这,也可以在send消息的时候指定更灵活
        MessageProducer producer = session.createProducer(null);//
        
        
        // 第六步:可以使用MessageProducer的setDeliveryMode方法为其设置持久化特性和非持久化特性(DeliveryMode)
        //producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
        
        
        // 第七步:使用JMS规范的TextMessage形式创建数据(通过Session对象),调用MessageProducer的send方法发送数据。
        //同理客户端使用receive方式接收数据,最后关闭Connection连接
        for (int i = 0; i < 20; i++) {
            TextMessage message = session.createTextMessage("我是消息内容  - "+i);
            //message.setText(string);
            //第一个参数   目标地址
            //第二个参数   具体的数据信息
            //第三个参数   传送数据的模式
            //第四个参数   优先级
            //第五个参数    消息的过期时间
//            producer.send(destination, message, deliveryMode, priority, timeToLive);
            
            producer.send(destination, message);
            TimeUnit.SECONDS.sleep(1); 
            
            System.err.println("生产者发送消息:"+message.getText()); 
        }
    
        if(connection != null){
            connection.close();
        }
    }

}

修改客户端连接的用户名密码:

修改 apache-activemq-5.15.3\conf\activemq.xml,在broker 节点添加配置

<plugins> 
           <simpleAuthenticationPlugin> 
                 <users> 
                      <authenticationUser username="lhy" password="123456" groups="users,admins"/> 
                 </users> 
           </simpleAuthenticationPlugin> 
</plugins>

生产者消费者再次就需要使用这个用户名密码了。

 ActiveMQ会缓存没有消费的数据,就算服务停了再次启动还是可以拿到数据。

Active切换为mysql数据源

修改activemq.xml

 

 <persistenceAdapter>
            <!--持久化策略,默认是卡哈DB-->
            <!--<kahaDB directory="${activemq.data}/kahadb"/>-->
            <!--改为mysql,my-ds 是下边配置数据源bead的id-->
            <jdbcPersistenceAdapter dataSource="#my-ds"/>
        </persistenceAdapter>

 

再配置一个数据源的bean:在activemq.xml的beans节点下配置,使用了dbcp2 连接池

 <bean id="my-ds" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close">
                <property name="driverClassName" value="com.mysql.jdbc.Driver" />
                <property name="url" value="jdbc:mysql://127.0.0.1:3306/activemq?characterEncoding=utf-8" />
                <property name="username" value="root" />
                <property name="password" value="root" />
                <property name="initialSize" value="5" />
                <property name="maxTotal" value="100" />
                <property name="maxIdle" value="30" />
                <property name="maxWaitMillis" value="10000" />
                <property name="minIdle" value="1" />
    </bean>

下载mysql驱动包mysql-connector-java-5.1.8-bin.jar、dbcp包 commons-dbcp2-2.2.0.jar 放在apache-activemq-5.15.3\lib 下

注意建mysql数据库的时候,要设置编码为latin1 否则启动报错。

启动activeMQ, 会自动建2个表

 

再执行生成消息代码,可以看到mysql中存储了消息数据:

 ActiveMQ API

1,Connection接口

2,Session接口

如果消息数量太多,可以多批次提交,如10万条数据,1000条提交一次,提高性能。

 

转载于:https://www.cnblogs.com/lihaoyang/p/8856636.html

以下是使用 C 语言和 ActiveMQ 的示例代码: ```c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <activemq-cpp-3.9.3/activemq-cpp.h> #include <decaf/lang/Thread.h> using namespace activemq; using namespace activemq::core; using namespace decaf::lang; class MyListener : public cms::MessageListener { public: virtual void onMessage( const cms::Message* message ) { try { const cms::TextMessage* textMessage = dynamic_cast< const cms::TextMessage* >( message ); if( textMessage != NULL ) { printf( "Received message: %s\n", textMessage->getText().c_str() ); } } catch( cms::CMSException& e ) { e.printStackTrace(); } } }; int main( int argc, char* argv[] ) { // Connection configuration std::string brokerURI = "tcp://localhost:61616"; std::string destURI = "queue://test"; // Initialize the connection factory activemq::library::ActiveMQCPP::initializeLibrary(); // Create a connection factory auto_ptr<ConnectionFactory> connectionFactory( ConnectionFactory::createCMSConnectionFactory( brokerURI ) ); // Create a connection auto_ptr<Connection> connection( connectionFactory->createConnection() ); connection->start(); // Create a session auto_ptr<Session> session( connection->createSession( Session::AUTO_ACKNOWLEDGE ) ); // Create a destination auto_ptr<Destination> destination( session->createQueue( destURI ) ); // Create a producer auto_ptr<MessageProducer> producer( session->createProducer( destination.get() ) ); producer->setDeliveryMode( DeliveryMode::NON_PERSISTENT ); // Create a message auto_ptr<TextMessage> message( session->createTextMessage( "Hello, World!" ) ); // Send the message producer->send( message.get() ); // Create a consumer auto_ptr<MessageConsumer> consumer( session->createConsumer( destination.get() ) ); // Register a message listener MyListener listener; consumer->setMessageListener( &listener ); // Wait for messages while( true ) { Thread::sleep( 1000 ); } // Cleanup connection->close(); activemq::library::ActiveMQCPP::shutdownLibrary(); return 0; } ``` 请注意,这里使用的是 ActiveMQ-CPP 库,因此您需要在您的项目中包含它。此外,您需要安装 ActiveMQ 服务器,并确保它正在运行并监听在默认端口 61616 上。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值