-
依赖配置
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-activemq</artifactId> <version>2.0.4.RELEASE</version> </dependency> <dependency> <groupId>org.apache.activemq</groupId> <artifactId>activemq-pool</artifactId> <version>5.7.0</version> </dependency>
-
yml文件配置
spring: activemq: broker-url: tcp://192.168.122.128:61616 in-memory: false pool: #true表示使用连接池 enabled: false #连接池最大连接数 max-connections: 5 #空闲的连接过期时间,默认为30秒 idle-timeout: 30000 packages: trust-all: true user: admin password: admin jms: #订阅模式要设置为true,默认false pub-sub-domain: true
-
配置启动类
@SpringBootApplication @ComponentScan("spring") @EnableJms//启用消息队列 public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } }
-
配置初始化文件
@Configuration public class Config { //点对点模式consumer @Bean public Queue queue() { return new ActiveMQQueue("consumer"); } //订阅模式topic @Bean public Topic topic(){ return new ActiveMQTopic("topic"); } }
-
创建生产者
@Component @EnableScheduling public class MqProducer { @Autowired private JmsMessagingTemplate jmsMessagingTemplate; @Autowired private Queue queue; @Autowired private Topic topic; //点对点模式 @Scheduled(fixedDelay = 2000) // 每2s执行1次 public void send1() { this.jmsMessagingTemplate.convertAndSend(this.queue, "生产者消息Queue"); } //订阅模式 //@Scheduled(fixedDelay = 2000) // 每2s执行1次 //public void send() { // this.jmsMessagingTemplate.convertAndSend(this.topic, "生产者消息Topic"); //} }
-
创建消费者
@Component public class MqConsumer { //点对点模式 @JmsListener(destination = "consumer") public void receiveQueue(String consumer) { System.out.println("消费者1:" + consumer); } //订阅模式 //@JmsListener(destination = "topic") //public void receiveQueue1(String consumer) { // System.out.println("消费者2:" + consumer); //} }
-
测试
- 订阅模式,此时需要设置yml文件
pub-sub-domain: true
;发布数据时,如果没有用户接收,数据会丢失。多个用户的话,每个用户都会接收相同的数据。 - 点对点模式,,此时需要设置yml文件
pub-sub-domain: false
;发布数据,发送给指定用户,(如果多个同名用户,不会重复消费)
- 订阅模式,此时需要设置yml文件
Springboot整合Activemq
最新推荐文章于 2022-10-11 08:32:03 发布