ในบทเรียนนี้ เราจะเรียนรู้วิธีการทำ CRUD operation บน hash value โดยใช้ Jedis library
Jedis Library
Jedis เป็น Java client library สำหรับ Redis datastore มีขนาดเล็ก ใช้งานง่าย และรองรับ Redis 2.8.x, 3.x.x และขึ้นไป
Hash Value
Hash เป็น map ของ field-value pair ใช้แทน object type เช่น Java object ใน Redis hash ถูกเก็บเป็น value
Project Setup
สร้าง Maven project และเพิ่ม dependency ใน pom.xml:
<dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>3.0.1</version> </dependency>
Redis Installation
ติดตั้ง Redis เวอร์ชันล่าสุด
Jedis Connection
Jedis jedis = new Jedis();
Create & Set Field's Value
มี 3 method สำหรับตั้งค่า field ใน hash:
- hset: ตั้งค่า field ใน hash หาก field มีอยู่แล้วจะทับที หาก key ไม่มีอยู่จะสร้าง key ใหม่
jedis.hset("hash-1", "name", "john"); jedis.hset("hash-2".getBytes(), "name".getBytes(), "john".getBytes()); - hsetnx: ตั้งค่า field เฉพาะเมื่อ field ไม่มีอยู่ หากมีอยู่แล้วไม่ทำงาน
jedis.hsetnx("hash-1", "name", "john"); jedis.hsetnx("hash-2".getBytes(), "age".getBytes(), "23".getBytes()); - hmset: ตั้งค่า field หลายคู่พร้อมกัน หาก field มีอยู่จะทับที
Map<String,String> map = new HashMap<>(); map.put("name","john"); map.put("age","23"); jedis.hmset("hash-1", map);
Get Field's Value
- hget: ดึงค่า field เดียว
jedis.hget("hash-1", "name"); - hmget: ดึงค่า field หลายรายการ
jedis.hmget("hash-1", "name", "age");
Size
hlen หาจำนวน field ใน hash:
jedis.hlen("hash-1");
Delete
hdel ลบ field หนึ่งหรือหลายรายการ:
jedis.hdel("hash-1", "name", "age");
jedis.hdel("hash-2".getBytes(),"name".getBytes(),"age".getBytes());
Check Field Existence
hexists ตรวจสอบ field เป็นสมาชิกของ hash หรือไม่:
jedis.hexists("hash-1", "name");
jedis.hexists("hash-2".getBytes(),"name".getBytes());
Get All
hgetall ดึง field และค่าทั้งหมด:
jedis.hgetAll("hash-1");
jedis.hgetAll("hash-2".getBytes());
Get All Keys
hkeys ดึงชื่อ field ทั้งหมด:
jedis.hkeys("hash-1");
jedis.hkeys("hash-2".getBytes());
Get All Values
hvals ดึงค่า field ทั้งหมด:
jedis.hvals("hash-1");
jedis.hvals("hash-2".getBytes());
อ้างอิง
- Hash Command Docs
ขอจบบทเรียนสำหรับวิธีทำ CRUD operation บน hash value โดยใช้ Jedis library หากชอบบทเรียนนี้ กรุณาแบ่งปันความคิดเห็นและแชร์ให้ผู้อื่นด้วยครับ