java对象消息传递_8.RabbitMQ 消息传递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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值