1. 程式人生 > >[筆記遷移][Redis][8]Redis的Java客戶端—Jedis

[筆記遷移][Redis][8]Redis的Java客戶端—Jedis

一、連通性測試

//獲取一個Redis客戶端
Jedis jedisClient = new Jedis("192.168.109.191", 6379);
//正常連線將返回PONG,若未關閉防火牆則丟擲超時異常
System.out.println(jedisClient.ping());

二、基本操作API參照之前的Shell命令

三、事務提交

  1. 一般API
    //1.開啟事務,注意區分Transaction類,不要導錯
    Transaction tx=jedisClient.multi();
    //2.Transaction可呼叫大部分方法
    tx.set("k1","v111");
    tx.set("k2",
    "v222"); //3.提交執行事務 tx.exec(); // 放棄本次事務 tx.discard();
  2. 併發“鎖機制”—watch與unwatch
    	public static  boolean txMethod(){
    	Jedis jedisClient = new Jedis("192.168.109.191",6379);
    	
    	int balance=0;
    	int debt=0;
    	int amtToSubtract=20;
    	
    	//1. 為balance加鎖監視
    	jedisClient.watch("balance");
    	
    	balance=Integer.parseInt(jedisClient.
    get("balance")); if(balance<amtToSubtract){ //2. 先行判斷,若不滿足直接解鎖,返回失敗 jedisClient.unwatch(); return false; }else{ System.out.println("=====Transaction start====="); //3. 滿足後,開啟事務修改,提交後解鎖,返回成功 Transaction tx = jedisClient.multi(); tx.decrBy("balance", amtToSubtract); tx.incrBy("debt"
    , amtToSubtract); tx.exec(); System.out.println("=====Transaction commit====="); balance=Integer.parseInt(jedisClient.get("balance")); debt=Integer.parseInt(jedisClient.get("debt")); System.out.println("=====balance====="+balance); System.out.println("=====debt====="+debt); return true; } }

四、主從複製

Jedis master = new Jedis("192.168.109.191",6379);
Jedis slave1 = new Jedis("192.168.109.191",6380);
Jedis slave2 = new Jedis("192.168.109.191",6381);
		 
slave1.slaveof("192.168.109.191", 6379);
slave2.slaveof("192.168.109.191", 6380);
		 
master.set("class", "1");
		 
System.out.println("slave1 get===>"+slave1.get("class"));