- jedis:Java操作redis数据库的工具
- 下载两个jar包:commons-pool2-2.9.0.jar jedis-2.9.0.jar
jedis操作String
set(key,value)
get(key)
setex(key,time,value)
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| @Test public void test(){ Jedis jedis = new Jedis("127.0.0.1",6379); jedis.set("username","hxx"); String username = jedis.get("username"); System.out.println(username); jedis.setex("activecode",20,"hehe"); jedis.close(); }
|
jedis操作hash
hset(key,field,value)
hget(key,field)
hgetAll(key)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| @Test public void test1(){ Jedis jedis = new Jedis("127.0.0.1",6379); jedis.hset("user","name","hxx"); jedis.hset("user","age","20"); String name = jedis.hget("user", "name"); System.out.println(name); Map<String, String> user = jedis.hgetAll("user"); Set<String> keySet = user.keySet(); for (String field : keySet) { System.out.println(field+":"+user.get(field)); } jedis.close(); }
|
jedis操作list
lpush/rpush
lpop/rpop
lrange start end
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| @Test public void test2(){ Jedis jedis = new Jedis("127.0.0.1",6379); jedis.lpush("mylist","a","b","c"); jedis.rpush("mylist","a","b","c"); List<String> mylist = jedis.lrange("mylist", 0, -1); System.out.println(mylist);
jedis.lpop("mylist"); jedis.rpop("mylist");
jedis.close(); }
|
jedis操作set
sadd
smembers:获取所有元素
1 2 3 4 5 6 7 8 9 10 11
| @Test public void test3(){ Jedis jedis = new Jedis("127.0.0.1",6379); jedis.sadd("myset","a","a","b"); Set<String> myset = jedis.smembers("myset"); System.out.println(myset); jedis.close(); }
|
jedis操作sortedset
zadd
zrange
1 2 3 4 5 6 7 8 9 10 11 12
| @Test public void test4(){ Jedis jedis = new Jedis("127.0.0.1",6379); jedis.zadd("sortedset",3,"hxx"); jedis.zadd("sortedset",4,"qzy"); Set<String> myset = jedis.zrange("sortedset",0,-1); System.out.println(myset); jedis.close(); }
|
jedis连接池
创建连接池对象JedisPool
调用方法getReasource获取Jedis连接
1 2 3 4 5 6 7 8 9 10 11 12
| @Test public void test5(){ JedisPoolConfig config = new JedisPoolConfig(); config.setMaxTotal(2);
JedisPool jedisPool = new JedisPool(config,"127.0.0.1",6379); JedisPool jedisPool1 = new JedisPool(); Jedis jedis = jedisPool.getResource(); jedis.close(); }
|
jedis工具类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| public class JedisBeanUtils { private static JedisPool jedisPool; static { InputStream is = JedisBeanUtils.class.getClassLoader().getResourceAsStream("jedis.properties"); Properties pro = new Properties(); try { pro.load(is); } catch (IOException e) { e.printStackTrace(); } JedisPoolConfig config = new JedisPoolConfig(); config.setMaxTotal(Integer.parseInt(pro.getProperty("maxTotal"))); config.setMaxIdle(Integer.parseInt( pro.getProperty("maxIdle"))); jedisPool = new JedisPool(config,pro.getProperty("host"), Integer.parseInt(pro.getProperty("port"))); } public static Jedis getJedis(){ return jedisPool.getResource(); } } @Test public void test6(){ Jedis jedis = JedisBeanUtils.getJedis(); jedis.set("name","hxx"); jedis.close(); }
|