[add a subtitle] Redis Strings Explained

GARIMOO
garimoo
Published in
14 min readApr 26, 2020

Redis University 영상에 자막달기

https://youtu.be/n0LQREq4GrY

Hello, today we’re going to explore the string, the most basic and common Redis data type.

안녕하세요, 오늘은 레디스의 가장 기본적인 데이터 타입인 스트링에 대해서 알아보겠습니다.

We’ll see just how powerful this little guy can be.

이 작은 친구가 얼마나 강력한지 함께 배워봅시다.

Redis strings are binary safe sequences of bytes.

레디스 스트링은 binary-safe한 바이트의 연속입니다.

And they’re a lot like the strings you use in your favorite programming languages.

또한 당신이 가장 좋아하는 프로그래밍 언어에서의 문자열과 상당히 비슷합니다.

You can store anything you can imagine in a Redis String.

당신이 레디스 스트링에 저장할 수 있다고 생각하는 모든 것을 저장할 수 있습니다.

Integers, binary values, comma-separated values, serialized JSON, and since they’re binary safe, you can even store larger objects, such as images, videos, documents, and sounds.

정수, 바이너리 값, 콤마로 나뉘어진 값들, 직렬화된 JSON 등을 저장할 수 있으며, 레디스 스트링은 바이너리-세이프 하기 때문에 이미지, 비디오, 문서, 소리 등 큰 오브젝트 또한 저장할 수 있습니다.

So what are some practical uses for Redis Strings?

그럼 레디스 스트링을 실제로 어디에 사용할까요?

The most common use is for caching.

가장 일반적으로 사용되는 곳은 캐시입니다.

API responses, session storage, HTML pages, the opportunities are vast.

API 응답값, 세션 저장소, HTML 페이지 등 다양한 곳에서 사용할 수 있습니다.

Redis strings are also great for implementing counts.

레디스 스트링은 카운터를 구현하는 데에도 좋습니다.

As there is built-in support for incrementing and decrementing integer and floating-point values.

정수와 소수값을 증가-감소시킬 수 있는 내장 함수가 존재하기 때문입니다.

Today we’re going to go over a couple of examples using the Redis String.

오늘 우리는 레디스 스트링을 사용한 몇 가지 예제들을 알아볼 것입니다.

First, we’ll cover how to store and retrieve a string.

첫 번째, 레디스 스트링에 어떻게 데이터를 저장하고 반환하는지 알아보겠습니다.

Second, we’ll examine a use case of storing JSON objects as strings, and how to set an expiration time until it’s deletion.

두 번째로, JSON 객체를 문자열로 저장하는 방법과, 삭제를 위한 만료시간을 설정하는 법에 대해 살펴보겠습니다.

We’ll also discuss the implications of storing JSON as a string and a couple of alternatives within Redis.

또한 JSON을 스트링으로 저장한 결과와, 레디스에서의 몇가지 대체 방법에 대해도 논의해보겠습니다.

Lastly, we’ll learn how to increment and decrement an integer value within a Redis String.

마지막으로 우리는 레디스 스트링에 정수 값을 저장하여 어떻게 증감시킬 수 있는지에 대해 배우겠습니다.

To create a string of Redis, we’ll use the SET command.

레디스 스트링을 만들기 위해서는 SET 커맨드를 사용할 수 있습니다.

After the SET keyword, you specify the key followed by the value you want to associate with it.

SET 키워드 뒤에는 특정 키와 저장할 값을 저장합니다.

For example, let’s create a time zone entry for users of an application that we’re building.

예를 들어, 어플리케이션을 사용하는 유저의 타임존을 저장할 엔트리를 만들어봅시다.

I’ll use user:101:time-zone as a key and UTC-8 as the value.

user:101:time-zone를 키로 잡고, UTC-8을 값으로 저장하겠습니다.

Redis returns OK, which means that the timezone string was successfully stored a key user:101:time-zone.

레디스는 OK를 반환하고, 이는 이 타임존 값이 user:101:time-zone 키에 성공적으로 저장되었음을 의미합니다.

To retrieve a Redis String, you use the GET command followed by the key you want to retrieve.

레디스 스트링 값을 검색하기 위해서는 GET 커맨드 뒤에 찾고자 하는 키를 입력합니다.

Let’s now get the user’s time zone.

이제 유저의 타임존을 가져와봅시다.

Redis returns the value of the KEY as a string.

레디스는 키의 값을 스트링으로 반환합니다.

Let’s consider an example use of strings.

이제 스트링의 사용 예시에 대해 알아봅시다.

Imagine you want to provide your user with site usage data.

사용자에게 사이트 사용에 대한 데이터를 제공한다고 상상해봅시다.

Normally you’d send the request to a data warehouse which might take several seconds to complete.

일반적으로 이 요청을 데이터 웨어하우스에 보낼 경우 완료될 때까지는 몇 초의 시간이 걸립니다.

You can cache this JSON response after initially fetching it as these responses don’t change often here.

이런 JSON 응답값은 자주 변경되지 않으므로 처음 가져온 뒤 이 값을 캐시에 저장할 수 있습니다.

We have a sample JSON response containing a user’s recent site usage requests.

여기 사용자의 최근 사이트 사용 요청값을 포함한 샘플 JSON 응답값이 있습니다.

Instead of accessing our data warehouses for this information on subsequent requests, we can cache this response as a string within Redis.

다음번 같은 요청이 올 때 이 정보를 얻기 위해 데이터 웨어하우스에 액세스하는 대신 이 응답을 캐시된 레디스 스트링에서 찾을 수 있습니다.

Let’s assign this information to the key usage:63

이 값을 키 usage:63에 할당해봅시다.

When caching data, it’s common to set an expiry time.

데이터를 캐시할 때 만료시간을 저장하는 것이 일반적입니다.

