java 链接远程redis_Java连接远程Redis

1、服务器得安装好Redis ,安装步骤看另一篇博文《Redis下载安装与基本使用(linux下)》

2、安装好之后,修改访问端口以及设置密码

编辑  /usr/local/redis/etc/redis.conf

找到 bind 127.0.0.1  在前面加#号注释掉

6d389aa30aecf9466188f2f82dc50c6c.png

找到   # requirepass foobared

把#去掉  把foobared换成你要设置的密码

保存后重启 (修改端口也是在此配置文件中修改)

3、启动报错

/usr/local/redis/bin/redis-cli

Could not connect to Redis at 127.0.0.1:6379: Connection refused

Could not connect to Redis at 127.0.0.1:6379: Connection refused

解决方法:

先执行:redis-server /usr/local/redis/etc/redis.conf

再执行:redis-cli

0956042a9db04a0e4e39e7f31c770c3e.png

此时操作数据会报 (error) NOAUTH Authentication required.

执行 AUTH 刚刚设置的密码。比如:AUTH redispassword

5099b40b920a35d8c02444b6a7ba06e2.png

50132b4b488c4de76ea93a54f3fa1baf.png

此时服务器端已经设置好了

4、写入两条数据以供测试

set test helloworld

set test1 helloworld1

get test

get test1

keys *

2caa11da89bc2abfaacef391991c96c3.png

5、在项目pom文件中加入相关依赖

jedis 和 commons-pool  由于我用springboot管理版本,所以此处的依赖没有写版本

redis.clients

jedis

commons-pool

commons-pool

6、新建测试类

import redis.clients.jedis.Jedis;

public class redisJava {

@SuppressWarnings("resource")

public static void main(String[] args) {

/** 远程服务器IP **/

String host = "119.78.189.135";

/** Redis端口 **/

int port = 6379;

Jedis jedis = new Jedis(host, port);

/** 权限认证 没有设置密码的话可以除去此步骤 **/

jedis.auth("redispassword");

/** redis服务器存在key为test和test1为redis的数据 **/

System.out.println(jedis.get("test"));

System.out.println(jedis.get("test1"));

jedis.set("test2", "helloworld2");

System.out.println(jedis.get("test2"));

}

}

跑一下   输出结果如下

helloworld

helloworld1

helloworld2

以上就是最简单的连接例子。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值