使用 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() 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()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 res=trans.exec(); if(res==null){ continue; } return true; } return false; }
总结
Redis 为了尽可能地减少客户端的等待时间,并不会在执行 watch 命令时对数据进行加锁(与关系数据库的区别)。相反的,redis 只会在数据已经被其他客户端抢先修改的情况下,通知执行了 watch 命令的客户端,这种做法称为乐观锁。
来源: http://www.92to.com/bangong/2017/08-17/27110928.html