MQ收发消息及日志输出实例

该博客介绍了如何使用Java实现RabbitMQ的消息发送和接收,并详细展示了代码示例。同时,文章还涵盖了如何配置日志系统,将发送和接收的消息记录到指定文件,支持日志级别调整。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本篇内容关注点有

  1. mq消息发送示例;
  2. mq消息接收示例;
  3. 生成日志输出到指定文件,日志级别可调;

发送至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);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值