Tüm Ürünler
Search
Belge Merkezi

PolarDB:Orca bağlantı kılavuzu (istemci/DMS)

Son Güncelleme:Oct 09, 2026

PolarDB for MySQL Redis protokolüyle uyumlu olan ve popüler Redis istemcilerini kullanarak veritabanına bağlanmanızı sağlayan Orca özelliğini sunar. Bu konu, bağlantı için gerekli hazırlıkları açıklar ve çeşitli popüler programlama dilleri için istemci bağlantısı kod örnekleri içerir.

Hazırlıklar

Orca özelliğine bağlanmadan önce aşağıdaki hazırlıkları tamamladığınızdan emin olun:

Kullanım notları

  • Kimlik doğrulama mekanizması farklılıkları: Orca ile yerel Redis farklı kimlik doğrulama mekanizmaları kullanır. Orca'nın varsayılan bir kullanıcısı yoktur. Tüm bağlantılar konsolda oluşturduğunuz bir Orca hesabı kullanılarak kimlik doğrulamasından geçmelidir.

  • AUTH komutu uyumluluğu: Yalnızca parola tabanlı kimlik doğrulamayı destekleyen istemcilerle uyumluluk sağlamak amacıyla Orca AUTH komutu iki formatı destekler. Bir istemci yapılandırırken istemcinin desteklediği kimlik doğrulama yöntemini seçin.

    • AUTH <username> <password>: Standart format. Kullanıcı adı ve parolayı ayrı ayrı belirtin.

    • AUTH <username>:<password>: Uyumluluk formatı. Kullanıcı adı ve parolayı iki nokta üst üste : işaretiyle birleştirin ve birleşik diziyi parola parametresinin değeri olarak iletin.

  • HELLO komutu uyumluluğu: AUTH komutuna benzer şekilde HELLO komutunun kimlik doğrulama bölümü de yukarıda açıklanan iki formatı destekler.

    • HELLO <protover> AUTH <username> <password>

    • HELLO <protover> AUTH <username>:<password>

redis-cli kullanarak bağlanma

  1. redis-cli yükleyin: redis-cli'yı istemci cihazınıza yüklemek için redis-cli kurulum öğreticisine bakın.

  2. Orca özelliğine bağlanın: Aşağıdaki komutu çalıştırın. Komuttaki uç noktayı ve bağlantı noktasını kendi bilgilerinizle değiştirin.

    redis-cli -h pz-****************.rwlb.rds.aliyuncs.com -p 6379
  3. Bağlantınızı doğrulayın: Bağlantı kurulduktan sonra kimlik doğrulaması yapmak için AUTH komutunu kullanın. Aşağıdaki her iki format da desteklenir. Yer tutucuları Orca hesabınız ve parolanızla değiştirin.

    # Format 1: Provide the username and password separately
    AUTH orca_user orca_password
    # Format 2: Provide the concatenated username and password as the password
    AUTH orca_user:orca_password

    OK yanıtı dönerse bağlantı ve kimlik doğrulama başarılı olmuştur.

İstemci kitaplıklarını kullanarak bağlanma

Kullandığınız programlama diline göre aşağıdaki örneklere başvurarak uygulamanızdan bağlanabilirsiniz.

Java (Jedis)

  1. Bağımlılıkları ekleyin (Maven):

    <dependency>
        <groupId>redis.clients</groupId>
        <artifactId>jedis</artifactId>
        <version>4.3.0</version>
    </dependency>
  2. Kod örneği: Yalnızca tek bir parola parametresi kabul eden Jedis ayarıyla uyumlu olmak için username:password formatını kullanmanız gerekir.

    import redis.clients.jedis.Jedis;
    import redis.clients.jedis.JedisPool;
    import redis.clients.jedis.JedisPoolConfig;
    public class JedisExample {
        public static void main(String[] args) {
            JedisPoolConfig poolConfig = new JedisPoolConfig();
            // Orca connection information
            String host = "pz-****************.rwlb.rds.aliyuncs.com"; // Replace with your Orca endpoint
            int port = 6379;
            String username = "orca_user"; // Replace with your Orca username
            String password = "orca_password"; // Replace with your Orca password
            // Jedis authentication requires concatenating the username and password
            String authPassword = username + ":" + password;
            JedisPool pool = new JedisPool(poolConfig, host, port, 3000, authPassword);
            try (Jedis jedis = pool.getResource()) {
                jedis.set("name", "jedis");
                System.out.println(jedis.get("name"));
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                pool.destroy();
            }
        }
    }
    

