You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:使用Blob数据类型在Aerospike中存储图片的C API文档

在Aerospike C客户端中存储二进制图片(Blob)的实现方法

Aerospike官方文档中提到的Blob数据类型,在C客户端里是通过**AS_BYTES类型**来实现的——并非单独的Blob类型,而是将二进制字节数据以bytes类型存入bin中。以下是完整的代码示例和关键说明:

核心步骤与代码示例

1. 读取图片文件到内存

首先将本地.png/.jpeg文件读取到内存缓冲区:

#include <stdio.h>
#include <stdlib.h>
#include <aerospike/aerospike.h>
#include <aerospike/aerospike_key.h>
#include <aerospike/as_record.h>
#include <aerospike/as_bytes.h>

// 读取文件到内存缓冲区
uint8_t* read_file(const char* path, size_t* out_size) {
    FILE* fp = fopen(path, "rb");
    if (!fp) return NULL;

    fseek(fp, 0, SEEK_END);
    *out_size = ftell(fp);
    fseek(fp, 0, SEEK_SET);

    uint8_t* buffer = malloc(*out_size);
    if (!buffer) {
        fclose(fp);
        return NULL;
    }

    fread(buffer, 1, *out_size, fp);
    fclose(fp);
    return buffer;
}

2. 写入二进制数据到Aerospike

构建as_bytes对象,将内存中的图片数据存入Aerospike的bin:

int main() {
    // 初始化Aerospike客户端(需提前配置好as_config参数)
    aerospike as;
    aerospike_init(&as, &config);
    as_error err;

    // 读取目标图片文件
    size_t img_size;
    uint8_t* img_data = read_file("test.png", &img_size);
    if (!img_data) {
        fprintf(stderr, "读取图片文件失败\n");
        return 1;
    }

    // 构建数据库key
    as_key key;
    as_key_init(&key, "test_namespace", "test_set", "image_key");

    // 构建record并添加bytes类型的bin
    as_record rec;
    as_record_inita(&rec, 1);
    // 初始化bytes:使用wrap表示客户端不接管内存(需自行释放img_data);若用as_bytes_init则会复制数据
    as_bytes bytes;
    as_bytes_init_wrap(&bytes, img_data, img_size, AS_BYTES_BINARY, true);
    as_record_set_bytes(&rec, "image_bin", &bytes);

    // 写入数据库
    if (aerospike_key_put(&as, &err, NULL, &key, &rec) != AEROSPIKE_OK) {
        fprintf(stderr, "写入失败: %d - %s\n", err.code, err.message);
        as_record_destroy(&rec);
        free(img_data);
        aerospike_destroy(&as);
        return 1;
    }

    // 清理写入阶段资源
    as_record_destroy(&rec);
    free(img_data);

    // ---------------------- 读取验证 ----------------------
    as_record* read_rec = NULL;
    if (aerospike_key_get(&as, &err, NULL, &key, &read_rec) == AEROSPIKE_OK) {
        as_bytes* read_bytes = as_record_get_bytes(read_rec, "image_bin");
        if (read_bytes) {
            printf("读取到的图片大小: %zu 字节\n", read_bytes->size);
            // 可将read_bytes->data写入本地文件验证完整性
        }
        as_record_destroy(read_rec);
    }

    aerospike_destroy(&as);
    return 0;
}

关键注意事项

  • 内存管理:使用as_bytes_init_wrap时,Aerospike客户端不会接管传入的内存缓冲区,需自行调用free释放;若使用as_bytes_init,客户端会复制数据,原缓冲区可提前释放。
  • 大小限制:单个bin的最大数据量为1MB,若图片超过此大小,需使用Aerospike的Large Object (LOB) API处理。
  • 数据类型标识:AS_BYTES_BINARY表示二进制数据,确保客户端和服务器正确解析数据格式。

内容的提问来源于stack exchange,提问作者Gopi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 03:35:17