新建工程
新建一个基于maven构建的java项目工程,新建后如下所示:
pom文件加入rabbitmq模块依赖,如下:
修改Main.java文件,这里让它作为rabbitmq的消息发送端:
package cn.linjk.send;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
/**
* Created by LinJK on 2017-07-25.
*/
public class Main {
// 消息队列名称
private final static String QUEUE_NAME = "linjk-test";
public static void main(String[] args) throws java.io.IOException,
java.lang.InterruptedException{
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("192.168.1.179");
factory.setPort(5672);
factory.setUsername("linjk");
factory.setPassword("ljk121");
// 创建连接
Connection connection = factory.newConnection();
// 创建频道
Channel channel = connection.createChannel();
// 指定队列
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
String message = "LinJK-Test";
// 向队列中发出一条消息
channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
System.out.println("Sent message: " + message);
channel.close();
connection.close();
}
}
执行命令mvn package
生成jar包,并运行,结果如下:
修改工程,生成可运行jar包
pom文件添加maven-assembly-plugin
插件支持,如下:
注意圈住的地方,这里说明了主类。
执行命令mvn clean assembly:assembly
生成jar包,生成后target目录如下:
这里多了一个rabbitmqSend-1.0-SNAPSHOT-jar-with-dependencies.jar
文件,这个jar包包含了依赖模块,因此,可以发现,其大小比没有包含依赖的大了接近100倍,运行这个jar包,结果如下:
消息已发送到rabbitmq了。
附rabbitmq消费消息端代码:
package cn.linjk.recvMsg;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.QueueingConsumer;
import java.io.IOException;
/**
* Created by admin on 2017-07-25.
*/
public class recv {
//队列名称
private final static String QUEUE_NAME = "linjk-test";
public static void main(String[] argv) throws java.io.IOException,
java.lang.InterruptedException
{
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("192.168.1.179");
factory.setPort(5672);
factory.setUsername("linjk");
factory.setPassword("ljk121");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
// 声明队列,主要为了防止消息接收者先运行此程序,队列还不存在时创建队列。
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
System.out.println("Waiting for messages, press CTRL+C to exit...");
// 创建队列消费者
QueueingConsumer consumer = new QueueingConsumer(channel);
// 指定消费队列
channel.basicConsume(QUEUE_NAME, true, consumer);
while (true) {
// nextDelivery是一个阻塞方法(内部实现其实是阻塞队列的take方法)
QueueingConsumer.Delivery delivery = consumer.nextDelivery();
String message = new String(delivery.getBody());
System.out.println("Received message: " + message);
if (message.equals("Succeed")) {
try {
Runtime.getRuntime().exec("/usr/local/bin/java/bin/java -jar /var/lib/jenkins/workspace/test/target/microservice-hystrix-dashboard-0.0.1-SNAPSHOT.jar &");
}
catch (IOException e) {
e.printStackTrace();
}
}
}
}
}