Java连接代码,需要导入jedis.jar包
public class JedisTest1 {
@Test
public void a(){
Jedis jedis = new Jedis("47.95.21.122",6379);
String username = jedis.get("username");
System.out.println(username);
}
}
执行后报错:
redis.clients.jedis.exceptions.JedisConnectionException: java.net.ConnectException: Connection refused: connect
解决:
打开 redis.conf 把bind 127.0.0.1 注释掉,如下
# bind 127.0.0.1
再执行,还是报错:
DENIED Redis is running in protected modebecause protected mode is enabled, no bind address was specified, noauthentication password is requested to clients.
In this mode connections areonly accepted from the loopback interface.
这是因为 redis 默认为保护模式,只允许本地链接,不允许远程连接
解决:
打开redis.conf 将保护模式设置为 no,如下
protected-mode no
现在执行,成功。
设置数据库连接验证密码
打开 redis.conf , 找到 requirePass ,将注释"#"去掉,设置成自己的密码
# requirepass foobared
requirepass redis123456
此时java代码中需要设置连接的密码
jedis.auth("123456");
连接池
@Test
public void b(){
JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
jedisPoolConfig.setMaxIdle(30); // 最大闲置个数: 当闲置的连接超过30时,开始关闭连接
jedisPoolConfig.setMinIdle(10); // 最小闲置个数: 保证连接池中至少有10个连接是闲置的,当闲置的连接小于10个时,创建新的连接
jedisPoolConfig.setMaxTotal(50); // 连接池中最大连接数 50
JedisPool jedisPool = new JedisPool(jedisPoolConfig,"47.95.213.329",6379,1000,"123456qq"); // 1000为允许超时时间,123456qq为
Jedis resource = jedisPool.getResource();
String username = resource.get("username");
System.out.println(username);
resource.set("hobby","basketball");
System.out.println(resource.get("hobby"));
resource.close();
}