说明
本篇是使用内存方式的ActiveMQ消息队列方案,不需要安装额外的软件,直接在程序里运行,不需要维护,适合小型的消息队列处理
实现
1、引入jar包
<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、在项目启动类里添加JMS支持
@SpringBootApplication
@EnableJms
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
3、添加生产者
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.stereotype.Service;
import javax.jms.Destination;
@Service
public class Producer {
@Autowired
private JmsMessagingTemplate jmsTemplate;
// 发送消息,destination是发送到的队列,message是待发送的消息
public void sendMessage(Destination destination, final Object message) {
jmsTemplate.convertAndSend(destination, message);
}
}
4、添加两个消费者
4.1 消费者1
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;
@Component
public class Consumer1{
private final Logger logger = LoggerFactory.getLogger(this.getClass());
// 使用JmsListener配置消费者监听的队列,其中text是接收到的消息
@JmsListener(destination = "message.queue")
public void receiveQueue(String text) {
logger.info("发送消息:"+text);
}
}
4.2 消费者2
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;
@Component
public class Consumer2 {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
// 使用JmsListener配置消费者监听的队列,其中text是接收到的消息
@JmsListener(destination = "log.queue")
public void receiveQueue(String text) {
logger.info("发送日志:"+text);
}
}
5、添加测试类
import org.apache.activemq.command.ActiveMQQueue;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import javax.jms.Destination;
import static org.junit.Assert.*;
@RunWith(SpringRunner.class)
@SpringBootTest
public class ProducerTest {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
private Producer producer;
@Test
public void sendMessage() {
Destination message = new ActiveMQQueue("message.queue");
Destination log = new ActiveMQQueue("log.queue");
producer.sendMessage(message, "生产者发送了消息");
producer.sendMessage(log, "生产者发送了日志");
}
}
其它说明
1、可以在配置文件添加连接池等,但是会报错没有研究
2、不能发送对象,需要转为String类型发送