使用MQ
Java获取MQ连接对象
SpringBoot Pom 文件
4.0.0 com.example demo02-mq 0.0.1-SNAPSHOT demo02-mq demo02-mq 1.8 UTF-8 UTF-8 2.3.6.RELEASE org.springframework.boot spring-boot-starter org.springframework.boot spring-boot-starter-test test org.springframework.boot spring-boot-starter-amqp org.springframework.boot spring-boot-dependencies ${spring-boot.version} pom import org.Apache.maven.plugins maven-compiler-plugin 3.8.1 1.8 1.8 UTF-8 org.springframework.boot spring-boot-maven-plugin ${spring-boot.version} com.example.demo02.mq.Demo02MqApplication true repackage repackage
connection Util 类
package com.example.demo02.mq.util; import com.rabbitmq.client.Connection; import com.rabbitmq.client.ConnectionFactory; import java.io.IOException; import java.util.concurrent.TimeoutException; /** * @author Allen * 4/10/2024 7:25 PM * @version 1.0 * @description: MQ连接工具类 * */ public class ConnectionUtils { //为什么使用静态代码块初始化连接工厂? //因为连接工厂只需要初始化一次,所以使用静态代码块初始化 private static ConnectionFactory connectionFactory; static { // 创建连接工厂 connectionFactory = new ConnectionFactory(); //mq服务主机地址 connectionFactory.setHost("*********"); //连接端口 connectionFactory.setPort(40991); connectionFactory.setVirtualHost("/my240410"); //设置用户名 connectionFactory.setUsername("allen"); //设置密码 connectionFactory.setPassword("123456"); } public static Connection getConnection() { try { //返回连接 通过工厂获取连接 return connectionFactory.newConnection(); } catch (Exception e) { e.printStackTrace(); return null; } } } @SpringBootTest class Demo02MqApplicationTests { @Test void contextLoads() { Connection connection = ConnectionUtils.getConnection(); System.out.println(connection); } } 结果: amqp://allen@************//my240410

(图片来源网络,侵删)