PolarDB MySQL版的Orca功能兼容Redis协议,允许您使用主流的Redis客户端连接数据库。本文将引导您完成连接前的准备工作,并提供多种常见编程语言的客户端连接代码示例。
准备工作
在尝试连接Orca功能前,请确保您已完成以下准备工作:
注意事项
认证机制差异:Orca功能与原生Redis在认证机制上存在核心差异。Orca没有默认用户,所有连接都需使用您在控制台上创建的Orca账号进行认证。
AUTH命令兼容性:为兼容部分只支持密码认证的客户端,Orca的
AUTH命令支持两种格式。在配置客户端时,请根据客户端的能力选择合适的认证方式。AUTH <username> <password>:标准格式,分别提供用户名和密码。AUTH <username>:<password>:兼容格式,将用户名和密码用冒号:拼接后,作为一个整体作为密码(password)参数传入。
HELLO命令兼容性:与
AUTH命令类似,HELLO命令中的认证部分也支持上述两种格式。HELLO <protover> AUTH <username> <password>HELLO <protover> AUTH <username>:<password>
通过redis-cli连接
安装redis-cli:您可以参考安装redis-cli教程,在您的客户端设备上进行安装。
连接Orca功能:执行以下命令,将命令中的连接地址和端口替换为您的实际信息。
redis-cli -h pz-****************.rwlb.rds.aliyuncs.com -p 6379进行身份认证:连接成功后,使用
AUTH命令进行认证。以下两种格式均可,请替换为您的Orca账号和密码。# 格式一:分别提供用户名和密码 AUTH orca_user orca_password # 格式二:将用户名和密码拼接后作为密码提供 AUTH orca_user:orca_password如果返回
OK,表示连接和认证均成功。
通过各语言客户端连接
您可以根据应用程序的开发语言,参考以下示例进行连接。
Java(Jedis)
添加依赖配置(Maven):
<dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>4.3.0</version> </dependency>代码示例:为兼容Jedis只接受一个密码参数的设定,需使用
username:password的格式。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连接信息 String host = "pz-****************.rwlb.rds.aliyuncs.com"; // 替换为您的Orca连接地址 int port = 6379; String username = "orca_user"; // 替换为您的Orca用户名 String password = "orca_password"; // 替换为您的Orca密码 // Jedis认证需要将用户名和密码拼接 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)
添加依赖配置(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>代码示例:Lettuce支持分别设置用户名和密码,推荐使用此方式。
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连接信息 String host = "pz-****************.rwlb.rds.aliyuncs.com"; // 替换为您的Orca连接地址 int port = 6379; String username = "orca_user"; // 替换为您的Orca用户名 String password = "orca_password"; // 替换为您的Orca密码 // Lettuce支持分别设置用户名和密码 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"); // 输出: Lettuce System.out.println("Get value: " + value); connection.close(); redisClient.shutdown(); } }
Java(Spring Data Redis)
添加依赖配置(Maven):
<!-- Spring Boot父项目,统一管理版本 --> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.7.18</version> <!-- 建议使用一个较新的稳定版本 --> <relativePath/> </parent> <!-- 其他配置项... --> <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> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build>代码示例:您可以选择以下任一方式进行配置信息与连接Orca。
通过
application.yml配置Spring Boot 2.x及以上版本支持在
application.yml中分别指定用户名和密码,这是推荐的方式。项目文件结构如下:
test_redis/ ├── pom.xml └── src/ └── main/ ├── java/ │ └── com/ │ └── example/ │ ├── MainApplication.java │ └── RedisTestRunner.java └── resources/ └── application.yml配置
application.yml:在src/main/resources/目录下创建application.yml文件。这里是存放所有配置信息的地方。spring: redis: host: pz-****************.rwlb.rds.aliyuncs.com # 替换为您的Orca连接地址 port: 6379 username: orca_user # 替换为您的Orca用户名 password: orca_password # 替换为您的Orca密码 database: 0 jedis: pool: max-active: 30 max-idle: 20 min-idle: 5 max-wait: -1ms创建主启动类
MainApplication.java:这是Spring Boot程序的入口。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); } }创建测试类
RedisTestRunner.java:这个类会在Spring Boot应用启动后自动运行,执行Redis的读写操作并打印结果。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 { // 定义一个键值对 String key = "name"; String value = "spring-data-redis"; // 1. 执行 SET 命令 stringRedisTemplate.opsForValue().set(key, value); System.out.println("SET " + key + " = " + value); // 2. 执行 GET 命令 String retrievedValue = stringRedisTemplate.opsForValue().get(key); System.out.println("GET " + key + " = " + retrievedValue); // 3. 验证结果 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配置
如果您的Spring版本较低或有自定义需求,可以使用Java配置类。由于底层使用Jedis,认证时仍需拼接用户名和密码。
项目文件结构如下:
test_redis/ ├── pom.xml └── src/ └── main/ ├── java/ │ └── com/ │ └── example/ │ ├── config/ │ │ └── RedisConfig.java <-- 核心配置类 │ ├── MainApplication.java │ └── RedisTestRunner.java └── resources/ └── application.yml <-- 这个文件可以删除或留空创建核心配置类
RedisConfig.java:在这个类中,手动创建一个RedisConnectionFactory的实例(Bean),并提供所有连接细节。Spring Boot会自动检测到这个Bean,并用它来配置所有Redis相关的操作(比如StringRedisTemplate)。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. 创建独立的Redis配置 RedisStandaloneConfiguration redisConfig = new RedisStandaloneConfiguration(); // 2. 设置Orca的连接信息 // 替换为您的Orca连接地址 redisConfig.setHostName("pz-****************.rwlb.rds.aliyuncs.com"); // Orca端口,默认为6379 redisConfig.setPort(6379); // 替换为您的Orca用户名 redisConfig.setUsername("orca_user"); // 替换为您的Orca密码 redisConfig.setPassword("orca_password"); // 3. 使用Lettuce作为客户端,并应用上面的配置 LettuceConnectionFactory lettuceFactory = new LettuceConnectionFactory(redisConfig); // 可选:如果不调用afterPropertiesSet,Spring容器在初始化bean时会自动调用。 // lettuceFactory.afterPropertiesSet(); // 4. 返回配置好的连接工厂实例 return lettuceFactory; } }创建主启动类
MainApplication.java:这是Spring Boot程序的入口。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); } }创建测试类
RedisTestRunner.java:这个类会在Spring Boot应用启动后自动运行,执行Redis的读写操作并打印结果。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 { // 定义一个键值对 String key = "name"; String value = "spring-data-redis"; // 1. 执行 SET 命令 stringRedisTemplate.opsForValue().set(key, value); System.out.println("SET " + key + " = " + value); // 2. 执行 GET 命令 String retrievedValue = stringRedisTemplate.opsForValue().get(key); System.out.println("GET " + key + " = " + retrievedValue); // 3. 验证结果 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)
安装依赖:
pip install redis代码示例:
redis-py从4.2版本开始支持独立的username参数。如果使用旧版本,请使用username:password的格式作为password参数。import redis # Orca连接信息 host = 'pz-****************.rwlb.rds.aliyuncs.com' # 替换为您的Orca连接地址 port = 6379 username = 'orca_user' # 替换为您的Orca用户名 password = 'orca_password' # 替换为您的Orca密码 # 推荐方式 (redis-py >= 4.2) r = redis.Redis(host=host, port=port, username=username, password=password) # 兼容旧版本方式 # 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)
安装依赖:
go get github.com/go-redis/redis/v8代码示例:
go-redis支持独立的Username字段,推荐使用。如果客户端版本较旧,请使用username:password作为Password字段的值。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", // 替换为您的Orca地址和端口 Username: "orca_user", // 替换为您的Orca用户名 Password: "orca_password", // 替换为您的Orca密码 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)
安装依赖:
npm install redis代码示例:
node-redis支持在连接URL中包含认证信息。import { createClient } from 'redis'; // Orca连接信息 const host = 'pz-****************.rwlb.rds.aliyuncs.com'; // 替换为您的Orca连接地址 const port = 6379; const username = 'orca_user'; // 替换为您的Orca用户名 const password = 'orca_password'; // 替换为您的Orca密码 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)
安装依赖:通常通过包管理器安装,例如在CentOS上:
sudo yum install php-redis代码示例:
PhpRedis扩展的auth方法支持传入包含用户名和密码的数组。<?php $redis = new Redis(); // Orca连接信息 $host = 'pz-****************.rwlb.rds.aliyuncs.com'; // 替换为您的Orca连接地址 $port = 6379; $user = 'orca_user'; // 替换为您的Orca用户名 $password = 'orca_password'; // 替换为您的Orca密码 if ($redis->connect($host, $port) === false) { die($redis->getLastError()); } // 使用包含用户名和密码的数组进行认证 if ($redis->auth([$user, $password]) === false) { die($redis->getLastError()); } $redis->set("name", "php-redis"); echo $redis->get("name"); $redis->close(); ?>
C (Hiredis)
安装依赖:从源码编译安装。
git clone https://github.com/redis/hiredis.git cd hiredis make && sudo make install代码示例:使用
redisCommand执行AUTH命令,可以采用username:password的拼接格式。#include <stdio.h> #include <stdlib.h> #include <string.h> #include <hiredis.h> int main() { // Orca 连接参数 const char *hostname = "********.rwlb.rds.aliyuncs.com"; // 替换为您的Orca连接地址 int port = 6379; // 将用户名和密码分开定义,便于使用 const char *username = "orca_user"; // 替换为您的Orca用户名 const char *password = "orca_password"; // 替换为您的Orca密码 redisContext *c; redisReply *reply; // 1. 连接 Redis (建议使用带超时的连接) struct timeval timeout = { 2, 0 }; // 2秒超时 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. 认证 (修正部分) // 使用 "AUTH <username> <password>" 格式 reply = redisCommand(c, "AUTH %s %s", username, password); if (reply == NULL) { // 如果 reply 为 NULL,说明IO错误,检查 c->errstr printf("AUTH command failed: %s\n", c->errstr); redisFree(c); exit(1); } // 检查 reply 本身是否是错误类型 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); // 认证成功后,别忘了释放reply // 3. 执行 SET 命令 reply = redisCommand(c, "SET mykey %s", "Hello, hiredis!"); if (reply == NULL) { printf("SET command failed: %s\n", c->errstr); redisFree(c); exit(1); } // hiredis对于SET命令成功返回的是一个状态(STATUS)类型的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. 执行 GET 命令 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. 关闭连接 redisFree(c); printf("Disconnected from Redis\n"); return 0; }编译与运行。
# 编译,-I和-L后的路径请根据您的实际安装位置调整 gcc -o orca orca.c -I/usr/local/include/hiredis -L/usr/local/lib -lhiredis # 运行 ./orca
通过DMS连接
连接Orca
点击新增,选择他云/自建,在NoSQL数据库中选择Redis。

点击下一步进入基本信息配置页面,按照下图方式选择。
实例来源选择VPC专线、实例地区选择PolarDB集群所在地区或就近地区、VPC ID选择PolarDB详情页中VPC、登录地址填写Orca连接地址。
访问方式选择安全托管+手动,数据库账号及密码按照已创建的Orca账号填写即可。
信息填写完成后点击测试连接,如无异常会显示连接成功。

点击下一步,进入高级信息界面,按照实际需要设置。
说明需要注意Orca目前不支持开启SSL。

点击提交,如无异常Orca将进入安全托管状态。

数据管理
在顶部菜单栏中,选择SQL窗口,并选择已托管完成的Orca集群。
Orca目前仅支持一个Redis逻辑数据库DB0,若您未看到当前数据库DB0,请单击刷新 / 同步字典。

若无异常,即可正常使用DMS管理Orca。

