Compute
Elastic Cloud Server
Huawei Cloud Flexus
Bare Metal Server
Auto Scaling
Image Management Service
Dedicated Host
FunctionGraph
Cloud Phone Host
Huawei Cloud EulerOS
Networking
Virtual Private Cloud
Elastic IP
Elastic Load Balance
NAT Gateway
Direct Connect
Virtual Private Network
VPC Endpoint
Cloud Connect
Enterprise Router
Enterprise Switch
Global Accelerator
Management & Governance
Cloud Eye
Identity and Access Management
Cloud Trace Service
Resource Formation Service
Tag Management Service
Log Tank Service
Config
OneAccess
Resource Access Manager
Simple Message Notification
Application Performance Management
Application Operations Management
Organizations
Optimization Advisor
IAM Identity Center
Cloud Operations Center
Resource Governance Center
Migration
Server Migration Service
Object Storage Migration Service
Cloud Data Migration
Migration Center
Cloud Ecosystem
KooGallery
Partner Center
User Support
My Account
Billing Center
Cost Center
Resource Center
Enterprise Management
Service Tickets
HUAWEI CLOUD (International) FAQs
ICP Filing
Support Plans
My Credentials
Customer Operation Capabilities
Partner Support Plans
Professional Services
Analytics
MapReduce Service
Data Lake Insight
CloudTable Service
Cloud Search Service
Data Lake Visualization
Data Ingestion Service
GaussDB(DWS)
DataArts Studio
Data Lake Factory
DataArts Lake Formation
IoT
IoT Device Access
Others
Product Pricing Details
System Permissions
Console Quick Start
Common FAQs
Instructions for Associating with a HUAWEI CLOUD Partner
Message Center
Security & Compliance
Security Technologies and Applications
Web Application Firewall
Host Security Service
Cloud Firewall
SecMaster
Anti-DDoS Service
Data Encryption Workshop
Database Security Service
Cloud Bastion Host
Data Security Center
Cloud Certificate Manager
Edge Security
Situation Awareness
Managed Threat Detection
Blockchain
Blockchain Service
Web3 Node Engine Service
Media Services
Media Processing Center
Video On Demand
Live
SparkRTC
MetaStudio
Storage
Object Storage Service
Elastic Volume Service
Cloud Backup and Recovery
Storage Disaster Recovery Service
Scalable File Service Turbo
Scalable File Service
Volume Backup Service
Cloud Server Backup Service
Data Express Service
Dedicated Distributed Storage Service
Containers
Cloud Container Engine
SoftWare Repository for Container
Application Service Mesh
Ubiquitous Cloud Native Service
Cloud Container Instance
Databases
Relational Database Service
Document Database Service
Data Admin Service
Data Replication Service
GeminiDB
GaussDB
Distributed Database Middleware
Database and Application Migration UGO
TaurusDB
Middleware
Distributed Cache Service
API Gateway
Distributed Message Service for Kafka
Distributed Message Service for RabbitMQ
Distributed Message Service for RocketMQ
Cloud Service Engine
Multi-Site High Availability Service
EventGrid
Dedicated Cloud
Dedicated Computing Cluster
Business Applications
Workspace
ROMA Connect
Message & SMS
Domain Name Service
Edge Data Center Management
Meeting
AI
Face Recognition Service
Graph Engine Service
Content Moderation
Image Recognition
Optical Character Recognition
ModelArts
ImageSearch
Conversational Bot Service
Speech Interaction Service
Huawei HiLens
Video Intelligent Analysis Service
Developer Tools
SDK Developer Guide
API Request Signing Guide
Terraform
Koo Command Line Interface
Content Delivery & Edge Computing
Content Delivery Network
Intelligent EdgeFabric
CloudPond
Intelligent EdgeCloud
Solutions
SAP Cloud
High Performance Computing
Developer Services
ServiceStage
CodeArts
CodeArts PerfTest
CodeArts Req
CodeArts Pipeline
CodeArts Build
CodeArts Deploy
CodeArts Artifact
CodeArts TestPlan
CodeArts Check
CodeArts Repo
Cloud Application Engine
MacroVerse aPaaS
KooMessage
KooPhone
KooDrive

Connecting to Redis on hiredis (C++)

Updated on 2024-07-29 GMT+08:00

This section describes how to access a Redis instance on hiredis. For more information about how to use other Redis clients, visit the Redis official website.

The following operations are based on an example of accessing a Redis instance on a client on an elastic cloud server (ECS).

