我在ballerina包中使用RabbitMQ模块沿着一个服务器和一个客户端。在客户端中,我接收的内容是byte[]
,需要在处理之前转换为CustomerDetails
记录类型。我们如何做到这一点?
client.bal
import ballerina/io;
import ballerinax/rabbitmq;
type CustomerDetails record {|
string name;
string ssn;
string phone;
int age;
|};
listener rabbitmq:Listener channelListener = new (rabbitmq:DEFAULT_HOST, rabbitmq:DEFAULT_PORT);
@rabbitmq:ServiceConfig {
queueName: "MOT_HOTEL"
}
service rabbitmq:Service on channelListener {
remote function onMessage(rabbitmq:AnydataMessage message) returns error? {
if message.content is () {
io:println("Message recived with `null` content");
}
io:println(message.content); // byte[]
...
}
}
字符串
server.bal
import ballerina/http;
import ballerina/io;
import ballerinax/rabbitmq;
const queueName = "MOT_HOTEL";
const exchangeName = "TheExchange";
service /orders on new http:Listener(8080) {
function init() returns error? {
check rabbitmqClient->exchangeDeclare(exchangeName, rabbitmq:DIRECT_EXCHANGE);
check rabbitmqClient->queueDeclare(queueName);
}
resource function post .(CustomerDetails payload)
returns http:Created|http:InternalServerError|error? {
check rabbitmqClient->publishMessage({content: payload, routingKey: queueName});
io:println("Message sent");
return <http:Created>{};
}
}
型
2条答案
按热度按时间zaqlnxep1#
您可以使用
CustomerDetails
记录而不是使用rabbitmq:AnydataMessage
,如下所示:字符串
参考https://ballerina.io/learn/by-example/rabbitmq-consumer/示例
uqzxnwby2#
如果您的需求是访问
rabbitmq:AnydataMessage
中定义的所有详细信息,同时将内容表示为记录类型,则可以使用type inclusion定义自定义记录类型,并将CustomerDetails
记录类型作为其内容类型,如下所示。字符串
现在,您可以在客户端代码中使用此自定义消息类型:
型