RabbitMQ 消息传递Java对象

通过消息服务器传递Java对象,Java类必须实现序列化接口,可以把Java对象转化为字节数组,从消费者或生产者传递到另外一个JVM中,一定需要两个JVM共享这个类,比如是UserInfo类。

1、定义序列化的类UserInfo
在这里插入图片描述
2、消费者中,实例化UserInfo的对象,并取出它的字节数组

在这里插入图片描述
在这里插入图片描述
3、编写生产者
在这里插入图片描述
在这里插入图片描述

UserInfo.java

package com.test.rfc;

public class UserInfo implements java.io.Serializable{
	private String name = null;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
}

Server.java

package com.test.rfc;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Consumer;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;

public class Server {
	public byte[] getUserByte() throws Exception
	{
		UserInfo u = new UserInfo();
		u.setName("Hello I come from MQ server");
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		ObjectOutputStream oos = new ObjectOutputStream(baos);
		oos.writeObject(u);
		oos.close();
		baos.close();
		return baos.toByteArray();
	}
	public static void main(String[] argv) {
		Server s = new Server();
		ConnectionFactory factory = new ConnectionFactory();
		factory.setUsername("admin");
		factory.setPassword("admin");
		factory.setHost("192.168.169.142"); //使用默认端口5672
		Connection connection = null;
			
		try {
			connection = factory.newConnection();
			final Channel channel = connection.createChannel();
			//序列化对象
			final byte[] data = s.getUserByte();
			System.out.println(data.length);
			String queueName = "queue_rpc";
			channel.queueDeclare(queueName, false, false, false, null);
			Consumer consumer = new DefaultConsumer(channel) {

				@Override
				public void handleDelivery(String consumerTag,
					Envelope envelope, AMQP.BasicProperties properties,
					byte[] body) throws IOException 
				{
					System.out.println("rfc=" + new String(body));
					AMQP.BasicProperties replyProps = new AMQP.BasicProperties.Builder()
					.correlationId(properties.getCorrelationId())
					.build();
					channel.basicPublish("", properties.getReplyTo(),
					replyProps, data);
					channel.basicAck(envelope.getDeliveryTag(), false);
				}
			};
			channel.basicConsume(queueName, false, consumer);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}

Client.java

package com.test.rfc;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.UUID;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

import com.rabbitmq.client.*;

public class Client {
	public static void main(String[] argv) {
		try
		{
			//发送消息的队列,Server在这个队列上接受消息
			String queueName = "queue_rpc";
			ConnectionFactory factory = new ConnectionFactory();
			factory.setUsername("admin");
			factory.setPassword("admin");
			factory.setHost("192.168.169.142"); //使用默认端口5672
			Connection connection = null;
			connection = factory.newConnection();
			Channel channel = connection.createChannel();
			//生成临时的队列,Client在这队列上等待Server返回信息,Server向这个队列发消息
			String replyQueueName = channel.queueDeclare().getQueue();
			//生成唯一ID
			final String corrId = UUID.randomUUID().toString();
			AMQP.BasicProperties props = new AMQP.BasicProperties.Builder()
			.correlationId(corrId).replyTo(replyQueueName).build();
			//客户端发送RFC请求
			channel.basicPublish("", queueName, props, "GetUserInfo".getBytes());
			//Server返回消息
			final BlockingQueue response = new ArrayBlockingQueue(1);
			channel.basicConsume(replyQueueName, true,
				new DefaultConsumer(channel) {
					@Override
					public void handleDelivery(String consumerTag,
						Envelope envelope, AMQP.BasicProperties properties,
						byte[] body) throws IOException 
					{
						System.out.println(properties.getCorrelationId()+",body="+body.length);
						if (properties.getCorrelationId().equals(corrId)) {
							response.offer(body);
						}
					}
			});
			byte[] b = response.take();
			System.out.println(b.length);
			//反序列化对象
			ByteArrayInputStream bais = new ByteArrayInputStream(b);
			ObjectInputStream oii = new ObjectInputStream(bais);
			UserInfo u = (UserInfo)oii.readObject();
			System.out.println(u.getName());
			channel.close();
			connection.close();
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
	}
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java中,可以使用RabbitMQ进行消息传递,并且可以对对象进行序列化和反序列化。下面是一个示例代码,展示了如何使用RabbitMQJava对象进行序列化。 首先,你需要在你的项目中引入RabbitMQ的相关依赖。可以在Maven中添加以下依赖项: ```xml <dependency> <groupId>com.rabbitmq</groupId> <artifactId>amqp-client</artifactId> <version>5.12.0</version> </dependency> ``` 接下来,你需要创建一个Java对象,该对象需要实现`Serializable`接口,以便能够在网络上进行序列化和反序列化。例如: ```java import java.io.Serializable; public class Message implements Serializable { private String content; public Message(String content) { this.content = content; } public String getContent() { return content; } } ``` 然后,你可以使用RabbitMQ发送和接收消息。下面是一个简单的示例: ```java import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; import com.rabbitmq.client.ConnectionFactory; import com.rabbitmq.client.MessageProperties; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.concurrent.TimeoutException; public class RabbitMQExample { private static final String QUEUE_NAME = "my_queue"; public static void main(String[] args) { // 创建连接工厂 ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); try (Connection connection = factory.newConnection(); Channel channel = connection.createChannel()) { // 创建队列 channel.queueDeclare(QUEUE_NAME, true, false, false, null); // 发送消息 Message messageToSend = new Message("Hello RabbitMQ!"); byte[] serializedMessage = serializeObject(messageToSend); channel.basicPublish("", QUEUE_NAME, MessageProperties.PERSISTENT_TEXT_PLAIN, serializedMessage); // 接收消息 channel.basicConsume(QUEUE_NAME, true, (consumerTag, delivery) -> { Message receivedMessage = (Message) deserializeObject(delivery.getBody()); System.out.println("Received message: " + receivedMessage.getContent()); }, consumerTag -> {}); } catch (IOException | TimeoutException | ClassNotFoundException e) { e.printStackTrace(); } } private static byte[] serializeObject(Object object) throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bos); oos.writeObject(object); oos.flush(); return bos.toByteArray(); } private static Object deserializeObject(byte[] bytes) throws IOException, ClassNotFoundException { ByteArrayInputStream bis = new ByteArrayInputStream(bytes); ObjectInputStream ois = new ObjectInputStream(bis); return ois.readObject(); } } ``` 在上面的示例中,`serializeObject`和`deserializeObject`方法分别将Java对象序列化为字节数组和将字节数组反序列化为Java对象。通过调用`basicPublish`方法,可以将序列化后的消息发送到指定的队列。 使用RabbitMQ进行对象序列化时,需要确保发送方和接收方都可以访问相同的对象类定义。否则,可能会导致反序列化失败。 希望以上信息能对你有所帮助!如有任何疑问,请随时提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值