package com.usoft.fin.grpc.bl.config;

import com.usoft.sso.grpc.api.protobuf.SSOGrpcServiceGrpc;
import io.grpc.CallOptions;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * grpc配置
 * @author wangmh
 * @date 2018-08-28 15:49
 **/
@Configuration
public class SsoGrpcConfig {
    /**
     * 接口连接超时时间,单位毫秒
     */
    public final static CallOptions.Key<Integer> CO_KEY_CONNECTION_TIMEOUT = CallOptions.Key.of("COKey_ConnectionTimeout", 0);

    @Value("${sso.grpc.host}")
    private String ssoGrpcHost;
    @Value("${sso.grpc.port}")
    private int ssoGrpcPort;

    @Bean(name = "ssoManagedChannel")
    public ManagedChannel getSsoManagedChannel() {
        return ManagedChannelBuilder.forAddress(ssoGrpcHost, ssoGrpcPort).usePlaintext().build();
    }

    @Bean(name = "ssoGrpcSBS")
    public SSOGrpcServiceGrpc.SSOGrpcServiceBlockingStub getSSOGrpcServiceBlockingStub(@Qualifier("ssoManagedChannel") ManagedChannel managedChannel) {
        SSOGrpcServiceGrpc.SSOGrpcServiceBlockingStub ssoGrpcServiceBlockingStub =
                SSOGrpcServiceGrpc.newBlockingStub(managedChannel).withOption(CO_KEY_CONNECTION_TIMEOUT, 5000);
        return ssoGrpcServiceBlockingStub;
    }

    @Bean(name = "ssoGrpcSFS")
    public SSOGrpcServiceGrpc.SSOGrpcServiceFutureStub getSSOGrpcServiceFutureStub(@Qualifier("ssoManagedChannel") ManagedChannel managedChannel) {
        SSOGrpcServiceGrpc.SSOGrpcServiceFutureStub ssoGrpcServiceFutureStub  =
                SSOGrpcServiceGrpc.newFutureStub(managedChannel).withOption(CO_KEY_CONNECTION_TIMEOUT, 5000);
        return ssoGrpcServiceFutureStub;
    }

}
