消息队列中间件是分布式系统中重要的组件,主要解决应用耦合,异步消息,流量削锋等问题。实现高性能,高可用,可伸缩和最终一致性架构。是大型分布式系统不可缺少的中间件。消息形式支持点对点和订阅-发布。
ActiveMQ是什么
ActiveMQ是消息队列技术,为解决高并发问题而生
ActiveMQ生产者消费者模型(生产者和消费者可以跨平台、跨系统)
ActiveMQ支持如下两种消息传输方式
点对点模式,生产者生产了一个消息,只能由一个消费者进行消费
发布/订阅模式,生产者生产了一个消息,可以由多个消费者进行消费
添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-activemq</artifactId>
</dependency>
<!--消息队列连接池-->
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-pool</artifactId>
<version>5.15.0</version>
</dependency>
配置文件
spring:
activemq:
#ActiveMQ通讯地址
broker-url: tcp://127.0.0.1:61616
#用户名
user: admin
#密码
password: admin
#是否启用内存模式(就是不安装MQ,项目启动时同时启动一个MQ实例)
in-memory: false
packages:
#信任所有的包
trust-all: true
pool:
#是否替换默认的连接池,使用ActiveMQ的连接池需引入的依赖
enabled: false
server:
port: 9072
1.使用线程调用生成类
@Component
@EnableScheduling
public class MqProducer {
@Autowired
private JmsMessagingTemplate jmsMessagingTemplate;
@Autowired
private Queue queue;
@Scheduled(fixedDelay = 30000)
public void send(){
this.jmsMessagingTemplate.convertAndSend(queue,"hello:Active");
}
}
生产者代码块
package com.zhouf.deamo.config;
import org.apache.activemq.command.ActiveMQQueue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AciveMqConfig {
@Bean
public ActiveMQQueue queue() {
return new ActiveMQQueue("test");
}
@Bean
public ActiveMQQueue queue2(){return new ActiveMQQueue("test2");}
}
Controller层
package com.zhouf.deamo.controller;
import com.alibaba.fastjson.JSONObject;
import com.zhouf.deamo.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import javax.jms.Queue;
@RestController
public class DemoController {
@Resource(name="queue")
private Queue queue;
@Resource(name="queue2")
private Queue queue2;
@Autowired
private JmsMessagingTemplate jmsMessagingTemplate;
@RequestMapping("index")
public String index(){
return "index";
}
@RequestMapping("indexDemo")
public String indexDemo(){
this.jmsMessagingTemplate.convertAndSend(queue,"ActiveMqDemo");
return "ActiveMqDemo";
}
/*
使用json字符串传递实体类对象
*/
@RequestMapping("indexDemo2")
public User indexDemo2(){
User user=new User();
user.setUsername("username");
user.setPassword("password");
user.setPhone("12312312312");
String s = JSONObject.toJSONString(user);
this.jmsMessagingTemplate.convertAndSend(queue2,s);
return user;
}
}
来源:CSDN
作者:qq_38075852
链接:https://blog.csdn.net/qq_38075852/article/details/103827549