AerospikeC客户端手册―――用户定义函数―注册用户定义函数

2015-07-24 08:04:14 · 作者: · 浏览: 1

注册用户定义函数

Aerospike C 客户端提供在 数据库中注册、更新或移除一个用户定义函数(UDF)模块的能力。目前,用户定义函数仅支持LUA语言。
aerospike_udf_put() — 注册或更新UDF模块。
aerospike_udf_remove() — 移除UDF模块。

下面的代码引用自示例目录【examples/basic_examples/udf】,由Aerospike C客户端安装包自带。

请先阅读【创建连接】章节内容,理解如何建立与集群的连接。

从文件读取UDF

很可能,试图注册的模块保存在一个文件中。所以首先读入这个文件:

FILE* file = fopen("myudf.lua", "r");

if (! file) {
    LOG("cannot open script file %s : %s", udf_file_path, strerror(errno));
    return false;
}

// Read the file's content into a local buffer.

uint8_t* content = (uint8_t*)malloc(1024 * 1024);

if (! content) {
    LOG("script content allocation failed");
    return false;
}

uint8_t* p_write = content;
int read = (int)fread(p_write, 1, 512, file);
int size = 0;

while (read) {
    size += read;
    p_write += read;
    read = (int)fread(p_write, 1, 512, file);
}

fclose(file);

// Wrap the local buffer as an as_bytes object.
as_bytes udf_content;
as_bytes_init_wrap(&udf_content, content, size, true);

向Aerospike服务器注册UDF

一旦UDF内容转换到as_bytes对象格式,就可以注册函数。

as_error err; // Register the UDF file in the database cluster. if (aerospike_udf_put(&as, &err, NULL, "myudf", AS_UDF_TYPE_LUA, &udf_content) != AEROSPIKE_OK) { LOG("aerospike_udf_put() returned %d - %s", err.code, err.message); } // This frees the local buffer. as_bytes_destroy(&udf_content);

此调用将发送UDF模块到集群中某一节点。这个节点会将UDF传播到集群中其它节点。

若在任何时候,需要更新UDF功能,简单地以相同模块名称重新注册新的拷贝即可。

通常UDF注册只需要几秒就可以注册到集群中所有节点。

检查UDF模块是否正确注册

检查UDF模块是否正确注册的最佳方法是通过使用aql工具。请参见【aql手册】。

从服务器移除UDF

若在任何时候服务器不再需要某UDF模块,可从集群中移除它。

as_error err; if (aerospike_udf_remove(&as, &err, NULL, "myudf") != AEROSPIKE_OK) { LOG("aerospike_udf_remove() returned %d - %s", err.code, err.message); return false; }