Linux安裝好Redis之后,使用Java進(jìn)行連接,Java代碼如下
package com.wzj.demo.test;
import redis.clients.jedis.Jedis;
/**
* Created by wzj on 2018/3/29.
*/
public class RedisJava
{
public static void main(String[] args)
{
//連接本地的 Redis 服務(wù)
Jedis jedis = new Jedis("192.168.3.45");
System.out.println("連接成功");
//設(shè)置 redis 字符串?dāng)?shù)據(jù)
jedis.set("runoobkey", "www.runoob.com");
// 獲取存儲(chǔ)的數(shù)據(jù)并輸出
System.out.println("redis 存儲(chǔ)的字符串為: "+ jedis.get("runoobkey"));
}
}
報(bào)如下錯(cuò)誤:
Exception in thread "main" redis.clients.jedis.exceptions.JedisConnectionException: java.net.SocketException: Connection reset
at redis.clients.util.RedisInputStream.ensureFill(RedisInputStream.java:202)
at redis.clients.util.RedisInputStream.readByte(RedisInputStream.java:40)
at redis.clients.jedis.Protocol.process(Protocol.java:151)
at redis.clients.jedis.Protocol.read(Protocol.java:215)
at redis.clients.jedis.Connection.readProtocolWithCheckingBroken(Connection.java:340)
at redis.clients.jedis.Connection.getStatusCodeReply(Connection.java:239)
at redis.clients.jedis.Jedis.set(Jedis.java:121)
at com.wzj.demo.test.RedisJava.main(RedisJava.java:17)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
Caused by: java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(SocketInputStream.java:209)
at java.net.SocketInputStream.read(SocketInputStream.java:141)
at java.net.SocketInputStream.read(SocketInputStream.java:127)
at redis.clients.util.RedisInputStream.ensureFill(RedisInputStream.java:196)
... 12 more
使用Telnet 192.168.3.45 6379,發(fā)現(xiàn)端口是不通的。
通過網(wǎng)上查找分析,原因是:Redis默認(rèn)只允許本地連接,不允許其他機(jī)器連接,需要進(jìn)行如下修改:
(1)修改redis.conf 文件,把bind 127.0.0.1 ::1這一行注釋掉。
(2)修改redis.conf 文件,protected-mode 要設(shè)置成no
(3)啟動(dòng)的時(shí)候,需要指定redis.conf 文件,執(zhí)行./src/redis-server redis.conf命令
設(shè)置之后,重啟測(cè)試,發(fā)現(xiàn)Java代碼可以正常連接了。
以上這篇Linux下Redis允許遠(yuǎn)程連接的實(shí)現(xiàn)方法就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。