Redis使用jedis如何连接远程服务器或者虚拟机

发布时间 2023-07-06 11:31:05作者: HFUUwzy
  1. pom文件中导入jedis
<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>4.4.0</version>
</dependency>
  1. 开启虚拟机的防火墙,可以指定端口6379
firewall-cmd --zone=public --add-port=6379/tcp --permanent (--permanent  是永久生效,没有此参数重启后失效,加不加都可以执行成功~)
  1. 注释redis.conf中的bind 127.0.0.1

  2. 另一种是在redis.conf中把protected-mode设置为no,允许外部访问,然后再把bind的ip从127.0.0.1改成0.0.0.0(0.0.0.0包含了127.0.0.1和服务器内网网卡ip,如果只bind服务器内网网卡ip那就会造成内部无法访问),为了安全要设置密码(本人没有测试这种方法)

    bind绑定的ip是针对本机(即服务器)而言的,绑定的是内网IP,比如127.0.0.1或者本地网卡的IP;外网IP在对服务器的内网IP+端口进行端口映射后才会与之形成映射关系,所以你绑定外网IP没有效果。有兴趣可以了解下端口映射。。。
    
  3. 在redis.conf中设置密码,查找requirepass foobared 可以设置为 123456

  4. shutdown关闭服务器并重启,进入cli后,执行命令 auth 123456(your password),否则提示NOAUTH Authentication required

  5. 最后在IDEA中连接ping测试即可,提示pong则成功

Jedis jedis = new Jedis(your port, 6379);
jedis.auth("123456");
System.out.println(jedis.ping());