IntelliJ IDEA生成jar包(工程基於maven構建)
阿新 • • 發佈:2018-12-27
新建工程
新建一個基於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();
}
}
}
}
}