Jedis
Jedis是Redis官方推荐的Java连接开发工具,是一个用于连接和操作Redis数据库的Java客户端库。它提供了一系列的方法来操作Redis的键值存储、列表、哈希、集合和有序集合等数据结构。要在Java开发中使用好Redis中间件,必须对Jedis熟悉才能写成漂亮的代码
添加Jedis依赖
在pom.xml文件中添加Jedis依赖
<!-- https://mvnrepository.com/artifact/redis.clients/jedis -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>5.1.0</version>
</dependency>
编写测试代码
public class EasyRedisA {
public static void main(String[] args) {
//通过Jedis链接数据库
Jedis jedis=new Jedis("127.0.0.1",6379);
System.out.println("连接成功");
String result = jedis.ping();
System.out.println("ping的结果是:"+ result);
result = jedis.set("name","Jon博士");
System.out.println("set的结果是:"+ result);
//获取所有的key
Set<String> keys = jedis.keys("*");
//打印每一个key
for(String key:keys){
System.out.println(key);
}
jedis.close();
}
}
启动Redis服务后测试
JedisAPI
常用API
1.基本操作
public class TestPassword {
public static void main(String[] args) {
Jedis jedis = new Jedis("127.0.0.1",6379);
//验证密码,如果没有设置密码可以省略
//jedis.auth("password123");
jedis.connect(); //连接
jedis.disconnect(); //断开连接
jedis.flushAll(); //清空所有的key
}
}
2.对key操作的命令
public class TestKey {
public static void main(String[] args) {
Jedis jedis = new Jedis("127.0.0.1",6379);
System.out.println("清空数据:" + jedis.flushDB());
System.out.println("判断某个键是否存在:" + jedis.exists("username"));
System.out.println("新增键值对:" + jedis.set("username","zhangsan"));
System.out.println("新增键值对:" + jedis.set("password","pass123"));
System.out.println("系统中所有的键如下:");
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("查看键所存储值的类型:" + 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("按索引查询:" + jedis.select(0));
System.out.println("返回当前数据库中key的数目:" + jedis.dbSize());
System.out.println("删除当前数据库中所有key:" + jedis.flushDB());
System.out.println("删除所有数据库中的所有key:" + jedis.flushAll());
}
}
3.对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("删除键key2:"+jedis.del("key2"));
System.out.println("获取键key2:"+jedis.get("key2"));
System.out.println("修改key1:"+jedis.set("key1","valueChange"));
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","key04"));
System.out.println("获取多个键值对:"+jedis.mget("key01","key02","key03"));
System.out.println("删除多个键值对:"+jedis.del("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","value-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));
}
}
4.对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","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代表倒数第二
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));
}
}
5.对Set的操作命令
public class TestSet {
public static void main(String[] args) {
Jedis jedis = new Jedis("127.0.0.1",6379);
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("e5是否在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"));
}
}
6.对Hash的操作命令
public class TestHash {
public static void main(String[] args) {
Jedis jedis = new Jedis("127.0.0.1",6379);
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"));
}
}
事务
public class TestMulti {
public static void main(String[] args) {
Jedis jedis = new Jedis("127.0.0.1",6379);
jedis.flushDB();
JSONObject jsonObject = new JSONObject();
jsonObject.put("hello","world");
jsonObject.put("name","java");
//开启事务
Transaction multi = jedis.multi();
String result = jsonObject.toString();
try {
//向redis存入一条数据
multi.set("json",result);
//再存入一条数据
multi.set("json2",result);
//这里引发异常,让0作为被除数
int i = 100/0;
//如果没引发异常,执行进入队列的命令
multi.exec();
}catch (Exception e){
e.printStackTrace();
//如果出现异常,回滚
multi.discard();
}finally {
System.out.println(jedis.get("json"));
System.out.println(jedis.get("json2"));
//最终关闭客户端
jedis.close();
}
}
}
如果触发异常,则回滚
没有异常,正常执行
SpringBoot整合
Spring Data Redis提供了一个高级封装RedisTemplate,用于简化与Redis的交互。它提供了一系列的方法来操作Redis数据库,包括增删改查键值、列表、哈希、集合和有序集合等数据结构。RedisTemplate使用起来更方便,并且支持数据的序列化和反序列化,可以直接操作Java对象而无需手动序列化和反序列化。
导入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<version>2.7.7</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.6.6</version>
</dependency>
yaml配置
resources文件夹下创建application.yml文件
测试
创建测试类EasyRedisController
依赖注入有两个注解可以用:@Resource、@Autowired
- Resource默认通过byName的形式去找,找不到会自动转成byType的形式去找
- Autowired默认通过byType去找,用byName的形式需要通过另一个注解的帮助,而且不会再调用byType形式
@RestController
public class EasyRedisController {
@Autowired
RedisTemplate redisTemplate;
@RequestMapping("addname")
public String addStr(){
redisTemplate.opsForValue().set("name","zhangsan");
return "OK";
}
@RequestMapping("getname")
public String getStr(){
Object obj = redisTemplate.opsForValue().get("name");
return obj.toString();
}
}
存入json数据
这里引入 Lombot 的使用
Lombok是一个Java库,通过注解的方式简化了Java类的编写。它通过注解在编译时自动生成一些常用的代码,如Getter、Setter、构造方法、equals()、hashCode()等,减少了冗余的样板代码,提高了开发效率。
Eclipse 安装Lombot在安装路径下运行cmd使用 java -jar 打开安装包,找到Eclipse安装路径
IDEA 在 File - Settings - Plugins插件中可以找到,默认已安装
在pom.xml导入lombot依赖
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.24</version>
<scope>provided</scope>
</dependency>
测试类Student
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student implements Serializable {
private static final long serialVersionUID = 1;
private int id;
private String name;
private int score;
private String sex;
}
使用注解自动生成Getter和Setter方法以及满参和无参的构造方法
另外,为了确保测试类的对象能够成功的序列化和反序列化,Student类需要实现Serializable接口,并自定义序列化编号。
测试方法
@RequestMapping("addobj")
public String addObj(){
Student stu = new Student();
stu.setId(22);
stu.setName("zhangsan");
stu.setScore(99);
redisTemplate.opsForValue().set("student",stu);
return "OK";
}
@RequestMapping("getobj")
public Student getObj(){
Object obj = redisTemplate.opsForValue().get("student");
return (Student)obj;
}