Connecting to a non-sharded Redis cluster
You can connect to a non-sharded Redis cluster:
-
Using Redis Sentinel.
Redis Sentinel is a Redis host management system that provides monitoring, notification, automatic failover, and reporting of up-to-date host addresses to the clients.
Unencrypted connection is supported via port
26379
for clusters with any version of Redis.If a client application does not support connecting via Sentinel, connect directly to the master host. If there is no need for a direct connection, use Sentinel for more reliable cluster host management.
For more information about Sentinel, see Replication and fault tolerance and the Redis documentation
. -
Directly to the master host.
Encrypted connection is supported via port
6380
and unencrypted via port6379
.Warning
When using SSL, you can only connect to clusters with TLS support enabled.
To always connect to the master host in a non-sharded cluster, use a special FQDN that always points to the master host, or track the roles of all the cluster hosts yourself.
Special FQDNs
Managed Service for Redis provides special FQDNs that can be used instead of regular host FQDNs to connect to non-sharded clusters.
Warning
If, when the master host is changed automatically, a host with no public access becomes a new master host, you will not be able to connect to it from the internet. To avoid this, enable public access for all cluster hosts.
Current master
Such FQDN as c-<cluster_ID>.rw.mdb.yandexcloud.net
in a non-sharded cluster always points to the current master host. You can request the cluster ID with a list of clusters in the folder.
When connecting to this FQDN, both read and write operations are allowed.
Here is an example of an SSL-encrypted connection to a master host for a cluster with the c9qash3nb1v9********
ID:
redis-cli -h c-c9qash3nb1v9********.rw.mdb.yandexcloud.net \
-p 6380 \
--tls \
--cacert ~/.redis/YandexInternalRootCA.crt \
-a <Redis_password>
Connecting from graphical IDEs
The connection was tested in the following environment:
- MacOS Big Sur 11.3.
- DBeaver Enterprise:
21.0
.
You can only use graphical IDEs to connect to cluster hosts through an SSL tunnel using a created VM. Before connecting, prepare a certificate.
To avoid connection errors, save the certificate
Connections to Redis clusters are only available in DBeaver business editions
To connect to a cluster:
- Create a new DB connection:
- In the Database menu, select New connection.
- Select Redis from the DB list.
- Click Next.
- Specify the connection parameters on the Main tab:
- Host: FQDN of the master host or a special FQDN always pointing to the current master host.
- Port:
6379
for a regular cluster or6380
for a cluster with SSL encryption enabled. - Under Authentication, specify the cluster password.
- On the SSH tab:
- Enable the Use SSL tunnel setting.
- Specify the SSH tunnel parameters:
- Host/IP: Public IP address of the VM to connect to.
- Username: Username for connecting to the VM.
- Authentication method:
Public key
. - Secret key: Path to the file with the private key used for connecting to the VM.
- Passphrase: Private key password.
- On the SSL tab:
- Enable the Use SSL and Skip hostname validation settings.
- Under Parameters:
- Select Method: Set of certificates.
- In the Root certificate field, specify the path to the saved SSL certificate file.
- Click Test connection ... to test a DB connection. If the connection is successful, you will see the connection status and information about the DBMS and driver.
- Click Ready to save the database connection settings.
Before you connect from a Docker container
To connect to a Managed Service for Redis cluster from a Docker container, add the following lines to the Dockerfile:
# Build the redis-tools utility with TLS support manually.
RUN apt-get update && \
apt-get install make gcc libssl-dev --yes && \
wget https://download.redis.io/redis-stable.tar.gz && \
tar -xzvf redis-stable.tar.gz && \
cd redis-stable && \
make BUILD_TLS=yes MALLOC=libc && \
make install && \
cp ./src/redis-cli /usr/bin/
# Build the redis-tools utility with TLS support manually.
RUN apt-get update && \
apt-get install wget make gcc libssl-dev --yes && \
wget https://download.redis.io/redis-stable.tar.gz && \
tar -xzvf redis-stable.tar.gz && \
cd redis-stable && \
make BUILD_TLS=yes MALLOC=libc && \
make install && \
cp ./src/redis-cli /usr/bin/ && \
# Get an SSL certificate.
mkdir --parents ~/.redis && \
wget "https://storage.yandexcloud.net/cloud-certs/CA.pem" \
--output-document ~/.redis/YandexInternalRootCA.crt && \
chmod 0655 ~/.redis/YandexInternalRootCA.crt
Examples of connection strings
The Linux examples were tested in the following environment:
- Yandex Cloud virtual machine running Ubuntu 20.04 LTS.
- Bash:
5.0.16
. - Python:
3.8.2
; pip3:20.0.2
. - PHP:
7.4.3
. - OpenJDK:
11.0.8
; Maven:3.6.3
. - Node.JS:
10.19.0
, npm:6.14.4
. - Go:
1.13.8
. - Ruby:
2.7.0p0
. - unixODBC:
2.3.6
.
The Windows examples were tested in the following environment:
- A local machine with Windows 10 Pro build
19042.1052
. - PowerShell:
5.1.19041
. - cURL:
7.55.1 WinSSL
.
To see code examples with the host FQDN filled in, open the cluster page in the management console
Bash
Before connecting, install the dependencies:
sudo apt update && sudo apt install -y redis-tools
Connecting via Sentinel:
-
Get the address of the master host by using Sentinel and any Redis host:
redis-cli \ -h <FQDN_of_any_Redis_host> \ -p 26379 \ sentinel \ get-master-addr-by-name <Redis_cluster_name> | head -n 1
-
Connect to the host with this address:
redis-cli \ -h <Redis_master_host_address> \ -a <Redis_password>
Connecting directly to the master host:
redis-cli \
-h c-<cluster_ID>.rw.mdb.yandexcloud.net \
-a <password>
Before connecting, install the dependencies:
Build the redis-tools
utility with TLS support in one of two ways:
-
From a repository
-
Connect a repository:
sudo apt-add-repository ppa:redislabs/redis
Packages in this repository have already been built with the
BUILD_TLS=yes
flag. -
Install the utility:
sudo apt update && sudo apt install -y redis-tools
-
-
Manually
Go to the directory you want to download the distribution to. Download the stable version of the utility, then build and install it:
wget https://download.redis.io/redis-stable.tar.gz && \ tar -xzvf redis-stable.tar.gz && \ cd redis-stable && \ make BUILD_TLS=yes && \ sudo make install && \ sudo cp ./src/redis-cli /usr/bin/
Connecting directly to the master host:
redis-cli \
-h c-<cluster_ID>.rw.mdb.yandexcloud.net \
-a <password> \
-p 6380 \
--tls \
--cacert ~/.redis/YandexInternalRootCA.crt
To learn how to get a host FQDN, see this guide.
When you are connected to the cluster, run the commands:
SET foo bar
GET foo
If the connection to the cluster and the test query are successful, the bar
string is output.
Go
Before connecting, install the dependencies:
sudo apt update && sudo apt install -y golang git && \
go mod init github.com/go-redis/redis && \
go get github.com/go-redis/redis/v7
Code example for connecting through Sentinel:
connect.go
package main
import (
"fmt"
"github.com/go-redis/redis/v7"
)
func main() {
conn := redis.NewUniversalClient(
&redis.UniversalOptions{
Addrs: []string{
"<Redis_host_1_FQDN>:26379",
...
"<Redis_host_N_FQDN>:26379"},
MasterName: "<Redis_cluster_name>",
Password: "<password>",
ReadOnly: false,
},
)
err := conn.Set("foo", "bar", 0).Err()
if err != nil {
panic(err)
}
result, err := conn.Get("foo").Result()
if err != nil {
panic(err)
}
fmt.Println(result)
conn.Close()
}
Code example for connecting directly to the master:
connect.go
package main
import (
"fmt"
"github.com/go-redis/redis/v7"
)
func main() {
conn := redis.NewUniversalClient(
&redis.UniversalOptions{
Addrs: []string{"c-<cluster_ID>.rw.mdb.yandexcloud.net:6379"},
Password: "<password>",
ReadOnly: false,
},
)
err := conn.Set("foo", "bar", 0).Err()
if err != nil {
panic(err)
}
result, err := conn.Get("foo").Result()
if err != nil {
panic(err)
}
fmt.Println(result)
conn.Close()
}
connect.go
package main
import (
"crypto/tls"
"crypto/x509"
"fmt"
"github.com/go-redis/redis/v7"
"io/ioutil"
)
const (
cert = "/home/<home_directory>/.redis/YandexInternalRootCA.crt"
)
func main() {
rootCertPool := x509.NewCertPool()
pem, err := ioutil.ReadFile(cert)
if err != nil {
panic(err)
}
if ok := rootCertPool.AppendCertsFromPEM(pem); !ok {
panic("Failed to append PEM.")
}
conn := redis.NewUniversalClient(
&redis.UniversalOptions{
Addrs: []string{"c-<cluster_ID>.rw.mdb.yandexcloud.net:6380"},
Password: "<password>",
ReadOnly: false,
TLSConfig: &tls.Config{
RootCAs: rootCertPool,
},
},
)
err = conn.Set("foo", "bar", 0).Err()
if err != nil {
panic(err)
}
result, err := conn.Get("foo").Result()
if err != nil {
panic(err)
}
fmt.Println(result)
conn.Close()
}
To learn how to get a host FQDN, see this guide.
Connecting:
go run connect.go
If the connection to the cluster and the test query are successful, the bar
string is output.
Java
Before connecting:
-
Install the dependencies:
sudo apt update && sudo apt install --yes default-jdk maven
-
Create a folder for the Maven project:
cd ~/ && mkdir --parents project/src/java/com/example && cd project/
-
Create a configuration file for Maven:
pom.xml
<?xml version="1.0" encoding="utf-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.example</groupId> <artifactId>app</artifactId> <packaging>jar</packaging> <version>0.1.0</version> <properties> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> </properties> <dependencies> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>3.7.0</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-simple</artifactId> <version>1.7.30</version> </dependency> </dependencies> <build> <finalName>${project.artifactId}-${project.version}</finalName> <sourceDirectory>src</sourceDirectory> <resources> <resource> <directory>src</directory> </resource> </resources> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-assembly-plugin</artifactId> <executions> <execution> <goals> <goal>attached</goal> </goals> <phase>package</phase> <configuration> <descriptorRefs> <descriptorRef> jar-with-dependencies</descriptorRef> </descriptorRefs> <archive> <manifest> <mainClass>com.example.App</mainClass> </manifest> </archive> </configuration> </execution> </executions> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jar-plugin</artifactId> <version>3.1.0</version> <configuration> <archive> <manifest> <mainClass>com.example.App</mainClass> </manifest> </archive> </configuration> </plugin> </plugins> </build> </project>
Up-to-date versions of dependencies for Maven:
-
To connect using SSL:
-
Create secure storage for certificates:
keytool -importcert \ -alias YARootCrt \ -file ~/.redis/YandexInternalRootCA.crt \ -keystore ~/.redis/YATrustStore \ -storepass <password_of_secure_certificate_storage> \ --noprompt && chmod 0655 ~/.redis/YATrustStore
Code example for connecting through Sentinel:
src/java/com/example/App.java
package com.example;
import java.util.HashSet;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisSentinelPool;
public class App {
public static void main(String[] args) {
String redisName = "<Redis_cluster_name>";
String redisPass = "<password>";
HashSet sentinels = new HashSet();
sentinels.add("<Redis_host_1_FQDN>:26379");
...
sentinels.add("<Redis_host_N_FQDN>:26379");
try {
JedisSentinelPool pool = new JedisSentinelPool(redisName, sentinels);
Jedis conn = pool.getResource();
conn.auth(redisPass);
conn.set("foo", "bar");
System.out.println(conn.get("foo"));
pool.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
Code example for connecting directly to the master:
src/java/com/example/App.java
package com.example;
import redis.clients.jedis.Jedis;
public class App {
public static void main(String[] args) {
String redisHost = "c-<cluster_ID>.rw.mdb.yandexcloud.net";
String redisPass = "<password>";
try {
Jedis conn = new Jedis(redisHost);
conn.auth(redisPass);
conn.set("foo", "bar");
System.out.println(conn.get("foo"));
conn.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
src/java/com/example/App.java
package com.example;
import redis.clients.jedis.DefaultJedisClientConfig;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.Jedis;
import javax.net.ssl.SSLParameters;
public class App {
public static void main(String[] args) {
String redisHost = "c-<cluster_ID>.rw.mdb.yandexcloud.net";
String redisPass = "<cluster_password>";
System.setProperty("javax.net.ssl.trustStore", "/home/<home_directory>/.redis/YATrustStore");
System.setProperty("javax.net.ssl.trustStorePassword", "<secure_certificate_storage_password>");
SSLParameters sslParameters = new SSLParameters();
DefaultJedisClientConfig jedisClientConfig = DefaultJedisClientConfig.builder().
password(redisPass).
ssl(true).
sslParameters(sslParameters).
build();
try {
Jedis conn = new Jedis(new HostAndPort(redisHost, 6380), jedisClientConfig);
conn.set("foo", "bar");
System.out.println(conn.get("foo"));
conn.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
To learn how to get a host FQDN, see this guide.
Connecting:
mvn clean package && \
java -jar target/app-0.1.0-jar-with-dependencies.jar
If the connection to the cluster and the test query are successful, the bar
string is output.
Node.js
Before connecting, install the dependencies:
sudo apt update && sudo apt install -y nodejs npm && \
npm install ioredis
Code example for connecting through Sentinel:
app.js
"use strict";
const Redis = require("ioredis");
const conn = new Redis({
sentinels: [
{ host: "<Redis_host_1_FQDN>", port: 26379 },
...
{ host: "<Redis_host_N_FQDN>", port: 26379 },
],
name: "<Redis_cluster_name>",
password: "<password>"
});
conn.set("foo", "bar", function (err) {
if (err) {
console.error(err);
conn.disconnect();
}
});
conn.get("foo", function (err, result) {
if (err) {
console.error(err);
} else {
console.log(result);
}
conn.disconnect();
});
Code example for connecting directly to the master:
app.js
"use strict";
const Redis = require("ioredis");
const conn = new Redis({
host: "c-<cluster_ID>.rw.mdb.yandexcloud.net",
port: 6379,
password: "<password>"
});
conn.set("foo", "bar", function (err) {
if (err) {
console.error(err);
conn.disconnect();
}
});
conn.get("foo", function (err, result) {
if (err) {
console.error(err);
} else {
console.log(result);
}
conn.disconnect();
});
app.js
"use strict";
const fs = require("fs");
const Redis = require("ioredis");
const conn = new Redis({
host: "c-<cluster_ID>.rw.mdb.yandexcloud.net",
port: 6380,
password: "<password>",
tls: {
ca: fs.readFileSync("/home/<home_directory>/.redis/YandexInternalRootCA.crt"),
}
});
conn.set("foo", "bar", function (err) {
if (err) {
console.error(err);
conn.disconnect();
}
});
conn.get("foo", function (err, result) {
if (err) {
console.error(err);
} else {
console.log(result);
}
conn.disconnect();
});
To learn how to get a host FQDN, see this guide.
Connecting:
node app.js
If the connection to the cluster and the test query are successful, the bar
string is output.
PHP
Before connecting, install the dependencies:
sudo apt update && sudo apt install -y php php-dev php-pear && \
sudo pear channel-discover pear.nrk.io && \
sudo pear install nrk/Predis
Code example for connecting through Sentinel:
connect.php
<?php
require "Predis/Autoloader.php";
Predis\Autoloader::register();
$sentinels = [
"<Redis_host_1_FQDN>:26379>",
...
"<Redis_host_N_FQDN>:26379>",
];
$options = [
"replication" => "sentinel",
"service" => "<Redis_cluster_name>",
"parameters" => [
"password" => "<password>",
],
];
$conn = new Predis\Client($sentinels, $options);
$conn->set("foo", "bar");
var_dump($conn->get("foo"));
$conn->disconnect();
?>
Code example for connecting directly to the master:
connect.php
<?php
require "Predis/Autoloader.php";
Predis\Autoloader::register();
$host = ["c-<cluster_ID>.rw.mdb.yandexcloud.net:6379"];
$options = [
"parameters" => [
"password" => "<password>",
],
];
$conn = new Predis\Client($host, $options);
$conn->set("foo", "bar");
var_dump($conn->get("foo"));
$conn->disconnect();
?>
connect.php
<?php
require "Predis/Autoloader.php";
Predis\Autoloader::register();
$host = ["c-<cluster_ID>.rw.mdb.yandexcloud.net:6380"];
$options = [
"parameters" => [
"scheme" => "tls",
"ssl" => [
"cafile" => "/home/<home_directory>/.redis/YandexInternalRootCA.crt",
"verify_peer" => true,
"verify_peer_name" => false,
],
"password" => "<password>",
],
];
$conn = new Predis\Client($host, $options);
$conn->set("foo", "bar");
var_dump($conn->get("foo"));
$conn->disconnect();
?>
To learn how to get a host FQDN, see this guide.
Connecting:
php connect.php
If the connection to the cluster and the test query are successful, the bar
string is output.
Python
Before connecting, install the dependencies:
sudo apt update && sudo apt install -y python3 python3-pip && \
pip3 install redis
Code example for connecting through Sentinel:
connect.py
from redis.sentinel import Sentinel
sentinels = [
"<Redis_host_1_FQDN>",
...
"<Redis_host_N_FQDN>"
]
name = "<Redis_cluster_name>"
pwd = "<password>"
sentinel = Sentinel([(h, 26379) for h in sentinels], socket_timeout=0.1)
master = sentinel.master_for(name, password=pwd)
slave = sentinel.slave_for(name, password=pwd)
master.set("foo", "bar")
print(slave.get("foo"))
Sample code for connecting without an SSL connection directly to the master host:
connect.py
import redis
r = redis.StrictRedis(
host="c-<cluster_ID>.rw.mdb.yandexcloud.net",
port=6379,
password="<password>",
)
r.set("foo", "bar")
print(r.get("foo"))
connect.py
import redis
r = redis.StrictRedis(
host="c-<cluster_ID>.rw.mdb.yandexcloud.net",
port=6380,
password="<password>",
ssl=True,
ssl_ca_certs="/home/<home_directory>/.redis/YandexInternalRootCA.crt",
)
r.set("foo", "bar")
print(r.get("foo"))
To learn how to get a host FQDN, see this guide.
Connecting:
python3 connect.py
If the connection to the cluster and the test query are successful, the bar
string is output.
Ruby
Before connecting, install the dependencies:
sudo apt update && sudo apt install -y ruby && \
sudo gem install redis
Code example for connecting through Sentinel:
connect.rb
# coding: utf-8
require 'redis'
SENTINELS = [
{ host: '<Redis_host_1_FQDN>', port: 26379 },
...
{ host: '<Redis_host_N_FQDN>', port: 26379 }
]
conn = Redis.new(
host: '<Redis_cluster_name>',
sentinels: SENTINELS,
role: 'master',
password: '<password>'
)
conn.set('foo', 'bar')
puts conn.get('foo')
conn.close
Sample code for connecting without an SSL connection directly to the master host:
connect.rb
# coding: utf-8
require 'redis'
conn = Redis.new(
host: 'c-<cluster_ID>.rw.mdb.yandexcloud.net',
port: 6379,
password: '<password>'
)
conn.set('foo', 'bar')
puts conn.get('foo')
conn.close
connect.rb
# coding: utf-8
require 'redis'
conn = Redis.new(
host: 'c-<cluster_ID>.rw.mdb.yandexcloud.net',
port: 6380,
password: '<password>',
ssl: true,
ssl_params: { ca_file: '/home/<home_directory>/.redis/YandexInternalRootCA.crt' },
)
conn.set('foo', 'bar')
puts conn.get('foo')
conn.close
To learn how to get a host FQDN, see this guide.
Connecting:
ruby connect.rb
If the connection to the cluster and the test query are successful, the bar
string is output.