ActiveMQ通过JmsTemplate来发送接收消息

添加activemq依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-activemq</artifactId>
</dependency>

配置文件配置消息队列的地址

spring:
  activemq:
#    broker地址 两个单机配置:failover:(tcp://localhost:61616,tcp://localhost:61617)?randomize=true
    broker-url: tcp://127.0.0.1:61616
    pool:
      max-connections: 100
  jms:
#    采用队列模式为false,主题模式为true
    pub-sub-domain: false
    cache:
      session-cache-size: 100
    template:
      receive-timeout: 100
#      是否持久化
      delivery-mode: persistent

生产者代码(入参是队列名和消息)

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Service;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;

@Service
public class ProducerService {

    @Autowired
    private JmsTemplate jmsTemplate;

    public void sendMessage(String destination, final String msg){
        System.out.println(Thread.currentThread().getName()+" 向队列"+destination.toString()+"发送消息---------------------->"+msg);
        jmsTemplate.send(destination, new MessageCreator() {
            public Message createMessage(Session session) throws JMSException {
                return session.createTextMessage(msg);
            }
        });
    }

}

消费者监听队列接收消息(注解是队列名)

import org.springframework.jms.annotation.EnableJms;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;

import javax.jms.*;

@Component
@EnableJms
public class ConsumerListener implements MessageListener {

    @Override
    @JmsListener(destination = "demoQueueDestination1")
    public void onMessage(Message message) {
        String msg = null;
        try {
            msg = ((TextMessage)message).getText();
        } catch (JMSException e) {
            e.printStackTrace();
        }
        System.out.println("listen:"+msg);
    }
}

消费者手动接收消息(入参是队列名)

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Service;

import javax.jms.JMSException;
import javax.jms.TextMessage;

@Service
public class ConsumerService {
    @Autowired
    private JmsTemplate jmsTemplate;

    public String receive(String destination) throws JMSException,NullPointerException {
        TextMessage textMessage = (TextMessage) jmsTemplate.receive(destination);
        String text = textMessage.getText();
        System.out.println("从队列" + destination.toString() + "收到了消息:\t" + text);
        return text;
    }
}
  • 1
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值