[StackExchage]Redis 的连接与操作(跨机器)

环境搭建


跨机器Redis 访问配置(版本4.0)
ubuntu
- 找到redis的目录(redis server服务器)下的redis.conf文件,我的目录是这样的home/lampard/Redis/redis-4.0.1/redis.conf
- 打开文件,找到bind配置节点,注释此节点,表示不绑定任何目标ip,允许所有ip访问此redis服务。
- 找到protected-mode,设置成no,这两项设置我暂时没有找到通过CONFIG SET 指令操作的方式,所以直接改的conf文件。
- 打开redis-cli 通过指令设置 config set requirepass xxx
windows
- 打开cmd命令,进入到上面解压的目录,运行redis-cli -h 服务器地址 -p 端口
- 使用auth 命令验证密码,$>auth xxx
- 测试 set get指令,ok 通过

以上是关于环境的搭建,这样整个redis的服务可以通过自己提供的客户端实现windows和ubuntu两台电脑之间的数据操作了。


开发环境搭建

选择使用StackExchange类库作为开发类库
下载地址: 点击这里
但是更推荐使用NuGet 搜索 StackExchange 安装项目引用

创建项目源码如下:

 public class Lampard
    {
        public static void Main(string[] args)
        { 
            using (var client = ConnectionMultiplexer.Connect("192.168.224.134:6379"))
            {
                if (client.IsConnected)
                    Console.WriteLine("Connect Success!");
                else
                    Console.WriteLine("Connect Fails");
                var db = client.GetDatabase(0);

                db.StringSet("a", 123);
                Console.WriteLine(db.StringGet("a"));
                Console.ReadLine();
            }
        }
    }

当运行程序之后出现了如下错误
It was not possible to connect to the redis server(s); to create a disconnected multiplexer, disable AbortOnConnectFail. AuthenticationFailure on PING
这个错误整整让我在网上找了一上午,痛苦过程不赘述,后来得到网友的启发,原来是连接字符串写错了,因为我们已经定义了密码,所以连接字符串要包含有密码
正确的连接字符串
192.168.224.134:6379,password=123

完整代码

    public class Lampard
    {
        public static void Main(string[] args)
        {
            using (var client = ConnectionMultiplexer.Connect("192.168.224.134:6379,abortConnect=false,ssl=false,password=123"))
            {
                if (client.IsConnected)
                    Console.WriteLine("Connect Success!");
                else
                    Console.WriteLine("Connect Fails");
                var db = client.GetDatabase(0);

                db.StringSet("a", 123);
                Console.WriteLine(db.StringGet("a"));
                Console.ReadLine();
            }
        }
    }

结束语:
到此 一切结束,顺利通过,后续再有进一步的学习分享。

http://www.redis.cn/
http://www.redis.cn/download.html
http://www.cnblogs.com/liusxg/p/5712493.html

原文地址:https://www.cnblogs.com/xiaoch/p/13417948.html