Java操作Redis事务
package com.example.redis.other;import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;import java.util.List;
public class TestTransaction {
public static void main(String[] args) throws InterruptedException {
boolean isSuccess = isSuccess("balance", "debt", 20l);
System.out.println("main retVal-------"+isSuccess);
}</span><span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">static</span> <span style="color: rgba(0, 0, 255, 1)">boolean</span> isSuccess(String balance,String debt,Long delAmount) <span style="color: rgba(0, 0, 255, 1)">throws</span><span style="color: rgba(0, 0, 0, 1)"> InterruptedException { Jedis jedis </span>= <span style="color: rgba(0, 0, 255, 1)">new</span> Jedis("127.0.0.1",6379<span style="color: rgba(0, 0, 0, 1)">);<br> <span style="color: rgba(0, 128, 0, 1)">// Watch 命令用于监视一个(或多个) key ,如果在事务执行之前这个(或这些) key 被其他命令所改动,那么事务将被打断</span> jedis.watch(balance); Long amount </span>=<span style="color: rgba(0, 0, 0, 1)"> Long.parseLong(jedis.get(balance)); Long debts </span>=<span style="color: rgba(0, 0, 0, 1)"> Long.parseLong(jedis.get(debt)); </span><span style="color: rgba(0, 0, 255, 1)">if</span>(amount<<span style="color: rgba(0, 0, 0, 1)">delAmount){<br> <span style="color: rgba(0, 128, 0, 1)">//Redis Unwatch 命令用于取消 WATCH 命令对所有 key 的监视。</span> jedis.unwatch(); System.out.println(</span>"amount can't Less than delAmount !!!!"<span style="color: rgba(0, 0, 0, 1)">); </span><span style="color: rgba(0, 0, 255, 1)">return</span> <span style="color: rgba(0, 0, 255, 1)">false</span><span style="color: rgba(0, 0, 0, 1)">; } {<br> <span style="color: rgba(0, 128, 0, 1)">//Redis 通过 MULTI 开始一个事务, 然后将多个命令入队到事务中, 最后由 EXEC 命令触发事务</span> Transaction transaction </span>=<span style="color: rgba(0, 0, 0, 1)"> jedis.multi(); transaction.decrBy(balance, delAmount); transaction.incrBy(debt,delAmount); </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">在这里模拟网络延迟时,我们通过redis命令窗口手动去修改balance值。<br> <img src="http://masterfile.aigcbbs.cn/FvP-chYe6GWlcO4VAcUYN8qC929u" alt="" class="medium-zoom-image"></span></pre>
Thread.sleep(3000); List<Object> exec = transaction.exec(); //执行 exec 操作时发现 balance 值被修改,因此终止操作。 if(exec.size()<=0){ System.out.println("balance is upfated by other person,debt is fail!!!"); return false; }
System.out.println("After updated balance=="+Long.parseLong(jedis.get(balance))); System.out.println("After updated debt=="+Long.parseLong(jedis.get(debt))); return true; } } }