qiqizhiyun 2020-01-05
Redis是一个开源的高性能键值对数据库。它通过提供多种键值数据类型来适应不同场景下的存储需求,并借助许多高层级的接口使其可以胜任如缓存、队列系统等不同的角色
支持字符串、散列、列表、集合、有序集合等类型。与MySQL相比,对于小数据集的复杂关系操作更直观,性能更好
Redis数据库中的所有数据都存储在内存中。由于内存的读写速度远快于硬盘,因此Redis在性能上对比其他基于硬盘存储的数据库有非常明显的优势
Redis提供了对持久化的支持,即将可以内存中的数据异步写入到硬盘中,同时不影响继续提供服务
缓存:为每个键设置生存时间(Time To Live,TTL),生存时间到期后键会自动被删除
队列:Redis的列表类型键可以用来实现队列,并且支持阻塞式读取,可以很容易地实现一个高性能的优先级队列
构建聊天室等系统:支持“发布/订阅”的消息模式
public void testString(){
Jedis jedis = RedisUtil.connect();
jedis.set("testKey", "testValue");
System.out.println("testKey: " + jedis.get("testKey"));
Long delResult = jedis.del("testKey");
System.out.println("del testKey, result = " + delResult);
System.out.println("del后,testKey: " + jedis.get("testKey"));
}public void testList(){
String testKey = "testKey";
jedis.lpush(testKey, "testValue", "testValue2");
System.out.println("testKey: " + jedis.lrange(testKey, 0, -1));
jedis.lpush(testKey, "testValue", "testValue2", "testValue3");
System.out.println("testKey set new: " + jedis.lrange(testKey, 0, -1));
jedis.lrem(testKey, 2, "testValue");
System.out.println("testKey lrem 2个数据后: " + jedis.lrange(testKey, 0, -1));
Long delResult = jedis.del(testKey);
System.out.println("del testKey, result = " + delResult);
System.out.println("del后,testKey: " + jedis.get(testKey));
System.out.println("del后,testKey: " + jedis.lrange(testKey, 0, -1));
}public void testSet(){
String testKey = "testKey";
jedis.sadd(testKey, "testValue", "testValue2");
System.out.println("testKey: " + jedis.smembers(testKey));
jedis.sadd(testKey, "testValue", "testValue2", "testValue3");
System.out.println("testKey set new: " + jedis.smembers(testKey));
jedis.srem(testKey, "testValue");
System.out.println("testKey srem后: " + jedis.smembers(testKey));
}public void testSortedSet(){
String testKey = "testKey";
jedis.zadd(testKey, 5, "testValue5");
jedis.zadd(testKey, 2, "testValue2");
System.out.println("testKey: " + jedis.zrange(testKey, 0, -1));
jedis.zadd(testKey, 2, "testValue2-2");
jedis.zadd(testKey, 9, "testValue9");
System.out.println("testKey zadd: " + jedis.zrange(testKey, 0, -1));
jedis.zrem(testKey, "testValue2");
System.out.println("testKey zrem后: " + jedis.zrange(testKey, 0, -1));
}public void testHash(){
String testKey = "testKey";
jedis.hset(testKey, "field", "100");
System.out.println("testKey: " + jedis.hget(testKey, "field"));
jedis.hincrBy(testKey, "field", 100);
System.out.println("testKey 的value hincrBy: " + jedis.hvals(testKey));
jedis.hset(testKey, "field", "testValue");
jedis.hset(testKey, "field2", "testValue2");
jedis.hset(testKey, "field3", "testValue3");
System.out.println("testKey new hset, keys= " + jedis.hkeys(testKey));
System.out.println("testKey new hset, values= " + jedis.hvals(testKey));
jedis.hdel(testKey, "field3");
System.out.println("testKey hdel, keys= " + jedis.hkeys(testKey));
System.out.println("testKey hdel, values= " + jedis.hvals(testKey));
}