Java (Lettuce)

  1. Bağımlılıkları ekleyin (Maven):

    <dependency>
        <groupId>io.lettuce</groupId>
        <artifactId>lettuce-core</artifactId>
        <version>6.3.0.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>io.netty</groupId>
        <artifactId>netty-transport-native-epoll</artifactId>
        <version>4.1.100.Final</version>
        <classifier>linux-x86_64</classifier>
    </dependency>
  2. Kod örneği: Lettuce kullanıcı adı ve parolayı ayrı ayrı ayarlamayı destekler. Bu yöntem önerilir.

    import io.lettuce.core.RedisClient;
    import io.lettuce.core.RedisURI;
    import io.lettuce.core.api.StatefulRedisConnection;
    import io.lettuce.core.api.sync.RedisCommands;
    public class LettuceExample {
        public static void main(String[] args) {
            // Orca connection information
            String host = "pz-****************.rwlb.rds.aliyuncs.com"; // Replace with your Orca endpoint
            int port = 6379;
            String username = "orca_user"; // Replace with your Orca username
            String password = "orca_password"; // Replace with your Orca password
            // Lettuce supports setting the username and password separately
            RedisURI uri = RedisURI.Builder
                    .redis(host, port)
                    .withAuthentication(username, password)
                    .build();
            RedisClient redisClient = RedisClient.create(uri);
            StatefulRedisConnection<String, String> connection = redisClient.connect();
            RedisCommands<String, String> syncCommands = connection.sync();
            syncCommands.set("name", "Lettuce");
            String value = syncCommands.get("name");
            // Output: Lettuce
            System.out.println("Get value: " + value); 
            connection.close();
            redisClient.shutdown();
        }
    }

