package com.usoft.credit.rest.config;

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

/**
 * @author liuam
 * @since 2018/8/30 0030 下午 17:15
 */
@Configuration
public class GrpcConfig {

    /**
     * 接口连接超时时间,单位毫秒
     */
    public final static CallOptions.Key<Integer> CO_KEY_CONNECTION_TIMEOUT = CallOptions.Key.of("COKey_ConnectionTimeout", 0);

    @Value("${grpc.port}")
    private Integer grpcPort;

    @Value("${grpc.host}")
    private String grpcHost;

    @Bean
    public ManagedChannel managedChannel() {
        return ManagedChannelBuilder.forAddress(grpcHost, grpcPort).usePlaintext().build();
    }

    @Bean
    public GrpcQueryServiceGrpc.GrpcQueryServiceBlockingStub grpcQueryServiceBlockingStub(ManagedChannel managedChannel) {
        GrpcQueryServiceGrpc.GrpcQueryServiceBlockingStub grpcQueryServiceBlockingStub =
                GrpcQueryServiceGrpc.newBlockingStub(managedChannel).withOption(CO_KEY_CONNECTION_TIMEOUT, 60000);
        return grpcQueryServiceBlockingStub;

    }

    @Bean
    public GrpcQueryServiceGrpc.GrpcQueryServiceFutureStub grpcQueryServiceFutureStub(ManagedChannel managedChannel) {
        GrpcQueryServiceGrpc.GrpcQueryServiceFutureStub grpcQueryServiceFutureStub =
                GrpcQueryServiceGrpc.newFutureStub(managedChannel).withOption(CO_KEY_CONNECTION_TIMEOUT, 5000);
        return grpcQueryServiceFutureStub;
    }
}
