这里用的是Ubuntu的linux虚拟机安装配置redis4.0.14
首先在官网下载redis压缩包 官网地址
下载后进入linux系统,将压缩包放到要安装的目录下,我这里放在了/usr/local/redis中
解压redis压缩包
解压完成后,首先确认你的linux有没有安装gcc编译器,如果没有,先安装gcc。如果使用的是Centos就直接使用yum命令来安装gcc,我这里用的是Ubuntu,所以使用以下命令
sudo apt-get install -y gcc
安装好后如下图显示
然后进入到刚才解压过后的redis目录中,执行以下命令:
make MALLOC=libc
等待redis安装完成,完成后如下图所示:
安装完成后,进入redis安装目录下的src文件夹
可以看到其中有两个文件redis-server和redis-cli
首先我们启动redis,执行./redis-server命令,成功启动后如下图:
可以看到端口号为6379也就是说我们后面访问redis要通过6379端口。
接下来进行简单的测试,在redis目录下启动redis-cli,输入set “key” “value”存入数据,再输入get “key”取得数据。
创建一个maven项目,添加jedis依赖。
redis.clients jedis 2.9.0
在Linux虚拟机中启动redis,测试项目中创建测试类如下:
public class RedisTest {
public static void main(String[] args) {
//连接本地的 Redis 服务
Jedis jedis = new Jedis("10.211.55.5");
//设置 redis 字符串数据
jedis.set("key02", "banana");
// 获取存储的数据并输出
System.out.println("redis 存储的字符串为: "+ jedis.get("key02"));
}
}
运行程序,报错:
objc[15063]: Class JavaLaunchHelper is implemented in both /Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home/bin/java (0x10412e4c0) and /Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home/jre/lib/libinstrument.dylib (0x1061c04e0). One of the two will be used. Which one is undefined.
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服务失败,因为开启了保护模式,绑定了访问地址,也给出了几个解决办法。
打开redis的配置文件
内容如下,其中有两项配置需要修改,一个是bind 127.0.0.0 表示redis只接受本地请求的访问,这里将bind注释掉
另一项就是protected-mode yes表示开启保护模式,这里将它关掉,yes改为no,保存并关闭。
按下command+c,输入./redis-server ../redis.conf 重启redis并启用配置,启动测试程序进行测试,结果如下