Java (Spring Data Redis)

  1. Bağımlılıkları ekleyin (Maven):

    <!-- Spring Boot parent project for unified version management -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.18</version> <!-- Use a recent stable version -->
        <relativePath/>
    </parent>
    <!-- Other configurations... -->
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-simple</artifactId>
            <version>1.7.36</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <!-- Spring Boot Maven plugin for packaging and running -->
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
  2. Kod örneği: Orca'ya bağlantıyı yapılandırmak için aşağıdaki yöntemlerden birini kullanabilirsiniz.

    application.yml kullanarak yapılandırma

    Spring Boot 2.x ve sonraki sürümler application.yml dosyasında kullanıcı adı ve parolayı ayrı ayrı belirtmeyi destekler. Bu yöntem önerilir.

    1. Proje dosya yapısı aşağıdaki gibidir:

      test_redis/
      ├── pom.xml
      └── src/
          └── main/
              ├── java/
              │   └── com/
              │       └── example/
              │           ├── MainApplication.java
              │           └── RedisTestRunner.java
              └── resources/
                  └── application.yml
      
    2. application.yml dosyasını yapılandırın: src/main/resources/ dizininde bir application.yml dosyası oluşturun. Bu dosya tüm yapılandırma bilgilerini saklar.

      spring:
        redis:
          host: pz-****************.rwlb.rds.aliyuncs.com # Replace with your Orca endpoint
          port: 6379
          username: orca_user      # Replace with your Orca username
          password: orca_password  # Replace with your Orca password
          database: 0
          jedis:
            pool:
              max-active: 30
              max-idle: 20
              min-idle: 5
              max-wait: -1ms
    3. Ana uygulama sınıfı MainApplication.java dosyasını oluşturun: Bu Spring Boot uygulamasının giriş noktasıdır.

      package com.example;
      import org.springframework.boot.SpringApplication;
      import org.springframework.boot.autoconfigure.SpringBootApplication;
      @SpringBootApplication
      public class MainApplication {
          public static void main(String[] args) {
              SpringApplication.run(MainApplication.class, args);
          }
      }
    4. Test sınıfı RedisTestRunner.java dosyasını oluşturun: Bu sınıf Spring Boot uygulaması başladıktan sonra otomatik olarak çalışır Redis okuma ve yazma işlemleri gerçekleştirir ve sonuçları yazdırır.

      package com.example;
      import org.springframework.beans.factory.annotation.Autowired;
      import org.springframework.boot.CommandLineRunner;
      import org.springframework.data.redis.core.StringRedisTemplate;
      import org.springframework.stereotype.Component;
      @Component
      public class RedisTestRunner implements CommandLineRunner {
          @Autowired
          private StringRedisTemplate stringRedisTemplate;
          @Override
          public void run(String... args) throws Exception {
              System.out.println("=== Starting Redis test with Spring Data Redis ===");
              try {
                  // Define a key-value pair
                  String key = "name";
                  String value = "spring-data-redis";
                  // 1. Run the SET command
                  stringRedisTemplate.opsForValue().set(key, value);
                  System.out.println("SET " + key + " = " + value);
                  // 2. Run the GET command
                  String retrievedValue = stringRedisTemplate.opsForValue().get(key);
                  System.out.println("GET " + key + " = " + retrievedValue);
                  // 3. Verify the result
                  if (value.equals(retrievedValue)) {
                      System.out.println("Test successful!");
                  } else {
                      System.out.println("Test failed! Retrieved value does not match.");
                  }
              } catch (Exception e) {
                  System.err.println("Redis operation failed: " + e.getMessage());
                  e.printStackTrace();
              }
              System.out.println("=== Redis test completed ===");
          }
      }

    Java Config kullanarak yapılandırma

    Spring'in daha eski bir sürümünü kullanıyorsanız veya özel gereksinimleriniz varsa Java yapılandırma sınıfı kullanabilirsiniz. Temel istemci olarak Jedis kullanıldığından kimlik doğrulama için kullanıcı adı ve parolayı yine de birleştirmeniz gerekir.

    1. Proje dosya yapısı aşağıdaki gibidir:

      test_redis/
      ├── pom.xml
      └── src/
          └── main/
              ├── java/
              │   └── com/
              │       └── example/
              │           ├── config/
              │           │   └── RedisConfig.java   <-- Core configuration class
              │           ├── MainApplication.java
              │           └── RedisTestRunner.java
              └── resources/
                  └── application.yml            <-- This file can be deleted or left empty
    2. Çekirdek yapılandırma sınıfı RedisConfig.java dosyasını oluşturun: Bu sınıfta manuel olarak bir RedisConnectionFactory örneği (bean) oluşturun ve tüm bağlantı ayrıntılarını sağlayın. Spring Boot bu bean'i otomatik olarak algılar ve StringRedisTemplate gibi Redis ile ilgili tüm işlemleri yapılandırmak için kullanır.

      package com.example.config;
      import org.springframework.context.annotation.Bean;
      import org.springframework.context.annotation.Configuration;
      import org.springframework.data.redis.connection.RedisConnectionFactory;
      import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
      import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
      @Configuration
      public class RedisConfig {
          @Bean
          public RedisConnectionFactory redisConnectionFactory() {
              // 1. Create a standalone Redis configuration
              RedisStandaloneConfiguration redisConfig = new RedisStandaloneConfiguration();
              // 2. Set the Orca connection information
              // Replace with your Orca endpoint
              redisConfig.setHostName("pz-****************.rwlb.rds.aliyuncs.com"); 
              // Orca port. The default value is 6379
              redisConfig.setPort(6379);
              // Replace with your Orca username
              redisConfig.setUsername("orca_user");
              // Replace with your Orca password
              redisConfig.setPassword("orca_password");
              // 3. Use Lettuce as the client and apply the preceding configuration
              LettuceConnectionFactory lettuceFactory = new LettuceConnectionFactory(redisConfig);
              // Optional: If you do not call afterPropertiesSet, the Spring container calls it automatically when the bean is initialized.
              // lettuceFactory.afterPropertiesSet();
              // 4. Return the configured connection factory instance
              return lettuceFactory;
          }
      }
      
    3. Ana uygulama sınıfı MainApplication.java dosyasını oluşturun: Bu Spring Boot uygulamasının giriş noktasıdır.

      package com.example;
      import org.springframework.boot.SpringApplication;
      import org.springframework.boot.autoconfigure.SpringBootApplication;
      @SpringBootApplication
      public class MainApplication {
          public static void main(String[] args) {
              SpringApplication.run(MainApplication.class, args);
          }
      }
    4. Test sınıfı RedisTestRunner.java dosyasını oluşturun: Bu sınıf Spring Boot uygulaması başladıktan sonra otomatik olarak çalışır Redis okuma ve yazma işlemleri gerçekleştirir ve sonuçları yazdırır.

    5. package com.example;
      import org.springframework.beans.factory.annotation.Autowired;
      import org.springframework.boot.CommandLineRunner;
      import org.springframework.data.redis.core.StringRedisTemplate;
      import org.springframework.stereotype.Component;
      @Component
      public class RedisTestRunner implements CommandLineRunner {
          @Autowired
          private StringRedisTemplate stringRedisTemplate;
          @Override
          public void run(String... args) throws Exception {
              System.out.println("=== Starting Redis test with Spring Data Redis ===");
              try {
                  // Define a key-value pair
                  String key = "name";
                  String value = "spring-data-redis";
                  // 1. Run the SET command
                  stringRedisTemplate.opsForValue().set(key, value);
                  System.out.println("SET " + key + " = " + value);
                  // 2. Run the GET command
                  String retrievedValue = stringRedisTemplate.opsForValue().get(key);
                  System.out.println("GET " + key + " = " + retrievedValue);
                  // 3. Verify the result
                  if (value.equals(retrievedValue)) {
                      System.out.println("Test successful!");
                  } else {
                      System.out.println("Test failed! Retrieved value does not match.");
                  }
              } catch (Exception e) {
                  System.err.println("Redis operation failed: " + e.getMessage());
                  e.printStackTrace();
              }
              System.out.println("=== Redis test completed ===");
          }
      }

