Work with Strings for Simple Data
In this step, we'll explore how to use Redis to store and retrieve simple string data. Redis is often used as a cache or a simple key-value store, and strings are the most basic data type it offers.
First, let's connect to the Redis server using the redis-cli command-line tool. Open a terminal in the LabEx VM. You should already be in the ~/project directory.
Type the following command to connect to the Redis server:
redis-cli
You should see a prompt that looks like this:
127.0.0.1:6379>
This indicates that you are now connected to the Redis server.
Now, let's set a simple string value. We'll use the SET command. The SET command takes two arguments: the key and the value. Let's set a key called mykey to the value Hello Redis:
SET mykey "Hello Redis"
You should see the following output:
OK
This means that the value has been successfully set.
Now, let's retrieve the value using the GET command. The GET command takes one argument: the key. Let's retrieve the value of mykey:
GET mykey
You should see the following output:
"Hello Redis"
This confirms that we have successfully stored and retrieved a string value in Redis.
Let's try another example. This time, let's store a number as a string.
SET counter 100
GET counter
You should see:
"100"
Redis treats this as a string, even though it represents a number.
You can also use the EXISTS command to check if a key exists.
EXISTS mykey
You should see:
(integer) 1
This indicates that the key mykey exists. If the key does not exist, the command will return (integer) 0.
Finally, let's delete the key using the DEL command.
DEL mykey
You should see:
(integer) 1
This indicates that the key mykey has been successfully deleted.
Now, if you try to get the value of mykey again:
GET mykey
You should see:
(nil)
This confirms that the key has been deleted.
Remember to exit the redis-cli to ensure your commands are logged. Type:
exit
This will return you to the regular terminal prompt.