redis配置密码 redis常用命令

时间:2023-03-09 03:45:35
redis配置密码 redis常用命令

redis配置密码

1.通过配置文件进行配置
yum方式安装的redis配置文件通常在/etc/redis.conf中,打开配置文件找到

[plain] view plain copy
  1. #requirepass foobared

去掉行前的注释,并修改密码为所需的密码,保存文件

[plain] view plain copy
  1. requirepass myRedis

重启redis

[plain] view plain copy
  1. sudo service redis restart
  2. #或者
  3. sudo service redis stop
  4. sudo redis-server /etc/redis.conf

这个时候尝试登录redis,发现可以登上,但是执行具体命令是提示操作不允许

[plain] view plain copy
  1. redis-cli -h 127.0.0.1 -p 6379
  2. redis 127.0.0.1:6379>
  3. redis 127.0.0.1:6379> keys *
  4. (error) ERR operation not permitted
  5. redis 127.0.0.1:6379> select 1
  6. (error) ERR operation not permitted
  7. redis 127.0.0.1:6379[1]>

尝试用密码登录并执行具体的命令看到可以成功执行

[plain] view plain copy
  1. redis-cli -h 127.0.0.1 -p 6379 -a myRedis
  2. redis 127.0.0.1:6379> keys *
  3. 1) "myset"
  4. 2) "mysortset"
  5. redis 127.0.0.1:6379> select 1
  6. OK
  7. redis 127.0.0.1:6379[1]> config get requirepass
  8. 1) "requirepass"
  9. 2) "myRedis"

2.通过命令行进行配置

[plain] view plain copy
  1. redis 127.0.0.1:6379[1]> config set requirepass my_redis
  2. OK
  3. redis 127.0.0.1:6379[1]> config get requirepass
  4. 1) "requirepass"
  5. 2) "my_redis"

无需重启redis
使用第一步中配置文件中配置的老密码登录redis,会发现原来的密码已不可用,操作被拒绝

[plain] view plain copy
  1. redis-cli -h 127.0.0.1 -p 6379 -a myRedis
  2. redis 127.0.0.1:6379> config get requirepass
  3. (error) ERR operation not permitted

使用修改后的密码登录redis,可以执行相应操作

[plain] view plain copy
  1. redis-cli -h 127.0.0.1 -p 6379 -a my_redis
  2. redis 127.0.0.1:6379> config get requirepass
  3. 1) "requirepass"
  4. 2) "my_redis

尝试重启一下redis,用新配置的密码登录redis执行操作,发现新的密码失效,redis重新使用了配置文件中的密码

[plain] view plain copy
  1. sudo service redis restart
  2. Stopping redis-server:                                     [  OK  ]
  3. Starting redis-server:                                     [  OK  ]
  4. redis-cli -h 127.0.0.1 -p 6379 -a my_redis
  5. redis 127.0.0.1:6379> config get requirepass
  6. (error) ERR operation not permitted
  7. redis-cli -h 127.0.0.1 -p 6379 -a myRedis
  8. redis 127.0.0.1:6379> config get requirepass
  9. 1) "requirepass"
  10. 2) "myRedis"

除了在登录时通过 -a 参数制定密码外,还可以登录时不指定密码,而在执行操作前进行认证。

[plain] view plain copy
  1. redis-cli -h 127.0.0.1 -p 6379
  2. redis 127.0.0.1:6379> config get requirepass
  3. (error) ERR operation not permitted
  4. redis 127.0.0.1:6379> auth myRedis
  5. OK
  6. redis 127.0.0.1:6379> config get requirepass
  7. 1) "requirepass"
  8. 2) "myRedis"

3.master配置了密码,slave如何配置

若master配置了密码则slave也要配置相应的密码参数否则无法进行正常复制的。
slave中配置文件内找到如下行,移除注释,修改密码即可

[plain] view plain copy
  1. #masterauth  mstpassword

总结redis常用命令

关闭redis
[root@aaa myredis]# redis-cli -p 6379 shutdown

启动redis 我的redis配置文件独立复制出一份到/opt/myredis/redis.conf  如果你的conf文件在其他目录就用其他目录
[root@aaa myredis]# redis-server /opt/myredis/redis.conf

登录redis  a是密码
[root@aaa myredis]# redis-cli -p 6379 -a a

得到redis登录密码
127.0.0.1:6379> config get requirepass
1) "requirepass"
2) "a"