SpringBoot整合ActiveMQ

编程

 

版本

  • spring-boot : 2.2.2

步骤

1.创建Maven项目

这里推荐spring提供的一个非常方便的建SpringBoot工程的网站:start.spring.io。打开如下页面:

如图所示填好你的groupId, artifactId,在Dependencies栏输入activemq即可搜索出相关依赖包,点击添加。

最后点击Generate生成工程项目。Gradle工程类似操作,这里不作细叙。

2.配置文件

在工程内的application.properties文件写入:

spring.jms.pubSubDomain=false 	         #默认false, 表示默认发送/监听的destination是queue,true则为topic

spring.jms.jndiName= #连接工厂的jndi路径,如果你的mq连接是jndi提供才填

spring.jms.cache.enabled=true #是否使用session缓存,默认true

spring.jms.cache.consumers=false #是否缓存消费者消息,默认false

spring.jms.cache.producers=true #是否缓存消费者消息,默认true

spring.jms.cache.sessionCacheSize=1 #session缓存个数(每一个session类型)

spring.jms.template.defaultDestination= #默认队列名

spring.jms.template.deliveryDelay=5S #延时发送时间,java8的Duration类表达式,如5S表示5秒

spring.jms.template.deliveryMode=NON_PERSISTENT #发送模式,有NON_PERSISTENT和PERSISTENT两个选项,即不持久化和持久化,如果有值则qosEnabled自动为true

spring.jms.template.priority=1 #消息优先级,数字越大优先级越高,如果有值则qosEnabled自动为true

spring.jms.template.timeToLive=5S #消息存活时间,如果有值则qosEnabled自动为true

spring.jms.template.qosEnabled=false #如果为true,deliveryMode、priority、timeToLive三个参数将会被使用

spring.jms.template.receiveTimeout=5000 #receive方法的超时时间

spring.jms.listener.concurrency=1 #消费者最低线程数

spring.jms.listener.max-concurrency=100 #消费者最高线程数

spring.jms.listener.acknowledge-mode=DUPS_OK #响应类型,有AUTO,CLIENT,DUPS_OK,暂不详细说明

spring.activemq.broker-url=failover:(tcp://10.10.10.31:61616,tcp://10.10.10.32:61616)?randomize=false&timeout=1000&maxReconnectDelay=5000

spring.activemq.user=admin

spring.activemq.password=password

spring.activemq.pool.enabled=true #开启连接池,新版本需加依赖包,见pom文件

spring.activemq.pool.max-connections=100 #连接池最大连接数

我们大可以忽略上述冗长的配置,使用以下的即可:

spring.jms.template.defaultDestination=test-queue

spring.activemq.broker-url=failover:(tcp://10.10.10.31:61616,tcp://10.10.10.32:61616)?randomize=false&timeout=1000&maxReconnectDelay=5000

spring.activemq.user=admin

spring.activemq.password=password

3.测试

新建两个java类:

MessageSender.java

package io.ben202.demo;

import org.apache.activemq.command.ActiveMQQueue;

import org.apache.activemq.command.ActiveMQTopic;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.jms.core.JmsTemplate;

import org.springframework.stereotype.Component;

@Component

public class MessageSender {

@Autowired

private JmsTemplate jmsTemplate;

/**

* 发送消息

* @param message

*/

public void send(String message) {

jmsTemplate.convertAndSend(message); //如果配置文件有默认队列名,可使用此方法

// jmsTemplate.convertAndSend("test-queue", message); //每次发送消息均指定队列

// jmsTemplate.convertAndSend(new ActiveMQQueue("test-queue"), message); //每次发送消息均指定QUEUE队列

// jmsTemplate.convertAndSend(new ActiveMQTopic("test-topic"), message); //每次发送消息均指定TOPIC队列

}

}

MessageListener.java

package io.ben202.demo;

import org.springframework.jms.annotation.JmsListener;

import org.springframework.stereotype.Component;

@Component

public class MessageListener {

/**

* 处理消息

* @param message

*/

@JmsListener(destination = "test-queue")

public void receive(String message) {

System.out.println("message receive: " + message);

}

}

启动类:

package io.ben202.demo;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

import org.springframework.jms.annotation.EnableJms;

import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication

@EnableScheduling

@EnableJms

public class DemoApplication {

public static void main(String[] args) {

SpringApplication.run(DemoApplication.class, args);

}

}

建一个定时任务用于测试:

package io.ben202.demo;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.scheduling.annotation.Scheduled;

import org.springframework.stereotype.Component;

@Component

public class TestRunner{

@Autowired

MessageSender sender;

@Scheduled(fixedRate = 2000)

public void run() {

sender.send("current time millis :" + System.currentTimeMillis());

}

}

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 https://maven.apache.org/xsd/maven-4.0.0.xsd">

<modelVersion>4.0.0</modelVersion>

<parent>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-parent</artifactId>

<version>2.2.2.RELEASE</version>

<relativePath/> <!-- lookup parent from repository -->

</parent>

<groupId>io.ben202</groupId>

<artifactId>demo</artifactId>

<version>0.0.1-SNAPSHOT</version>

<name>demo</name>

<description>Demo project for Spring Boot</description>

<properties>

<java.version>1.8</java.version>

</properties>

<dependencies>

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-activemq</artifactId>

</dependency>

<!-- JMS连接池 -->

<dependency>

<groupId>org.messaginghub</groupId>

<artifactId>pooled-jms</artifactId>

</dependency>

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-test</artifactId>

<scope>test</scope>

<exclusions>

<exclusion>

<groupId>org.junit.vintage</groupId>

<artifactId>junit-vintage-engine</artifactId>

</exclusion>

</exclusions>

</dependency>

</dependencies>

<build>

<plugins>

<plugin>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-maven-plugin</artifactId>

</plugin>

</plugins>

</build>

</project>

执行结果:

. ____ _ __ _ _

/\ / ___"_ __ _ _(_)_ __ __ _

( ( )\___ | "_ | "_| | "_ / _` |

\/ ___)| |_)| | | | | || (_| | ) ) ) )

