ActiveMQ代码示例

ActiveMQ 注意用5.11版本,5.12与spring有冲突

ActiveMQTest:

测试类示例

package com.igeek.test.jedis;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.command.ActiveMQTextMessage;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;

import javax.jms.*;
import java.io.IOException;

public class ActiveMQTest {


    /**
     * PTP(点对点)
     */
    //生产者
    public void producer_queue() throws JMSException {
//        第一步:创建 ConnectionFactory 对象,需要指定服务端 ip 及端口号。
        ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://192.168.8.101:61616");//192.168.8.101:8161
//        第二步:使用 ConnectionFactory 对象创建一个 Connection 对象。
        Connection connection = connectionFactory.createConnection();
//        第三步:开启连接,调用 Connection 对象的 start 方法。
        connection.start();
//        第四步:使用 Connection 对象创建一个 Session 对象。
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);//参数:1.是否使用分布式事务(false 不使用) 2.activemq的响应类型(自动应答)
//        第五步:使用 Session 对象创建一个 Destination 对象(topic、queue),此处创建一个 Queue对象。
        Queue queue = session.createQueue("test_queue");//参数:给队列设置名称
//        第六步:使用 Session 对象创建一个 Producer 对象。
        MessageProducer producer = session.createProducer(queue);
//        第七步:创建一个 Message 对象,创建一个 TextMessage 对象。
        TextMessage message = new ActiveMQTextMessage();
        message.setText("hello queue...message03");
//        第八步:使用 Producer 对象发送消息。
        producer.send(message);
//        第九步:关闭资源。
        session.close();
        connection.close();

    }

    //消费者

    public void consumer_queue() throws JMSException, IOException {

//        第一步:创建 ConnectionFactory 对象,需要指定服务端 ip 及端口号。
        ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://192.168.8.101:61616");
//        第二步:使用 ConnectionFactory 对象创建一个 Connection 对象。
        Connection connection = connectionFactory.createConnection();
//        第三步:开启连接,调用 Connection 对象的 start 方法。
        connection.start();
//        第四步:使用 Connection 对象创建一个 Session 对象。
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);//参数:1.是否使用分布式事务(false 不使用) 2.activemq的响应类型(自动应答)
//        第五步:使用 Session 对象创建一个 Destination 对象(topic、queue),此处创建一个 Queue对象。
        Queue queue = session.createQueue("test_queue");//参数:给队列设置名称
//        第六步:使用 Session 对象创建一个 Consumer 对象。
        MessageConsumer cosumer = session.createConsumer(queue);

//        第七步:使用 Consumer 对象消费消息。
        cosumer.setMessageListener(new MessageListener() {
            @Override
            public void onMessage(Message message) {

                TextMessage _message = (TextMessage) message;
                try {
                    System.out.println("消费者接收到消息..."+_message.getText());
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }
        });


        System.in.read();

//        第八步:关闭资源。
        session.close();
        connection.close();

    }

    /**
     * Topic(发布/订阅)
     */
    //生产者

    public void producer_topic() throws JMSException {
//        第一步:创建 ConnectionFactory 对象,需要指定服务端 ip 及端口号。
        ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://192.168.8.101:61616");
//        第二步:使用 ConnectionFactory 对象创建一个 Connection 对象。
        Connection connection = connectionFactory.createConnection();
//        第三步:开启连接,调用 Connection 对象的 start 方法。
        connection.start();
//        第四步:使用 Connection 对象创建一个 Session 对象。
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);//参数:1.是否使用分布式事务(false 不使用) 2.activemq的响应类型(自动应答)
//        第五步:使用 Session 对象创建一个 Destination 对象(topic、queue),此处创建一个 Topic对象。
        Topic topic = session.createTopic("test-topic");//参数:给队列设置名称
//        第六步:使用 Session 对象创建一个 Producer 对象。
        MessageProducer producer = session.createProducer(topic);
//        第七步:创建一个 Message 对象,创建一个 TextMessage 对象。
        TextMessage message = new ActiveMQTextMessage();
        message.setText("hello topic...message03");
//        第八步:使用 Producer 对象发送消息。
        producer.send(message);
//        第九步:关闭资源。
        session.close();
        connection.close();

    }

    //消费者

    public void consumer_topic() throws JMSException, IOException {

//        第一步:创建 ConnectionFactory 对象,需要指定服务端 ip 及端口号。
        ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://192.168.8.101:61616");
//        第二步:使用 ConnectionFactory 对象创建一个 Connection 对象。
        Connection connection = connectionFactory.createConnection();
//        第三步:开启连接,调用 Connection 对象的 start 方法。
        connection.start();
//        第四步:使用 Connection 对象创建一个 Session 对象。
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);//参数:1.是否使用分布式事务(false 不使用) 2.activemq的响应类型(自动应答)
//        第五步:使用 Session 对象创建一个 Destination 对象(topic、queue),此处创建一个 Queue对象。
        Topic topic = session.createTopic("test-topic");//参数:给队列设置名称
