天天看點

springboot2整合ActiveMQ

直接上代碼,按流程搭建配置即可,其他講解網上肯定可以自己跟進需要搜尋

1、導入依賴

<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、添加配置

spring:
  activemq:
    broker-url: tcp://192.168.199.145:61616
    in-memory: false #true 使用内置的MQ,false連接配接伺服器
    user: admin
    password: admin
    pool:
      enabled: true #開啟連接配接池
      max-connections: 10      

3、相關bean對象

import javax.jms.ConnectionFactory;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.jms.core.JmsTemplate;

@Configuration
public class BeanConfig {

    @Autowired
    private Environment environment;

    @Bean
    public ConnectionFactory connectionFactory() {
        ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory();
        connectionFactory.setBrokerURL(environment.getProperty("spring.activemq.broker-url"));
        connectionFactory.setUserName(environment.getProperty("spring.activemq.user"));
        connectionFactory.setPassword(environment.getProperty("spring.activemq.password"));
        return connectionFactory;
    }

    @Bean
    public JmsTemplate genJmsTemplate() {
        return new JmsTemplate(connectionFactory());
    }

    @Bean
    public JmsMessagingTemplate jmsMessageTemplate() {
        return new JmsMessagingTemplate(connectionFactory());
    }
}      

4、send資訊

import com.example.demo.service.ProducerService;
import lombok.extern.slf4j.Slf4j;
import org.apache.activemq.command.ActiveMQQueue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.jms.Destination;


@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private ProducerService producerService;

    @GetMapping("/activemq")
    private Object order(String msg) {
        try {
            Destination destination = new ActiveMQQueue("order.queue");
            producerService.sendMsg(destination, msg);
        }catch (Exception e){
            e.printStackTrace();
        }
        return "success";
    }
}
      

5、消費資訊

@Component
public class MyListener {

    @JmsListener(destination = "order.queue") // 監聽test隊列
    public void receiveQueue(String text) {
        System.out.println("Message: " + text);
    }
}