2.1 Jedis的基本用法
Jedis提供了三种方式连接到Redis,即Jedis、JedisPool、SharedJedisPool,Jedis是单线程,而JedisPool和SharedJedisPool采用线程池的方式链接Redis,本章对Jedis、JedisPool的用法进行,SharedJedisPool的用法后续章节会展开描述。
通过Jedis连接Redis
实例化Jedis对象
Jedis jedis = new Jedis(host, port, timeout);
如果设置了密码,需要进行密码验证
jedis.auth(password); // 验证密码,如果有设置的话
完整代码如下
@Test
public void testJedis() {
String host = "192.168.1.222"; // redis地址
int port = 6379; //端口
int timeout = 10000; //超时时间
String password = "potato"; //redis密码
Jedis jedis = new Jedis(host, port, timeout);
// 验证密码,如果有设置的话
jedis.auth(password);
//进行简单的测试
check(jedis);
}
通过JedisPool连接Redis
JedisPool以线程池的方式连接到Redis上,并提供JedisPoolConfig对线程池进行配置,如
JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
jedisPoolConfig.setMaxTotal(200); // 最大连接数:能够同时建立的“最大链接个数”
jedisPoolConfig.setMaxIdle(20); // 最大空闲数:空闲链接数大于maxIdle时,将进行回收
jedisPoolConfig.setMinIdle(5); // 最小空闲数:低于minIdle时,将创建新的链接
jedisPoolConfig.setMaxWaitMillis(3000); //最大等待时间:单位ms
jedisPoolConfig.setTestOnBorrow(true); //使用连接时,检测连接是否成功
jedisPoolConfig.setTestOnReturn(true); //返回连接时,检测连接是否成功
从线程池中获取Jedis对象
Jedis jedis = jedisPool.getResource();
最终使用完成,需要关闭jedis,把线程还给JedisPool,如下
public void close(Jedis jedis) {
if (jedis != null) {
jedis.close();
}
}
完整代码如下:
@Test
public void testJedisPool() {
String host = "192.168.1.222"; // redis地址
int port = 6379; //端口
int timeout = 10000; //超时时间
String password = "potato"; //redis密码
JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
jedisPoolConfig.setMaxTotal(200); // 最大连接数:能够同时建立的“最大链接个数”
jedisPoolConfig.setMaxIdle(20); // 最大空闲数:空闲链接数大于maxIdle时,将进行回收
jedisPoolConfig.setMinIdle(5); // 最小空闲数:低于minIdle时,将创建新的链接
jedisPoolConfig.setMaxWaitMillis(3000); //最大等待时间:单位ms
jedisPoolConfig.setTestOnBorrow(true); //使用连接时,检测连接是否成功
jedisPoolConfig.setTestOnReturn(true); //返回连接时,检测连接是否成功
JedisPool jedisPool = new JedisPool(jedisPoolConfig, host, port, timeout, password);
Jedis jedis = jedisPool.getResource();
// 验证密码,如果有设置的话
jedis.auth(password);
//进行简单的测试
check(jedis);
//归还给线程池
close(jedis);
}
进行测试的代码如下:
Jedis的基本操作
// 写入
jedis.set("hello", "world");
//读取
String value = jedis.get("hello");
//删除
jedis.del("hello");
完整的测试方法如下:
public void check(Jedis jedis) {
String after = "hehe";
String before = "haha";
// 测试 读
String valueBefore = jedis.get("potato");
System.out.println("获取 potato : " + valueBefore);
Assert.check(before.equals(valueBefore));
//测试 写
jedis.set("potato", after);
String valueAfter = jedis.get("potato");
System.out.println("修改 potato : " + valueAfter);
Assert.check(after.equals(valueAfter));
//还原
jedis.set("potato", before);
}
常见问题
连接Redis的时候,可能会报以下错误
redis.clients.jedis.exceptions.JedisConnectionException: java.net.ConnectException: Connection refused
可能原因如下:
原因一:Redis设置了只能本机访问
解决方式:把配置文件 (如6379.conf )中的 bind 127.0.0.1
注释掉
原因二 开启了防火墙
解决方式:关闭防火墙
chkconfig iptables off