使用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命令的客户端,这种做法称为乐观锁。