Redis 实战------java版本代码优化

来源:互联网 发布:淘宝店铺地址怎么填写 编辑:程序博客网 时间:2024/06/05 02:51

代码清单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;    }