本篇内容关注点有
- mq消息发送示例;
- mq消息接收示例;
- 生成日志输出到指定文件,日志级别可调;
发送至MQ消息代码块示例
package sendAndGetMqMessage;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.*;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;
public class SendMessage {
static String url;//mq的ip地址
static String queue;//队列名称
static String username;//mq登录账户
static String password;//mq登录密码
static String message;//发送消息内容
static String sendLogPath;//文件输出路径
private static Logger fileLogger;
//消息过期时间
private static String expiration = "60000";
public static void main(String[] argv) throws Exception {
SendMessage send = new SendMessage();
send.getMqUrlProperties();
ConnectionFactory factory = new ConnectionFactory();
factory.setHost(url);
factory.setUsername(username);
factory.setPassword(password);
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel = connection.createChannel();
channel.basicPublish("", queue, new AMQP.BasicProperties.Builder().contentType("text/plain")
.expiration(expiration)
.deliveryMode(2).build(),(message).getBytes(Charset.forName("utf-8")));
// channel.basicPublish("", queue, null, message.getBytes(Charset.forName("utf-8")));
System.out.println(" [x] SentMessage '" + message + "'");
//发送内容输出到日志
writeFileLogger(message);
channel.close();
connection.close();
}
public void getMqUrlProperties() {
try {
Properties properties = new Properties();
properties.load(new InputStreamReader(Objects.requireNonNull(getClass().getClassLoader().getResourceAsStream("mqConfig.properties"))));
url = properties.getProperty("url");
queue = properties.getProperty("queue");
username = properties.getProperty("username");
password = properties.getProperty("password");
message = properties.getProperty("message");
sendLogPath = properties.getProperty("sendLogPath");
} catch (Exception e) {
System.out.println("加载配置文件失败:获取到的配置文件为空");
}
}
static {
SendMessage send = new SendMessage();
send.getMqUrlProperties();
fileLogger = Logger.getLogger("com.bsk.doctor.util");
fileLogger.setLevel(Level.INFO);
Handler[] hs = fileLogger.getHandlers();
for (Handler h : hs) {
h.close();
fileLogger.removeHandler(h);
}
try {
CustomFileStreamHandler fh = new CustomFileStreamHandler(sendLogPath, 0, 1000, true);
fh.setEncoding("UTF-8");
fh.setFormatter(new CustomFormatter());
fileLogger.setUseParentHandlers(false);
fileLogger.addHandler(fh);
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static synchronized Logger getFileLogger() {
return fileLogger;
}
public static void writeFileLogger(String info) {
getFileLogger().logp(Level.INFO, "ewrwerwer", "werwerw", info);
}
}
接收MQ消息代码块示例
package sendAndGetMqMessage;
import com.rabbitmq.client.*;
import java.io.IOException;
import java.util.Properties;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;
public class RecvMessage {
static String url;
static String queue;
static String username;
static String password;
static String recLogPath;
private static Logger fileLogger;
public static void main(String[] argv)throws Exception {
if ((url == "") || (url == null) || (queue == "") || (queue == null)) {
System.out.println("mq的url或队列名为空");
return;
}
System.out.println("mqUrl=" + url);
System.out.println("queue=" + queue);
System.out.println("username=" + username);
System.out.println("password=" + password);
ConnectionFactory factory = new ConnectionFactory();
factory.setHost(url);
factory.setUsername(username);
factory.setPassword(password);
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
System.out.println("等待" + queue + "队列的消息...");
QueueingConsumer consumer = new QueueingConsumer(channel);
// channel.basicConsume(queue, true, consumer);
channel.basicConsume(queue, true, new DefaultConsumer(channel){
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
System.out.println("接收:"+new String(body, "UTF-8"));
writeFileLogger(new String(body, "UTF-8"));
}
});
// for (;;) {
// Delivery delivery = consumer.nextDelivery();
// String meaasge = new String(delivery.getBody());
// ByteArrayOutputStream baos = new ByteArrayOutputStream();
// ObjectOutputStream oos = new ObjectOutputStream(baos);
// oos.writeObject(meaasge);
// byte[] str = baos.toByteArray();
// String message = null;
// try{
// Map<String, String> deSerialize = (Map<String, String>) SerializationUtils.deserialize(str);
// System.out.println(queue + "中的消息内容:" + deSerialize.toString());
// message = deSerialize.toString();
// }catch (Exception e){
// String msg = (String) SerializationUtils.deserialize(str);
// System.out.println(queue + "中的消息内容11:" + msg);
// message = msg;
// }
// writeFileLogger(message);
// }
}
public void getMqUrlProperties() {
try {
Properties properties = new Properties();
properties.load(getClass().getClassLoader().getResourceAsStream("mqConfig.properties"));
url = properties.getProperty("url");
queue = properties.getProperty("queue");
username = properties.getProperty("username");
password = properties.getProperty("password");
recLogPath = properties.getProperty("recLogPath");
} catch (Exception e) {
System.out.println("加载配置文件失败:获取到的配置文件为空");
}
}
static {
RecvMessage recv = new RecvMessage();
recv.getMqUrlProperties();
fileLogger = Logger.getLogger("com.bsk.doctor.util");
fileLogger.setLevel(Level.INFO);
Handler[] hs = fileLogger.getHandlers();
for (Handler h : hs) {
h.close();
fileLogger.removeHandler(h);
}
try {
CustomFileStreamHandler fh = new CustomFileStreamHandler(recLogPath, 0, 1000, true);
fh.setEncoding("UTF-8");
fh.setFormatter(new CustomFormatter());
fileLogger.setUseParentHandlers(false);
fileLogger.addHandler(fh);
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static synchronized Logger getFileLogger() {
return fileLogger;
}
public static void writeFileLogger(String info) {
getFileLogger().logp(Level.INFO, "ewrwerwer", "werwerw", info);
}
}