当前位置 : 主页 > 编程语言 > java >

Redis专题(十三)-Redis的Java客户端Jedis

来源:互联网 收集:自由互联 发布时间:2022-07-04
1.项目中添加redis和junit的依赖 dependencies !-- jedis客户端 -- dependency groupId redis.clients / groupId artifactId jedis / artifactId version 3.0.1 / version / dependency !--Junit测试依赖-- dependency groupId junit / group

1.项目中添加redis和junit的依赖

<dependencies>

<!-- jedis客户端 -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>3.0.1</version>
</dependency>

<!--Junit测试依赖-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>

</dependencies>

2.创建JedisUtil工具类

/**
* @author bruceliu
* @create 2019-06-09 22:32
* @description Jedis工具类
*/
public class JedisUtil {

private static JedisUtil jedisUtil;

private JedisUtil(){};

public static JedisUtil getInstance(){
if (jedisUtil == null){
synchronized(JedisUtil.class){
if (jedisUtil == null){
jedisUtil = new JedisUtil();
}
}
}
return jedisUtil;
}

//Jedis的连接池
private static Map<String,JedisPool> maps = new HashMap<String,JedisPool>();

private static JedisPool getPool(String ip, int port){
String key = ip+":"+port;
JedisPool pool = null;
if(!maps.containsKey(key)){
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxIdle(RedisConfig.MAX_IDLE);
config.setMinIdle(RedisConfig.MIN_IDLE);
config.setMaxTotal(RedisConfig.MAX_TOTAL);
config.setMaxWaitMillis(RedisConfig.MAX_WAIT);
config.setTestOnBorrow(true);
config.setTestOnReturn(true);

pool = new JedisPool(config,ip,port,RedisConfig.TIMEOUT);
maps.put(key, pool);
}else{
pool = maps.get(key);
}
return pool;
}

public Jedis getJedis(String ip, int port){
Jedis jedis = null;
int count = 0;
do{
try{
jedis = getPool(ip,port).getResource();
}catch (Exception e){
getPool(ip,port).close ();
}
}while(jedis == null && count<RedisConfig.RETRY_NUM);
return jedis;
}

public void closeJedis(Jedis jedis, String ip, int port){
if(jedis != null){
getPool(ip,port).close();
}
}

public static class RedisConfig {
//最大实例总数
public static int MAX_TOTAL = 150;

//最大空闲连接数, 默认8个
public static int MAX_IDLE = 100;

//最小空闲连接数, 默认8个
public static int MIN_IDLE = 10;

//等待可用连接的最大时间,单位毫秒,默认值为-1,表示永不超时。如果超过等待时间,则直接抛出JedisConnectionException;
public static int MAX_WAIT = 10000;

public static int TIMEOUT = 10000;

public static int RETRY_NUM = 5;

public RedisConfig(){};
}
}

3.用Juint单元测试命令操作1.静态变量,ip,端口号

3.1.静态变量,ip,端口号
private static final String ipAddr = "192.168.16.XXX";
private static final int port = 6379;
private static Jedis jedis = null;
3.2.测试类方法执行之前从连接池中获取jedis对象,执行之后关闭jedis对象
@Before
public void init() { jedis = JedisUtil.getInstance().getJedis(ipAddr, port); }
@After
public void close() { JedisUtil.getInstance().closeJedis(jedis,ipAddr, port); }
3.1.静态变量,ip,端口号

4.对key操作的命令

@Test
public void testKey(){
System.out.println("清空数据:"+jedis.flushDB());
System.out.println("判断某个键是否存在:"+jedis.exists("username"));
System.out.println("新增<'username','zzh'>的键值对:"+jedis.set("username", "zzh"));
System.out.println("新增<'password','password'>的键值对:"+jedis.set("password", "password"));
System.out.print("系统中所有的键如下:");
Set<String> keys = jedis.keys("*");
System.out.println(keys);
System.out.println("删除键password:"+jedis.del("password"));
System.out.println("判断键password是否存在:"+jedis.exists("password"));
System.out.println("查看键username所存储的值的类型:"+jedis.type("username"));
System.out.println("随机返回key空间的一个:"+jedis.randomKey());
System.out.println("重命名key:"+jedis.rename("username","name"));
System.out.println("取出改后的name:"+jedis.get("name"));
System.out.println("切换数据库(Redis默认有0-15个数据库):"+jedis.select(0));
System.out.println("删除当前选择数据库中的所有key:"+jedis.flushDB());
System.out.println("返回当前数据库中key的数目:"+jedis.dbSize());
System.out.println("删除所有数据库中的所有key:"+jedis.flushAll());
}

