User-Profile-Image
hankin
  • 5
  • Java
  • Kotlin
  • Spring
  • Web
  • SQL
  • MegaData
  • More
  • Experience
  • Enamiĝu al vi
  • 分类
    • Zuul
    • Zookeeper
    • XML
    • WebSocket
    • Web Notes
    • Web
    • Vue
    • Thymeleaf
    • SQL Server
    • SQL Notes
    • SQL
    • SpringSecurity
    • SpringMVC
    • SpringJPA
    • SpringCloud
    • SpringBoot
    • Spring Notes
    • Spring
    • Servlet
    • Ribbon
    • Redis
    • RabbitMQ
    • Python
    • PostgreSQL
    • OAuth2
    • NOSQL
    • Netty
    • MySQL
    • MyBatis
    • More
    • MinIO
    • MegaData
    • Maven
    • LoadBalancer
    • Kotlin Notes
    • Kotlin
    • Kafka
    • jQuery
    • JavaScript
    • Java Notes
    • Java
    • Hystrix
    • Git
    • Gateway
    • Freemarker
    • Feign
    • Eureka
    • ElasticSearch
    • Docker
    • Consul
    • Ajax
    • ActiveMQ
  • 页面
    • 归档
    • 摘要
    • 杂图
    • 问题随笔
  • 友链
    • Spring Cloud Alibaba
    • Spring Cloud Alibaba - 指南
    • Spring Cloud
    • Nacos
    • Docker
    • ElasticSearch
    • Kotlin中文版
    • Kotlin易百
    • KotlinWeb3
    • KotlinNhooo
    • 前端开源搜索
    • Ktorm ORM
    • Ktorm-KSP
    • Ebean ORM
    • Maven
    • 江南一点雨
    • 江南国际站
    • 设计模式
    • 熊猫大佬
    • java学习
    • kotlin函数查询
    • Istio 服务网格
    • istio
    • Ktor 异步 Web 框架
    • PostGis
    • kuangstudy
    • 源码地图
    • it教程吧
    • Arthas-JVM调优
    • Electron
    • bugstack虫洞栈
    • github大佬宝典
    • Sa-Token
    • 前端技术胖
    • bennyhuo-Kt大佬
    • Rickiyang博客
    • 李大辉大佬博客
    • KOIN
    • SQLDelight
    • Exposed-Kt-ORM
    • Javalin—Web 框架
    • http4k—HTTP包
    • 爱威尔大佬
    • 小土豆
    • 小胖哥安全框架
    • 负雪明烛刷题
    • Kotlin-FP-Arrow
    • Lua参考手册
    • 美团文章
    • Java 全栈知识体系
    • 尼恩架构师学习
    • 现代 JavaScript 教程
    • GO相关文档
    • Go学习导航
    • GoCN社区
    • GO极客兔兔-案例
    • 讯飞星火GPT
    • Hollis博客
    • PostgreSQL德哥
    • 优质博客推荐
    • 半兽人大佬
    • 系列教程
    • PostgreSQL文章
    • 云原生资料库
    • 并发博客大佬
Help?

Please contact us on our email for need any support

Support
    首页   ›   Web   ›   ActiveMQ   ›   正文
ActiveMQ

SpringBoot—ActiveMQ简单使用

2020-04-19 02:02:13
687  0 0
参考目录 隐藏
1) 1.先写配置文件
2) 2.Message的bean
3) 3.编写JmsComponent
4) 4.启动
5) 5.测试
6) 结果:
7) 第二个例子:
8) 1、yml配置文件
9) 2、pom.xml文件
10) 点对点模式(开启点对点模式,请把yml文件的pub-sub-domain设为false)
11) 1、生产者
12) 2、消费者
13) 主题-发布订阅模式
14) 1、生产者
15) 2、消费者
16) 消息可靠保证机制

阅读完需:约 4 分钟

最简单的使用(总目录):

1.先写配置文件

spring.activemq.broker-url=tcp://127.0.0.1:61616 //地址
spring.activemq.packages.trust-all=true
spring.activemq.user=admin //用户名
spring.security.user.password=admin //密码

2.Message的bean

public class Message implements Serializable {
    private  String content;
    private Date SendDate;

    @Override
    public String toString() {
        return "Message{" +
                "content='" + content + '\'' +
                ", SendDate=" + SendDate +
                '}';
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public Date getSendDate() {
        return SendDate;
    }

    public void setSendDate(Date sendDate) {
        SendDate = sendDate;
    }
}

3.编写JmsComponent

@Component
public class JmsComponent {

    @Autowired
    JmsMessagingTemplate jmsMessagingTemplate;
    @Autowired
    Queue queue;

    public void send(Message message){
        jmsMessagingTemplate.convertAndSend(this.queue,message);
    }

    @JmsListener(destination = "hello.java")
    public void receive(Message msg){
        System.out.println(msg);
    }

}

4.启动

@SpringBootApplication
public class ActiveApplication {

    public static void main(String[] args) {
        SpringApplication.run(ActiveApplication.class, args);
    }

