LoginSignup
10
8

More than 5 years have passed since last update.

CでRedisにアクセスする

Last updated at Posted at 2015-01-20

概要

Redisの公式から出ているCのドライバを使って
Redisにアクセスするサンプルを作りましたので、そのソースと手順などを共有したいと思います。

環境構築

CentOSを想定しています。

yum update -y
yum install -y git gcc wget vim
# yumからインストール可能にする
wget http://dl.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpm
wget http://rpms.famillecollet.com/enterprise/remi-release-6.rpm
rpm -Uvh remi-release-6*.rpm epel-release-6*.rpm
yum --enablerepo=remi,epel install -y redis
# ライブラリのインストール
git clone https://github.com/redis/hiredis.git
cd hiredis
make
make install

データベースの設定

テスト用のデータを入れます。

service redis start  # redisサーバ起動
redis-cli            # redisクライアント起動
# データ投入
set 1 aaa
set 2 bbb
set 3 ccc
exit                 # 終了

Redisへアクセス

redis.c
#include <stdio.h>
#include <stdlib.h>
#include <hiredis.h>

int main(void){
  redisContext *conn = NULL;
  redisReply *resp   = NULL;
  int loop           = 0;

  // 接続
  conn = redisConnect( "127.0.0.1" ,  // 接続先redisサーバ
                       6379           // ポート番号
         );
  if( ( NULL != conn ) && conn->err ){
    // error
    printf("error : %s\n" , conn->errstr );
    redisFree( conn );
    exit(-1);
  }else if( NULL == conn ){
    exit(-1);
  }

  // Valueの取得
  for( loop=1 ; loop < 4 ; loop++ ){
    resp = (redisReply *) redisCommand( conn ,          // コネクション
                                        "GET %d" , loop // コマンド
                                      );
    if( NULL == resp ){
      // error
      redisFree( conn );
      exit(-1);
    }
    if( REDIS_REPLY_ERROR == resp->type ){
      // error
      redisFree( conn );
      freeReplyObject( resp );
      exit(-1);
    }
    printf( "%d : %s\n" , loop , resp->str );
    freeReplyObject( resp );
  }

  // 後片づけ
  redisFree( conn );
  return 0;
}

コンパイル、実行

gcc -Wall -o redis redis.c -lhiredis -L/usr/local/lib -I/usr/local/include/hiredis

このまま実行したい所だが私の環境ではライブラリが見つからない主旨のエラーが
出てしまったので対処します。

vi /etc/ld.so.conf.d/redis.conf/redis.conf  # 新規作成
# ファイル内容
/usr/local/lib  # 追記

ldconfig        # 設定反映

実行

./redis
1 : aaa
2 : bbb
3 : ccc
10
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
8