ActiveMQ(四)——四、用ActiveMQ构建应用

一、多种启动Broker的方法

  • broker:相当于一个ActiveMQ服务器实例
  • 命令行启动参数示例如下:
    1:activemq start:使用默认的activemq.xml来启动
    2:activemq start xbean:file:../conf/activemq-2.xml:使用指定的配置文件来启动
    3:如果不指定file,也就是xbean:activemq-2.xml,那么必须在classpath下面
  • 如果需要启动多个broker,需要为broker设置一个名字
    broker.setName(“name2”);

二、单独应用的开发

  • 用ActiveMQ来构建Java应用
        主要将ActiveMQ Broker作为独立的消息服务器米构建JAVA应用。ActiveMQ也支持在vm中通信基于嵌入式的broker,能够无缝的集成其它java应用
  • 嵌入式Broker启动
    //1:Broker Service启动broker,示例如下
    BrokerService broker = new BrokerService();
    broker.setUseJmx(true);
    broker.addConnector("tcp://localhost:61616");
    broker.start();
    //2:BrokerFactory 启动broker,示例如下:
    String uri = "properties:broker.properties";
    BrokerService broker1 = BrokerFactory.createBroker(new URI(uri));
    broker1.addConnector("tcp://localhost:61616");
    broker1.start();
    //3:broker.properties的内容如下:
    useJms=true
    persistent=false
    brokerName=Cheese

三、结合spring boot的开发
参考:https://blog.csdn.net/liuchuanhong1/article/details/54603546

  • 配置pom.xml

    <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-activemq</artifactId>
    </dependency>
    <dependency>
    <groupId>org.apache.activemq</groupId>
    <artifactId>activemq-pool</artifactId>
    </dependency>
  • 配置文件
    spring.activemq.broker-url=tcp://localhost:61616
    spring.activemq.in-memory=true
    #如果此处设置为true,需要加如下的依赖包,否则会自动配置失败,报JmsMessagingTemplate注入失败
    spring.activemq.pool.enabled=false
  • 生产者

    @Service
    public class Producer {
    @Autowired // 也可以注入JmsTemplate,JmsMessagingTemplate对JmsTemplate进行了封装
    private JmsMessagingTemplate jmsTemplate;
    
    // 发送消息,destination是发送到的队列,message是待发送的消息
    public void sendMessage(Destination destination, final String message){
        jmsTemplate.convertAndSend(destination, message);
    }
    }
  • 消费者
    @Component
    public class Consumer {
    使用JmsListener配置消费者监听的队列,其中text是接收到的消息
    @JmsListener(destination = "springboot-activemq")
    public void receiveQueue(String text) {
        System.out.println("Consumer收到的报文为:"+text);
    }
    }
  • 测试类

    @RunWith(SpringRunner.class)
    @SpringBootTest
    public class SpringBootJmsApplicationTests {
    
    @Autowired
    private Producer producer;
    
    @Test
    public void contextLoads() {
      Destination destination = new ActiveMQQueue("springboot-activemq");
      for (int i = 0; i < 10; i++) {
         producer.sendMessage(destination,"this message is " + i);
      }
    }
    }
  • 测试结果
    ActiveMQ(四)——四、用ActiveMQ构建应用

猜你喜欢

转载自blog.51cto.com/mazongfei/2415546