[关闭]
@xtccc 2016-12-05T12:30:23.000000Z 字数 1287 阅读 2192

Pooling

给我写信
GitHub

此处输入图片的描述

开发技巧


参考:



借助于 Apache Commons Pool 我们可以自己实现pooling,例如Phoenix Connection/Redis Connection连接池。



Redis Connector Pooling


首先以Redis Connector Pooling 为例。

我们将使用一个Scala的Redis Connection Client, debasishg/scala-redis

它的基本用法是:

  1. import com.redis._
  2. val r = new RedisClient("localhost", 6379)
  3. r.set("key", "some value")
  4. r.get("key")



下面我们要为它引入pooling机制。

首先要实现一个Factory,它定义了怎样为RedisClient生成PooledObject以及怎样创建一个新的RedisClient

这里我们使用默认的BasePooledObjectFactory

  1. class RedicClientFactory(host: String, port: Int)
  2. extends BasePooledObjectFactory[RedisClient] {
  3. override def wrap(client: RedisClient): PooledObject[RedisClient] =
  4. new DefaultPooledObject[RedisClient](client)
  5. override def create(): RedisClient = new RedisClient(host, port)
  6. }



现在可以使用上面定义的pool。

  1. val pool = new GenericObjectPool[RedisClient](new RedicClientFactory(Host, Port))
  2. pool.setMaxTotal(30)
  3. //pool.setMaxIdle(0) 不能将maxIdle设置地太小,不设置就可以
  4. pool.setBlockWhenExhausted(true)
  5. val manager = new RedisConnManager(pool)
  6. // 开启5000个并发的线程去调用RedisClient
  7. // 但是Pool中最多只有30个可用的RedisClient
  8. val tasks =
  9. for (i <- Range(0, 5000)) yield Future {
  10. val client = manager.borrowConn()
  11. val v = client.get("kk")
  12. if (v.isEmpty)
  13. client.set("kk", 1)
  14. else {
  15. println(i + " : " + v.get)
  16. client.set("kk", v.get.toInt + 1)
  17. }
  18. Thread.sleep(100)
  19. manager.returnConn(client)
  20. }
  21. Await.result(Future.sequence(tasks), 2000 seconds)
  22. println("down")
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注