實戰(zhàn)代碼(九):Springboot集成ActiveMQ

一、理論基礎(chǔ)

1.1 什么是ActiveMQ

ActiveMQ是Apache出品的開源消息總線。ActiveMQ 是一個完全支持JMS1.1和J2EE1.4規(guī)范的JMS Provider實現(xiàn)。JMS即Java消息服務(wù)(Java Message Service)

1.2 ActiveMQ的應(yīng)用場景

ActiveMQ的優(yōu)勢在于安裝簡單、學(xué)習(xí)成本較低,而且內(nèi)置管理界面。有種即插即用的感覺

缺點是對大數(shù)據(jù)量的支持比較差,數(shù)據(jù)量越大,消費和查找的速度越慢。

ActiveMQ適合對吞吐量要求較低的場景,如果是大數(shù)據(jù)場景下建議使用RocketMQ、kafka等消息隊列

二、實戰(zhàn)代碼

2.1 依賴引入

<!--ActiveMq-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-activemq</artifactId>
</dependency>
<!--ActiveMq 連接池 -->
<dependency>
    <groupId>org.apache.activemq</groupId>
    <artifactId>activemq-pool</artifactId>
</dependency>

2.2 配置項

spring:
  activemq:
    broker-url: tcp://127.0.0.1:61616
    user: admin
    password: admin
    pool:
      enabled: true
      max-connections: 50

2.3 配置文件

@Configuration
public class ActiveMqConfig {

    @Value("${spring.activemq.broker-url}")
    private String brokerUrl;

    @Value("${spring.activemq.user}")
    private String username;

    @Value("${spring.activemq.password}")
    private String password;

    @Bean
    public ConnectionFactory connectionFactory(){
        return new ActiveMQConnectionFactory(username, password, brokerUrl);
    }

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

    @Bean("queueListener")
    public JmsListenerContainerFactory<?> queueJmsListenerContainerFactory(ConnectionFactory connectionFactory){
        SimpleJmsListenerContainerFactory factory = new SimpleJmsListenerContainerFactory();
        factory.setConnectionFactory(connectionFactory);
        factory.setPubSubDomain(false);
        return factory;
    }
}

2.4 consumer示例

/**
 * 消費者示例
 * @author smile
 */
@Component
public class DemoConsumer {


    /**
     * queueListener 對應(yīng) ActiveMqConfig中的Bean
     */
    @JmsListener(destination="smile.event.demo", containerFactory = "queueListener")
    public void receiveData(String message) {
        System.out.println("!!receive message: " + message);
    }
}

2.5 發(fā)送消息的簡單示例

@RestController
public class DemoProducer {

    @Autowired
    private JmsMessagingTemplate jmsMessagingTemplate;

    @GetMapping("producer/demo")
    public String producerDemo() {
        jmsMessagingTemplate.convertAndSend("smile.event.demo", "producer send message demo");
        return "send message success";
    }
}

三、源碼地址

https://github.com/lysmile/spring-boot-demo/tree/master/spring-boot-activemq-demo

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容