Redis入门(九)——Jedis的基本使用
目录
- Jedis简介与安装
- Jedis的常用API
- Jedis事物
- Jedis连接池
1.Jedis简介与安装
Jedis简介:
Jedis Client是Redis官网推荐的一个面向java客户端,库文件实现了对redis各类API进行封装调用。
Jedis的安装:Java操作Redis之前,首先需要确保已经安装了 redis 服务及 Java redis 驱动。并开启redis服务。
然后新建一个maven工程,在pom文件中添加对Jedis的依赖。等待maven下载完Jedis的jar包后,就可以使用Jedis了。
下面我们来写一个测试程序测试Jedis是否可以正常使用。测试代码如下:
package com.zyl.demo.JedisDemo; import junit.framework.TestCase; import redis.clients.jedis.Jedis; public class JedisTest extends TestCase { public void testJedis() { Jedis jedis = new Jedis("127.0.0.1", 6379); System.out.println(jedis.ping()); } }
此时可见程序最后输出PONG。表示我们已经成功连上redis服务。接下来可以通过Java代码操作redis数据库了。
2.Jedis的常用API
使用Jedis操作redis数据库跟直接操作redis的方式相同。下面的代码使用其中部分命令。(本程序中采用了TestNG测试框架)
package com.zyl.demo.JedisDemo; import org.testng.annotations.Test; import redis.clients.jedis.Jedis; import org.testng.annotations.BeforeSuite; import java.util.HashMap; import java.util.List; import java.util.Map; import org.testng.annotations.AfterSuite; public class JedisAPITest { private Jedis jedis; /** * Jedis操作字符串 */ @Test public void testString() { System.out.println("test Sting"); //添加数据 jedis.set("k1", "v1"); System.out.println("k1:"+jedis.get("k1")); //在k1后面追加新的值 jedis.append("k1", "new"); System.out.println("k1:"+jedis.get("k1")); //删除k1 jedis.del("k1"); System.out.println("k1:"+jedis.get("k1")); //设置多个k-v对 jedis.mset("name", "Ann","age","20","sex","F"); jedis.incr("age"); jedis.incrBy("age", 2); System.out.println("Student:"+jedis.mget("name","age","sex")); } /** * jedis操作List */ @Test public void testList() { System.out.println("====================================="); System.out.println("test List"); jedis.lpush("Fruits", "apple","orange","banana"); System.out.println("length:"+jedis.llen("Fruits")); System.out.println("Fruits:"+jedis.lrange("Fruits", 0, -1)); System.out.println("the frist fruit:"+jedis.lpop("Fruits")); } /** * jedis操作Map */ @Test public void testMap() { System.out.println("====================================="); System.out.println("test Map"); Map<String, String> map = new HashMap<String, String>(); map.put("id","1"); map.put("name","Lily"); map.put("email","Lily@abc.com"); jedis.hmset("user",map); List<String> list = jedis.hmget("user", "id","name"); System.out.println(list); System.out.println("user的键中存放的值的个数:" + jedis.hlen("user")); //返回key为user的键中存放的值的个数2 System.out.println("是否存在key为user的记录:" + jedis.exists("user"));//是否存在key为user的记录 返回true System.out.println("user对象中的所有key:" + jedis.hkeys("user"));//返回user对象中的所有key System.out.println("user对象中的所有value:" + jedis.hvals("user"));//返回map对象中的所有value
System.out.println("user对象中的所有value:" + jedis.hgetAll("user")); } /** * jedis操作Map */ public void testSet() { System.out.println("====================================="); System.out.println("test set"); jedis.sadd("set1", "member1"); jedis.sadd("set1", "member2"); jedis.sadd("set1", "member3"); jedis.srem("set1", "member3"); System.out.println("set1中全部的值:" + jedis.smembers("se1")); System.out.println("abc是否是set1中的元素:"+jedis.sismember("set1","abc"));//判断chx是否是user集合中的元素 System.out.println("集合中的一个随机元素:"+jedis.srandmember("set1"));//返回集合中的一个随机元素 System.out.println("set1中元素的个数:"+jedis.scard("set1")); } /** * jedis操作Map */ @Test public void testZset() { System.out.println("====================================="); System.out.println("test zset"); Map<String,Double> map = new HashMap<String,Double>(); map.put("ksy1",(double) 100); map.put("key2",(double) 80); map.put("key3",(double) 60); map.put("key4",(double) 40); jedis.zadd("zset1", map); System.out.println("大于等于60小于等于100的元素个数"+jedis.zcount("zset1", 60, 100)); System.out.println("key3排在第四位"+jedis.zrank("zset1","key3")); System.out.println("key4的分数"+jedis.zscore("zset1", "keys4")); System.out.println("大于等于60小于等于90的元素"+jedis.zrangeByScore("zset1",60,90)); System.out.println("删除key4"+jedis.zrem("zset1", "keys4")); } @BeforeSuite public void beforeSuite() { System.out.println("start to connect jedis......."); this.jedis = new Jedis("127.0.0.1", 6379); System.out.println(jedis.ping()); } @AfterSuite public void afterSuite() { jedis.close(); } }
相应的输出结果如下
3.Jedis事物
package com.zyl.demo.JedisDemo;
import java.util.ArrayList;
import java.util.List;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;
public class TestTX {
public boolean transMethon() throws InterruptedException {
Jedis jedis = new Jedis("127.0.0.1", 6379);
int balance = 100; //余额
int debt = 0; //欠额
int amtToSubtract = 10; //消费额
List<Object> result = new ArrayList<Object>();
jedis.watch("balance");
System.out.println("*********watching balance*****************");
Thread.sleep(10000);//这里预留时间可以去修改balance的值
balance = Integer.parseInt(jedis.get("balance"));
try {
// 若余额<消费额,提示余额不足
if (balance < amtToSubtract) {
jedis.unwatch();
System.out.println("not enough money");
return false;
} else {
System.out.println("*********transaction**************");
Transaction transaction= jedis.multi();
transaction.decrBy("balance", amtToSubtract);
transaction.incrBy("debt",amtToSubtract);
result = transaction.exec();
// 若执行结果的返回值为空,则说明执行失败
if (result == null) {
System.out.println("transaction execute failed");
return false;
}
balance = Integer.parseInt(jedis.get("balance"));
debt = Integer.parseInt(jedis.get("debt"));
System.out.println("balance:"+Integer.parseInt(jedis.get("balance")));
System.out.println("debt:"+Integer.parseInt(jedis.get("debt")));
}
}catch( Exception e) {
e.printStackTrace();
}finally {
jedis.close();
}
System.out.println("your account costs ¥10");
return true;
}
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
boolean reValue;
TestTX testTX = new TestTX();
reValue = testTX.transMethon();
System.out.println("reValue:"+reValue);
}
}
4. Jedis连接池
JedisPool在创建时初始化一些连接资源存储到连接池中,使用Jedis连接资源时不需要创建,而是从连接池中获取一个资源进行redis的操作,使用完毕后,不需要销毁该jedis连接资源,而是将该资源归还给连接池,供其他请求使用。
下面通过一个简单的程序说明Jedis连接池的使用。首先利用单例模式来写一个获取Jedis池的工具类。
package com.zyl.demo.JedisDemo; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig; public class JedisPoolUitl { private static volatile JedisPool jedisPool = null; private JedisPoolUitl() {} public static JedisPool getJedisPoolInstance() { if (null == jedisPool) { synchronized(JedisPoolUitl.class) { if (null == jedisPool) {//双端检索机制 JedisPoolConfig poolConfig = new JedisPoolConfig(); poolConfig.setMaxTotal(1000); poolConfig.setMaxIdle(32); poolConfig.setMaxWaitMillis(100*1000); poolConfig.setTestOnBorrow(true); jedisPool = new JedisPool(poolConfig,"127.0.0.1",6379); } } } return jedisPool; } public static void release(final Jedis jedis){//释放资源 if (null != jedis) { jedis.close(); } } }
然后通过Jedis池新建Jedis实例,通过实例往redis写入数据。
package com.zyl.demo.JedisDemo; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; public class TestJedisPool { public static void main(String[] args) { // TODO Auto-generated method stub JedisPool jedisPool = JedisPoolUitl.getJedisPoolInstance(); //JedisPool jedisPool1 = JedisPoolUitl.getJedisPoolInstance(); //System.out.println(jedisPool == jedisPool1); Jedis jedis = new Jedis(); try { jedis = jedisPool.getResource(); if (null != jedis.get("aa")) { jedis.del("aa"); } System.out.println("aa:"+jedis.get("aa")); jedis.set("aa", "bb"); Thread.sleep(2000);//暂停两秒。保证数据已经成功写入redis System.out.println("aa:"+jedis.get("aa")); } catch (Exception e) { e.printStackTrace(); }finally { JedisPoolUitl.release(jedis); } } }