0
0
RedisHow-ToBeginner · 3 min read

How to Connect to Redis: Simple Steps and Example

To connect to Redis, use the redis-cli command-line tool or a Redis client library in your programming language. The connection requires specifying the host and port, usually localhost and 6379 by default.
📐

Syntax

Connecting to Redis involves specifying the server address and port. The common syntax for the command-line tool is:

  • redis-cli -h <host> -p <port> connects to Redis at the given host and port.
  • If no host or port is given, it defaults to localhost and 6379.

In programming languages, you create a client object with host and port parameters to connect.

bash
redis-cli -h localhost -p 6379
💻

Example

This example shows how to connect to Redis using Python with the redis library. It connects to the default Redis server and sets a key-value pair.

python
import redis

# Connect to Redis server on localhost and default port 6379
client = redis.Redis(host='localhost', port=6379)

# Set a key 'greeting' with value 'Hello, Redis!'
client.set('greeting', 'Hello, Redis!')

# Retrieve and print the value of 'greeting'
value = client.get('greeting')
print(value.decode('utf-8'))
Output
Hello, Redis!
⚠️

Common Pitfalls

Common mistakes when connecting to Redis include:

  • Not running the Redis server before connecting.
  • Using wrong host or port values.
  • Forgetting to decode byte responses in some client libraries.
  • Not handling connection errors properly.

Always ensure the Redis server is running and accessible at the specified host and port.

python
## Wrong way: Trying to connect without server running
# client = redis.Redis(host='localhost', port=6379)
# client.ping()  # This will raise a connection error

## Right way: Check server status before connecting
import redis
try:
    client = redis.Redis(host='localhost', port=6379)
    client.ping()
    print('Connected to Redis successfully')
except redis.exceptions.ConnectionError:
    print('Failed to connect to Redis server')
Output
Connected to Redis successfully
📊

Quick Reference

Here is a quick summary of connection parameters and commands:

ParameterDescriptionDefault
hostRedis server addresslocalhost
portRedis server port number6379
passwordPassword for Redis authenticationnone (optional)
dbDatabase index to select0

Key Takeaways

Use redis-cli or a client library to connect to Redis specifying host and port.
Default Redis connection is at localhost on port 6379.
Ensure the Redis server is running before attempting to connect.
Handle connection errors gracefully in your code.
Decode byte responses when retrieving data from Redis clients.