Python (redis-py)

  1. Bağımlılığı yükleyin:

    pip install redis
  2. Kod örneği: redis-py 4.2 ve sonraki sürümler ayrı bir username parametresini destekler. Daha eski bir sürüm kullanıyorsanız password parametresinin değeri olarak username:password formatını kullanın.

    import redis
    # Orca connection information
    host = 'pz-****************.rwlb.rds.aliyuncs.com'  # Replace with your Orca endpoint
    port = 6379
    username = 'orca_user'  # Replace with your Orca username
    password = 'orca_password'  # Replace with your Orca password
    # Recommended method (redis-py >= 4.2)
    r = redis.Redis(host=host, port=port, username=username, password=password)
    # Compatibility method for earlier versions
    # auth_password = f'{username}:{password}'
    # r = redis.Redis(host=host, port=port, password=auth_password)
    r.set('name', 'redis-py')
    print(r.get('name').decode('utf-8'))
    r.close()
    

Go (go-redis)

  1. Bağımlılığı yükleyin:

    go get github.com/go-redis/redis/v8
  2. Kod örneği: go-redis ayrı bir Username alanını destekler; bu yöntem önerilir. İstemci sürümü daha eskiyse Password alanının değeri olarak username:password kullanın.

    package main
    import (
        "context"
        "fmt"
        "github.com/go-redis/redis/v8"
    )
    var ctx = context.Background()
    func main() {
        client := redis.NewClient(&redis.Options{
            Addr:     "pz-****************.rwlb.rds.aliyuncs.com:6379", // Replace with your Orca endpoint and port
            Username: "orca_user",     // Replace with your Orca username
            Password: "orca_password", // Replace with your Orca password
            DB:       0,
        })
        err := client.Set(ctx, "name", "go-redis", 0).Err()
        if err != nil {
            panic(err)
        }
        val, err := client.Get(ctx, "name").Result()
        if err != nil {
            panic(err)
        }
        fmt.Println("Get value:", val)
    }
    

