如何在多线程环境中进行事务时组织OrientDB DAO?

时间:2016-05-25 09:24:53

标签: orientdb

我尝试用OrientDB组织我的DAO架构 下面 - 我的例子:

连接经理:

public class DB {

    private static final OPartitionedDatabasePoolFactory poolFactory = new OPartitionedDatabasePoolFactory();

    public static ODatabaseDocumentTx fromPool() {
        return poolFactory.get(sDbUrl, sDbUser, sDbPassword).acquire();
    }
}

Dao(它在多线程环境中使用):

public class Dao {

    public static void addGold(String rid, long gold) {
        try (ODatabaseDocumentTx db = DB.fromPool()) {
            final String updateQuery = "UPDATE " + rid + " INCREMENT gold = " + gold + " LOCK RECORD";
            db.command(new OCommandSQL(updateQuery)).execute();
        }
    }

    public static void removeGold(String rid, long gold) {
        try (ODatabaseDocumentTx db = DB.fromPool()) {
            final String updateQuery = "UPDATE " + rid + " INCREMENT gold = " + -gold + " LOCK RECORD";
            db.command(new OCommandSQL(updateQuery)).execute();
        }
    }

    public static String transferGold(String fromRid, String toRid, long gold) {
        try (ODatabaseDocumentTx db = DB.fromPool()) {
            int numTries = 100;
            while (true) {
                try {
                    db.begin(OTransaction.TXTYPE.OPTIMISTIC);
                    removeGold(fromRid, gold);
                    addGold(toRid, gold);
                    db.commit();
                    return "ok";
                } catch (OConcurrentModificationException e) {
                    db.rollback();
                    if (--numTries == 0) {
                        return "error";
                    }
                }
            }
        }
    }
}

在交易的情况下从池中获取连接是否有效?那么相同的数据库实例将在同一个线程中返回吗?

欢迎任何其他建议

1 个答案:

答案 0 :(得分:0)

使用OPartitionedDatabasePool应该是线程安全的,并提供一种获取连接的方法。我认为OPartitionedDatabasePoolFactory仅在您要创建多个OPartitionedDatabasePool实例时使用。

OPartitionedDatabasePool的静态实例:

OPartitionedDatabasePool myPool = new OPartitionedDatabasePool(dbUrl, user, password);

然后任何时候线程都需要连接:

ODatabaseDocumentTx dbConnection = MyClass.myPool.acquire();

(与使用OPartitionedDatabasePoolFactory的代码一样)。

池应该自动处理获取将在您的线程上运行的数据库连接。