Managing server connections
This section will guide you through the process and steps of configuring the client to talk to a variety of cluster setups and options.
Connection parameters
The client object must first be instantiated using an lcb_create_ststructure. This contains fields needed to initialize the client with the proper parameters in order to connect to a bucket. The structure contains these notable fields: connstr and passwd.
The connstr field accepts a specifier known as a connection string that indicates which bucket to connect to and which hosts comprise the cluster. The passwd field should contain your bucket password, if your bucket has been configured with authentication.
struct lcb_create_st cropts;
memset(&cropts, 0, sizeof cropts);
cropts.version = 3;
cropts.v.v3.connstr = "couchbase://localhost/mybucket";
cropts.v.v3.passwd = "topsecret";
In
the example, localhost is a host of your cluster,
mybucket is the bucket you want to connect to, and
passwd is the bucket password.For increased redundancy you can specify multiplehosts, separated by a semicolon, like "couchbase://host1.net;host2.net/mybucket". Specifying multiple hosts allows the library to connect to the cluster as long as any of the hosts specified are up.
Initializing the client handle
lcb_t instance = NULL;
lcb_error_t err = lcb_create(&instance, &cropts);
if (err != LCB_SUCCESS) {
fprintf(stderr, “Could not create library handle: %s\n”, lcb_strerror(NULL, err));
}
The lcb_create() function initializes and allocates a new handle with the settings provided inside the lcb_create_st object.
After the handle has been initialized, a connection to the cluster must be scheduled. Invoke the lcb_connect() call to initiate the connection sequence. After the connection is scheduled, you need to wait for the connection to actually complete by using the lcb_wait() function, which waits for pending I/O to complete on behalf of the library. Finally, when lcb_wait() returns, use the lcb_get_bootstrap_status() function to determine if the connection completed successfully or if an error occurred:
lcb_error_t err;
lcb_connect(instance);
lcb_wait(instance);
err = lcb_get_bootstrap_status(instance);
if (err != LCB_SUCCESS) {
fprintf(stderr, “Couldn’t bootstrap: %s\n”, lcb_strerror(instance, err));
}
Connecting with SSL
Couchbase Sever features the ability to have clients communicate securely via SSL.
To use SSL, you need Couchbase Server Enterprise 3.0 or later
- Obtain the SSL certificate in use by the Cluster (...).
- Make the certificate available to the file system of the client host.
- Employ the couchbases:// scheme for the connstr field.
- Specify the local path to the certificate as the value for the certpath field.
cropts.v.v3.connstr = "couchbases://10.3.4.33/mybucket?certpath=/var/cbcert.pem";
Closing the connection
lcb_destroy(instance);
After
lcb_destroy() is called on an instance, the instance may no longer
be passed to any other function.