You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

123 lines
2.4 KiB

  1. // Copyright 2011 Xing Xing <mikespook@gmail.com>.
  2. // All rights reserved.
  3. // Use of this source code is governed by a MIT
  4. // license that can be found in the LICENSE file.
  5. package client
  6. import (
  7. "sync"
  8. "math/rand"
  9. "github.com/mikespook/gearman-go/common"
  10. )
  11. const (
  12. PoolSize = 10
  13. )
  14. type poolClient struct {
  15. *Client
  16. Rate int
  17. }
  18. type SelectionHandler func(map[string]*poolClient, string) string
  19. func SelectWithRate(pool map[string]*poolClient,
  20. last string) (addr string) {
  21. total := 0
  22. for _, item := range pool {
  23. total += item.Rate
  24. if rand.Intn(total) < item.Rate {
  25. return item.addr
  26. }
  27. }
  28. return last
  29. }
  30. func SelectRandom(pool map[string]*poolClient,
  31. last string) (addr string) {
  32. r := rand.Intn(len(pool))
  33. i := 0
  34. for k, _ := range pool {
  35. if r == i {
  36. return k
  37. }
  38. i ++
  39. }
  40. return last
  41. }
  42. type Pool struct {
  43. SelectionHandler SelectionHandler
  44. ErrHandler common.ErrorHandler
  45. clients map[string]*poolClient
  46. mutex sync.Mutex
  47. }
  48. // Create a new pool.
  49. func NewPool() (pool *Pool) {
  50. return &Pool{
  51. clients: make(map[string]*poolClient, PoolSize),
  52. SelectionHandler: SelectWithRate,
  53. }
  54. }
  55. // Add a server with rate.
  56. func (pool *Pool) Add(addr string, rate int) (err error) {
  57. pool.mutex.Lock()
  58. defer pool.mutex.Unlock()
  59. var item *poolClient
  60. var ok bool
  61. if item, ok = pool.clients[addr]; ok {
  62. item.Rate = rate
  63. } else {
  64. var client *Client
  65. client, err = New(addr)
  66. item = &poolClient{Client: client, Rate: rate}
  67. err = item.connect()
  68. pool.clients[addr] = item
  69. }
  70. return
  71. }
  72. // Remove a server.
  73. func (pool *Pool) Remove(addr string) {
  74. pool.mutex.Lock()
  75. defer pool.mutex.Unlock()
  76. delete(pool.clients, addr)
  77. }
  78. func (pool *Pool) Do(funcname string, data []byte,
  79. flag byte, h JobHandler) (handle string, err error) {
  80. return
  81. }
  82. func (pool *Pool) DoBg(funcname string, data []byte,
  83. flag byte) (handle string, err error) {
  84. return
  85. }
  86. // Get job status from job server.
  87. // !!!Not fully tested.!!!
  88. func (pool *Pool) Status(handle string) (status *Status) {
  89. return
  90. }
  91. // Send a something out, get the samething back.
  92. func (pool *Pool) Echo(data []byte) (r []byte) {
  93. return
  94. }
  95. // Close
  96. func (pool *Pool) Close() (err map[string]error) {
  97. err = make(map[string]error)
  98. for _, c := range pool.clients {
  99. err[c.addr] = c.Close()
  100. }
  101. return
  102. }