使用 **Jedis** 连接 虚拟机错误解决

本文介绍使用Jedis客户端连接Redis服务器时遇到的连接拒绝错误及解决方法,包括关闭虚拟机防火墙、修改Redis配置文件等步骤,并针对特定错误提供详细解决方案。

使用 Jedis 连接 虚拟机报错,错误如下:
redis.clients.jedis.exceptions.JedisConnectionException: java.net.ConnectException: Connection refused: connect

代码如下:

public void demo(){
        //获得连接池配置对象
        JedisPoolConfig config = new JedisPoolConfig();
        //获得最大连接数
        config.setMaxTotal(30);
        //设置最小连接数
        config.setMinIdle(10);
        //获得连接池
        JedisPool jp = new JedisPool(config,"192.168.234.129",6379);
        //获得核心对象
        Jedis jedis = null;
        try {
            jedis = jp.getResource();
            jedis.set("qqq", "成功了");
            // 
            String value = jedis.get("qqq");
            //
            System.out.println(value);
        } catch (Exception e) {
            // TODO: handle exception
        } finally {
            if (jedis != null) {
                jedis.close();
            }
            if (jp != null) {
                jp.close();
            }
        }
    }

解决步骤如下:
1、关闭虚拟机的防火墙,步骤如下
1.1、chkconfig iptables off
1.2、检查防火墙状态 /etc/init.d/iptables status
1.3、重启虚拟机
1.4、再次检查防火墙状态如下图
这里写图片描述

2、修改redis.conf配置文件,将端口号127.0.0.1注释掉或者改为0.0.0.0 。如下图:
这里写图片描述

运行结果:
这里写图片描述

补充
如果你遇到以下错误:
Exception in thread “main” redis.clients.jedis.exceptions.JedisDataException: 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.

解决方案如下:
修改redis.conf配置文件,将protected-mode yes 改为no,如下图所示:
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值