debian:trixie 환경에서 공부하며 작성한 게시글입니다.

ai의 도움을 받아 공부하며 작성한 게시글입니다.

 

여기선 hiredis 라이브러리의 사용만 다루기때문에 redis는 아래 게시글에서 알아보자.

 

Redis

도커 redis:8.2.4 컨테이너 환경에서 작성된 게시글입니다.유튜브 채널 JSCODE의 강의를 보며 공부한걸 정리한 게시글입니다.Redis 란?짱빠른 nosql 데이터베이스. 모든 데이터를 메모리에 저장하기때

dodontak.tistory.com


설치

apt install libhiredis-dev

사용

빌드할 때 추가할 라이브러리 옵션

-lhiredis

연결/ 연결해제

"redis" 는 도커 컴포즈 서비스 이름이다. 같은 도커네트워크라서 가능한것. ip주소가 들어갈 자리다.

연결해제는 redisFree() 함수로 한다.

#include <hiredis.h>

int main()
{
	redisContext *conn = redisConnect("redis", 6379);
	if (conn == nullptr || conn->err) {
		std::cout << "fail to connect" << std::endl;
		return 1;
	}
	redisFree(conn);
}

쿼리 사용

지난번에 배운 7가지 쿼리를 모두 사용해보자.

int main()
{
    /*...*/
	redisReply	*reply;

	reply = (redisReply *)redisCommand(c, "set %s %s", "dodontak:name", "dodontak");
	cout << "set: " << reply->str << endl;
	freeReplyObject(reply);

	reply = (redisReply *)redisCommand(c, "set %s %i %s %i", "dodontak:age", 30, "ex", 5);
	cout << "set(ttl): " << reply->str << endl;
	freeReplyObject(reply);

	reply = (redisReply *)redisCommand(c, "get %s", "dodontak:name");
	cout << "get: " << reply->integer << endl;
	freeReplyObject(reply);

	reply = (redisReply *)redisCommand(c, "ttl %s", "dodontak:age");
	cout << "ttl: " << reply->integer << endl;
	freeReplyObject(reply);

	reply = (redisReply *)redisCommand(c, "keys *");
	for (int i = 0; i < reply->elements; ++i)
		cout << "keys : " << reply->element[i]->str << endl;
	freeReplyObject(reply);

	reply = (redisReply *)redisCommand(c, "del %s", "dodontak:age");
	cout << "del: " << reply->integer << endl;
	freeReplyObject(reply);

	reply = (redisReply *)redisCommand(c, "flushall");
	cout << "flushall: " << reply->integer << endl;
	freeReplyObject(reply);

	redisFree(c);
    /*...*/
}

잘 된다!

  • 리턴값은 void포인터이고, redisReply 구조체 포인터로 변환하면 그안에 결과가 적혀있다.
  • 리턴값이 nullptr 라면 연결 오류다.
  • 매번 쿼리실행을 마칠때마다 freeReplyObject를 호출해줘야만 한다.

redisReply 구조체

typedef struct redisReply {
    int type; /* REDIS_REPLY_* */
    long long integer; /* The integer when type is REDIS_REPLY_INTEGER */
    double dval; /* The double when type is REDIS_REPLY_DOUBLE */
    size_t len; /* Length of string */
    char *str; /* Used for REDIS_REPLY_ERROR, REDIS_REPLY_STRING
                  REDIS_REPLY_VERB, REDIS_REPLY_DOUBLE (in additional to dval),
                  and REDIS_REPLY_BIGNUM. */
    char vtype[4]; /* Used for REDIS_REPLY_VERB, contains the null
                      terminated 3 character content type, such as "txt". */
    size_t elements; /* number of elements, for REDIS_REPLY_ARRAY */
    struct redisReply **element; /* elements vector for REDIS_REPLY_ARRAY */
} redisReply;

redisReply의 type 종류

  • REDIS_REPLY_STRING : 단순 문자열 응답. str, len 사용
  • REDIS_REPLY_ARRAY : 배열 응답. elements, element 사용
  • REDIS_REPLY_INTEGER : 정수 응답 integer 사용
  • REDIS_REPLY_NIL : NULL 응답.
  • REDIS_REPLY_STATUS : 상태 문자열 응답. str사용 (OK, PONG)
  • REDIS_REPLY_ERROR : 에러 응답. str 아용
  • REDIS_REPLY_DOUBLE : 실수 응답. dval, str 사용
  • REDIS_REPLY_BOOL : 불리언 응답. integer 사용
  • REDIS_REPLY_BIGNUM : 큰 정수 응답. str 사용
  • REDIS_REPLY_MAP : 맵 응답.
  • REDIS_REPLY_SET : 셋 응답.
  • REDIS_REPLY_ATTR : 속성 응답
  • REDIS_REPLY_PUSH : push 메시지
  • REDIS_REPLY_VERB : Verbatim string 응답. str, vtype 사용

요청에 따른 응답이 한정되어있기 때문에 매번 확인할 것은 reply == nullptr(연결 오류), type == REDIS_REPLY_ERROR 정도.


보안에 대해

Redis는 신뢰할 수 있는 내부 네트워크 전용으로 설계됐기 때문에 그런 환경에서 사용한다면 보안은 신경쓰지 않아도 된다.

하지만 보안 수단을 추가할 수 있다.

  • 인증/허가 : 비밀번호인증, ACL(Access Control List) - 사용자별 권한 분리
  • 네트워크 접근 제한
     bind - 특정 IP만 listen
    protected-mode - 외부 접근 차단 (기본값 on)
    방화벽/iptables로 특정 IP만 허용
  • 암호화
    TLS - 전송구간 암호화
  • 커맨드 제한
    rename-command - 위험한 커맨드 숨기기/비활성화 (FLUSHALL, CONFIG 등)

'공부 > DB' 카테고리의 다른 글

Redis 기초  (0) 2026.03.08
postgresql libpq C/C++  (0) 2026.03.04
DBCP (DB connection pool)  (0) 2026.02.19
DB Partitioning, Sharding, Replication  (0) 2026.02.19
postgreSQL EXPLAIN ANALYZE  (0) 2026.02.18

+ Recent posts