" |____| .__|_| |_|_| |_\__, | / / / /

=========|_|==============|___/=/_/_/_/

:: Spring Boot :: (v2.2.2.RELEASE)

2019-12-25 16:11:05.448 INFO 7400 --- [ main] io.ben202.demo.DemoApplication : Starting DemoApplication on DESKTOP-GJ3A74T with PID 7400 (D:myworkplacedevspring-boot-activemq-demo argetclasses started by ben in D:myworkplacejoinpay_devspring-boot-activemq-demo)

2019-12-25 16:11:05.454 INFO 7400 --- [ main] io.ben202.demo.DemoApplication : No active profile set, falling back to default profiles: default

2019-12-25 16:11:06.431 INFO 7400 --- [ main] o.s.s.c.ThreadPoolTaskScheduler : Initializing ExecutorService "taskScheduler"

2019-12-25 16:11:06.736 INFO 7400 --- [ActiveMQ Task-1] o.a.a.t.failover.FailoverTransport : Successfully connected to tcp://10.10.10.31:61616

2019-12-25 16:11:06.782 INFO 7400 --- [ main] io.ben202.demo.DemoApplication : Started DemoApplication in 1.896 seconds (JVM running for 2.929)

message receive: current time millis :1577261466805

message receive: current time millis :1577261468778

message receive: current time millis :1577261470777

message receive: current time millis :1577261472777

message receive: current time millis :1577261474778

message receive: current time millis :1577261476778

message receive: current time millis :1577261478777

message receive: current time millis :1577261480778

message receive: current time millis :1577261482777

message receive: current time millis :1577261484777

message receive: current time millis :1577261486777

message receive: current time millis :1577261488778

message receive: current time millis :1577261490778

message receive: current time millis :1577261492777

4.总结

是的,有了SpringBoot,一切就是这么简单,仅需简单的几行代码即可完成对ActiveMQ的使用。当然,业务是复杂的,场景是多样的,技术不会脱离业务而存在。你在实际应用中遇到什么问题?欢迎大家踊跃提问和讨论。

个人经验:学习一门新技术,永远都要把它看得很简单,永远都是从最基础的功能应用起来。

以上是 SpringBoot整合ActiveMQ 的全部内容, 来源链接: utcz.com/z/512043.html

回到顶部