Redis Connections Tutorial
In this Redis tutorial we learn how to authenticate and manage client connections with the Redis server by using connection commands.
We cover how to authenticate clients, test whether a server is runnig, select a database and finally how to close a server connection.
Here's a table of contents of what you'll learn in this lesson:
(click on a link to skip to its section)
Let's jump right in.
What are Redis Connection Commands
Redis allows us to manage client connections with the Redis server by using connection commands such as AUTH and SELECT .
How to authenticate a client to a Redis server
To authenticate a client to a Redis server, we use the AUTH command with a password.
The server will attempt to match the given password with the one in the configuration file. If it succeeds, the server will reply with an OK status and start accepting commands from the client.
Up until now, we’ve been using Redis without any password configured. If we try to use any type of password, we’ll get an error.
This password doesn’t exist in the configuration file, so Redis returns an error.
(error) ERR AUTH <password> called without any password configured for the default user. Are you sure your configuration is correct?
We can quickly set a password by using the CONFIG SET requirepass command.
CONFIG SET requirepass "mypassword"
Now if we try to authenticate again, the operation will succeed and Redis will respond with an OK status.
If we get the password wrong, Redis will raise a WRONGPASS error.
(error) WRONGPASS invalid username-password pair
And if we don’t enter a password at all, Redis will raise a NOAUTH error.
(error) NOAUTH Authentication required.
How to test whether a Redis server is running
The PING command checks if the server is running or not. If the server is running, Redis will respond with PONG .
We can customize the return message by specifying it as an argument.
PING "Server is running"
Redis will then return that message, instead of PONG , if the server is running.
"Server is running"
How to select a Redis database
We use the SELECT command to select a database with a numeric, zero-based index as the argument.
For example, a new connection will always use the 0 database. If we want to change it, we simply pass the index of the database we want to connect to.
When Redis changes to another database, its index number will be displayed after the port number between square brackets.
This indicates that we’re working in DB 1.
How to close a Redis server connection
We use the QUIT command to ask the server to its connection. The connection will only be closed once all pending replies have been written to the client.
The client will be kicked out of the Redis CLI. If the client connects through a Docker image, it will be kicked out of that as well.
If you’re using the Docker image from the Environment Setup lesson, you can quickly reconnect with the command below.
docker exec -it test-redis redis-cli