Jedis操作redis
创个空项目 记得jdk javac 要修改配置
1.导入依赖
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>3.2.0</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.61</version>
</dependency>
2.编码测试:
- 连接数据库
- 操作命令
- 断开连接
package com.tian;
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所有的命令就是我们之前学习的所有指令!
System.out.println(jedis.ping());
}
}
输出 : PONG
常用的API
String
//jedis所有的命令就是我们之前学习的所有指令!
System.out.println(jedis.ping());
System.out.println("清空数据:"+jedis.flushDB());
System.out.println("判断某个键是否存在: "+jedis.exists( "username"));
System.out.println("新增<'username','kuangshen'>的键值对: "+jedis.set("username","kuangshen"));
System.out.println("新增< 'password','password'>的键值对:"+jedis.set("password","password"));
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("查看键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("按索引查询:"+jedis.select(0));
System.out.println("删除当前选择数据库中的所有key: "+jedis.flushDB());
System.out.println("返回当前数据库中key的数目: "+jedis.dbSize());
System.out.println("删除所有数据库中的所有key: "+jedis.flushAll());
所有的api命令就是我们上面的学的命令,一个都没有变化
Jedis再次理解事务
package com.tian;
import com.alibaba.fastjson.JSONObject;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;
public class TestShiWu {
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","kuangshen");
//开启事务
Transaction multi = jedis.multi();
String result = jsonObject.toJSONString();
// jedis.watch(result);
try {
multi.set("user1",result);
multi.set("user2",result);
int i=1/0;
multi.exec(); //执行事务
} catch (Exception e) {
multi.discard();//如果失败放弃事务
e.printStackTrace();
}finally {
System.out.println(jedis.get("user1"));
System.out.println(jedis.get("user2"));
jedis.close();
}
jedis.close();//关闭连接
}
}