这篇随笔主要写启动 jar 时,如果需要依赖其他的 jar 包该怎么处理,我会以 rabbitMQ 客服端启动为例。
package com.rockcode.www.rabbitmq;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;
public class Consumer {
private final static String QUEUE_NAME = "rock";
public static void main(String[] args) {
ConnectionFactory factory = new ConnectionFactory();
factory.setUsername("guest");
factory.setPassword("guest");
factory.setHost("localhost");
Connection conn;
try {
conn = factory.newConnection();
Channel channel = conn.createChannel();
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
System.out.println(" [*] Waiting for messages. To exit press CTRL+C");
com.rabbitmq.client.Consumer con = new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope,
AMQP.BasicProperties properties, byte[] body)
throws IOException {
String message = new String(body, "UTF-8");
System.out.println(" [x] Received '" + message + "'");
try {
doWork(message);
} catch (InterruptedException e) {
e.printStackTrace();
}
finally {
System.out.println(" [x] Done");
}
}
};
channel.basicConsume(QUEUE_NAME, true, con);
} catch (IOException e) {
} catch (TimeoutException e) {
}
}
private static void doWork(String task) throws InterruptedException {
for (char ch: task.toCharArray()) {
if (ch == '.') Thread.sleep(1000);
}
}
}
客服端依赖 amqp-client-5.0.0.jar 和 slf4j-api-1.7.25.jar,先看看 MANIFEST.MF 文件
再看看目录结构
lib 下面就是所依赖的 jar 文件 amqp-client-5.0.0.jar 和 slf4j-api-1.7.25.jar。
我们在打开 CMD,先设置路径 set CP=.;lib/amqp-client-5.0.0.jar;lib/slf4j-api-1.7.25.jar;再执行 java -cp %CP% -jar consumer.jar
[x] Received 'hello.'
[x] Done
没错,收到了消息。但是上面有报错, Failed to load class "org.slf4j.impl.StaticLoggerBinder".
我们将 slf4j-nop-1.7.21.jar 加入 lib 目录下,重新设置路径,set CP=.;lib/amqp-client-5.0.0.jar;lib/slf4j-api-1.7.25.jar;lib/slf4j-nop-1.7.21.jar;
同时修改 MANIFEST.MF 文件
再试下 java -cp %CP% -jar consumer.jar
这样就没问题了。
下一篇我会将 producer 和 consumer 分别打包成 jar,通过命令行和脚本来执行,谢谢大家,希望有所帮助!