Node.js (node-redis)

  1. Bağımlılığı yükleyin:

    npm install redis
  2. Kod örneği: node-redis kimlik doğrulama bilgilerinin bağlantı URL'sine dahil edilmesini destekler.

    import { createClient } from 'redis';
    // Orca connection information
    const host = 'pz-****************.rwlb.rds.aliyuncs.com'; // Replace with your Orca endpoint
    const port = 6379;
    const username = 'orca_user'; // Replace with your Orca username
    const password = 'orca_password'; // Replace with your Orca password
    const client = createClient({
        url: `redis://${username}:${encodeURIComponent(password)}@${host}:${port}/0`
    });
    client.on('error', (err) => console.error('Redis Client Error:', err));
    async function runExample() {
        try {
            await client.connect();
            await client.set('name', 'node-redis');
            const value = await client.get('name');
            console.log('get name:', value);
        } finally {
            await client.disconnect();
        }
    }
    runExample();
    

PHP (PhpRedis)

  1. Bağımlılığı yükleyin: Eklenti genellikle bir paket yöneticisi kullanılarak yüklenir. Örneğin CentOS üzerinde:

    sudo yum install php-redis
  2. Kod örneği: PhpRedis bir eklentidir ve auth yöntemi kullanıcı adı ile parolayı içeren bir diziyi destekler.

    <?php
    $redis = new Redis();
    // Orca connection information
    $host = 'pz-****************.rwlb.rds.aliyuncs.com'; // Replace with your Orca endpoint
    $port = 6379;
    $user = 'orca_user';     // Replace with your Orca username
    $password = 'orca_password'; // Replace with your Orca password
    if ($redis->connect($host, $port) === false) {
        die($redis->getLastError());
    }
    // Authenticate by using an array that contains the username and password
    if ($redis->auth([$user, $password]) === false) {
        die($redis->getLastError());
    }
    $redis->set("name", "php-redis");
    echo $redis->get("name");
    $redis->close();
    ?>
    

C (Hiredis)

  1. Bağımlılığı yükleyin: Kaynak koddan derleyip yükleyin.

    git clone https://github.com/redis/hiredis.git
    cd hiredis
    make && sudo make install
  2. Kod örneği: redisCommand kullanarak AUTH komutunu çalıştırın. username:password birleştirilmiş formatını kullanabilirsiniz.

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <hiredis.h>
    int main() {
        // Orca connection parameters
        const char *hostname = "********.rwlb.rds.aliyuncs.com"; // Replace with your Orca endpoint
        int port = 6379;
        // Define the username and password separately for ease of use
        const char *username = "orca_user"; // Replace with your Orca username
        const char *password = "orca_password"; // Replace with your Orca password
        redisContext *c;
        redisReply *reply;
        // 1. Connect to Redis (a connection with a timeout is recommended)
        struct timeval timeout = { 2, 0 }; // 2-second timeout
        c = redisConnectWithTimeout(hostname, port, timeout);
        if (c == NULL || c->err) {
            if (c) {
                printf("Connection error: %s\n", c->errstr);
                redisFree(c);
            } else {
                printf("Can't allocate redis context\n");
            }
            exit(1);
        }
        // 2. Authenticate (corrected part)
        // Use the "AUTH <username> <password>" format
        reply = redisCommand(c, "AUTH %s %s", username, password);
        if (reply == NULL) {
            // If reply is NULL, an I/O error occurred. Check c->errstr
            printf("AUTH command failed: %s\n", c->errstr);
            redisFree(c);
            exit(1);
        }
        // Check whether reply itself is an error type
        if (reply->type == REDIS_REPLY_ERROR) {
            printf("Authentication failed: %s\n", reply->str);
            freeReplyObject(reply);
            redisFree(c);
            exit(1);
        }
        printf("Authenticated successfully\n");
        freeReplyObject(reply); // After authentication succeeds, remember to release reply
        // 3. Run the SET command
        reply = redisCommand(c, "SET mykey %s", "Hello, hiredis!");
        if (reply == NULL) {
            printf("SET command failed: %s\n", c->errstr);
            redisFree(c);
            exit(1);
        }
        // hiredis returns, for a successful SET command, a status (STATUS) type reply
        if (reply->type == REDIS_REPLY_STATUS && strcmp(reply->str, "OK") == 0) {
            printf("SET mykey succeeded\n");
        } else {
            printf("SET failed with reply: %s\n", reply->str);
        }
        freeReplyObject(reply);
        // 4. Run the GET command
        reply = redisCommand(c, "GET mykey");
        if (reply == NULL) {
            printf("GET command failed: %s\n", c->errstr);
            redisFree(c);
            exit(1);
        }
        if (reply->type == REDIS_REPLY_STRING) {
            printf("GET mykey = %s\n", reply->str);
        } else if (reply->type == REDIS_REPLY_NIL) {
            printf("Key 'mykey' does not exist\n");
        } else {
            printf("GET returned unexpected type: %d, error: %s\n", reply->type, reply->str);
        }
        freeReplyObject(reply);
        // 5. Close the connection
        redisFree(c);
        printf("Disconnected from Redis\n");
        return 0;
    }
  3. Derleyin ve çalıştırın.

    # Compile. Adjust the paths after -I and -L based on your actual installation location
    gcc -o orca orca.c -I/usr/local/include/hiredis -L/usr/local/lib -lhiredis
    # Run
    ./orca