//        第六步:使用 Session 对象创建一个 Consumer 对象。
        MessageConsumer cosumer = session.createConsumer(topic);

//        第七步:使用 Consumer 对象消费消息。
        cosumer.setMessageListener(new MessageListener() {
            @Override
            public void onMessage(Message message) {

                TextMessage _message = (TextMessage) message;
                try {
                    System.out.println("消费者接收到消息..."+_message.getText());
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }
        });


        System.in.read();

//        第八步:关闭资源。
        session.close();
        connection.close();

    }

    /**
     * Spring与ActiveMQ整合测试
     */
    //@Test
    public void test_spring_activeMq(){
        ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:spring/applicationContext-activemq.xml");
        JmsTemplate jmsTemplate = ac.getBean(JmsTemplate.class);
        Destination destination = (Destination) ac.getBean("topicDestination");
        jmsTemplate.send(destination, new MessageCreator() {
            @Override
            public Message createMessage(Session session) throws JMSException {
                TextMessage message = new ActiveMQTextMessage();
                message.setText("hello...");
                return message;
            }
        });//参数:1.目的地 2.消息创建器
    }


}

与Spring整合的配置文件:

发送消息:

applicationContext-activemq.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	   xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"
	   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
	http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
	http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
	http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd
	http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd ">


	<!-- 真正可以产生Connection的ConnectionFactory,由对应的 JMS服务厂商提供 -->
	<bean id="targetConnectionFactory"
		  class="org.apache.activemq.ActiveMQConnectionFactory">
		<property name="brokerURL" value="tcp://192.168.8.101:61616" />
	</bean>

	<!-- Spring用于管理真正的ConnectionFactory的ConnectionFactory -->
	<bean id="connectionFactory"
		  class="org.springframework.jms.connection.SingleConnectionFactory">
		<!-- 目标ConnectionFactory对应真实的可以产生JMS Connection的ConnectionFactory
        -->
		<property name="targetConnectionFactory" ref="targetConnectionFactory" />
	</bean>


	<!-- Spring提供的JMS工具类,它可以进行消息发送、接收等 -->
	<bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
		<!-- 这个connectionFactory对应的是我们定义的Spring提供的那个ConnectionFactory
        对象 -->
		<property name="connectionFactory" ref="connectionFactory" />
	</bean>

	<!--新增商品 -->
	<bean id="addItemDestination" class="org.apache.activemq.command.ActiveMQTopic">
		<constructor-arg value="ITEM_ADD" />
	</bean>

	<!--这个是队列目的地,点对点的 -->
	<bean id="queueDestination" class="org.apache.activemq.command.ActiveMQQueue">
		<constructor-arg>
			<value>spring-queue</value>
		</constructor-arg>
	</bean>
	<!--这个是主题目的地,一对多的 -->
	<bean id="topicDestination" class="org.apache.activemq.command.ActiveMQTopic">
		<constructor-arg value="topic" />
	</bean>






</beans>

 

ItemServiceImpl 业务层应用

package com.igeek.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.igeek.mapper.TbItemMapper;
import com.igeek.pojo.TbItem;
import com.igeek.pojo.TbItemDesc;
import com.igeek.service.ItemDescService;
import com.igeek.service.ItemService;
import com.igeek.util.DataGridResult;
import org.apache.activemq.command.ActiveMQTextMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Service;

import javax.jms.*;
import java.util.Date;
import java.util.List;
@Service
public class ItemServiceImpl implements ItemService {
    @Autowired
    private TbItemMapper tbItemMapper;

    @Autowired
    private ItemDescService itemDescService;

    @Autowired
    private JmsTemplate jmsTemplate;

    @Autowired
    @Qualifier("addItemDestination")
    private Topic topic;
    @Override
    public List<TbItem> selectItems() {


        return tbItemMapper.selectAll();
    }

