代码清单4-5 listItem()函数
原版代码:
public boolean listItem(
Jedis conn, String itemId, String sellerId, double price) {
String inventory = "inventory:" + sellerId;
String item = itemId + '.' + sellerId;
long end = System.currentTimeMillis() + 5000;
while (System.currentTimeMillis() < end) {
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> results = trans.exec();
// null response indicates that the transaction was aborted due to
// the watched key changing.
if (results == null){
continue;
}
return true;
}
return false;
}
在实际项目运行的改进代码
public boolean listItem(Jedis conn, String itemId, String sellerId, double price) {
//1.执行初始化操作:拼接字符串得到key值
String inventory=new StringBuffer().append("inventory:").append(sellerId).toString();
String item=new StringBuffer().append(itemId).append(".").append(sellerId).toString();
long end = System.currentTimeMillis() + 5000;
while (System.currentTimeMillis() < end) {
//2.对卖家包裹进行监视
conn.watch(inventory);
//3.验证卖家想要销售的商品是否存在与卖家的包裹当中
if (!conn.sismember(inventory, itemId)){
conn.unwatch();
return false;
}
//商品存在于卖家的包裹之中,开启事物
Transaction trans = conn.multi();
//在商品添加到买卖市场中
trans.zadd("market:", price, item);
//移除卖家包裹中的商品
trans.srem(inventory, itemId);
//提交事物
List<Object> results = trans.exec();
// null response indicates that the transaction was aborted due to
// the watched key changing.
//判断事物是否成功执行
if (results == null){
//事物执行失败,继续执行事物
continue;
}
//事物执行成功,返回
return true;
}
conn.close();
//超时
return false;
}
版权声明:本文为xl3379307903原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。