如果使用MySQL设置了Slave和主从程序,如何确保将写入(INSERT、UPDATE等)发送给主,并将读(SELECT)发送给奴隶?
发布于 2013-10-15 09:59:31
根据这方面的MySQL文档,我们需要设置Connection#setReadOnly(true|false)。
在slick中这样做的一个很好的方法是在数据库代码中添加以下函数:
/**
* Runs a block of read only database code. No transaction required.
*/
def readOnly[T](f: => T) = db withSession {
Database.threadLocalSession.conn.setReadOnly(true)
f
}
/**
* Runs a block of read/write database code in a transaction.
* Any exceptions will rollback any writes.
*/
def readWrite[T](f: => T) = db withTransaction {
Database.threadLocalSession.conn.setReadOnly(false)
f
}然后您可以编写如下所示的查询:
/**
* Goes to slave
*/
def findUser(id: String) = readOnly {
sql"SELECT ... FROM user WHERE id = $id".as[User].firstOption
}
/**
* Goes to master
*/
def createUser(id: String) = readWrite {
sqlu"INSERT INTO user VALUES(...)".execute
}https://stackoverflow.com/questions/19378293
复制相似问题