[root@node2 /etc/yum.repos.d]# redis-cli -h 192.168.213.133
192.168.213.133:6379>

在redis客户端上,执行一条redis命令,查看连接是否正常可用:

192.168.213.133:6379> get foo
(error) DENIED Redis is running in protected mode because protected mode is enabled, no bind address was specified, no authentication password is requested to clients. In this mode connections are only accepted from the loopback interface. If you want to connect from external computers to Redis you may adopt one of the following solutions: 1) Just disable protected mode sending the command 'CONFIG SET protected-mode no' from the loopback interface by connecting to Redis from the same host the server is running, however MAKE SURE Redis is not publicly accessible from internet if you do so. Use CONFIG REWRITE to make this change permanent. 2) Alternatively you can just disable the protected mode by editing the Redis configuration file, and setting the protected mode option to 'no', and then restarting the server. 3) If you started the server manually just for testing, restart it with the '--protected-mode no' option. 4) Setup a bind address or an authentication password. NOTE: You only need to do one of the above things in order for the server to start accepting connections from the outside.
192.168.213.133:6379>

从上述返回结果能够看到,redis客户端命令执行失败了,原因是远端的redis服务端启用了保护模式,在保护模式下,redis服务器只接收本地环回接口的连接请求。为了解决这个问题,可以:

1)禁用redis服务器的安全模式;

2)设置认证密码;

3)设置redis服务器的绑定IP(默认只绑定了127.0.0.1)

在本文中,采用了在启动redis服务器时,暂时禁用redis服务器安全模式的方式,如下:

redis-server --protected-mode no

此时,再次通过远程redis客户端连接此redis服务器时,就可以正常执行redis命令了,如下:

[root@node2 /etc/yum.repos.d]# redis-cli -h 192.168.213.133
192.168.213.133:6379> get foo
(nil)
192.168.213.133:6379>

**说明:**本文后面的操作,如无特殊说明,默认都是在连接到redis服务器的redis客户端的命令行中执行的。

2. 增加数据

redis是通过键值对(key-value)形式进行数据存储的。

通过SET命令向redis数据库中添加数据时,能够看到系统有灰色字体的命令提示,如下:

redis monitor 时间戳具体时间_c语言

从上面的提示可以知道,使用SET命令添加数据的格式为:SET key value

下面我们通过SET命令向redis数据库中添加数据,如下:

127.0.0.1:6379> SET zhang zhangsan
OK

上面的SET命令执行结果返回OK,说明我们添加数据成功了。

3. 查询数据

通过GET命令查询redis数据库中的数据时,能够看到系统有灰色字体的命令提示,如下:

redis monitor 时间戳具体时间_redis_02

从上面的提示可以知道,使用GET命令获取数据的格式为:GET key

下面我们通过GET命令获取redis数据库中的指定数据(我们前面添加的数据),如下:

127.0.0.1:6379> GET zhang
"zhangsan"
127.0.0.1:6379>

上面的GET命令执行结果返回了我们想要查询的数据。