# 建立连接
兼容提示
Sudis默认兼容Redis协议,在连接时可以使用Redis的SDK,直接替换对应的IP,端口号等配置即可。
以下演示部分语言SDK连接示例
# C/C++
#include <stdio.h>
#include <hiredis/hiredis.h>
int main()
{
//1、连接redis服务器
redisContext *c = redisConnect("127.0.0.1", 9999);
if (c == NULL || c->err != 0) {
printf("Failed to connect to Redis!\n");
return 1;
}
//2、执行redis命令
const char *key = "name";
const char *value = "Sudis";
void *ptr = redisCommand(c, "SET %s %s", key, value);
redisReply *ply = (redisReply *)ptr;
if (ply->type == 5) {
printf("status:%s\n", ply->str);
}
freeReplyObject(ply);
//3、从数据库中读数据
ptr = redisCommand(c, "GET %s", key);
ply = (redisReply *)ptr;
printf("key: %s,value: %s\n", key, ply->str);
freeReplyObject(ply);
return 0;
}
# Java
package org.example;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
public class Main {
public static void main(String[] args) {
JedisPool pool = new JedisPool("127.0.0.1", 9999);
try (Jedis jedis = pool.getResource()) {
jedis.set("name", "sudis");
System.out.println(jedis.get("name"));
Map<String, String> hash = new HashMap<>();;
hash.put("name", "sudis");
hash.put("company", "eancs");
jedis.hset("user:1", hash);
System.out.println(jedis.hgetAll("user:1"));
}
}
}
# Python
import redis
if __name__ == '__main__':
rc = redis.Redis(host="192.168.5.76", port=9999, decode_responses=True)
print(rc.info())
rc.set('name', 'sudis')
print(rc.get("name"))
# GO
import (
"fmt"
"github.com/go-redis/redis"
)
func main() {
client := redis.NewClient(&redis.Options{
Addr: "localhost:9999", // Sudis 服务器地址
Password: "", // Sudis 密码
DB: 0, // Sudis 数据库
})
pong, err := client.Ping().Result()
fmt.Println(pong, err)
}
# Node.js
import { createClient } from 'redis';
const client = createClient();
client.on('error', err => console.log('Redis Client Error', err));
await client.connect();
await client.set('key', 'value');
const value = await client.get('key');
console.log(value);
# PHP
<?php
$redis = new Redis();
$connected = $redis->connect('127.0.0.1', 9999);
if (!$connected) {
die('Failed to connect to Redis: ' . $redis->getLastError());
}
// 设置键值对
$redis->set('name', 'Sudis');
// 获取键值对
$value = $redis->get('name');
if ($value !== false) {
echo "Read: " . $value . "\n";
} else {
echo "Key not found.\n";
}
// 关闭 Redis 客户端连接
$redis->close();
?>
# c#
using System;
using StackExchange.Redis;
namespace RedisConnectionExample
{
class Program
{
static void Main(string[] args)
{
var configuration = new ConfigurationOptions
{
EndPoints = { { "localhost", 9999, 0 } }, // 指定 Sudis 服务器的地址和端口号
Password = "password"
};
var redis = ConnectionMultiplexer.Connect(configuration);
IDatabase db = redis.GetDatabase();
db.StringSet("name", "Sudis");
string value = db.StringGet("name");
Console.WriteLine($"Read: {value}");
redis.Close();
}
}
}