dubbo.apache.org/dubbo-go/v3@v3.1.1/metrics/bus.go (about)

     1  /*
     2   * Licensed to the Apache Software Foundation (ASF) under one or more
     3   * contributor license agreements.  See the NOTICE file distributed with
     4   * this work for additional information regarding copyright ownership.
     5   * The ASF licenses this file to You under the Apache License, Version 2.0
     6   * (the "License"); you may not use this file except in compliance with
     7   * the License.  You may obtain a copy of the License at
     8   *
     9   *     http://www.apache.org/licenses/LICENSE-2.0
    10   *
    11   * Unless required by applicable law or agreed to in writing, software
    12   * distributed under the License is distributed on an "AS IS" BASIS,
    13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    14   * See the License for the specific language governing permissions and
    15   * limitations under the License.
    16   */
    17  
    18  package metrics
    19  
    20  import (
    21  	"sync"
    22  )
    23  
    24  // eventListener is a struct that encapsulates the listener map and provides thread-safe access to it.
    25  type eventListener struct {
    26  	mu       sync.RWMutex
    27  	listener map[string]chan MetricsEvent
    28  }
    29  
    30  var listener = &eventListener{
    31  	listener: make(map[string]chan MetricsEvent),
    32  }
    33  
    34  // Publish publishes an event to all subscribers of the same type.
    35  func Publish(event MetricsEvent) {
    36  	listener.mu.RLock()
    37  	defer listener.mu.RUnlock()
    38  
    39  	if ch, ok := listener.listener[event.Type()]; ok {
    40  		select {
    41  		case ch <- event:
    42  		default:
    43  			// If the channel is full, drop the event to avoid blocking.
    44  		}
    45  	}
    46  }
    47  
    48  // Subscribe subscribes to events of the given type.
    49  func Subscribe(typ string, ch chan MetricsEvent) {
    50  	listener.mu.Lock()
    51  	defer listener.mu.Unlock()
    52  
    53  	listener.listener[typ] = ch
    54  }
    55  
    56  // Unsubscribe unsubscribes from events of the given type.
    57  func Unsubscribe(typ string) {
    58  	listener.mu.Lock()
    59  	defer listener.mu.Unlock()
    60  
    61  	if ch, ok := listener.listener[typ]; ok {
    62  		close(ch)
    63  		delete(listener.listener, typ)
    64  	}
    65  }