github.com/cloudwego/hertz@v0.9.3/pkg/app/client/loadbalance/loadbalance.go (about)

     1  /*
     2   * Copyright 2022 CloudWeGo Authors
     3   *
     4   * Licensed under the Apache License, Version 2.0 (the "License");
     5   * you may not use this file except in compliance with the License.
     6   * You may obtain a copy of the License at
     7   *
     8   *     http://www.apache.org/licenses/LICENSE-2.0
     9   *
    10   * Unless required by applicable law or agreed to in writing, software
    11   * distributed under the License is distributed on an "AS IS" BASIS,
    12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13   * See the License for the specific language governing permissions and
    14   * limitations under the License.
    15   */
    16  
    17  package loadbalance
    18  
    19  import (
    20  	"time"
    21  
    22  	"github.com/cloudwego/hertz/pkg/app/client/discovery"
    23  )
    24  
    25  // Loadbalancer picks instance for the given service discovery result.
    26  type Loadbalancer interface {
    27  	// Pick is used to select an instance according to discovery result
    28  	Pick(discovery.Result) discovery.Instance
    29  
    30  	// Rebalance is used to refresh the cache of load balance's information
    31  	Rebalance(discovery.Result)
    32  
    33  	// Delete is used to delete the cache of load balance's information when it is expired
    34  	Delete(string)
    35  
    36  	// Name returns the name of the Loadbalancer.
    37  	Name() string
    38  }
    39  
    40  const (
    41  	DefaultRefreshInterval = 5 * time.Second
    42  	DefaultExpireInterval  = 15 * time.Second
    43  )
    44  
    45  var DefaultLbOpts = Options{
    46  	RefreshInterval: DefaultRefreshInterval,
    47  	ExpireInterval:  DefaultExpireInterval,
    48  }
    49  
    50  // Options for LoadBalance option
    51  type Options struct {
    52  	// refresh discovery result timely
    53  	RefreshInterval time.Duration
    54  
    55  	// Balancer expire check interval
    56  	// we need remove idle Balancers for resource saving
    57  	ExpireInterval time.Duration
    58  }
    59  
    60  // Check checks option's param
    61  func (v *Options) Check() {
    62  	if v.RefreshInterval <= 0 {
    63  		v.RefreshInterval = DefaultRefreshInterval
    64  	}
    65  	if v.ExpireInterval <= 0 {
    66  		v.ExpireInterval = DefaultExpireInterval
    67  	}
    68  }