Class: Xconsul::LoadBalancer

Inherits:
Object
  • Object
show all
Defined in:
lib/xconsul/load_balancer.rb

Overview

balancer = Xconsul::LoadBalancer.new({}); balancer.host

Constant Summary collapse

DEFAULT_CACHE_EXPIRED_SECONDS =
30

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(consul_options, balance_options = {}) ⇒ LoadBalancer

consul_options

service_name(必填): consul服务的名称
cache_expired_seconds(可选):hosts缓存有效期,每隔一定时间从consul获取最新list,不传使用默认值
use_fixed_hosts(可选,默认false): 为true使用固定hosts,主要用于dev环境,或者暂时不使用consul
fixed_hosts(可选): 手工配置的hosts列表,当use_fixed_hosts 为true时必须传入,格式为['10.10.142.233:8890', 'xxx']

balance_options [Hash]:

balance_algorithm 负载均衡算法,暂时无用,只有一种算法,自动使用


23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/xconsul/load_balancer.rb', line 23

def initialize(consul_options, balance_options = {})
  @consul_service_name = consul_options[:service_name]
  @cache_expired_seconds = consul_options[:cache_expired_seconds].to_i
  @cache_expired_seconds = DEFAULT_CACHE_EXPIRED_SECONDS if @cache_expired_seconds <= 5

  balance_algorithm = :round_robin
  @load_balance_processor = generate_load_balance_processor(balance_algorithm)

  if consul_options[:use_fixed_hosts] == true
    @latest_hosts = consul_options[:fixed_hosts]
    @last_timestamp = Time.now.to_i + 315360000 # 设置一个未来10年的时间戳,cache不过期
  else
    @latest_hosts = []
  end
end

Instance Attribute Details

#cache_expired_secondsObject

hosts缓存有效期,每隔一定时间从consul获取最新list,不传使用默认值



13
14
15
# File 'lib/xconsul/load_balancer.rb', line 13

def cache_expired_seconds
  @cache_expired_seconds
end

#consul_service_nameObject

consul service 名称



10
11
12
# File 'lib/xconsul/load_balancer.rb', line 10

def consul_service_name
  @consul_service_name
end

#last_timestampObject

上次获取hosts的时间戳



12
13
14
# File 'lib/xconsul/load_balancer.rb', line 12

def last_timestamp
  @last_timestamp
end

#latest_hostsObject

最近一次获取的hosts



11
12
13
# File 'lib/xconsul/load_balancer.rb', line 11

def latest_hosts
  @latest_hosts
end

#load_balance_processorObject

load balancer



14
15
16
# File 'lib/xconsul/load_balancer.rb', line 14

def load_balance_processor
  @load_balance_processor
end

Instance Method Details

#hostObject

获取一个host with port,示例:‘10.10.142.233:8890’



40
41
42
43
44
# File 'lib/xconsul/load_balancer.rb', line 40

def host
  hosts = hosts_with_cache
  raise "consul_service:#{consul_service_name} 无可用hosts" if hosts.length.zero?
  @load_balance_processor.select(hosts)
end