瀏覽代碼

Factor out locked registration and alphabetize.

Richard Crowley 12 年之前
父節點
當前提交
d49553bfb5
共有 2 個文件被更改,包括 19 次插入21 次删除
  1. 18 20
      registry.go
  2. 1 1
      registry_test.go

+ 18 - 20
registry.go

@@ -15,12 +15,12 @@ type Registry interface {
 	// Get the metric by the given name or nil if none is registered.
 	Get(string) interface{}
 
-	// Register the given metric under the given name.
-	Register(string, interface{})
-
 	// Gets an existing metric or creates and registers a new one.
 	GetOrRegister(string, interface{}) interface{}
 
+	// Register the given metric under the given name.
+	Register(string, interface{})
+
 	// Run all registered healthchecks.
 	RunHealthchecks()
 
@@ -54,34 +54,25 @@ func (r *StandardRegistry) Get(name string) interface{} {
 	return r.metrics[name]
 }
 
-// Register the given metric under the given name.
-func (r *StandardRegistry) Register(name string, i interface{}) {
-	switch i.(type) {
-	case Counter, Gauge, Healthcheck, Histogram, Meter, Timer:
-		r.mutex.Lock()
-		defer r.mutex.Unlock()
-		r.metrics[name] = i
-	}
-}
-
 // Gets an existing metric or creates and registers a new one. Threadsafe
 // alternative to calling Get and Register on failure.
 func (r *StandardRegistry) GetOrRegister(name string, i interface{}) interface{} {
 	r.mutex.Lock()
 	defer r.mutex.Unlock()
 	if metric, ok := r.metrics[name]; ok {
-		// Found existing metric, return it instead of the new instance
 		return metric
 	}
-
-	// No existing metric, register the new instance
-	switch i.(type) {
-	case Counter, Gauge, Healthcheck, Histogram, Meter, Timer:
-		r.metrics[name] = i
-	}
+	r.register(name, i)
 	return i
 }
 
+// Register the given metric under the given name.
+func (r *StandardRegistry) Register(name string, i interface{}) {
+	r.mutex.Lock()
+	defer r.mutex.Unlock()
+	r.register(name, i)
+}
+
 // Run all registered healthchecks.
 func (r *StandardRegistry) RunHealthchecks() {
 	r.mutex.Lock()
@@ -100,6 +91,13 @@ func (r *StandardRegistry) Unregister(name string) {
 	delete(r.metrics, name)
 }
 
+func (r *StandardRegistry) register(name string, i interface{}) {
+	switch i.(type) {
+	case Counter, Gauge, Healthcheck, Histogram, Meter, Timer:
+		r.metrics[name] = i
+	}
+}
+
 func (r *StandardRegistry) registered() map[string]interface{} {
 	metrics := make(map[string]interface{}, len(r.metrics))
 	r.mutex.Lock()

+ 1 - 1
registry_test.go

@@ -35,7 +35,7 @@ func TestRegistry(t *testing.T) {
 	}
 }
 
-func TestGetOrRegister(t *testing.T) {
+func TestRegistryGetOrRegister(t *testing.T) {
 	r := NewRegistry()
 
 	// First metric wins with GetOrRegister