redis java客户端connection refused问题

来源:互联网 发布:四川广电网络客服中心 编辑:程序博客网 时间:2024/05/21 09:17

java连接redis之前,确保项目中导入jedis.jar和commons-pool.jar。

在MyEclipse中创建java项目,

Jedis redis=new Jedis("Ip地址",6379);

redis.ping();

如果出现connection refused异常,可能有如下原因,:


1,服务未启动:

执行:lsof -i :6379

isof-i命令查看是否开启进程

结果如下,证明开启

COMMAND     PID USER   FD   TYPE DEVICE SIZE/OFF NODE NAME

redis-ser 11560 root    4u  IPv4  69938      0t0  TCP *:6379 (LISTEN)


2,进入redis.conf配置文件,我的配置文件在/etc/redis.conf

查看是否将默认只能本地访问redis改为所有IP均可以访问

bind 127.0.0.1 改为 bind 0.0.0.0 

查看端口号是否为6379


3,关闭防火墙测试:

systemctl stop firewalld.service

如果不在eclipse中测试程序,可以打开windows系统cmd,输入tenlent Ip 6379,若连接成功,则是防火墙阻挡外界访问,需要处理防火墙。

否则可能是redis安装问题,建议重新安装。


4,处理防火墙问题:

执行:netstat -ano

命令netstat-ano用于查看服务器对应的端口监听情况。

4.1,关闭防火墙

systemctl stop firewalld.service #停止firewall

systemctl disable firewalld.service #禁止firewall开机启动

4.2,设置 iptables service

yum -y install iptables-services

如果要修改防火墙配置,如增加防火墙端口6379

vi /etc/sysconfig/iptables 

增加规则

-A INPUT -p tcp -m state --state NEW -m tcp --dport 6379 -j ACCEPT

增加后iptables配置文件如下:

:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
-A INPUT -p icmp -j ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -p tcp -m state --state NEW -m tcp --dport 22 -j ACCEPT
-A INPUT -p tcp -m state --state NEW -m tcp --dport 6379 -j ACCEPT
-A INPUT -p tcp -m state --state NEW -m tcp --dport 8080 -j ACCEPT
-A INPUT -j REJECT --reject-with icmp-host-prohibited
-A FORWARD -j REJECT --reject-with icmp-host-prohibited
COMMIT

保存退出后

systemctl restart iptables.service #重启防火墙使配置生效

systemctl enable iptables.service #设置防火墙开机启动

4.3,重启使得配置文件生效

4.4,如果redis没有设置开机自动开启,利用service redis start开启redis服务

5,重新测试

lsof -i :6379确认开启redis服务

netstat -ano确认服务器对应监听端口6379开启

tenlent Ip地址 6379确认连接redis成功

6,在使用service redis stop关闭redis服务时可能出现:

/var/run/redis_6379.pid does not exist, process is not running  

这说明在run下没有这个文件,我们进入到/var/run下发先真的没有这个文件,但是有redis.pid文件。

 我们要将/etc/rc.d/init.d/redis 文件中的PIDFILE=/var/run/redis_${REDISPORT}.pid中

redis_${REDISPORT}.pid修改为redis.pid



2 0
原创粉丝点击