rabbitmq-c 传递json字符串
时间: 2023-10-29 18:05:21 浏览: 166
RabbitMQDemo_RabbitMQ发布与订阅Demo_rabbitmq_JSON_中间件_
5星 · 资源好评率100%
要在rabbitmq-c中传递JSON字符串,可以将其转换为字符数组,然后将其作为消息体发送到RabbitMQ消息队列中。以下是一个示例代码片段:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdint.h>
#include <stdbool.h>
#include <amqp.h>
#include <amqp_framing.h>
#include <amqp_tcp_socket.h>
#include <jansson.h>
int main(int argc, char const *const *argv) {
const char *hostname;
int port, status;
char const *exchange;
char const *routingkey;
char const *messagebody;
amqp_socket_t *socket = NULL;
amqp_connection_state_t conn;
// Set up the connection parameters
hostname = "localhost";
port = 5672;
exchange = "my-exchange";
routingkey = "my-routing-key";
// Create a connection object
conn = amqp_new_connection();
// Create a TCP socket object
socket = amqp_tcp_socket_new(conn);
if (!socket) {
printf("Error creating TCP socket object\n");
return 1;
}
// Connect to the RabbitMQ server
status = amqp_socket_open(socket, hostname, port);
if (status) {
printf("Error connecting to RabbitMQ server\n");
return 1;
}
// Authenticate with the RabbitMQ server
amqp_login(conn, "/", 0, 131072, 0, AMQP_SASL_METHOD_PLAIN, "guest", "guest");
amqp_channel_open(conn, 1);
amqp_get_rpc_reply(conn);
// Create a JSON object
json_t *root;
root = json_pack("{s:s, s:s}", "name", "John", "age", "30");
if (!root) {
printf("Error creating JSON object\n");
return 1;
}
// Convert the JSON object to a string
messagebody = json_dumps(root, JSON_COMPACT);
if (!messagebody) {
printf("Error converting JSON object to string\n");
return 1;
}
// Create a message object
amqp_basic_properties_t props;
props._flags = AMQP_BASIC_CONTENT_TYPE_FLAG | AMQP_BASIC_DELIVERY_MODE_FLAG;
props.content_type = amqp_cstring_bytes("text/json");
props.delivery_mode = 2; // persistent delivery mode
amqp_bytes_t message_bytes = amqp_cstring_bytes(messagebody);
amqp_basic_publish(conn,
1, // channel number
amqp_cstring_bytes(exchange),
amqp_cstring_bytes(routingkey),
0, // mandatory
0, // immediate
&props,
message_bytes);
amqp_get_rpc_reply(conn);
// Clean up
json_decref(root);
free(messagebody);
amqp_channel_close(conn, 1, AMQP_REPLY_SUCCESS);
amqp_connection_close(conn, AMQP_REPLY_SUCCESS);
amqp_destroy_connection(conn);
return 0;
}
```
在上面的代码中,我们使用了JSON-C库来创建和转换JSON对象。我们首先创建一个JSON对象,然后将其转换为字符串,最后将字符串作为消息体发布到RabbitMQ消息队列中。注意,我们还需要设置消息属性,例如内容类型和持久性标志。消息的发送和接收可以使用RabbitMQ-C库中提供的一些函数进行操作。
阅读全文