5.对String操作的命令

@Test
public void testString(){
jedis.flushDB();
System.out.println("===========增加数据===========");
System.out.println(jedis.set("key1","value1"));
System.out.println(jedis.set("key2","value2"));
System.out.println(jedis.set("key3", "value3"));
System.out.println("删除键key2:"+jedis.del("key2"));
System.out.println("获取键key2:"+jedis.get("key2"));
System.out.println("修改key1:"+jedis.set("key1", "value1Changed"));
System.out.println("获取key1的值:"+jedis.get("key1"));
System.out.println("在key3后面加入值:"+jedis.append("key3", "End"));
System.out.println("key3的值:"+jedis.get("key3"));
System.out.println("增加多个键值对:"+jedis.mset("key01","value01","key02","value02","key03","value03"));
System.out.println("获取多个键值对:"+jedis.mget("key01","key02","key03"));
System.out.println("获取多个键值对:"+jedis.mget("key01","key02","key03","key04"));
System.out.println("删除多个键值对:"+jedis.del(new String[]{"key01","key02"}));
System.out.println("获取多个键值对:"+jedis.mget("key01","key02","key03"));

jedis.flushDB();
System.out.println("===========新增键值对防止覆盖原先值==============");
System.out.println(jedis.setnx("key1", "value1"));
System.out.println(jedis.setnx("key2", "value2"));
System.out.println(jedis.setnx("key2", "value2-new"));
System.out.println(jedis.get("key1"));
System.out.println(jedis.get("key2"));

System.out.println("===========新增键值对并设置有效时间=============");
System.out.println(jedis.setex("key3", 2, "value3"));
System.out.println(jedis.get("key3"));
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(jedis.get("key3"));

System.out.println("===========获取原值,更新为新值==========");
System.out.println(jedis.getSet("key2", "key2GetSet"));
System.out.println(jedis.get("key2"));

System.out.println("获得key2的值的字串:"+jedis.getrange("key2", 2, 4));
}

6.对List操作命令

@Test
public void testList(){
jedis.flushDB();
System.out.println("===========添加一个list===========");
//jedis.lpush("collections", "ArrayList", "Vector", "Stack", "HashMap", "WeakHashMap", "LinkedHashMap");
jedis.lpush("collections", "HashSet");
jedis.lpush("collections", "TreeSet");
jedis.lpush("collections", "TreeMap");
System.out.println("collections的内容:"+jedis.lrange("collections", 0, -1));//-1代表倒数第一个元素,-2代表倒数第二个元素,end为-1表示查询全部
System.out.println("collections区间0-3的元素:"+jedis.lrange("collections",0,3));
System.out.println("===============================");
// 删除列表指定的值 ,第二个参数为删除的个数(有重复时),后add进去的值先被删,类似于出栈
System.out.println("删除指定元素个数:"+jedis.lrem("collections", 2, "HashMap"));
System.out.println("collections的内容:"+jedis.lrange("collections", 0, -1));
System.out.println("删除下表0-3区间之外的元素:"+jedis.ltrim("collections", 0, 3));
System.out.println("collections的内容:"+jedis.lrange("collections", 0, -1));
System.out.println("collections列表出栈(左端):"+jedis.lpop("collections"));
System.out.println("collections的内容:"+jedis.lrange("collections", 0, -1));
System.out.println("collections添加元素,从列表右端,与lpush相对应:"+jedis.rpush("collections", "EnumMap"));
System.out.println("collections的内容:"+jedis.lrange("collections", 0, -1));
System.out.println("collections列表出栈(右端):"+jedis.rpop("collections"));
System.out.println("collections的内容:"+jedis.lrange("collections", 0, -1));
System.out.println("修改collections指定下标1的内容:"+jedis.lset("collections", 1, "LinkedArrayList"));
System.out.println("collections的内容:"+jedis.lrange("collections", 0, -1));
System.out.println("===============================");
System.out.println("collections的长度:"+jedis.llen("collections"));
System.out.println("获取collections下标为2的元素:"+jedis.lindex("collections", 2));
System.out.println("===============================");
//jedis.lpush("sortedList", "3","6","2","0","7","4");
System.out.println("sortedList排序前:"+jedis.lrange("sortedList", 0, -1));
System.out.println(jedis.sort("sortedList"));
System.out.println("sortedList排序后:"+jedis.lrange("sortedList", 0, -1));
}

