module Yrpc class Server def initialize(options = {}) @options = options || {} @interceptors = options.fetch(:interceptor_registry, Yrpc.interceptors) @interceptors = Yrpc::Interceptors::Registry.new unless @interceptors.is_a?(Yrpc::Interceptors::Registry) @services = [] @started = false @stop_server = false @stop_server_cv = ConditionVariable.new @stop_server_mu = Monitor.new @server_mu = Monitor.new @hostname = options.fetch(:hostname, Yrpc.server_binding_url) load_models load_controllers end attr_reader :options def controllers_path options.fetch(:controllers_path, Yrpc.controllers_path) end def grpc_server # 互斥锁 操作相同的资源 @server_mu.synchronize do @server ||= begin server = GRPC::RpcServer.new(@options) @port = server.add_http2_port(@hostname, ssl_credentials) @services.each do |service| server.handle(service) end server end end end def add_service(service) @services << service unless @services.include?(service) end def ssl_credentials if options.fetch(:use_ssl, Yrpc.use_ssl) private_key = File.read(options.fetch(:ssl_key_file, Yrpc.ssl_key_file)) cert_chain = File.read(options.fetch(:ssl_crt_file, Yrpc.ssl_crt_file)) certs = [nil, [{private_key: private_key, cert_chain: cert_chain}], false] GRPC::Core::ServerCredentials.new(*certs) else :this_port_is_insecure end end def load_controllers return unless File.directory?(controllers_path) path = File.realpath(controllers_path) $LOAD_PATH.unshift(path) p path Dir["#{path}/**/*.rb"].each do |f| # 把pb文件给exclue next if f.include?('_pb') Yrpc.logger.info "- Loading gRPC service file: #{f}" load File.realpath(f) end end def load_models return unless File.directory?("app/models") path = File.realpath("app/models") $LOAD_PATH.unshift(path) Dir["#{path}/**/*.rb"].each do |f| # 把pb文件给exclue next if f.include?('_pb') Yrpc.logger.info "- Loading gRPC Model file: #{f}" load File.realpath(f) end end end end