    @Bean
    Queue queue(){
        return new ActiveMQQueue("hello.java");
    }

}

5.测试

@SpringBootTest
class ActiveApplicationTests {
    @Autowired
    JmsComponent jmsComponent;
    @Test
    void contextLoads() {
        Message message=new Message();
        message.setContent("hello javaaa");
        message.setSendDate(new Date());
        jmsComponent.send(message);
    }

}

结果:

第二个例子:

说明:这里的生产者生产消息采用浏览器访问方式,方便控制消息生产和消费,当然也可以单独起一个线程自动生产消息。

1、yml配置文件

server:
  port: 8081
spring:
  #如果是点对点(queue),那么此处默认应该是false,如果发布订阅,那么一定设置为true
  jms:
    pub-sub-domain: true
  activemq:
    user: admin
    password: admin
    #定义ActivMQ的连接地址
    broker-url: tcp://127.0.0.1:61616
    #mq连接池
    pool:
      enabled: true
      max-connections: 8
      #空闲的连接过期时间,默认为30秒
      idle-timeout: 30000
    #定义队列名称
    queueName: myQueue
    #定义主题名称
    topicName: myTopic

2、pom.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>com.example</groupId>
        <artifactId>activemq</artifactId>
        <version>1.0-SNAPSHOT</version>
    </parent>

    <groupId>com.example</groupId>
    <artifactId>jmsdemo</artifactId>
    <version>1.0-SNAPSHOT</version>


</project>

点对点模式(开启点对点模式,请把yml文件的pub-sub-domain设为false)

访问路径:127.0.0.1:8081/sendToQueue?msg=要发送的消息

1、生产者

@RestController
public class QueueProducer {

    @Autowired
    private JmsMessagingTemplate jmsMessagingTemplate;

    @RequestMapping("sendToQueue")
    public void sendMessage(String msg, HttpServletResponse response) throws IOException {

        //队列名称
        ActiveMQQueue queue = new ActiveMQQueue("myQueue");

        //发送消息
        jmsMessagingTemplate.convertAndSend(queue, msg);

        System.out.println("客户端发送消息成功");

        response.getWriter().write("success");
    }
}

2、消费者

@Component
public class QueueConsumer {

//    @Autowired
//    private JmsMessagingTemplate jmsMessagingTemplate;

    // 使用JmsListener配置消费者监听的队列
    @JmsListener(destination = "myQueue")
    public void handleMessage(String msg) {
        System.out.println("服务端成功接收queue消息成功:" + msg);
    }

    /*
    @JmsListener(destination = "myQueue")
    // SendTo 会将此方法返回的数据, 写入到 OutQueue 中去.
    @SendTo("outQueue")
    public String handleMessage2(String msg) {
        System.out.println("成功接受msg" + msg);
        return "成功接受msg" + msg;
    }
    */
}

主题-发布订阅模式

访问路径:127.0.0.1:8081/sendToTopic?msg=要发送的消息

1、生产者

@RestController
public class TopicProducer {
    @Autowired
    private JmsMessagingTemplate jmsMessagingTemplate;

    @RequestMapping("sendToTopic")
    public void sendMessage(String msg, HttpServletResponse response) throws IOException {

        //队列名称
        ActiveMQTopic topic = new ActiveMQTopic("myTopic");

        //发送消息
        jmsMessagingTemplate.convertAndSend(topic, msg);

        System.out.println("客户端发送消息成功");

        response.getWriter().write("success");
    }
}

2、消费者

@Component
public class TopicConsumer {

    // 使用JmsListener配置消费者监听的队列
    @JmsListener(destination = "myTopic")
    public void handleMessage1(String msg) {
        System.out.println("消费者1成功接收topic消息成功:" + msg);
    }

    // 使用JmsListener配置消费者监听的队列
    @JmsListener(destination = "myTopic")
    public void handleMessage2(String msg) {
        System.out.println("消费者2成功接收topic消息成功:" + msg);
    }
}
}

消息可靠保证机制

  • 事务控制模式
生产者:
//生产者必须要将消息提交事务,才可以提交到队列中
Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
...此处省略中间代码...
// 发送消息
producer.send(message);
//手动提交事务
session.commit();

消费者:
Session session = createConnection.createSession(true, Session.AUTO_ACKNOWLEDGE);
...此处省略中间代码...
TextMessage textMessage = (TextMessage) message;
String text = textMessage.getText();
session.commit();
  • 手动签收模式
生产者:开启手动签收,在消费者接受完消息后手动签收
Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);

消费者:
Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
TextMessage textMessage = (TextMessage) message;
String text = textMessage.getText();
message.acknowledge();
  • 消息持久化
//若需要持久化,只需要在生产者设置
// 创建消息生产者
MessageProducer producer = session.createProducer(destination);
// 持久化消息,当MQ关闭后,消息会保存成文件(在acitvemq的data目录中)
producer.setDeliveryMode(DeliveryMode.PERSISTENT);

如本文“对您有用”,欢迎随意打赏作者,让我们坚持创作!

0 打赏
Enamiĝu al vi
不要为明天忧虑.因为明天自有明天的忧虑.一天的难处一天当就够了。
543文章 68评论 294点赞 593415浏览

随机文章
WebSocket(三)—群聊
5年前
Java—反射机制
5年前
FastDFS—— 构建分布式文件管理系统
5年前
SpringCloud—GateWay(一)
5年前
HttpServletRequest常用的方法
5年前
博客统计
  • 日志总数:543 篇
  • 评论数目:68 条
  • 建站日期:2020-03-06
  • 运行天数:1927 天
  • 标签总数:23 个
  • 最后更新:2024-12-20
Copyright © 2025 网站备案号: 浙ICP备20017730号 身体没有灵魂是死的,信心没有行为也是死的。
主页
页面
  • 归档
  • 摘要
  • 杂图
  • 问题随笔
博主
Enamiĝu al vi
Enamiĝu al vi 管理员
To be, or not to be
543 文章 68 评论 593415 浏览
测试
测试
看板娘
赞赏作者

请通过微信、支付宝 APP 扫一扫

感谢您对作者的支持!

 支付宝 微信支付