zoukankan      html  css  js  c++  java
  • 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);
        }
    
    
    
        public static boolean isSuccess(String balance,String debt,Long delAmount) throws InterruptedException {
            Jedis jedis = new Jedis("127.0.0.1",6379);
         // Watch 命令用于监视一个(或多个) key ,如果在事务执行之前这个(或这些) key 被其他命令所改动,那么事务将被打断 jedis.watch(balance); Long amount
    = Long.parseLong(jedis.get(balance)); Long debts = Long.parseLong(jedis.get(debt)); if(amount<delAmount){
           //Redis Unwatch 命令用于取消 WATCH 命令对所有 key 的监视。 jedis.unwatch(); System.out.println(
    "amount can't Less than delAmount !!!!"); return false; } {
           //Redis 通过 MULTI 开始一个事务, 然后将多个命令入队到事务中, 最后由 EXEC 命令触发事务 Transaction transaction
    = jedis.multi(); transaction.decrBy(balance, delAmount); transaction.incrBy(debt,delAmount); //在这里模拟网络延迟时,我们通过redis命令窗口手动去修改balance值。
            
                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;
            }
        }
    }

  • 相关阅读:
    破解密码那些事儿(Hacking Secret Ciphers with Python)
    Hacking Secret Ciphers with Python翻译序言
    闲话高并发的那些神话,看京东架构师如何把它拉下神坛
    实现rabbitmq 延迟队列功能
    日志文件的编写
    依赖倒置、控制反转和依赖注入的区分
    Oracle ORA-01722: 无效数字 处理方法
    Time.timeScale 对 协程WaitForSeconds的影响
    [转]Coroutine,你究竟干了什么?
    转:Automatic Layout Groups
  • 原文地址:https://www.cnblogs.com/Eugene-Jin/p/12883757.html
Copyright © 2011-2022 走看看