In the development and maintenance of Redis, the redis-cli in the bin directory is the most commonly used tool. This section gives a brief description of its usage so that readers can get a brief idea of how to connect to and use Redis with redis-cli.
Connecting to Redis with redis-cli
Getting ready…
You need an up-and-running Redis Server, as we described in the Starting and shutting down Redis recipe in this chapter.
How to do it...
The steps for connecting to Redis using redis-cli down a Redis Server are as follows:
- Open a Terminal and connect to Redis with redis-cli:
$ bin/redis-cli 127.0.0.1:6379>
The pattern of the preceding prompt is IP:port, indicating redis-cli has connected to this Redis instance successfully.
- Send some simple commands for testing. More data types and features will be discussed in the following chapters.
- First, set two string key-value pairs: foo value1, bar value2:
127.0.0.1:6379> set foo value1 OK 127.0.0.1:6379> set bar value2 OK
- After that, fetch the values we just set:
127.0.0.1:6379> get foo "value1" 127.0.0.1:6379> get bar "value2"
- Finally, we terminate the Redis instance by sending the shutdown command:
$ bin/redis-cli 127.0.0.1:6379> shutdown not connected>
- After shutting down, the Command Prompt changed to not connected. Then, we quit from redis-cli and make the connection again with redis-cli. The following error message will be shown:
not connected>quit $ bin/redis-cli Could not connect to Redis at 127.0.0.1:6379: Connection refused Could not connect to Redis at 127.0.0.1:6379: Connection refused not connected>
How it works...
By default, redis-cli connects to a Redis instance running on localhost at default port 6379. You can also specify the hostname/IP address the Redis Server is running on with the -h option. Just make sure that the network connectivity between the redis-cli side and the Redis Server side has no problem.
redis-cli allows you to specify the port with the -p option, if your Redis Server is not running on the default port 6379. This option is also useful if you would like to connect to multiple Redis instances with different binding ports on the same host.
Also, if a Redis instance is protected by password, the -a option can be used to set the password when connecting to Redis.
In addition, if a Unix socket file is enabled in Redis, you can connect to the Redis Server simply by using the -s option.
There's more...
It is often necessary to do some data prototype verification before hooking up your application to Redis. redis-cli is a very useful tool for this. It provides an interactive command-line interface for you to quickly verify your data design. In the daily maintenance of Redis Server, redis-cli also offers a set of commands, including obtaining the metrics, manipulating system states, and performing configuration settings.
See also
- Refer to Chapter 9, Administrating Redis for a more detailed discussion on how to manage a Redis instance with redis-cli