Redis 事务

使用Java实现一个商品买卖市场

将商品放到市场上销售

代码如下

public boolean listItem(Jedis conn,String itemId,String sellerId,double price){
        String inventory="inventory:"+sellerId;//卖家包裹
        String item=itemId+'.'+sellerId;//商品号由商品id和卖家id组成
        long end=System.currentTimeMillis()+5000;
        while (System.currentTimeMillis()<end) {//超出5秒,结束
            conn.watch(inventory);//首先监视卖家的包裹的变化
            if(!conn.sismember(inventory, itemId)){
                conn.unwatch();
                return false;
            }
            Transaction trans=conn.multi();//事务
            trans.zadd("market:", price, item);
            trans.srem(inventory, itemId);//移除是因为卖家把自己的东西从包裹中拿出来放到了市场中卖
            List<Object> res=trans.exec();
            if(res==null){//如果res为空,说明事务被中断,因为被监视的键正在改变
                continue;
            }
            return true;
        }
        return false;
    }

购买商品

代码如下

public boolean purchaseItem(Jedis conn,String buyerId,String itemId,String sellerId,double lprice){
        String buyer="users:"+buyerId;
        String seller="users:"+sellerId;
        String item=itemId+'.'+sellerId;
        String inventory="inventory:"+buyerId;
        long end=System.currentTimeMillis()+10000;
        while(System.currentTimeMillis()<end){
            conn.watch("market:"+buyer);//对市场以及买家的个人信息进行监视
            double price=conn.zscore("market:", item);
            double funds=Double.parseDouble(conn.hget(buyer, "funds"));
            if(price!=lprice||price>funds){//检查买家想要购买的商品价格是否变化,以及是否有足够的钱购买
                conn.unwatch();
                return false;
            }
            Transaction trans=conn.multi();
            trans.hincrBy(seller, "funds", (int)price);
            trans.hincrBy(buyer, "funds", (int)-price);
            trans.sadd(inventory, itemId);
            trans.zrem("market:", item);
            List<Object> res=trans.exec();
            if(res==null){
                continue;
            }
            return true;
        }
        return false;
    }

总结

Redis为了尽可能地减少客户端的等待时间,并不会在执行watch命令时对数据进行加锁(与关系数据库的区别)。相反的,redis只会在数据已经被其他客户端抢先修改的情况下,通知执行了watch命令的客户端,这种做法称为乐观锁。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值