7.对Set的操作命令

@Test
public void testSet(){
jedis.flushDB();
System.out.println("============向集合中添加元素(不重复)============");
System.out.println(jedis.sadd("eleSet", "e1","e2","e4","e3","e0","e8","e7","e5"));
System.out.println(jedis.sadd("eleSet", "e6"));
System.out.println(jedis.sadd("eleSet", "e6"));
System.out.println("eleSet的所有元素为:"+jedis.smembers("eleSet"));
System.out.println("删除一个元素e0:"+jedis.srem("eleSet", "e0"));
System.out.println("eleSet的所有元素为:"+jedis.smembers("eleSet"));
System.out.println("删除两个元素e7和e6:"+jedis.srem("eleSet", "e7","e6"));
System.out.println("eleSet的所有元素为:"+jedis.smembers("eleSet"));
System.out.println("随机的移除集合中的一个元素:"+jedis.spop("eleSet"));
System.out.println("随机的移除集合中的一个元素:"+jedis.spop("eleSet"));
System.out.println("eleSet的所有元素为:"+jedis.smembers("eleSet"));
System.out.println("eleSet中包含元素的个数:"+jedis.scard("eleSet"));
System.out.println("e3是否在eleSet中:"+jedis.sismember("eleSet", "e3"));
System.out.println("e1是否在eleSet中:"+jedis.sismember("eleSet", "e1"));
System.out.println("e1是否在eleSet中:"+jedis.sismember("eleSet", "e5"));
System.out.println("=================================");
System.out.println(jedis.sadd("eleSet1", "e1","e2","e4","e3","e0","e8","e7","e5"));
System.out.println(jedis.sadd("eleSet2", "e1","e2","e4","e3","e0","e8"));
System.out.println("将eleSet1中删除e1并存入eleSet3中:"+jedis.smove("eleSet1", "eleSet3", "e1"));//移到集合元素
System.out.println("将eleSet1中删除e2并存入eleSet3中:"+jedis.smove("eleSet1", "eleSet3", "e2"));
System.out.println("eleSet1中的元素:"+jedis.smembers("eleSet1"));
System.out.println("eleSet3中的元素:"+jedis.smembers("eleSet3"));
System.out.println("============集合运算=================");
System.out.println("eleSet1中的元素:"+jedis.smembers("eleSet1"));
System.out.println("eleSet2中的元素:"+jedis.smembers("eleSet2"));
System.out.println("eleSet1和eleSet2的交集:"+jedis.sinter("eleSet1","eleSet2"));
System.out.println("eleSet1和eleSet2的并集:"+jedis.sunion("eleSet1","eleSet2"));
System.out.println("eleSet1和eleSet2的差集:"+jedis.sdiff("eleSet1","eleSet2"));//eleSet1中有,eleSet2中没有
jedis.sinterstore("eleSet4","eleSet1","eleSet2");//求交集并将交集保存到dstkey的集合
System.out.println("eleSet4中的元素:"+jedis.smembers("eleSet4"));
}

8.对Hash的操作命令

@Test
public void testHash(){
jedis.flushDB();
Map<String,String> map = new HashMap<>();
map.put("key1","value1");
map.put("key2","value2");
map.put("key3","value3");
map.put("key4","value4");
//添加名称为hash(key)的hash元素
jedis.hmset("hash",map);
//向名称为hash的hash中添加key为key5,value为value5元素
jedis.hset("hash", "key5", "value5");
System.out.println("散列hash的所有键值对为:"+jedis.hgetAll("hash"));//return Map<String,String>
System.out.println("散列hash的所有键为:"+jedis.hkeys("hash"));//return Set<String>
System.out.println("散列hash的所有值为:"+jedis.hvals("hash"));//return List<String>
System.out.println("将key6保存的值加上一个整数,如果key6不存在则添加key6:"+jedis.hincrBy("hash", "key6", 6));
System.out.println("散列hash的所有键值对为:"+jedis.hgetAll("hash"));
System.out.println("将key6保存的值加上一个整数,如果key6不存在则添加key6:"+jedis.hincrBy("hash", "key6", 3));
System.out.println("散列hash的所有键值对为:"+jedis.hgetAll("hash"));
System.out.println("删除一个或者多个键值对:"+jedis.hdel("hash", "key2"));
System.out.println("散列hash的所有键值对为:"+jedis.hgetAll("hash"));
System.out.println("散列hash中键值对的个数:"+jedis.hlen("hash"));
System.out.println("判断hash中是否存在key2:"+jedis.hexists("hash","key2"));
System.out.println("判断hash中是否存在key3:"+jedis.hexists("hash","key3"));
System.out.println("获取hash中的值:"+jedis.hmget("hash","key3"));
System.out.println("获取hash中的值:"+jedis.hmget("hash","key3","key4"));
}

