Redis(15) jedis

OVO_LQ_Start發表於2020-11-02

jedis

Jedis是Redis官方推薦的Java連線開發工具。要在Java開發中使用好Redis中介軟體,必須對Jedis熟悉才能寫成漂亮的程式碼

使用方式。

1.匯入依賴

 <!--匯入jedis的包-->
    <dependencies>
        <!-- https://mvnrepository.com/artifact/redis.clients/jedis -->
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>3.2.0</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.39</version>
        </dependency>
    </dependencies>

2.連線redis


public class TestPing {
    public static void main(String[] args) {
	 Jedis jedis = new Jedis("主機IP",6379);//連線
	 jedis.close(); //斷開
 }

3.五大基本資料類操作與三大特殊資料型別

jedis + 命令名 就能操作。

		jedis.flushDB();
        System.out.println("============向集合中新增元素(不重複)============");
        System.out.println(jedis.sadd("eleSet", "e1","e2","e4","e3","e0","e8","e7","e5"));
        System.out.println(jedis.sadd("eleSet", "e6"));
        System.out.println(jedis.sadd("eleSet", "e6"));
        System.out.println("eleSet的所有元素為:"+jedis.smembers("eleSet"));
        System.out.println("刪除一個元素e0:"+jedis.srem("eleSet", "e0"));
        System.out.println("eleSet的所有元素為:"+jedis.smembers("eleSet"));
        System.out.println("刪除兩個元素e7和e6:"+jedis.srem("eleSet", "e7","e6"));

4.事務操作

 public static void main(String[] args) {
        Jedis jedis = new Jedis("主機IP",6379);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("name","liuqing");
        jsonObject.put("ok","baby");

        System.out.println(jedis.ping());

        Transaction multi = jedis.multi();

        String result = jsonObject.toJSONString();

        //jedis.watch() 樂觀鎖

        try {
            multi.set("user1",result);
            multi.set("user2",result);
            multi.exec();
        } catch (Exception e) {

            multi.discard();
            e.printStackTrace();

        } finally {
            System.out.println(jedis.get("user1"));
            System.out.println(jedis.get("user2"));
            jedis.close();
        }



    }

相關文章