    @Override
    public DataGridResult selectItemsByPage(Long page, Long rows) {

        DataGridResult result = new DataGridResult();

        //设置页码 以及 每页条数
        PageHelper.startPage(page.intValue(),rows.intValue());

        //查询所有
        List<TbItem> tbItems = tbItemMapper.selectAll();

        //真正的查询操作
        /*
        查询对象:
        pageInfo.getList() 每页的数据
        pageInfo.getPages() 总页数
        ...
         */
        PageInfo<TbItem> pageInfo = new PageInfo<>(tbItems);

        //result.setRows(rows);
        result.setTotal(pageInfo.getTotal());
        result.setRows(pageInfo.getList());

        return result;
    }
    //事务传播行为
    @Override
    public int addItem(TbItem item,String desc) {//开启事务
        tbItemMapper.insert(item);
        //封装商品描述对象
        TbItemDesc itemDesc = new TbItemDesc();
        itemDesc.setItemId(item.getId());
        itemDesc.setItemDesc(desc);
        itemDesc.setCreated(new Date());
        itemDesc.setUpdated(itemDesc.getCreated());
        //int i = 10/0;
        //保存描述对象
        itemDescService.addItemDesc(itemDesc);

        //发送消息
        jmsTemplate.send(topic, new MessageCreator() {
            @Override
            public Message createMessage(Session session) throws JMSException {
                TextMessage message = new ActiveMQTextMessage();
                message.setText(item.getId()+"");//发送消息(消息内容:商品id)
                return message;
            }
        });
        return 1;
    }

    @Override
    public void updateItem(TbItem item, String desc) {
        //设置更新时间
        item.setUpdated(new Date());
        //设置不需要更新的字段值为null
        item.setCreated(null);
        item.setStatus(null);
        tbItemMapper.updateByPrimaryKeySelective(item);//status->0 create->null  Selective:选择性更新,如果为null不更新

        TbItemDesc itemDesc = new TbItemDesc();
        itemDesc.setItemId(item.getId());
        itemDesc.setItemDesc(desc);
        itemDescService.updateItemDesc(itemDesc);

    }

    @Override
    public TbItem selectItemById(Long id) {
        //加缓存  ITEM_CACHE->(id+"INFO"=内容)
        return tbItemMapper.selectByPrimaryKey(id);
    }
}

 

接收消息:

创建监听器:

package com.igeek.search.listener;

import com.igeek.search.service.SearchItemService;
import org.apache.solr.client.solrj.SolrServerException;
import org.springframework.beans.factory.annotation.Autowired;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;
import java.io.IOException;

/**
 * ActiveMQ消息监听器(商品添加)
 */
public class ItemAddMessageListener implements MessageListener {
    @Autowired
    private SearchItemService searchItemService;
    @Override
    public void onMessage(Message message) {
        TextMessage _message = (TextMessage)message;
        try {
            String text = _message.getText();//商品ID

            //根据商品ID获取商品信息 同步索引库
            Thread.sleep(200);//确保数据保存到数据库
            searchItemService.addItem(Long.parseLong(text));
        } catch (JMSException e) {
            e.printStackTrace();
        } catch (SolrServerException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

 

配置监听器:

applicationContext-activemq.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	   xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"
	   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
	http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
	http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
	http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd
	http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd ">


	<!-- 真正可以产生Connection的ConnectionFactory,由对应的 JMS服务厂商提供 -->
	<bean id="targetConnectionFactory"
		  class="org.apache.activemq.ActiveMQConnectionFactory">
		<property name="brokerURL" value="tcp://192.168.8.101:61616" />
	</bean>

	<!-- Spring用于管理真正的ConnectionFactory的ConnectionFactory -->
	<bean id="connectionFactory"
		  class="org.springframework.jms.connection.SingleConnectionFactory">
		<!-- 目标ConnectionFactory对应真实的可以产生JMS Connection的ConnectionFactory
        -->
		<property name="targetConnectionFactory" ref="targetConnectionFactory" />
	</bean>


	<!-- Spring提供的JMS工具类,它可以进行消息发送、接收等 -->
	<bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
		<!-- 这个connectionFactory对应的是我们定义的Spring提供的那个ConnectionFactory
        对象 -->
		<property name="connectionFactory" ref="connectionFactory" />
	</bean>

	<!--新增商品 -->
	<bean id="addItemDestination" class="org.apache.activemq.command.ActiveMQTopic">
		<constructor-arg value="ITEM_ADD" />
	</bean>

	<!--配置消息监听器-->
	<bean id="myMessageListener"
		  class="com.igeek.search.listener.ItemAddMessageListener"/>
	<!-- 消息监听容器 -->
	<bean class="org.springframework.jms.listener.DefaultMessageListenerContainer">
		<property name="connectionFactory" ref="connectionFactory" />
		<property name="destination" ref="addItemDestination" />
		<property name="messageListener" ref="myMessageListener" />
	</bean>










</beans>

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
以下是使用 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
发出的红包

打赏作者

_无往而不胜_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值