cluster.go 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139
  1. // Copyright (c) 2012 The gocql Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package gocql
  5. import (
  6. "errors"
  7. "sync"
  8. "time"
  9. "github.com/golang/groupcache/lru"
  10. )
  11. const defaultMaxPreparedStmts = 1000
  12. //Package global reference to Prepared Statements LRU
  13. var stmtsLRU preparedLRU
  14. //preparedLRU is the prepared statement cache
  15. type preparedLRU struct {
  16. sync.Mutex
  17. lru *lru.Cache
  18. }
  19. //Max adjusts the maximum size of the cache and cleans up the oldest records if
  20. //the new max is lower than the previous value. Not concurrency safe.
  21. func (p *preparedLRU) Max(max int) {
  22. for p.lru.Len() > max {
  23. p.lru.RemoveOldest()
  24. }
  25. p.lru.MaxEntries = max
  26. }
  27. func initStmtsLRU(max int) {
  28. if stmtsLRU.lru != nil {
  29. stmtsLRU.Max(max)
  30. } else {
  31. stmtsLRU.lru = lru.New(max)
  32. }
  33. }
  34. // To enable periodic node discovery enable DiscoverHosts in ClusterConfig
  35. type DiscoveryConfig struct {
  36. // If not empty will filter all discoverred hosts to a single Data Centre (default: "")
  37. DcFilter string
  38. // If not empty will filter all discoverred hosts to a single Rack (default: "")
  39. RackFilter string
  40. // The interval to check for new hosts (default: 30s)
  41. Sleep time.Duration
  42. }
  43. // ClusterConfig is a struct to configure the default cluster implementation
  44. // of gocoql. It has a varity of attributes that can be used to modify the
  45. // behavior to fit the most common use cases. Applications that requre a
  46. // different setup must implement their own cluster.
  47. type ClusterConfig struct {
  48. Hosts []string // addresses for the initial connections
  49. CQLVersion string // CQL version (default: 3.0.0)
  50. ProtoVersion int // version of the native protocol (default: 2)
  51. Timeout time.Duration // connection timeout (default: 600ms)
  52. Port int // port (default: 9042)
  53. Keyspace string // initial keyspace (optional)
  54. NumConns int // number of connections per host (default: 2)
  55. NumStreams int // number of streams per connection (default: 128)
  56. Consistency Consistency // default consistency level (default: Quorum)
  57. Compressor Compressor // compression algorithm (default: nil)
  58. Authenticator Authenticator // authenticator (default: nil)
  59. RetryPolicy RetryPolicy // Default retry policy to use for queries (default: 0)
  60. SocketKeepalive time.Duration // The keepalive period to use, enabled if > 0 (default: 0)
  61. ConnPoolType NewPoolFunc // The function used to create the connection pool for the session (default: NewSimplePool)
  62. DiscoverHosts bool // If set, gocql will attempt to automatically discover other members of the Cassandra cluster (default: false)
  63. MaxPreparedStmts int // Sets the maximum cache size for prepared statements globally for gocql (default: 1000)
  64. PageSize int // Default page size to use for created sessions (default: 0)
  65. Discovery DiscoveryConfig
  66. SslOpts *SslOptions
  67. }
  68. // NewCluster generates a new config for the default cluster implementation.
  69. func NewCluster(hosts ...string) *ClusterConfig {
  70. cfg := &ClusterConfig{
  71. Hosts: hosts,
  72. CQLVersion: "3.0.0",
  73. ProtoVersion: 2,
  74. Timeout: 600 * time.Millisecond,
  75. Port: 9042,
  76. NumConns: 2,
  77. NumStreams: 128,
  78. Consistency: Quorum,
  79. ConnPoolType: NewSimplePool,
  80. DiscoverHosts: false,
  81. MaxPreparedStmts: defaultMaxPreparedStmts,
  82. }
  83. return cfg
  84. }
  85. // CreateSession initializes the cluster based on this config and returns a
  86. // session object that can be used to interact with the database.
  87. func (cfg *ClusterConfig) CreateSession() (*Session, error) {
  88. //Check that hosts in the ClusterConfig is not empty
  89. if len(cfg.Hosts) < 1 {
  90. return nil, ErrNoHosts
  91. }
  92. pool := cfg.ConnPoolType(cfg)
  93. //Adjust the size of the prepared statements cache to match the latest configuration
  94. stmtsLRU.Lock()
  95. initStmtsLRU(cfg.MaxPreparedStmts)
  96. stmtsLRU.Unlock()
  97. //See if there are any connections in the pool
  98. if pool.Size() > 0 {
  99. s := NewSession(pool, *cfg)
  100. s.SetConsistency(cfg.Consistency)
  101. s.SetPageSize(cfg.PageSize)
  102. if cfg.DiscoverHosts {
  103. hostSource := &ringDescriber{
  104. session: s,
  105. dcFilter: cfg.Discovery.DcFilter,
  106. rackFilter: cfg.Discovery.RackFilter,
  107. }
  108. go hostSource.run(cfg.Discovery.Sleep)
  109. }
  110. return s, nil
  111. }
  112. pool.Close()
  113. return nil, ErrNoConnectionsStarted
  114. }
  115. var (
  116. ErrNoHosts = errors.New("no hosts provided")
  117. ErrNoConnectionsStarted = errors.New("no connections were made when creating the session")
  118. ErrHostQueryFailed = errors.New("unable to populate Hosts")
  119. )