Here we’ll do that by adding the ex option to our set command followed by a number of seconds.

여기서는 set 명령에 뒤에 ex 커맨드를 추가하고, 뒤에 초를 의미하는 숫자값을 추가했습니다.

ex specifies a time in seconds after which Redis will expire and delete the key and its associated string value.

ex는 몇 초 뒤에 이 키와 할당된 스트링 값이 만료되어 삭제되는지를 지정하는 커맨드입니다.

So, this registering will now expire in 7200 seconds or two hours.

여기에서는 이 키가 7200초, 즉 2시간 후에 만료됨을 의미합니다.

By using Redis as a cache, subsequent responses that might have taken several seconds to fetch from the data warehouses will instead be served instantly.

데이터 웨어하우스에서는 몇 초의 시간이 걸리는 응답도 레디스를 캐시로 사용한다면 즉시 반환됩니다.

We can check on the remaining time to live for a key by using the TTL command.

키의 남은 시간을 확인하려면 TTL 커맨드를 사용합니다.

TTL returns the number of seconds remaining before the key expires.

TTL은 키가 만료되기까지의 남은 시간을 반환합니다.

Now, expiry is a complex enough topic to warn in its own video segment.

키의 만료시간에 대한 주제는 따로 영상을 제작할 만큼 매우 복잡하고 중요합니다.

So check back soon for a dedicated video.

다음 비디오에서 설명할 예정이니 기다려주시기 바랍니다.

Lastly, let’s check out the abilities of the Redis string in regards to integer manipulation.

마지막으로, 정수 값을 조작하는 레디스 스트링의 기능을 확인해봅시다.

With the INCR & INCRBY commands, you can increment a keys value by one or by a specified number.

INCR, INCRBY 커맨드를 사용하면 키 값을 1 또는 지정된 값만큼 증가시킬 수 있습니다.

You can also use a negative number, which will decrement the value.

음수값을 사용할 수 있기 때문에 값을 감소시키는것 또한 가능합니다.

There is no key already present, the INCR and INCRBY commands will create a new string and increment its value appropriately.

미리 지정된 키가 없을 때 INCR, INCRBY 커맨드는 새로운 스트링을 만들고 이 값을 적절하게 조절합니다.

See how they work, let’s run the INCR command with a key it doesn’t exist yet.

어떻게 동작하는지 알아보기 위해서, 존재하지 않는 키에 대해서 INCR 커맨드를 실행시켜보겠습니다.

Since the key user:23:visit-count doesn’t exist yet, the INCR command simply creates a new key and string with a value of 1.

user:23:visit-count 이라는 키가 존재하지 않기 때문에, INCR 커맨드는 새로운 키를 만들고 이 키 값을 1로 설정합니다.

This is the Redis way.

이것이 레디스가 동작하는 방식입니다.

If a data structure doesn’t exist, then it’ll be creating the moment you write to it.

해당되는 데이터 구조가 존재하지 않을 때 커맨드를 실행하면 데이터가 입력되면서 새로운 값을 생성합니다.

Now let’s take a quick look at the incrby commands.

이제 INCRBY 커맨드도 빨리 알아봅시다.

INCRBY increment the value of a given key by the specified number we provide in the command line.

INCRBY는 주어진 키 값을 지정된 숫자만큼 증가시킵니다.

Let’s say we have a key user:23:credit-balance with the value 40.

user:23:credit-balance 라는 키의 값이 40이라고 생각해봅시다.

Let’s increase the value to 70 with command incrby user:23:credit-balance 30.

이 값을 INCRYBY user:23:credit-balance 30 이라는 커맨드를 이용해서 70으로 증가시켜봅시다.

Finally let’s reflect the usage of the available credits for this user by running incrby with the negative number.

이제 INCRYBY와 음수를 함께 사용해서 사용가능한 크레딧을 나타내봅시다.

Let’s see our user consumes 50 credits.

이 유저가 50크레딧을 사용했다고 생각해봅시다.

The command would be incrby user:23:credit-balance -50.

커맨드는 INCRBY user:23:credit-balance -50 이 될 수 있습니다.

Now the user is 20 credits left.

이제 20의 크레딧만이 남았네요.

Okay, let’s do a quick review of what we just covered for Redis Strings.

좋아요, 이제 우리가 공부한 레디스 스트링에 대해 빠르게 리뷰해봅시다.

Strings are the fundamental Redis Data type, and you can use them to store plain old strings, numerical values, serialized JSON, and anything that can be represented in binary.

스트링은 가장 기본적인 레디스의 데이터 타입입니다.

기본적인 문자열, 숫자값, 직렬화된 JSON을 포함해 바이너리로 나타낼 수 있는 모든 값을 저장할 수 있습니다.

Strings combined with key expiry are your first go-to data structure for caching.

스트링 타입을 캐시로 활용하기 위해서는 만료 시간을 추가하는 것이 일반적입니다.

Finally you can also use Redis Strings to store and manipulate numerical values.

또한 숫자를 저장하고 조작하기 위해서도 레디스의 스트링을 이용할 수 있습니다.

To learn more Redis Strings, check our free online course introduction to Redis data structures.

레디스의 스트링에 대해서 더 알고 싶다면, 레디스의 데이터구조에 대해 소개하는 우리의 무료 강의를 들어보세요.

As part of Redis University, our online learning platform for all things Redis.

레디스에 대한 모든 온라인 교육을 제공하는 플랫폼인 RedisUniversity에서 확인할 수 있습니다.

Thanks for joining me in this quick dive into Redis strings.

레디스 스트링에 대한 수업을 들어주셔서 감사합니다.

Hope to see you again and happy learning.

즐거운 배움이 되길 바라며, 다음에 또 만나기를 바라겠습니다.

--

--