zoukankan      html  css  js  c++  java
  • mysql asyn 示例

    这篇文章摘自mysql asyn作者的博客,博客地址

    开头有一个简单示例,然后是一个在play上的应用。例子我并没有跑过,但是仍能学到不少东西。

    object BasicExample {
        def main(args: Array[String]) {
            // 这个Parser我发现好像用不了。。
            val configuration = URLParser.parse("")
            val connection: Connection = new PostgreSQLConnection(configuration)
    
            //阻塞等待连接
            Await.result(connection.connect, 5 seconds)
    
            //sendQuery直接就执行了,不像slick那样,还要单独的run
            val future: Future[QueryResult] = connection.sendQuery("SELECT * FROM USERS")
    
            val mapResult: Future[Any] = future.map(queryResult => queryResult.rows match {
                case Some(resultSet) => {
                    val row: RowDat = resultSet.head
                    row(0)
                }
                //注意,这里的-1是Any而不是Future[Any]
                case None => -1
            })
    
            val result = Await.result(mapResult, 5 seconds)
            println(result)
            //关闭数据库链接
            connection.disconnect
        }
    }

    The basic usage pattern is quite simple, you ask for something, you get a future[_] back. The PostgreSQLConnection is a real connection to database. it implements the Connection trait and you should try to use the trait as much as possible. 

    When you create a connection handler, it's not connected to the db yet, you have to connect it yourself calling connect and waiting for the future to return or composing on the future to do something else.

    下面是一个play app. 包括MVC模型。因为Controller牵扯了太多play的知识,我就暂时不抄了,只把持久化部分写上。

    这个持久化实现了ResultSet到case class的mapping,虽然是手动进行的,但是写的非常好。如果能使用implicit写mapping应该会更加优雅。

    此外,一个play app应该选用connection pool而不是每次用到数据库都重新建立连接。下面给出了用法。

    // 需要提前创建好数据库,id应该是自增的
    case class Message(id: Option[Long], content: String: LocalDate = LocalDate.now())
    
    object MessageRepository {
        val Insert = "INSERT INTO messages (content, moment) VALUES(?, ?)"
        val Update = "UPDATE messages SET content = ?, moment = ? WHERE id = ?"
        val Select = "SELECT id, content, moment FROM messages ORDER BY id asc"
        val SelectOne = "SELECT id, content, momment FROM messages WHERE id = ?"
    }
    
    // 这个有点dependency injection的意思
    class MessageRepository(pool: Content) {
        import MessageRepository._
    
        def save(m: Message): Future[Message] = {
            // queryResult => m 是什么意思
            case Some(id) => pool.sendPreparedStatement(Update, Array(m.content, m.moment, id)).
                map { queryResult => m }
            case None => pool.sendPreparedStatement(Insert, Array(m.content, m.moment)).
                map { queryResult => m }
        }
    
        def list: Future[IndexSeq[Message]] = {
            pool.sendQuery(Select). map {
                //rows 返回resultSet, get返回什么呢,返回的是 Iterator 类型的东西么
                queryResult => queryResult.rows.get.map {
                    item => rowToMessage(item)
                }
            }
        }
    
        def find(id: Long): Future[Option[Message]] = {
            //[Any] 非得加么
            pool.sendPreparedStatement(SelectOne, Array[Any](id)).map {
                queryResult =>
                    queryResult.rows match {
                        case Some(rows) => 
                            Some(rowToMessage(rows.apply(0)))
                        case None => None
                    }
            }
        }
    
        private def rowToMessage(row: RowData): Message = {
            new Message(
                id = Some(row("id".asInstanceOf[Long]))
                content = row("content").asInstanceOf[String]
                moment = row("moment").asInstanceOf[LocalDate]
            )
        }
    }

    对于mysql的每一张表,都应该有一个这样的插入语句,对于多表join的情况,可能要单独处理吧。

    上面实现了DAO,下面一小段代码可以充当配置文件来用,相当于dependency injection

    object Global extends GlobalSettings {
        private val databaseConfiguration = System.getenv("DATABASE_URL") match {
            case url: String => URLParser.parse(url)
            case _ => new Configuration(
                username = "postgres"
                database = Some("databasename")
                port     = 5433
            )
        }
    
        // factory 还有mysql专用版么
        private val factory = new PostgreSQLFactory(databaseConfiguration)
        private val pool    = new ConnectionPool(factory, PoolConfiguration.Default)
        val messageRepository = new MessageRepository( pool )
    
    //    play 的东西,普通的程序不晓得如何处理close问题
        override def onStop(app: Application)
            pool.close
    }

    对于一般的程序,用connectionPool要好一点,但是要注意,不能直接在connectionPool上应用transacation。当需要用到transacation时,从connectionPool中获取一个connection,还要记得还回去。

  • 相关阅读:
    opencv ellipse
    Spring.NET实用技巧4——NHibernate分布式事务(下)
    Spring.NET企业架构实践之 Nhibernate + WCF + ASP.NET MVC + NVelocity 对PetShop4.0重构(二)——领域模型
    Spring.NET实用技巧3——NHibernate分布式事务(上)
    Spring.NET企业架构实践之 NHibernate + Spring.NET + WCF + Windows服务 + Silverlight 中小企业应用架构完整Demo
    关于nunit调试VS2010中的4.0程序集的问题
    Spring.NET企业架构实践之 Nhibernate + WCF + ASP.NET MVC + NVelocity 对PetShop4.0重构(三)——持久层
    Spring.NET实用技巧5——WCF环境下的NHibernate分布式事务
    有多少可爱IT精英,他们的爱情屡屡“挨踢”
    Spring.NET 1.3.1 正式版已发布
  • 原文地址:https://www.cnblogs.com/xinsheng/p/4335919.html
Copyright © 2011-2022 走看看