【问题标题】:Sending writes to the mysql master and reads to slave in slick向 mysql master 发送写入并在 slick 中读取到 slave
【发布时间】:2023-03-27 11:36:01
【问题描述】:

使用 Slick 和 MySQL 设置的 Master/Slave,我如何确保将写入(INSERT、UPDATE 等)发送到主服务器,并将读取(SELECT)发送到从服务器?

【问题讨论】:

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


    【解决方案1】:

    根据MySQL docs on this,我们需要设置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
    }
    

    【讨论】:

    • 如果在运行“Database.threadLocalSession.conn.setReadOnly(false)”时出现“java.sql.SQLException: No database selected”,我可以通过升级到 MySQL 连接器 5.1 来解决这个问题。 32
    猜你喜欢
    • 2016-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-17
    • 1970-01-01
    • 2017-09-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多