Jedis是java调用Redis的接口。
一。Maven中的jedis依赖包
<!-- https://mvnrepository.com/artifact/redis.clients/jedis -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
二。配置redis.properties.xml
# *************** jedis connection parameters setting ************** #
# redis server ip #
redis.ip=127.0.0.1
# redis server port #
redis.port=6379
# password
redis.password=redis123 # *************** jedis pool parameters setting ************** #
# jedis's max connected objects #
redis.pool.maxTotal=1000
# jedis's max saved idel objects #
redis.pool.maxIdle=10
# jedis's max waiting time when no object returnd #
redis.pool.maxWaitMillis=5000
# whether test when jedis is calling borrowObject() #
redis.pool.testOnBorrow=true
# whether test when jedis is calling returnObject() #
redis.pool.testOnReturn=true
三。编写JAVA类获取Jedis连接池
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig; import java.io.IOException;
import java.util.Properties; /**
* Created by XA on 2017/11/6.
*/
public class MyJedisPool { private volatile static JedisPool pool;
private static Jedis jedis; private static JedisPool getJedisPool() {
if(pool==null) {
synchronized (MyJedisPool.class) {
if(pool==null) {
try{
Properties props = new Properties();
props.load(MyJedisPool.class.getClassLoader().getResourceAsStream("config/redis.properties"));
// create jedis pool instance
JedisPoolConfig config = new JedisPoolConfig();
// set property items of jedis pool
config.setMaxTotal(Integer.valueOf(props.getProperty("redis.pool.maxTotal")));
config.setMaxIdle(Integer.valueOf(props.getProperty("redis.pool.maxIdle")));
config.setMaxWaitMillis(Integer.valueOf(props.getProperty("redis.pool.maxWaitMillis")));
config.setTestOnBorrow(Boolean.valueOf(props.getProperty("redis.pool.testOnBorrow")));
config.setTestOnReturn(Boolean.valueOf(props.getProperty("redis.pool.testOnReturn")));
// instance
pool = new JedisPool(config, props.getProperty("redis.ip"), Integer.valueOf(props.getProperty("redis.port")), 5000, props.getProperty("redis.password")); }catch (IOException e) {
e.printStackTrace();
}
}
}
}
return pool;
} // get jedis
public static Jedis getJedis() {
return getJedisPool().getResource();
} // recycle jedis
public synchronized static void recycleJedis(Jedis jedis) {
if(jedis!=null) {
jedis.close();
}
}
}
四。使用jedis的常用示例
public static void main(String[] args){
try{
Jedis jedis = MyJedisPool.getJedis();
Set<String> keys = jedis.keys("*");
System.out.println(keys.size());
}catch (Exception e) {
e.printStackTrace();
}finally {
MyJedisPool.recycleJedis(jedis);
} }
注意:1. 不要忘记调用recycleJedis()回收jedis示例
2. 实际调用recycleJedis()后发现,jedis仍然有效。原因暂时未知。
五。使用反射和泛型封装jedis的申请和回收
@SuppressWarnings("unchecked")
public static <T> T invokeJedisMethod(String methodName, Object[] args) {
Jedis jedis = MyJedisPool.getJedis(); T returnObject = null;
try {
Class[] argsTypes = new Class[args.length];
for (int i = 0; i < args.length; i++) {
Class argClazz = args[i].getClass();
if (argClazz.equals(HashMap.class)) {
argsTypes[i] = Map.class;
} else {
argsTypes[i] = argClazz;
} }
Method method = jedis.getClass().getDeclaredMethod(methodName, argsTypes); returnObject = (T) method.invoke(jedis, args);
} catch (Exception e) {
System.out.print(e.getStackTrace()[1].getClassName() + " --> " +
e.getStackTrace()[1].getMethodName() + " --> " +
e.getClass().getName() + "\n");
e.printStackTrace();
} finally {
MyJedisPool.recycleJedis(jedis);
}
return returnObject;
}
运行测试:
import org.junit.Assert;
import org.junit.Test;
import org.springframework.test.annotation.Rollback;
import org.springframework.transaction.annotation.Transactional; import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set; public class JedisServiceTest { public enum CommonAPI {
// keys
keys("keys", 1), del("del", 20), exists("exists", 22),
// hash
hget("hget", 2), hgetAll("hgetAll", 3), hset("hset", 4), hmset("hmset", 5), hlen("hlen", 6), hexists("hexists", 7), hdel("hdel", 8), hkeys("hkeys", 9), hmget("hmget", 23),
// zsort
zadd("zadd", 10), zrem("zrem", 11), zrange("zrange", 12), zcard("zcard", 13), zcount("zcount", 14),
// list
linsert("linsert", 15), llen("llen", 16), lpop("lpop", 17), lpush("lpush", 18), lrange("lrange", 19),
// sub-pub
subscribe("subscribe", 21); private String name;
private int index; CommonAPI(String name, int index) {
this.name = name;
this.index = index;
} public String getName() {
return name;
}
} /**
* 事务回滚无效,redis并不支持可回滚的事务
*/
@Test
@Transactional
@Rollback
public void invokeJedisMethod() { //
JedisService.invokeJedisMethod(JedisService.CommonAPI.hset.getName(), new Object[]{"key1", "hkey1", "value1"});
Assert.assertTrue(JedisService.invokeJedisMethod(JedisService.CommonAPI.exists.getName(), "key1"));
Set<String> keys = JedisService.invokeJedisMethod(JedisService.CommonAPI.keys.getName(), "key1");
Assert.assertTrue(keys.contains("key1")); Assert.assertTrue(JedisService.invokeJedisMethod(JedisService.CommonAPI.hexists.getName(), new Object[] {"key1", "hkey1"}));
Set<String> hkeys = JedisService.invokeJedisMethod(JedisService.CommonAPI.hkeys.getName(), "key1");
Assert.assertTrue(hkeys.contains("hkey1")); Assert.assertEquals(JedisService.invokeJedisMethod(JedisService.CommonAPI.hget.getName(), new Object[] {"key1", "hkey1"}), "value1"); JedisService.invokeJedisMethod(JedisService.CommonAPI.hdel.getName(), new Object[] {"key1", new String[]{"hkey1"}});
Assert.assertFalse(JedisService.invokeJedisMethod(JedisService.CommonAPI.hexists.getName(), new Object[] {"key1", "hkey1"})); JedisService.invokeJedisMethod(JedisService.CommonAPI.del.getName(), "key1");
Assert.assertFalse(JedisService.invokeJedisMethod(JedisService.CommonAPI.exists.getName(), "key1")); //
Map<String, String> map = new HashMap<String, String>();
map.put("hkey1", "hvalue1");map.put("hkey2", "hvalue2");
JedisService.invokeJedisMethod(JedisService.CommonAPI.hmset.getName(), new Object[] {"key2", map});
Assert.assertTrue(JedisService.invokeJedisMethod(JedisService.CommonAPI.exists.getName(), "key2"));
Assert.assertTrue(JedisService.invokeJedisMethod(JedisService.CommonAPI.hexists.getName(), new Object[] {"key2", "hkey2"}));
Assert.assertEquals(JedisService.invokeJedisMethod(JedisService.CommonAPI.hget.getName(), new Object[] {"key2", "hkey2"}), "hvalue2");
Assert.assertEquals((long)JedisService.invokeJedisMethod(JedisService.CommonAPI.hlen.getName(), "key2"), map.size()); Map<String, String> res = JedisService.invokeJedisMethod(JedisService.CommonAPI.hgetAll.getName(), "key2");
Assert.assertEquals(res.size(), map.size()); List<String> hvalues = JedisService.invokeJedisMethod(JedisService.CommonAPI.hmget.getName(), new Object[] {"key2", map.keySet().toArray(new String[map.size()])});
Assert.assertEquals(hvalues.size(), 2);
Assert.assertTrue(hvalues.contains("hvalue1"));
Assert.assertTrue(hvalues.contains("hvalue2")); JedisService.invokeJedisMethod(JedisService.CommonAPI.del.getName(), "key2");
Assert.assertFalse(JedisService.invokeJedisMethod(JedisService.CommonAPI.exists.getName(), "key2")); } }
测试全部通过。