9.排序操作指令

@Test
public void testSort(){
jedis.flushDB();
//jedis.lpush("collections", "ArrayList", "Vector", "Stack", "HashMap", "WeakHashMap", "LinkedHashMap");
jedis.lpush("collections","ArrayList");
jedis.lpush("collections","Vector");
jedis.lpush("collections","Stack");
jedis.lpush("collections","HashMap");
jedis.lpush("collections","WeakHashMap");
jedis.lpush("collections","LinkedHashMap");
System.out.println("collections的内容:"+jedis.lrange("collections", 0, -1));
SortingParams sortingParameters = new SortingParams();
System.out.println(jedis.sort("collections",sortingParameters.alpha()));
System.out.println("===============================");
//jedis.lpush("sortedList", "3","6","2","0","7","4");
jedis.lpush("sortedList","3");
jedis.lpush("sortedList","6");
jedis.lpush("sortedList","2");
jedis.lpush("sortedList","0");
jedis.lpush("sortedList","7");
jedis.lpush("sortedList","4");
System.out.println("sortedList排序前:"+jedis.lrange("sortedList", 0, -1));
System.out.println("升序:"+jedis.sort("sortedList", sortingParameters.asc()));
System.out.println("降序:"+jedis.sort("sortedList", sortingParameters.desc()));
}

10.对Sorted-Sets操作

