文档首页
MySQL NDB Cluster API 开发人员指南
相关文档 下载此手册
PDF (US Ltr) - 3.6Mb
PDF (A4) - 3.6Mb


2.1.2.3 建立连接

要建立与服务器的连接,您必须创建 Ndb_cluster_connection 的实例,其构造函数以集群连接字符串作为参数。如果未提供连接字符串,则假定为 localhost

集群连接实际上直到调用 Ndb_cluster_connection::connect() 方法才会启动。当不带任何参数调用时,连接尝试会无限期地重试,每秒一次,直到成功。在建立连接之前,不会进行任何报告。

默认情况下,API 节点连接到 最近的 数据节点。这通常是由于共享内存传输可用而导致的数据节点在与最近节点相同的机器上运行,从而比 TCP/IP 更快。在某些情况下,这会导致负载分配不佳,因此可以通过在调用 connect() 之前将 0 作为参数调用 set_optimized_node_selection() 方法来强制执行循环节点连接方案。

connect() 只启动与 NDB Cluster 管理节点的连接。要启用与数据节点的连接,请在调用 connect() 之后使用 wait_until_ready()wait_until_ready() 等待最多给定秒数,直到与数据节点的连接建立。

在以下示例中,初始化和连接在两个函数 example_init()example_end() 中处理,这两个函数通过包含文件 example_connection.h 包含在后续示例中。

示例 2-1:连接示例。 

Press CTRL+C to copy
#include <stdio.h> #include <stdlib.h> #include <NdbApi.hpp> #include <mysql.h> #include <mgmapi.h> Ndb_cluster_connection* connect_to_cluster(); void disconnect_from_cluster(Ndb_cluster_connection *c); Ndb_cluster_connection* connect_to_cluster() { Ndb_cluster_connection* c; if(ndb_init()) exit(EXIT_FAILURE); c= new Ndb_cluster_connection(); if(c->connect(4, 5, 1)) { fprintf(stderr, "Unable to connect to cluster within 30 seconds.\n\n"); exit(EXIT_FAILURE); } if(c->wait_until_ready(30, 0) < 0) { fprintf(stderr, "Cluster was not ready within 30 seconds.\n\n"); exit(EXIT_FAILURE); } return c; } void disconnect_from_cluster(Ndb_cluster_connection *c) { delete c; ndb_end(2); } int main(int argc, char* argv[]) { Ndb_cluster_connection *ndb_connection= connect_to_cluster(); printf("Connection Established.\n\n"); disconnect_from_cluster(ndb_connection); return EXIT_SUCCESS; }