NOTE:

The operations described in this section apply only to single-node, master/standby, and Proxy Cluster instances. To use C++ to connect to a Redis Cluster instance, see the C++ Redis client description.

Prerequisites

  • A DCS Redis instance has been created and is in the Running state.
  • An ECS has been created. For details about how to create an ECS, see the Elastic Cloud Server User Guide.
  • If the ECS runs the Linux OS, ensure that the GCC compilation environment has been installed on the ECS.

Connecting to Redis on hiredis

  1. View the IP address and port number of the DCS Redis instance to be accessed.

    For details, see Viewing Details of a DCS Instance.

  2. Log in to the ECS.

    The following uses CentOS as an example to describe how to access an instance in C++.

  3. Install GCC, Make, and hiredis.

    If the system does not provide a compiling environment, run the following yum command to install the environment:

    yum install gcc make

  4. Run the following command to download and decompress the hiredis package:

    wget https://github.com/redis/hiredis/archive/master.zip

    unzip master.zip

  5. Go to the directory where the decompressed hiredis package is saved, and compile and install hiredis.

    make

    make install

  6. Access the DCS instance by using hiredis.

    The following describes connection and password authentication of hiredis. For more information on how to use hiredis, visit the Redis official website.

    1. Edit the sample code for connecting to a DCS instance, and then save the code and exit.

      vim connRedis.c

      Example:

      #include <stdio.h>
      #include <stdlib.h>
      #include <string.h>
      #include <hiredis.h>
      int main(int argc, char **argv) {
           unsigned int j;
           redisContext *conn;
           redisReply *reply;
           if (argc < 3) {
                   printf("Usage: example {instance_ip_address} 6379 {password}\n");
                   exit(0);
           }
           const char *hostname = argv[1];
           const int port = atoi(argv[2]);
           const char *password = argv[3];
           struct timeval timeout = { 1, 500000 }; // 1.5 seconds
           conn = redisConnectWithTimeout(hostname, port, timeout);
           if (conn == NULL || conn->err) {
      		if (conn) {
                   printf("Connection error: %s\n", conn->errstr);
                   redisFree(conn);
      		} else {
                   printf("Connection error: can't allocate redis context\n");
      		}
           exit(1);
           }
           /* AUTH */
           reply = redisCommand(conn, "AUTH %s", password);
           printf("AUTH: %s\n", reply->str);
           freeReplyObject(reply);
      
           /* Set */
           reply = redisCommand(conn,"SET %s %s", "welcome", "Hello, DCS for Redis!");
           printf("SET: %s\n", reply->str);
           freeReplyObject(reply);
      
           /* Get */
           reply = redisCommand(conn,"GET welcome");
           printf("GET welcome: %s\n", reply->str);
           freeReplyObject(reply);
      
           /* Disconnects and frees the context */
           redisFree(conn);
           return 0;
      }
    2. Run the following command to compile the code:

      gcc connRedis.c -o connRedis -I /usr/local/include/hiredis -lhiredis

      If an error is reported, locate the directory where the hiredis.h file is saved and modify the compilation command.

      After the compilation, an executable connRedis file is obtained.

    3. Run the following command to access the chosen DCS Redis instance:

      ./connRedis {redis_instance_address} 6379 {password}

      {redis_instance_address} indicates the IP address of DCS instance and 6379 is an example port number of DCS instance. For details about how to obtain the IP address and port, see 1. Change them as required. {password} indicates the password used to log in to the chosen DCS Redis instance. This password is defined during DCS Redis instance creation.

      You have successfully accessed the instance if the following command output is displayed:

      AUTH: OK
      SET: OK
      GET welcome: Hello, DCS for Redis!
    NOTICE:

    If an error is reported, indicating that the hiredis library files cannot be found, run the following commands to copy related files to the system directories and add dynamic links:

    mkdir /usr/lib/hiredis

    cp /usr/local/lib/libhiredis.so.0.13 /usr/lib/hiredis/

    mkdir /usr/include/hiredis

    cp /usr/local/include/hiredis/hiredis.h /usr/include/hiredis/

    echo '/usr/local/lib' >>;>>;/etc/ld.so.conf

    ldconfig

    Replace the locations of the so and .h files with actual ones before running the commands.

We use cookies to improve our site and your experience. By continuing to browse our site you accept our cookie policy. Find out more

Feedback

Feedback

Feedback

0/500

Selected Content

Submit selected content with the feedback