引言
代码已提交至Github,有兴趣的同学可以下载来看看:https://github.com/ylw-github/SpringBoot-ActiveMQ-Demo
在上一篇博客《ActiveMQ -安装&入门案例》中,里面的入门案例其实是ActiveMQ点对点的模式了,本文主要来讲解一下Active的发布订阅模式。
1.生产者1.添加mave依赖:
org.springframework.boot
spring-boot-starter-parent
2.0.1.RELEASE
org.springframework.cloud
spring-cloud-dependencies
Finchley.M7
pom
import
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-activemq
spring-milestones
Spring Milestones
https://repo.spring.io/libs-milestone
false
2.配置application.yml文件:
server:
port: 8080
spring:
activemq:
broker-url: tcp://192.168.162.131:61616
user: admin
password: admin
kafka:
template:
default-topic:
queue: springboot-queue
topic: spring-topic
3.主题生产者TopicProducer:
@Component
public class TopicProducer {
@Autowired
private JmsMessagingTemplate jmsMessagingTemplate;
@Autowired
private Topic topic;
@Scheduled(fixedDelay = 5000)
public void send() {
String msg = System.currentTimeMillis() + "";
System.out.println("采用发布订阅方式,生产者向消费者发送内容:" + msg);
jmsMessagingTemplate.convertAndSend(topic, msg);
}
}
4.主题配置:
import javax.jms.Topic;
@Component
public class TopicConfig {
@Value("${topic}")
private String topicName;
@Bean
public Topic topic() {
return new ActiveMQTopic(topicName);
}
}
5.启动类:
@SpringBootApplication
@EnableScheduling
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
2.消费者
1.添加maven依赖:
org.springframework.boot
spring-boot-starter-parent
2.0.1.RELEASE
org.springframework.cloud
spring-cloud-dependencies
Finchley.M7
pom
import
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-activemq
com.alibaba
fastjson
1.2.49
spring-milestones
Spring Milestones
https://repo.spring.io/libs-milestone
false
2.配置文件:
server:
port: 8081
spring:
activemq:
broker-url: tcp://192.168.162.131:61616
user: admin
password: admin
#### 开启发布订阅
jms:
pub-sub-domain: true
topic: spring-topic
queue: springboot-queue
3.主题消费者:
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;
@Component
public class TopicConsumer {
@JmsListener(destination = "spring-topic")
public void receive(String msg) {
System.out.println("发布与订阅消费者接受,生产者内容:" + msg);
}
}
3.测试
step1.启动ActiveMQ服务:
/usr/local/apache-activemq-5.15.10/bin/activemq start
step2.浏览器访问:http://192.168.162.131:8161/admin(账号:admin、密码:admin),可以看到ActiveMQ服务开启成功。
step3.启动生产者和消费者项目,在生产者控制台可以看到:
消费者控制台可以看到: