感谢秦疆老师的redis视频教程,更多了解哔哩哔哩搜索【狂神说Java】。
本文内容源于秦疆老师的redis视频教程。给狂神推荐,点赞吧!
Jedis
我们要使用Java来操作Redis!
什么是Jedis ?是Redis官方推荐的java连接开发工具!使用Java操作Redis操作reids,那么一定要对Jedis十分的熟悉!
测试
- 导入pom.xml依赖
<dependencies>
<!--导入jedis包-->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>3.2.0</version>
</dependency>
<!--fastjson-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.62</version>
</dependency>
</dependencies>
- 编码测试:
- 连接数据库
- 操作命令
- 断开连接
package com.beiluo;
import redis.clients.jedis.Jedis;
public class TestPing {
public static void main(String[] args) {
//1. new Jedis() 对象即可
Jedis jedis = new Jedis("127.0.0.1",6379);
//jedis所有的命令就是之前在redis-cli 操作的所有命令
//看本地redis是否ping通
System.out.println(jedis.ping());
}
}
输出:
常用的API
- String
- List
- Set
- Hash
- Zset
1.测试key
package com.beiluo;
import redis.clients.jedis.Jedis;
import java.util.Set;
public class TestKey {
public static void main(String[] args) {
Jedis jedis = new Jedis("127.0.0.1",6379);
//测试key-value的用法
System.out.println("1.清空数据:"+jedis.flushDB());
System.out.println("2.判断某个键是否存在:"+jedis.exists("username"));
System.out.println("3.新增<'username','lq'>的键值对:"+jedis.set("username","lq"));
System.out.println("4.新增<'password','123456'>的键值对:"+jedis.set("password","123456"));
System.out.println("5.系统中所有的键如下:");
Set<String > keys = jedis.keys("*");
System.out.println(keys);
System.out.println("6.删除键password:"+jedis.del("password"));
System.out.println("7.判断键password是否存在:"+jedis.exists("password"));
System.out.println("8.查看键username缩存储的值的类型:"+jedis.type("username"));
System.out.println("9.随机返回key空间的某一个:"+jedis.randomKey());
System.out.println("10.重命名key:"+jedis.rename("username","myname"));
System.out.println("11.取出改后的myname:"+jedis.get("myname"));
System.out.println("12.按索引查询:"+jedis.select(0));
System.out.println("13.删除当前选择数据库的所有key:"+jedis.flushDB());
System.out.println("14.返回当前数据库中key的数目:"+jedis.dbSize());
System.out.println("15.删除所有数据库中的所有key:"+jedis.flushAll());
}
}
输出:
2.测试String
public class TestString {
public static void main(String[] args) {
Jedis jedis = new Jedis("127.0.0.1", 6379);
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("1.删除键key2:" + jedis.del("key2"));
System.out.println("2.获取键key2:" + jedis.get("key2"));
System.out.println("3.修改key1:" + jedis.set("key1", "valueChanged"));
System.out.println("4.获取key1的值:" + jedis.get("key1"));
System.out.println("5.在key3后面追加值:" + jedis.append("key3", "End"));
System.out.println("6.获取key3的值:" + jedis.get("key3"));
System.out.println("7.增加多个键值对:" + jedis.mset("key4", "value4", "key5", "value5"));
System.out.println("8.获取多个键值对:" + jedis.mget("key1", "key4"));
System.out.println("9.获取多个键值对:" + jedis.mget(""));
System.out.println("10.删除多个键值对:" + jedis.del("key1", "key4"));
System.out.println("11.获取多个键值对:" + jedis.mget("key1", "key2"));
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-newValue"));
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));
}
}
输出:
Connected to the target VM, address: '127.0.0.1:59337', transport: 'socket'
===================增加数据====================
OK
OK
OK
1.删除键key2:1
2.获取键key2:null
3.修改key1:OK
4.获取key1的值:valueChanged
5.在key3后面追加值:9
6.获取key3的值:value3End
7.增加多个键值对:OK
8.获取多个键值对:[valueChanged, value4]
9.获取多个键值对:[null]
10.删除多个键值对:2
11.获取多个键值对:[null, null]
================新增键值对防止被覆盖================
1
1
0
value1
value2
================新增键值对并设置有效时间================
OK
value3
null
================获取原值,更新为新值================
value2
key2GetSet
截取指定下标key2的字符串:y2G
3.测试List
public class TestList {
public static void main(String[] args) {
Jedis jedis = new Jedis("127.0.0.1", 6379);
jedis.flushDB();
System.out.println("=========添加一个List========");
jedis.lpush("collections","ArrayList","Vector","Stack","HashMap");
jedis.lpush("collections","HashSet");
jedis.lpush("collections","TreeSet");//从左边往进加
jedis.rpush("collections","HashMap");//从右边往进加
jedis.lpush("collections","TreeMap");
System.out.println("collections中的内容:"+jedis.lrange("collections",0,-1));//-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列表出栈(右):"+jedis.rpop("collections"));
System.out.println("collections中的内容:"+jedis.lrange("collections",0,-1));
System.out.println("修改指定下标1的内容:"+jedis.lset("collections",1,"hahaaha"));
System.out.println("collections中的内容:"+jedis.lrange("collections",0,-1));
System.out.println("============================");
System.out.println("collections的长度:"+jedis.llen("collections"));
System.out.println("获取指定下标1的元素:"+jedis.lindex("collections",1));
System.out.println("==============排序==============");
jedis.lpush("sortedList","5","6","4","3","9","1");
System.out.println("排序前:"+jedis.lrange("sortedList",0,-1));
System.out.println("排序后:"+jedis.sort("sortedList"));
}
}
输出:
Connected to the target VM, address: '127.0.0.1:59438', transport: 'socket'
=========添加一个List========
collections中的内容:[TreeMap, TreeSet, HashSet, HashMap, Stack, Vector, ArrayList, HashMap]
collections中0到3区间的内容:[TreeMap, TreeSet, HashSet, HashMap]
============================
删除指定个数的元素:2
collections中的内容:[TreeMap, TreeSet, HashSet, Stack, Vector, ArrayList]
删除下标0-3区间之外的元素:OK
collections中的内容:[TreeMap, TreeSet, HashSet, Stack]
collections列表出栈(左):TreeMap
collections中的内容:[TreeSet, HashSet, Stack]
collections列表出栈(右):Stack
collections中的内容:[TreeSet, HashSet]
修改指定下标1的内容:OK
collections中的内容:[TreeSet, hahaaha]
============================
collections的长度:2
获取指定下标1的元素:hahaaha
==============排序==============
排序前:[1, 9, 3, 4, 6, 5]
排序后:[1, 3, 4, 5, 6, 9]
4.测试Set
public class TestSet {
public static void main(String[] args) {
Jedis jedis = new Jedis("127.0.0.1", 6379);
jedis.flushDB();
System.out.println("===============向集合中添加元素(不重复)================");
System.out.println(jedis.sadd("set","e1","e3","e2","e5","e7","e4","e0","e8"));
System.out.println(jedis.sadd("set","e6"));
System.out.println(jedis.sadd("set","e6"));
System.out.println("set集合中所有的元素为:"+jedis.smembers("set"));
System.out.println("删除一个指定元素e0:"+jedis.srem("set","e0"));
System.out.println("set集合中所有的元素为:"+jedis.smembers("set"));
System.out.println("删除多个指定元素e7,e5:"+jedis.srem("set","e7","e5"));
System.out.println("set集合中所有的元素为:"+jedis.smembers("set"));
System.out.println("随机的移除集合中的一个元素:"+jedis.spop("set"));
System.out.println("随机的移除集合中的一个元素:"+jedis.spop("set"));
System.out.println("set集合中所有的元素为:"+jedis.smembers("set"));
System.out.println("set集合中的元素个数:"+jedis.scard("set"));
System.out.println("e1是否在set集合中:"+jedis.sismember("set","e1"));
System.out.println("========================================================");
System.out.println(jedis.sadd("set1","e1","e3","e2","e5","e7","e4","e6"));
System.out.println(jedis.sadd("set2","e1","e3","e0","e5","e8","e4","e6"));
System.out.println("将set1中的元素删掉e1并将e1存入set3中:"+jedis.smove("set1","set3","e1"));
System.out.println("将set1中的元素删掉e5并将e5存入set3中:"+jedis.smove("set1","set3","e5"));
System.out.println("set1集合中所有的元素为:"+jedis.smembers("set1"));
System.out.println("set3集合中所有的元素为:"+jedis.smembers("set3"));
System.out.println("=====================集合运算=======================");
System.out.println("set1集合中所有的元素为:"+jedis.smembers("set1"));
System.out.println("set2集合中所有的元素为:"+jedis.smembers("set2"));
System.out.println("set1与set2集合的并集:"+jedis.sunion("set1","set2"));
System.out.println("set1与set2集合的交集:"+jedis.sinter("set1","set2"));
System.out.println("set1与set2集合的差集:"+jedis.sdiff("set1","set2"));//set1与set2中去掉交集后剩余的元素
jedis.sinterstore("set4","set1","set2");//求交集并将交集保存在dstkey中
System.out.println("set4集合中所有的元素为:"+jedis.smembers("set4"));
}
}
输出:
Connected to the target VM, address: '127.0.0.1:59524', transport: 'socket'
===============向集合中添加元素(不重复)================
8
1
0
set集合中所有的元素为:[e0, e7, e1, e3, e2, e5, e4, e6, e8]
删除一个指定元素e0:1
set集合中所有的元素为:[e7, e1, e3, e2, e5, e4, e6, e8]
删除多个指定元素e7,e5:2
set集合中所有的元素为:[e4, e6, e2, e3, e1, e8]
随机的移除集合中的一个元素:e1
随机的移除集合中的一个元素:e4
set集合中所有的元素为:[e6, e2, e3, e8]
set集合中的元素个数:4
e1是否在set集合中:false
========================================================
7
7
将set1中的元素删掉e1并将e1存入set3中:1
将set1中的元素删掉e5并将e5存入set3中:1
set1集合中所有的元素为:[e6, e7, e3, e2, e4]
set3集合中所有的元素为:[e1, e5]
=====================集合运算=======================
set1集合中所有的元素为:[e6, e7, e3, e2, e4]
set2集合中所有的元素为:[e8, e6, e0, e1, e3, e5, e4]
set1与set2集合的并集:[e0, e7, e1, e3, e2, e4, e6, e8, e5]
set1与set2集合的交集:[e6, e3, e4]
set1与set2集合的差集:[e7, e2]
set4集合中所有的元素为:[e3, e6, e4]
5.测试Hash
public class TestHash {
public static void main(String[] args) {
Jedis jedis = new Jedis("127.0.0.1", 6379);
jedis.flushDB();
HashMap<String, String> map = new HashMap<String, String>();
map.put("k1","v1");
map.put("k2","v2");
map.put("k3","v3");
map.put("k4","v4");
//添加元素
jedis.hmset("hash",map);
//还可以这么添加
jedis.hset("hash","k5","v5");
System.out.println("散列hash的所有键值对:"+jedis.hgetAll("hash"));
System.out.println("散列hash的所有键:"+jedis.hkeys("hash"));
System.out.println("散列hash的所有值:"+jedis.hvals("hash"));
System.out.println("将k6的保存的值加上一个整数,如果k6不存在则添加k6:"+jedis.hincrBy("hash","k6",5));
System.out.println("散列hash的所有键值对:"+jedis.hgetAll("hash"));
System.out.println("将k6的保存的值加上一个整数,如果k6不存在则添加k6:"+jedis.hincrBy("hash","k6",5));
System.out.println("散列hash的所有键值对:"+jedis.hgetAll("hash"));
System.out.println("删除一个或者多个键值对:"+jedis.hdel("hash","k1","k3"));
System.out.println("散列hash的所有键值对:"+jedis.hgetAll("hash"));
System.out.println("散列hash的所有键值对个数:"+jedis.hlen("hash"));
System.out.println("判断k2是否在hash中:"+jedis.hexists("hash","k2"));
System.out.println("判断k1是否在hash中:"+jedis.hexists("hash","k1"));
System.out.println("获取hash中的一个值:"+jedis.hmget("hash","k4"));
System.out.println("获取hash中的多个值:"+jedis.hmget("hash","k4","k6"));
}
}
输出:
Connected to the target VM, address: '127.0.0.1:59560', transport: 'socket'
散列hash的所有键值对:{k3=v3, k4=v4, k5=v5, k1=v1, k2=v2}
散列hash的所有键:[k3, k4, k5, k1, k2]
散列hash的所有值:[v4, v3, v1, v2, v5]
将k6的保存的值加上一个整数,如果k6不存在则添加k6:5
散列hash的所有键值对:{k3=v3, k4=v4, k5=v5, k6=5, k1=v1, k2=v2}
将k6的保存的值加上一个整数,如果k6不存在则添加k6:10
散列hash的所有键值对:{k3=v3, k4=v4, k5=v5, k6=10, k1=v1, k2=v2}
删除一个或者多个键值对:2
散列hash的所有键值对:{k4=v4, k5=v5, k2=v2, k6=10}
散列hash的所有键值对个数:4
判断k2是否在hash中:true
判断k1是否在hash中:false
获取hash中的一个值:[v4]
获取hash中的多个值:[v4, 10]
6.测试Zset
public class TestZset {
public static void main(String[] args) {
Jedis jedis = new Jedis("127.0.0.1", 6379);
jedis.flushDB();
jedis.zadd("myset",1,"one");
jedis.zadd("myset",2,"two");
jedis.zadd("myset",3,"three");
System.out.println("查看全部的值:"+jedis.zrange("myset",0,-1));
jedis.flushDB();
jedis.zadd("salsry",2500,"zhangsan");
jedis.zadd("salsry",500,"lisi");
jedis.zadd("salsry",5000,"wangwu");
System.out.println("由高到低排序:"+jedis.zrangeByScore("salsry","-inf","+inf"));
System.out.println("由高到低排序:"+jedis.zrevrangeByScore("salsry","+inf","-inf"));
System.out.println("查看全部的值:"+jedis.zrange("salsry",0,-1));
jedis.zrem("salsry","lisi");
System.out.println("查看全部的值:"+jedis.zrange("salsry",0,-1));
System.out.println("查看所有元素的个数:"+jedis.zcard("salsry"));
jedis.flushDB();
jedis.zadd("myset",1,"one");
jedis.zadd("myset",2,"two");
jedis.zadd("myset",3,"three");
jedis.zadd("myset",4,"four");
System.out.println("获取指定区间元素的个数:"+jedis.zcount("myset", 0, 3));
}
}
输出:
Connected to the target VM, address: '127.0.0.1:59609', transport: 'socket'
查看全部的值:[one, two, three]
由高到低排序:[lisi, zhangsan, wangwu]
由高到低排序:[wangwu, zhangsan, lisi]
查看全部的值:[lisi, zhangsan, wangwu]
查看全部的值:[zhangsan, wangwu]
查看所有元素的个数:2
获取指定区间元素的个数:3
通过Jedis再次理解事务
1.正常执行事务
package com.beiluo;
import com.alibaba.fastjson.JSONObject;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;
import java.util.Random;
public class TestTransaction {
public static void main(String[] args) {
Jedis jedis = new Jedis("127.0.0.1",6379);
JSONObject jsonObject = new JSONObject();
jsonObject.put("username","lq");
jsonObject.put("age",23);
//开启事务
Transaction transaction =jedis.multi();
String result = jsonObject.toJSONString();
//jedis.watch(result);
try{
transaction.set("user1",result);
transaction.set("user2",result);
//执行事务
transaction.exec();
}catch (Exception e){
//放弃事务
transaction.discard();
e.printStackTrace();
}finally {
System.out.println(jedis.get("user1"));
System.out.println(jedis.get("user2"));
//关闭连接
jedis.close();
}
}
}
输出:
- 加入异常代码测试
//事务执行失败,代码发送异常
int i = 1/0;
输出: