[Yandex Cloud documentation](../../../index.md) > [Yandex Managed Service for Valkey™](../../index.md) > [Step-by-step guides](../index.md) > [Connection](index.md) > Code examples > Connection examples for non-sharded clusters

# Code examples for connecting to a non-sharded Valkey™ cluster

## C# {#csharp}

**Before connecting:**

1. Install the dependencies:

   ```bash
   sudo apt update && sudo apt install --yes apt-transport-https dotnet-sdk-6.0
   ```

1. Create a directory for the project:

    ```bash
    cd ~/ && mkdir cs-project && cd cs-project
    ```

1. Create a configuration file:

    {% cut "RedisClient.csproj" %}

    ```xml
    <Project Sdk="Microsoft.NET.Sdk">
      <PropertyGroup>
        <OutputType>Exe</OutputType>
        <TargetFramework>net6.0</TargetFramework>
      </PropertyGroup>
      <ItemGroup>
        <PackageReference Include="StackExchange.Redis" Version="2.8.58" />
      </ItemGroup>
    </Project>
    ```

    {% endcut %}

1. To connect with SSL, [get an SSL certificate](index.md#get-ssl-cert).

{% list tabs group=connection %}

- Connecting without SSL {#without-ssl}

    **Code example for connecting via Sentinel:**

    `Program.cs`

    ```csharp
    using System;
    using System.Threading.Tasks;
    using StackExchange.Redis;

    namespace RedisClient
    {
        class Program
        {
            // Configuration constants
            private const string TEST_KEY = "test-key";
            private const string TEST_VALUE = "test-value";
            private const string USERNAME = "default";
            private const string PASSWORD = "<password>";

            static async Task<int> Main(string[] args)
            {
                try
                {
                    var sentinelOptions = new ConfigurationOptions
                    {
                        EndPoints = {
                            "<Valkey™_host_1_FQDN>:26379",
                            ...
                            "<Valkey™_host_N_FQDN>:26379"
                        },
                        CommandMap = CommandMap.Sentinel
                    };

                    var sentinelConnection = await ConnectionMultiplexer.ConnectAsync(sentinelOptions);

                    var endpoints = sentinelConnection.GetEndPoints();
                    var sentinelServer = sentinelConnection.GetServer(endpoints[0]);
                    var masterEndpoint = await sentinelServer.SentinelGetMasterAddressByNameAsync("mymaster");
                    await sentinelConnection.CloseAsync();

                    var masterOptions = new ConfigurationOptions
                    {
                        EndPoints = { masterEndpoint },
                        User = USERNAME,
                        Password = PASSWORD,
                        Ssl = false
                    };

                    var connection = await ConnectionMultiplexer.ConnectAsync(masterOptions);

                    var db = connection.GetDatabase();

                    bool setResult = await db.StringSetAsync(TEST_KEY, TEST_VALUE);
                    if (!setResult)
                    {
                        Console.WriteLine($"SET failed for key {TEST_KEY}");
                        return 1;
                    }
                    Console.WriteLine($"Successfully set {TEST_KEY} = {TEST_VALUE}");

                    var getResult = await db.StringGetAsync(TEST_KEY);
                    if (!getResult.HasValue)
                    {
                        Console.WriteLine($"GET failed: Key {TEST_KEY} not found");
                        return 1;
                    }

                    string retrievedValue = getResult.ToString();
                    if (retrievedValue != TEST_VALUE)
                    {
                        Console.WriteLine($"GET failed. Expected: '{TEST_VALUE}' Actual: '{retrievedValue}'");
                        return 1;
                    }
                    Console.WriteLine($"Successfully retrieved {TEST_KEY} = {retrievedValue}");

                    return 0;
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Operation failed: {ex.Message}");
                    return 1;
                }
            }
        }
    }
    ```

    **Code example for connecting directly to the master:**

    `Program.cs`

    ```csharp
    using System;
    using System.Threading.Tasks;
    using StackExchange.Redis;

    namespace RedisClient
    {
        class Program
        {
            // Configuration constants
            private const string TEST_KEY = "test-key";
            private const string TEST_VALUE = "test-value";
            private const string USERNAME = "default";
            private const string PASSWORD = "<password>";

            static async Task<int> Main(string[] args)
            {
                try
                {
                    var masterOptions = new ConfigurationOptions
                    {
                        EndPoints = { "<Valkey™_master_host_FQDN>:6379" },
                        User = USERNAME,
                        Password = PASSWORD
                    };

                    var connection = await ConnectionMultiplexer.ConnectAsync(masterOptions);

                    var db = connection.GetDatabase();

                    bool setResult = await db.StringSetAsync(TEST_KEY, TEST_VALUE);
                    if (!setResult)
                    {
                        Console.WriteLine($"SET failed for key {TEST_KEY}");
                        return 1;
                    }
                    Console.WriteLine($"Successfully set {TEST_KEY} = {TEST_VALUE}");

                    var getResult = await db.StringGetAsync(TEST_KEY);
                    if (!getResult.HasValue)
                    {
                        Console.WriteLine($"GET failed: Key {TEST_KEY} not found");
                        return 1;
                    }

                    string retrievedValue = getResult.ToString();
                    if (retrievedValue != TEST_VALUE)
                    {
                        Console.WriteLine($"GET failed. Expected: '{TEST_VALUE}' Actual: '{retrievedValue}'");
                        return 1;
                    }
                    Console.WriteLine($"Successfully retrieved {TEST_KEY} = {retrievedValue}");

                    return 0;
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Operation failed: {ex.Message}");
                    return 1;
                }
            }
        }
    }
    ```

- Connecting with SSL {#with-ssl}

    `Program.cs`

    ```csharp
    using System;
    using System.Threading.Tasks;
    using System.Net.Security;
    using System.Security.Authentication;
    using System.Security.Cryptography.X509Certificates;
    using StackExchange.Redis;

    namespace RedisClient
    {
        class Program
        {
            // Configuration constants
            private const string TEST_KEY = "test-key";
            private const string TEST_VALUE = "test-value";
            private const string USERNAME = "default";
            private const string PASSWORD = "<password>";
            private const string CERT = "/home/<home_directory>/.redis/YandexInternalRootCA.crt"

            static async Task<int> Main(string[] args)
            {
                try
                {
                    var masterOptions = new ConfigurationOptions
                    {
                        EndPoints = { "<Valkey™_master_host_FQDN>:6380" },
                        User = USERNAME,
                        Password = PASSWORD,
                        Ssl = true,
                        SslProtocols = SslProtocols.Tls12 | SslProtocols.Tls13
                    };
                    masterOptions.CertificateValidation += (
                        object sender,
                        X509Certificate? certificate,
                        X509Chain? chain,
                        SslPolicyErrors sslPolicyErrors) =>
                    {
                        if (certificate == null) {
                            return false;       
                        }
                        var ca = new X509Certificate2(CERT);
                        bool verdict = (certificate.Issuer == ca.Subject);
                        if (verdict) {
                            return true;
                        }
                        Console.WriteLine("Certificate error: {0}", sslPolicyErrors);
                        return false;
                    }

                    var connection = await ConnectionMultiplexer.ConnectAsync(masterOptions);

                    var db = connection.GetDatabase();

                    // Send SET command
                    bool setResult = await db.StringSetAsync(TEST_KEY, TEST_VALUE);
                    if (!setResult)
                    {
                        Console.WriteLine($"SET failed for key {TEST_KEY}");
                        return 1;
                    }
                    Console.WriteLine($"Successfully set {TEST_KEY} = {TEST_VALUE}");

                    // Send GET command
                    var getResult = await db.StringGetAsync(TEST_KEY);
                    if (!getResult.HasValue)
                    {
                        Console.WriteLine($"GET failed: Key {TEST_KEY} not found");
                        return 1;
                    }

                    string retrievedValue = getResult.ToString();
                    if (retrievedValue != TEST_VALUE)
                    {
                        Console.WriteLine($"GET failed. Expected: '{TEST_VALUE}', Actual: '{retrievedValue}'");
                        return 1;
                    }
                    Console.WriteLine($"Successfully retrieved {TEST_KEY} = {retrievedValue}");

                    return 0;
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Operation failed: {ex.Message}");
                    return 1;
                }
            }
        }    
    }
    ```

{% endlist %}

To learn how to get a host FQDN, see [this guide](fqdn.md).

**Connecting:**

```bash
cd ~/cs-project && \
dotnet build && dotnet run bin/Debug/net6.0/RedisClient
```

If your cluster connection and test command are successful, the output will contain the following strings:

```text
Successfully set test-key = test-value
Successfully retrieved test-key = test-value
```

## Go {#go}

**Before connecting, install the required dependencies:**

```bash
sudo apt update && sudo apt install --yes golang git && \
go mod init github.com/go-redis/redis && \
go get github.com/go-redis/redis/v7
```

{% list tabs group=connection %}

- Connecting without SSL {#without-ssl}

    **Code example for connecting through Sentinel:**

    `connect.go`

    ```go
    package main

    import (
    	"fmt"
    	"github.com/go-redis/redis/v7"
    )

    func main() {
    	conn := redis.NewUniversalClient(
    		&redis.UniversalOptions{
    			Addrs: []string{
    				"<Valkey™_host_1_FQDN>:26379",
    				...
    				"<Valkey™_host_N_FQDN>:26379"},
    			MasterName: "<Valkey™_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`

    ```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()
    }
    ```

- Connecting with SSL {#with-ssl}

    `connect.go`

    ```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()
    }
    ```

{% endlist %}

To learn how to get a host FQDN, see [this guide](fqdn.md).

**Connecting:**

```bash
go run connect.go
```

If your cluster connection and test command are successful, you will see the `bar` string in the output.

## Java {#java}

**Before connecting:**

1. Install the dependencies:

    ```bash
    sudo apt update && sudo apt install --yes default-jdk maven
    ```

1. Create a directory for the Maven project:

    ```bash
    cd ~/ && mkdir --parents project/src/java/com/example && cd project/
    ```

1. Create a configuration file for Maven:

    {% cut "pom.xml" %}

    ```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>
    ```

    {% endcut %}

    Current versions of Maven dependencies:

    * [jedis](https://mvnrepository.com/artifact/redis.clients/jedis)
    * [slf4j-simple](https://mvnrepository.com/artifact/org.slf4j/slf4j-simple)

1. To connect with SSL:

    1. [Get an SSL certificate](index.md#get-ssl-cert).
    1. Create a secure certificate store:

        ```bash
        keytool -importcert \
                -alias YARootCrt \
                -file ~/.redis/YandexInternalRootCA.crt \
                -keystore ~/.redis/YATrustStore \
                -storepass <secure_store_password> \
                --noprompt && chmod 0655 ~/.redis/YATrustStore
        ```

{% list tabs group=connection %}

- Connecting without SSL {#without-ssl}

    **Code example for connecting via Sentinel:**

    `src/java/com/example/App.java`

    ```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 = "<Valkey™_cluster_name>";
        String redisPass = "<password>";

        HashSet sentinels = new HashSet();
        sentinels.add("<Valkey™_host_1_FQDN>:26379");
        ...
        sentinels.add("<Valkey™_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`

    ```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();
        }
      }
    }
    ```

- Connecting with SSL {#with-ssl}

    `src/java/com/example/App.java`

    ```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();
        }
      }
    }
    ```

{% endlist %}

To learn how to get a host FQDN, see [this guide](fqdn.md).

**Connecting:**

```bash
mvn clean package && \
java -jar target/app-0.1.0-jar-with-dependencies.jar
```

If your cluster connection and test command are successful, you will see the `bar` string in the output.

## Node.js {#nodejs}

**Before connecting, install the required dependencies:**

```bash
sudo apt update && sudo apt install --yes nodejs npm && \
npm install ioredis
```

{% list tabs group=connection %}

- Connecting without SSL {#without-ssl}

    **Code example for connecting via Sentinel:**

    `app.js`

    ```javascript
    "use strict";
    const Redis = require("ioredis");

    const conn = new Redis({
        sentinels: [
            { host: "<Valkey™_host_1_FQDN>", port: 26379 },
            ...
            { host: "<Valkey™_host_N_FQDN>", port: 26379 },
        ],
        name: "<Valkey™_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`

    ```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();
    });
    ```

- Connecting with SSL {#with-ssl}

    `app.js`

    ```javascript
    "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();
    });
    ```

{% endlist %}

To learn how to get a host FQDN, see [this guide](fqdn.md).

**Connecting:**

```bash
node app.js
```

If your cluster connection and test command are successful, you will see the `bar` string in the output.

## PHP {#php}

**Before connecting, install the required dependencies:**

```bash
sudo apt update && sudo apt install --yes php php-dev php-pear && \
sudo pear channel-discover pear.nrk.io && \
sudo pear install nrk/Predis
```

{% list tabs group=connection %}

- Connecting without SSL {#without-ssl}

    **Code example for connecting via Sentinel:**

    `connect.php`

    ```php
    <?php
    require "Predis/Autoloader.php";
    Predis\Autoloader::register();

    $sentinels = [
        "<Valkey™_host_1_FQDN>:26379>",
        ...
        "<Valkey™_host_N_FQDN>:26379>",
    ];
    $options = [
        "replication" => "sentinel",
        "service" => "<Valkey™_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
    <?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();
    ?>
    ```

- Connecting with SSL {#with-ssl}

    `connect.php`

    ```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();
    ?>
    ```

{% endlist %}

To learn how to get a host FQDN, see [this guide](fqdn.md).

**Connecting:**

```bash
php connect.php
```

If your cluster connection and test command are successful, you will see the `bar` string in the output.

## Python {#python}

**Before connecting, install the required dependencies**:

```bash
sudo apt update && sudo apt install -y python3 python3-pip && \
pip3 install redis
```

{% list tabs group=connection %}

- Connecting without SSL {#without-ssl}

    **Code example for connecting via Sentinel:**

    `connect.py`

    ```python
    from redis.sentinel import Sentinel

    sentinels = [
        "<Valkey™_host_1_FQDN>",
        ...
        "<Valkey™_host_N_FQDN>"
    ]
    name = "<Valkey™_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"))
    ```

    **Code example for connecting directly to the master without SSL**:

    `connect.py`

    ```python
    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"))
    ```

- Connecting with SSL {#with-ssl}

    `connect.py`

    ```python
    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"))
    ```

{% endlist %}

To learn how to get a host FQDN, see [this guide](fqdn.md).

**Connecting:**

```bash
python3 connect.py
```

If your cluster connection and test command are successful, you will see the `bar` string in the output.

## Ruby {#ruby}

**Before connecting, install the required dependencies:**

```bash
sudo apt update && sudo apt install --yes ruby && \
sudo gem install redis
```

{% list tabs group=connection %}

- Connecting without SSL {#without-ssl}

    **Code example for connecting via Sentinel:**

    `connect.rb`

    ```ruby
    # coding: utf-8

    require 'redis'

    SENTINELS = [
      { host: '<Valkey™_host_1_FQDN>', port: 26379 },
      ...
      { host: '<Valkey™_host_N_FQDN>', port: 26379 }
    ]

    conn = Redis.new(
      host: '<Valkey™_cluster_name>',
      sentinels: SENTINELS,
      role: 'master',
      password: '<password>'
    )

    conn.set('foo', 'bar')
    puts conn.get('foo')

    conn.close
    ```

    **Code example for connecting directly to the master without SSL**:

    `connect.rb`

    ```ruby
    # 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
    ```

- Connecting with SSL {#with-ssl}

    `connect.rb`

    ```ruby
    # 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
    ```

{% endlist %}

To learn how to get a host FQDN, see [this guide](fqdn.md).

**Connecting:**

```bash
ruby connect.rb
```

If your cluster connection and test command are successful, you will see the `bar` string in the output.