如何将来自RabbitMQ broker的`byte[]`数据转换为Ballerina中的记录类型

slwdgvem  于 12个月前  发布在  RabbitMQ
关注(0)|答案(2)|浏览(245)

我在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>{};
    }
}

zaqlnxep

zaqlnxep1#

您可以使用CustomerDetails记录而不是使用rabbitmq:AnydataMessage,如下所示:

service rabbitmq:Service on channelListener {
    remote function onMessage(CustomerDetails customerDetails) returns error? {
        io:println(customerDetails.name); // you can handle fields here
    }
}

字符串
参考https://ballerina.io/learn/by-example/rabbitmq-consumer/示例

uqzxnwby

uqzxnwby2#

如果您的需求是访问rabbitmq:AnydataMessage中定义的所有详细信息,同时将内容表示为记录类型,则可以使用type inclusion定义自定义记录类型,并将CustomerDetails记录类型作为其内容类型,如下所示。

public type CustomerDetailsMessage record {|
    *rabbitmq:AnydataMessage;
    CustomerDetails? content;
|};

字符串
现在,您可以在客户端代码中使用此自定义消息类型:

import ballerina/io;
import ballerinax/rabbitmq;

public type CustomerDetails record {|
    string name;
    string ssn;
    string phone;
    int age;
|};

public type CustomerDetailsMessage record {|
    *rabbitmq:AnydataMessage;
    CustomerDetails? content;
|};

listener rabbitmq:Listener channelListener = new (rabbitmq:DEFAULT_HOST, rabbitmq:DEFAULT_PORT);

@rabbitmq:ServiceConfig {
    queueName: "MOT_HOTEL"
}
service rabbitmq:Service on channelListener {
    remote function onMessage(CustomerDetailsMessage message) returns error? {
        if message.content is () {
            io:println("Message received with `null` content");
        }
        io:println(message.content); // CustomerDetailsMessage
    }
}

相关问题