队列模式
生产者
1、首先新建springboot项目并添加依赖
</dependency>
<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、启动类添加注解
@EnableJms
3、创建CreatBean类,用来创建bean
@Component
public class CreatBean {
@Bean
public Queue queue() {
return new ActiveMQQueue("my.queue");
}
@Bean
public JmsListenerContainerFactory<?> jmsListenerContainerTopic(ConnectionFactory activeMQConnectionFactory) {
DefaultJmsListenerContainerFactory bean = new DefaultJmsListenerContainerFactory();
bean.setPubSubDomain(true);
bean.setConnectionFactory(activeMQConnectionFactory);
return bean;
}
}
4、配置文件添加activeMq配置
spring.activemq.broker-url=tcp://127.0.0.1:61616
spring.activemq.user=admin
spring.activemq.password=admin
spring.activemq.pool.enabled=true
spring.activemq.pool.max-connections=100
5、添加service
@Service
public class ProducerServiceImpl implements ProducerService {
Logger logger = LoggerFactory.getLogger(ProducerServiceImpl.class);
@Autowired
private JmsMessagingTemplate jmsTemplate;
@Override
public void sendMessage(Destination destination, String message) {
logger.info("准备发送消息的是:" + message);
jmsTemplate.convertAndSend(destination, message);
}
}
6、添加Controller
@RestController
@RequestMapping("/queue")
public class QueueController {
@Autowired
private ProducerService producerService;
@Autowired
private Queue queue;
@RequestMapping("/{msg}")
public String sendQueue(@PathVariable String msg) {
producerService.sendMessage(queue, msg);
return msg + "发送成功";
}
}
启动主函数访问http://localhost:8081/queue/XXX就可以往队列中添加数据
消费者
1、添加maven依赖,同上
2、添加配置文件,同上
3、主函数添加注解,同上
4、添加QueueConsumer类用户接收数据
@Component
public class QueueConsumer {
Logger logger = LoggerFactory.getLogger(QueueConsumer.class);
@JmsListener(destination = "my.queue")
public void receiveQueue1(String text) {
logger.info("消费者1收到的报文为:" + text);
}
@JmsListener(destination = "my.queue")
public void receiveQueue2(String text) {
logger.info("消费者2收到的报文为:" + text);
}
}