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

1、多种启动Broker的方法java

  • 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”);

2、单独应用的开发spring

  • 用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

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

  • 配置pom.xmlspringboot

    <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);
    }
    }
  • 测试类tcp

    @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(四)——4、用ActiveMQ构建应用
相关文章
相关标签/搜索