selector.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. /*
  2. Copyright 2011 Google Inc.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package memcache
  14. import (
  15. "hash/crc32"
  16. "os"
  17. "net"
  18. "strings"
  19. "sync"
  20. )
  21. // ServerSelector is the interface that selects a memcache server
  22. // as a function of the item's key.
  23. //
  24. // All ServerSelector implementations must be threadsafe.
  25. type ServerSelector interface {
  26. // PickServer returns the server address that a given item
  27. // should be shared onto.
  28. PickServer(key string) (net.Addr, os.Error)
  29. }
  30. // ServerList is a simple ServerSelector. Its zero value is usable.
  31. type ServerList struct {
  32. lk sync.RWMutex
  33. addrs []net.Addr
  34. }
  35. // SetServers changes a ServerList's set of servers at runtime and is
  36. // threadsafe.
  37. //
  38. // Each server is given equal weight. A server is given more weight
  39. // if it's listed multiple times.
  40. //
  41. // SetServers returns an error if any of the server names fail to
  42. // resolve. No attempt is made to connect to the server. If any error
  43. // is returned, no changes are made to the ServerList.
  44. func (ss *ServerList) SetServers(servers ...string) os.Error {
  45. naddr := make([]net.Addr, len(servers))
  46. for i, server := range servers {
  47. if strings.Contains(server, "/") {
  48. addr, err := net.ResolveUnixAddr("unix", server)
  49. if err != nil {
  50. return err
  51. }
  52. naddr[i] = addr
  53. } else {
  54. tcpaddr, err := net.ResolveTCPAddr("tcp", server)
  55. if err != nil {
  56. return err
  57. }
  58. naddr[i] = tcpaddr
  59. }
  60. }
  61. ss.lk.Lock()
  62. defer ss.lk.Unlock()
  63. ss.addrs = naddr
  64. return nil
  65. }
  66. func (ss *ServerList) PickServer(key string) (net.Addr, os.Error) {
  67. ss.lk.RLock()
  68. defer ss.lk.RUnlock()
  69. if len(ss.addrs) == 0 {
  70. return nil, ErrNoServers
  71. }
  72. // TODO-GO: remove this copy
  73. cs := crc32.ChecksumIEEE([]byte(key))
  74. return ss.addrs[cs%uint32(len(ss.addrs))], nil
  75. }