Jedis是Redis官方推荐的java连接开发工具,我们使用Java操作Redis中间件!
1、添加依赖
<!--jedis-->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>3.1.0</version>
</dependency>
<!--fastjson-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.79</version>
</dependency>
</dependencies>
2、编码测试
- 连接数据库
- 操作命令
- 断开连接
import redis.clients.jedis.Jedis;
public class TestPing {
public static void main(String[] args) throws Exception {
//new Jedis 对象
Jedis jedis = new Jedis("127.0.0.1",6379);
System.err.println(jedis.ping());
}
}
进行事务操作
import com.alibaba.fastjson.JSONObject;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;
public class TestTX {
public static void main(String[] args) throws Exception {
//new Jedis 对象
Jedis jedis = new Jedis("127.0.0.1",6379);
JSONObject jsonObject = new JSONObject();
jsonObject.put("hello","world");
jsonObject.put("fusheng","hello");
//开启事务
Transaction multi = jedis.multi();
String result = jsonObject.toJSONString();
try {
multi.set("user1",result);
multi.exec();
} catch (Exception e) {
multi.discard();//放弃事务
throw new RuntimeException(e);
} finally {
System.out.println(jedis.get("user1"));
jedis.close();
}
}
}