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

使用 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 。如下图:
使用 **Jedis** 连接 虚拟机错误解决_第1张图片

运行结果:
使用 **Jedis** 连接 虚拟机错误解决_第2张图片

补充
如果你遇到以下错误:
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,如下图所示:
这里写图片描述

你可能感兴趣的:(Redis)