在Redis官方给出了下列Java客户端
这里主要介绍一下两种使用Jedis来连接Redis的方法:
1、通过Jedis对象,每次创建一个连接
2、通过Jedis提供的连接池,用连接池连接Redis
源码如下:
package com.yf.redis;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
public class RedisOperator {
public static void main(String[] args) {
final String HOST = "192.168.1.182";
final int PORT = 6379;
singleThread(HOST, PORT);
mutiThread(HOST, PORT);
}
//通过Jedis对象与Redis建立连接,每个实例对应一个连接
public static void singleThread(String host, int port) {
Jedis jedis = new Jedis(host, port);
System.out.println(jedis.get("single"));
jedis.append("single", "test");
System.out.println(jedis.get("single"));
}
//通过JedisPool对象与Redis建立连接池
public static void mutiThread(String host, int port) {
JedisPool pool = null;
Jedis jedis = null;
try {
// JedisPool依赖于apache-commons-pools1
pool = new JedisPool(new JedisPoolConfig(), host, port);
jedis = pool.getResource();
jedis.set("muti", "bar");
System.out.println(jedis.get("muti"));
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != jedis) {
//释放已经用过的连接
pool.returnBrokenResource(jedis);
pool.destroy();
}
}
}
}
这里需要注意,使用JedisPool时,依赖于apache-commons-pools1