Java连接远程Redis

本文介绍如何在Linux环境下安装配置Redis,并通过Java进行连接及简单操作。包括修改Redis配置文件、设置密码、解决常见错误及示例代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

https://my.oschina.net/xiaozhiwen/blog/912185

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

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

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

141008_tEZf_2437179.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

141308_3CCD_2437179.png

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

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

141406_3tPj_2437179.png

141440_hd2b_2437179.png

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

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

set test helloworld

set test1 helloworld1

get test

get test1

keys *

141629_iXXF_2437179.png

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

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

		<dependency>
			<groupId>redis.clients</groupId>
			<artifactId>jedis</artifactId>
		</dependency>
		<dependency>
			<groupId>commons-pool</groupId>
			<artifactId>commons-pool</artifactId>
		</dependency>

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

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

 

 

 

 

 

 

 

转载于:https://my.oschina.net/xiaozhiwen/blog/1589753

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值