/**
* @author bruceliu
* @create 2019-06-09 22:43
* @description 对Sorted-Sets操作
*/
public class TestSorted {

private static final String ipAddr = "192.168.16.XXX";
private static final int port = 6379;
private static Jedis jedis = null;


@Before
public void init() { jedis = JedisUtil.getInstance().getJedis(ipAddr, port); }
@After
public void close() { JedisUtil.getInstance().closeJedis(jedis,ipAddr, port); }


//对Sorted-Sets操作
/**
* Sorted-Sets和Sets类型极为相似,它们都是字符串的集合,都不允许重复的成员出现在一个Set中。
* 它们之间的主要差别是Sorted-Sets中的每一个成员都会有一个分数(score)与之关联,Redis正是通过分数来为集合中的成员进行从小到大的排序。
* 然而需要额外指出的是,尽管Sorted-Sets中的成员必须是唯一的,但是分数(score)却是可以重复的。
* 在Sorted-Set中添加、删除或更新一个成员都是非常快速的操作,其时间复杂度为集合中成员数量的对数。
* 由于Sorted-Sets中的成员在集合中的位置是有序的,因此,即便是访问位于集合中部的成员也仍然是非常高效的。
* @throws Exception
*/
@Test
public void testSorted_Sets() throws Exception {
jedis.flushAll();

//添加一个分数为1的成员
jedis.zadd("myzset", 1, "one");

Map<String,Double> map = new LinkedHashMap<String,Double>();
map.put("two", (double) 2);
map.put("three", (double) 3);
//添加两个分数分别是2和3的两个成员。
jedis.zadd("myzset", map);//这个单独测一下

//0表示第一个成员,-1表示最后一个成员。返回的结果中包含每个成员
Set<String> zrange = jedis.zrange("myzset", 0, -1);
System.out.println("zrange="+zrange);//zrange=[one, two, three]



//获取成员one在Sorted-Set中的位置索引值。0表示第一个位置
Long zrank = jedis.zrank("myzset", "one");
System.out.println("zrank = "+zrank);//zrank = 0

//成员four并不存在,因此返回null
System.out.println(jedis.zrank("myzset", "four"));//null

//#返回与myzset关联的Sorted-Set中,分数满足表达式1 <= score <= 2的成员的数量。
Long zcount = jedis.zcount("myzset", 1, 2);
System.out.println("zcount="+zcount);//zcount=2

//获取myzset键中成员的数量。
System.out.println(jedis.zcard("myzset"));//3

//删除成员one和two,返回实际删除成员的数量。
Long zrem = jedis.zrem("myzset", "one","two");
System.out.println("zrem="+zrem);//zrem=2

//查看是否删除成功。 获取键中成员的数量
System.out.println(jedis.zcard("myzset"));//1

//获取成员three的分数。返回值是字符串形式。
Double zscore = jedis.zscore("myzset", "three");
System.out.println("zscore="+zscore);//zscore=3.0

//由于成员two已经被删除,所以该命令返回null
System.out.println(jedis.zscore("myzset", "two"));//null

//将成员three的分数增加2,并返回该成员更新后的分数。
Double zincrby = jedis.zincrby("myzset", 2, "three");
System.out.println("zincrby="+zincrby);//zincrby=5.0

//将成员three的分数增加-1,并返回该成员更新后的分数。
System.out.println(jedis.zincrby("myzset", -1, "three"));//4.0

//====================》》》》》》
jedis.del("myzset");

Map<String,Double> map3 = new LinkedHashMap<String,Double>();
map3.put("one", 1.0);
map3.put("two", 2.0);
map3.put("three", 3.0);
map3.put("four", 4.0);
//一次添加多个
jedis.zadd("myzset",map3);

//获取分数满足表达式1 <= score <= 2的成员。
Set<String> zrangeByScore = jedis.zrangeByScore("myzset", 1, 2);
System.out.println("zrangeByScore= "+zrangeByScore);zrangeByScore= [one, two]



//删除分数满足表达式1 <= score <= 2的成员,并返回实际删除的数量。
Long zremrangeByScore = jedis.zremrangeByScore("myzset", 1, 2);
System.out.println("zremrangeByScore="+zremrangeByScore);//zremrangeByScore=2

//看出一下上面的删除是否成功。
System.out.println(jedis.zrange("myzset", 0, -1));//[three, four]


//删除位置索引满足表达式0 <= rank <= 1的成员。返回实际删除的数量
Long zremrangeByRank = jedis.zremrangeByRank("myzset", 0, 1);
System.out.println("zremrangeByRank="+zremrangeByRank);//zremrangeByRank=2

//查看上一条命令是否删除成功。
Long zcard = jedis.zcard("myzset");
System.out.println("zcard = "+zcard);//zcard = 0

//======================>>>>>>>>>>>>>>>>>

jedis.del("myzset");
Map<String,Double> map2 = new LinkedHashMap<String,Double>();
map2.put("one", 1.0);
map2.put("two", 2.0);
map2.put("three", 3.0);
map2.put("four", 4.0);
//一次添加多个
jedis.zadd("myzset",map2);

//以位置索引从高到低的方式获取并返回此区间内的成员。
Set<String> zrevrange = jedis.zrevrange("myzset", 0, -1);
System.out.println("zrevrange="+zrevrange);//zrevrange=[four, three, two, one]

Set<String> zrevrange2 = jedis.zrevrange("myzset", 1, 3);
System.out.println("zrevrange2="+zrevrange2);//zrevrange2=[three, two, one]

//由于是从高到低的排序,所以one的位置是3。
System.out.println(jedis.zrevrank("myzset", "one"));//3

//由于是从高到低的排序,所以four的位置是0。
System.out.println(jedis.zrevrank("myzset", "four"));//0

//获取分数满足表达式3 >= score >= 0的成员,并以相反的顺序输出,即从高到底的顺序。
System.out.println(jedis.zrevrangeByScore("myzset", 3, 0));//[three, two, one]

System.out.println("数据:="+jedis.zrange("myzset", 0, -1));//数据:=[one, two, three, four]


/**
* zrangeByScoreWithScores(String key, double min, double max, int offset, int count)
* key:键
* min:最小分值
* max:最大分值
* offset:偏移量,也就是从哪个位置开始。
* count:元素个数
*
* 返回的元素用ASCII码表示的,该元素的值用double类型数据表示
*/
System.out.println(jedis.zrangeByScoreWithScores("myzset", 2, 3, 0, 2));//[[[116, 119, 111],2.0], [[116, 104, 114, 101, 101],3.0]]

}
}


上一篇:JavaWeb开发专题(一)-JavaWeb入门
下一篇:没有了
网友评论