java对redis的操作
需要两个包的支持
jedis-2.1.0.jar
commons-pool-1.5.4.jar
一个连接池一个工具类
pool代码
1 public class RedisUtil { 2 3 private static String ADDR = "127.0.0.1"; 4 5 private static int PORT = 6379; 6 7 private static String AUTH = "123456789"; 8 9 private static int MAX_ACTIVE = 1024; 10 11 private static int MAX_IDLE = 200; 12 13 private static int MAX_WAIT = 10000; 14 15 private static int TIMEOUT = 10000; 16 17 private static boolean TEST_ON_BORROW = true; 18 19 private static JedisPool jedisPool = null; 20 21 static { 22 try { 23 JedisPoolConfig config = new JedisPoolConfig(); 24 config.setMaxActive(MAX_ACTIVE); 25 config.setMaxIdle(MAX_IDLE); 26 config.setMaxWait(MAX_WAIT); 27 config.setTestOnBorrow(TEST_ON_BORROW); 28 jedisPool = new JedisPool(config, ADDR, PORT, TIMEOUT, AUTH); 29 } catch (Exception e) { 30 e.printStackTrace(); 31 } 32 } 33 34 public synchronized static Jedis getJedis() { 35 try { 36 if (jedisPool != null) { 37 Jedis resource = jedisPool.getResource(); 38 return resource; 39 } else { 40 return null; 41 } 42 } catch (Exception e) { 43 e.printStackTrace(); 44 return null; 45 } 46 } 47 48 public static void returnResource(final Jedis jedis) { 49 if (jedis != null) { 50 jedisPool.returnResource(jedis); 51 } 52 } 53 }
工具类的代码
1 public void tools() { 2 //连接redis服务器 3 jedis = new Jedis("127.0.0.1", 6379); 4 //权限认证 5 jedis.auth("123456789"); 6 //-----添加数据---------- 7 jedis.set("name","xinxin");//向key-->name中放入了value-->xinxin 8 System.out.println(jedis.get("name"));//执行结果:xinxin 9 10 jedis.append("name", " is my lover"); //拼接 11 System.out.println(jedis.get("name")); 12 13 jedis.del("name"); //删除某个键 14 System.out.println(jedis.get("name")); 15 }
实际上
set就包括插入修改的功能
get查询,一定有结果,应用时应判断查询结果是不是null
del删除