Java操作Redis-Jedis
Jedis:Redis官方推荐的java连接开发工具,使用java操作Redis中间件,如果你要使用java操作Jedis,那么一定要对Jedis十分的熟悉
- 导入对应依赖
<!--导入jedis包-->
<!-- https://mvnrepository.com/artifact/redis.clients/jedis -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>3.6.3</version>
</dependency>
<!--导入fastjson-->
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.78</version>
</dependency>
- 编码测试
- 连接数据库
- 操作命令
- 断开连接
public class TestPing {
public static void main(String[] args) {
//1. new Jedis对象即可
Jedis jedis = new Jedis("127.0.0.1", 6379);
String ping = jedis.ping();
//2. 测试是否连接成功
System.out.println(ping); //PONG
}
}
public class TestTs {
public static void main(String[] args) {
//new Jedis对象即可
Jedis jedis = new Jedis("xxx.xxx.xxx.xxx", 6379);
JSONObject jsonObject = new JSONObject();
jedis.flushDB();
jsonObject.put("hello","world");
jsonObject.put("name","Lys");
String s = jsonObject.toJSONString();
//开启事务
// jedis.watch(s); 监控对象
Transaction multi = jedis.multi();
try {
multi.set("user1",s);
multi.set("user2",s);
int i=1/0;
multi.exec();
}catch(Exception e){
multi.discard();
e.printStackTrace();
}
finally {
System.out.println(jedis.get("user1")+jedis.get("user2"));
jedis.close();
}
}
}