发送写入到mysql主服务器并以光滑方式读取到从服务器

时间:2013-10-15 09:59:32

标签: mysql scala slick master-slave slick-2.0

使用Slick和Master / Slave设置MySQL时,如何确保将写入(INSERTUPDATE等)发送到主服务器并读取(SELECT)发送给奴隶?

1 个答案:

答案 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
}