1、服务器得安装好Redis ,安装步骤看另一篇博文《Redis下载安装与基本使用(linux下)》
2、安装好之后,修改访问端口以及设置密码
编辑 /usr/local/redis/etc/redis.conf
找到 bind 127.0.0.1 在前面加#号注释掉
找到 # 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
此时操作数据会报 (error) NOAUTH Authentication required.
执行 AUTH 刚刚设置的密码。比如:AUTH redispassword
此时服务器端已经设置好了
4、写入两条数据以供测试
set test helloworld
set test1 helloworld1
get test
get test1
keys *
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
以上就是最简单的连接例子。