Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Redis

Redis List CRUD ด้วย Jedis: คู่มือ Java ครบถ้วน

ในบทเรียนนี้ เราจะเรียนรู้วิธีการทำ CRUD operation บน list value โดยใช้ Jedis library

Jedis Library

Jedis เป็น Java client library สำหรับ Redis datastore มีขนาดเล็ก ใช้งานง่าย และรองรับ Redis 2.8.x, 3.x.x และขึ้นไป

List Value

List คือลำดับของ string ที่เรียงตาม insertion order ใน Redis list ถูกเก็บเป็น 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 & Add

Jedis มีหลาย method สำหรับสร้างและแทรกสมาชิกใน list:

  1. lpush: แทรกที่ head ของ list หาก list ไม่มีอยู่จะสร้างก่อน
    jedis.lpush("list-1", "a", "b", "c"); 
    jedis.lpush("list-2".getBytes(), new BigInteger("1").toByteArray(), new BigInteger("2").toByteArray());
  2. rpush: แทรกที่ tail ของ list
    jedis.rpush("list-3", "a", "b", "c"); 
    jedis.rpush("list-4".getBytes(), new BigInteger("1").toByteArray(), new BigInteger("2").toByteArray());
  3. lpushx: แทรกที่ head เฉพาะเมื่อ list มีอยู่แล้ว
    jedis.lpushx("list-1", "d", "e"); 
    jedis.lpushx("list-2".getBytes(), new BigInteger("3").toByteArray(), new BigInteger("4").toByteArray());
  4. rpushx: แทรกที่ tail เฉพาะเมื่อ list มีอยู่แล้ว
    jedis.rpushx("list-3", "d", "e"); 
    jedis.rpushx("list-4".getBytes(), new BigInteger("3").toByteArray(), new BigInteger("4").toByteArray());

Remove & Return

  1. lpop: ลบและคืนค่าสมาชิกแรก
    jedis.lpop("list-1"); 
    jedis.lpop("list-2".getBytes());
  2. rpop: ลบและคืนค่าสมาชิกสุดท้าย
    jedis.rpop("list-3"); 
    jedis.rpop("list-4".getBytes());

Length

llen หาความยาวของ list:

jedis.llen("list-1"); 
jedis.llen("list-2".getBytes());

Delete

lrem ลบทุก occurrence ของสมาชิก:

jedis.lrem("list-1", 1, "a"); 
jedis.lrem("list-2".getBytes(), 2, "1".getBytes());

Get By Index

lindex ดึงสมาชิกตาม index:

jedis.lindex("list-1", 3); 
jedis.lindex("list-2".getBytes(), 2);

Update By Index

lset อัปเดตสมาชิกตาม index:

jedis.lset("list-1", 3, "g"); 
jedis.lset("list-2".getBytes(), 2, "6".getBytes());

Get Multiple Elements

lrange ดึงสมาชิกในช่วง offset:

jedis.lrange("list-1", 1, 5); 
jedis.lrange("list-2".getBytes(), 0, -1);

อ้างอิง

  1. List Command Docs

ขอจบบทเรียนสำหรับวิธีทำ CRUD operation บน list value โดยใช้ Jedis library หากชอบบทเรียนนี้ กรุณาแบ่งปันความคิดเห็นและแชร์ให้ผู้อื่นด้วยครับ