redis筆記2(千峰教育)
阿新 • • 發佈:2021-01-16
四 redis連線資料庫
1.下載依賴jedis
2.連線資料庫, 和redis一樣的操作命令, 關閉資源
// 連線Redis
Jedis jedis = new Jedis("192.168.43.30", 6379);
// 操作Redis, jedis的操作命令和redis完全一樣
jedis.set("name","coco");
String name = jedis.get("name");
System.out.println(name);
// 釋放資源
jedis.close();
3. 存物件.(物件要求k,v都必須是byte[])
1.定義的物件必須實現Serializable
@Data @AllArgsConstructor public class User implements Serializable { private int id; private String name; private Date brithday; }
2.將k,v都轉成byte[]
新增依賴, 可以利用SerializationUtils
<dependency>
<groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.2.12.RELEASE</version> </dependency>
String key = "user"; User value = new User(1,"tony",new Date()); // 2,將key value轉成byte[] byte[] key_b = key.getBytes(); byte[] value_b = SerializationUtils.serialize(value); // 3.儲存 String set = jedis.set(key_b, value_b); // System.out.println(set); // 4.獲取 byte[] bytes = jedis.get(key_b); User user = (User)SerializationUtils.deserialize(bytes); System.out.println(user);