需要两个包的支持
jedis-2.1.0.jar
commons-pool-1.5.4.jar
一个连接池一个工具类
pool代码
public class RedisUtil { private static String ADDR = "127.0.0.1"; private static int PORT = 6379; private static String AUTH = "123456789"; private static int MAX_ACTIVE = 1024; private static int MAX_IDLE = 200; private static int MAX_WAIT = 10000; private static int TIMEOUT = 10000; private static boolean TEST_ON_BORROW = true; private static JedisPool jedisPool = null; static {
try {
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxActive(MAX_ACTIVE);
config.setMaxIdle(MAX_IDLE);
config.setMaxWait(MAX_WAIT);
config.setTestOnBorrow(TEST_ON_BORROW);
jedisPool = new JedisPool(config, ADDR, PORT, TIMEOUT, AUTH);
} catch (Exception e) {
e.printStackTrace();
}
} public synchronized static Jedis getJedis() {
try {
if (jedisPool != null) {
Jedis resource = jedisPool.getResource();
return resource;
} else {
return null;
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
} public static void returnResource(final Jedis jedis) {
if (jedis != null) {
jedisPool.returnResource(jedis);
}
}
}
工具类的代码
public void tools() {
//连接redis服务器
jedis = new Jedis("127.0.0.1", 6379);
//权限认证
jedis.auth("123456789");
//-----添加数据----------
jedis.set("name","xinxin");//向key-->name中放入了value-->xinxin
System.out.println(jedis.get("name"));//执行结果:xinxin jedis.append("name", " is my lover"); //拼接
System.out.println(jedis.get("name")); jedis.del("name"); //删除某个键
System.out.println(jedis.get("name"));
}
实际上
set就包括插入修改的功能
get查询,一定有结果,应用时应判断查询结果是不是null
del删除