演示如何通过java连接rabbitmq,此代码为后面获取rabbitmq连接的工具代码。
新建工程
新建一个maven project工程,名字为rabbitmq-demo
Pom配置
增加rabbitmq的依赖工程:
<dependency>
<groupId>com.rabbitmq</groupId>
<artifactId>amqp-client</artifactId>
<version>4.0.2</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.10</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.5</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
</dependency>
<dependency>
<groupId>org.springframework.amqp</groupId>
<artifactId>spring-rabbit</artifactId>
<version>1.7.5.RELEASE</version>
</dependency>
代码
package com.lin.rabbit.utils;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
public class ConnectionUtils {
public static Connection getConnection() throws IOException, TimeoutException {
//创建工厂
ConnectionFactory factory = new ConnectionFactory();
//设置ip
factory.setHost("127.0.0.1");
//设置端口
factory.setPort(5672);
//设置virtual host
factory.setVirtualHost("/vhost_linwu");
//设置用户名
factory.setUsername("linwu");
//设置密码
factory.setPassword("linwu");
//获取连接
return factory.newConnection();
}
}