企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
[TOC] # 测试是否能ping通 ~~~ //创建一个jedis客户端对象(redis的客户端连接) Jedis jedis = new Jedis("127.0.0.1",6379); //设置auth密码 jedis.auth("root"); //测试服务器是否连通 String ping = jedis.ping(); System.out.println(ping); ~~~ # 命令行 ![](https://box.kancloud.cn/e05330b96f10ef19923070a970fd9c17_479x457.png) # string操作 ~~~ public Jedis init() { //创建一个jedis客户端对象(redis的客户端连接) Jedis jedis = new Jedis("127.0.0.1",6379); //设置auth密码 jedis.auth("root"); return jedis; } @Test public void testString() { Jedis jedis = this.init(); jedis.set("user02:name", "jdxia"); jedis.set("user03:name","xjd"); String u02 = jedis.get("user02:name"); String u03 = jedis.get("user03:name"); System.out.println(u02); System.out.println(u03); } ~~~ # 存个对象 ## 对象序列化 ~~~ @Test public void testObjectCache() throws IOException, ClassNotFoundException { Jedis jedis = this.init(); ProductInfo productInfo = new ProductInfo(); productInfo.setName("jdxia"); productInfo.setCatelog("大数据"); productInfo.setPrice(20.0); //将对象序列化成字节数组,这个productInfo对象需要implements Serializable //字节数组流 ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); //对象序列化流 ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); //用对象的序列化流将productInfo对象序列化,然后把序列化之后的二进制数据写到byteArrayOutputStream流中 objectOutputStream.writeObject(productInfo); //将byteArrayOutputStream流转为byte数组 byte[] bytes = byteArrayOutputStream.toByteArray(); //将对象序列化之后的byte数组存到redis的string中 jedis.set("product:01".getBytes(),bytes); //根据key从redis中取出对象的byte数据 byte[] pBytesResp = jedis.get("product:01".getBytes()); //将byte数据反序列出对象 ByteArrayInputStream bi = new ByteArrayInputStream(pBytesResp); ObjectInputStream oi = new ObjectInputStream(bi); //从对象读取流中读取出p对象 ProductInfo productInfo1= (ProductInfo) oi.readObject(); System.out.println(productInfo1); } ~~~ ## 对象转Gson ~~~ //对象转Gson @Test public void testObjectToJsonCache() { Jedis jedis = this.init(); ProductInfo productInfo = new ProductInfo(); productInfo.setName("jdxia"); productInfo.setCatelog("大数据---人工智能"); productInfo.setPrice(30.0); //利用gson将对象转成json串 Gson gson = new Gson(); String pJson = gson.toJson(productInfo); //将json串存入redis jedis.set("product:02",pJson); //从redis中取出对象的json串 String pJsonResp = jedis.get("product:02"); //将返回的json解析成对象 ProductInfo pResponse = gson.fromJson(pJson, ProductInfo.class); System.out.println(pResponse); } ~~~