DMS kullanarak bağlanma

Orca'ya bağlanma

  1. Data Management (DMS) konsoluna gidin.

  2. Üst gezinme çubuğunda Data Assets > Instances seçeneğini belirleyin.

  3. Add seçeneğine tıklayın Third-party Cloud/Self-managed seçeneğini belirleyin ve NoSQL veritabanı için Redis seçeneğini belirleyin.

    image

  4. Temel bilgi yapılandırma sayfasına gitmek için Next seçeneğine tıklayın ve ardından aşağıdaki şekilde gösterildiği gibi parametreleri yapılandırın.

    • Instance Source: VPC PrivateLine seçeneğini belirleyin. Region için PolarDB kümenizin bulunduğu bölgeyi veya yakın bir bölgeyi seçin. VPC ID için PolarDB kümenizin ayrıntılar sayfasındaki VPC'yi seçin. Logon Address alanına Orca uç noktasını girin.

    • Access Method: Security Hosting + Manual seçeneğini belirleyin. Oluşturduğunuz Orca hesabının veritabanı hesabını ve parolasını girin.

    • Bilgileri girdikten sonra Test Connectivity seçeneğine tıklayın. Bir hata oluşmazsa bağlantının başarılı olduğuna ilişkin bir ileti görüntülenir.

    image

  5. Advanced Information sayfasına gitmek için Next seçeneğine tıklayın ve ihtiyaçlarınıza göre ayarları yapılandırın.

    Not

    Orca şu anda SSL etkinleştirmeyi desteklememektedir.

    image

  6. Submit seçeneğine tıklayın. Bir hata oluşmazsa Orca güvenlik barındırma durumuna geçer.

    image

Verileri yönetme

  1. Üst gezinme çubuğunda SQL Console seçeneğini belirleyin ve ardından barındırması tamamlanan Orca kümesini seçin.

  2. Orca şu anda yalnızca bir Redis mantıksal veritabanını (DB0) destekler. Geçerli veritabanı DB0'yı görmüyorsanız Refresh / Sync Dictionary seçeneğine tıklayın.

    image

  3. Bir hata oluşmazsa DMS'yi kullanarak Orca'yı yönetebilirsiniz.

    Örneğin SQL Console içinde ping key01 komutunu çalıştırın. PONG yanıtı dönerse bağlantı başarılıdır.