• 【ActiveMQ】ActiveMQ在Spring Boot下使用


    1.activemq服务端安装

    下载apache-activemq-5.15.3:

    wget http://mirror.bit.edu.cn/apache//activemq/5.15.3/apache-activemq-5.15.3-bin.tar.gz
    

    解压

    tar -zxvf apache-activemq-5.15.3
    

    启动

    ./activemq start
    

    连接管理界面

    (需关闭linux防火墙:systemctl stop firewalld.service

    http://ip:8161(ip为安装activemq的ip,如为本机则为localhost)

    1.activemq依赖

            //核心
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-activemq</artifactId>
            </dependency>
            //连接池
            <dependency>
                <groupId>org.apache.activemq</groupId>
                <artifactId>activemq-pool</artifactId>
            </dependency>

    2.连接配置

        #连接地址tcp://ip:port,默认为61616端口
        spring.activemq.broker-url=tcp://192.168.179.132:61616
        #用户名和密码,默认为admin    
        spring.activemq.user=admin
        spring.activemq.password=admin

    测试

        //生产者
        @Component
        public class Producer {
            private final JmsTemplate jmsTemplate;
    
            @Autowired
            public Producer(JmsTemplate jmsTemplate) {
                this.jmsTemplate = jmsTemplate;
            }
    
            /**
             * 发送消息
             * @param destination
             * 发送到的队列
             * @param message
             * 待发送的消息
             */
            void sendMessage(Destination destination, final String message) {
                jmsTemplate.convertAndSend(destination, message);
            }
        }

    //消费者
        @Component
        public class Consumer {
    
            @JmsListener(destination = "queue")
            public void receiveQueue(String text) {
                System.out.println("收到消息"+text);
            }
        }

    //测试类
        @RunWith(SpringRunner.class)
        @SpringBootTest(classes = Application.class)
        public class ActivemqTest {
            @Autowired
            private Producer producer;
    
            @Test
            public void contextLoads() throws InterruptedException {
                Destination destination = new ActiveMQQueue("queue");
                int times = 10;
                for (int i = 0; i < times; i++) {
                    producer.sendMessage(destination, "hello"+i);
                }
            }
        }

    结果:

    收到消息hello0
    收到消息hello1
    收到消息hello2
    收到消息hello3
    收到消息hello4
    收到消息hello5
    收到消息hello6
    收到消息hello7
    收到消息hello8
    收到消息hello9
    

  • 相关阅读:
    用同余理解补码
    objenesis
    spring 事务处理
    SOCKS5 协议解析
    WebSocket 的鉴权授权方案
    加密解密基础问题:字节数组和16进制字符串的相互转换
    主机字节序 与 网络字节序
    RSA 理论
    分类算法----k近邻算法
    R语言统计分析应用与SAS、SPSS的比较
  • 原文地址:https://www.cnblogs.com/cnsec/p/13286691.html
Copyright © 2020-2023  润新知