使用Slick和Master / Slave设置MySQL时,如何确保将写入(INSERT
,UPDATE
等)发送到主服务器并读取(SELECT
)发送给奴隶?
答案 0 :(得分:7)
根据此MySQL文档,我们需要设置Connection#setReadOnly(true|false)
。
在光滑中执行此操作的一种好方法是将以下函数添加到数据库代码中:
/**
* 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
}