springboot整合activeMq简单实现

ActiveMQ下载启动
首先第一步肯定是下载了,自己笔记本下载window版,服务器上下载linux版,不详细赘述了,安装好了,启动activemq.bat。
2.pom引入相关依赖
<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>

3.配置文件修改(生产者和消费者两个项目是一样的)

spring:
activemq:
broker-url: failover:(tcp://localhost:61616)?randomize=false&timeout=3000&jms.useAsyncSend=true&jms.redeliveryPolicy.maximumRedeliveries=3&jms.redeliveryPolicy.useExponentialBackOff=true&jms.redeliveryPolicy.backOffMultiplier=10&jms.redeliveryPolicy.initialRedeliveryDelay=1000
password: admin
user: admin

4.启动类上加注解@EnableJms(生产者和消费者两个项目同样)

@SpringBootApplication
@EnableJms //启动消息队列
public class ProviderApplication {
public static void main(String[] args) {
SpringApplication.run(ProviderApplication.class, args);
}
}

5.定义一个配置类(生产者项目需要)

import javax.jms.Queue;
import org.apache.activemq.command.ActiveMQQueue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class BeanConfig {

//定义存放消息的队列ActiveMQQueue是队列名
@Bean
public Queue queue() {
return new ActiveMQQueue("ActiveMQQueue");
}
}

6.生产者生产消息

import javax.jms.Queue;
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;

@RestController
@RequestMapping("/test")
public class ProviderController {

//注入存放消息的队列,用于下列方法一
@Autowired
private Queue queue;

//注入springboot封装的工具类
@Autowired
private JmsMessagingTemplate jmsMessagingTemplate;

@RequestMapping("/send")
public void send(String name) {
//方法一:添加消息到消息队列ActiveMQQueue这个队列中
jmsMessagingTemplate.convertAndSend(queue, name);
//方法二:这种方式不需要手动创建queue,系统会自行创建名为test的队列
//jmsMessagingTemplate.convertAndSend("test", name);
}
}

启动,并执行该方法生产消息
7.消费者 消费消息(随意一个类中即可)

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Component;

@Component
public class ConsumerService {

// 使用JmsListener配置消费者监听的队列,其中name是接收到的消息
@JmsListener(destination = "ActiveMQQueue")
public String handleMessage(String name) {
System.out.println("成功接受Name" + name);
return "成功接受Name" + name;
}
}

启动消费者项目,即可看到消息消费成功。
下篇文章会对消费者处理消息进行一个升级,即配置不同的handler实现不同的消费逻辑
————————————————
版权声明:本文为CSDN博主「莫知莫言」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weixin_43190879/article/details/123127703

posted @ 2023-01-30 17:59  疯子110  阅读(117)  评论(0编辑  收藏  举报