Java 类io.grpc.BindableService 实例源码

项目:saluki    文件:GrpcServerStrategy.java   
public GrpcServerStrategy(GrpcURL providerUrl, Object protocolImpl){
    if (protocolImpl instanceof BindableService) {
        this.exporter = new GrpcStubServerExporter();
        this.protocolClass = protocolImpl.getClass();
    } else {
        Class<?> protocol;
        try {
            protocol = ReflectUtils.name2class(providerUrl.getServiceInterface());
            if (!protocol.isAssignableFrom(protocolImpl.getClass())) {
                throw new IllegalStateException("protocolClass " + providerUrl.getServiceInterface()
                                                + " is not implemented by protocolImpl which is of class "
                                                + protocolImpl.getClass());
            }
        } catch (ClassNotFoundException e) {
            protocol = protocolImpl.getClass();
        }
        this.protocolClass = protocol;
        this.exporter = new DefaultProxyExporter(providerUrl);
    }
    this.protocolImpl = protocolImpl;
}
项目:grpc-java-contrib    文件:GrpcServerHostTest.java   
@Test
public void getPortReturnsServerPortForRunningServer() throws Exception {
    final int configPort = ThreadLocalRandom.current().nextInt(1000, 2000);
    final int serverPort = ThreadLocalRandom.current().nextInt(2000, 3000);
    final int serviceCount = ThreadLocalRandom.current().nextInt(5, 10);
    final long shutdownWaitTimeInMillis = ThreadLocalRandom.current().nextLong(1000, 10000);

    final ApplicationContext applicationContext = mock(ApplicationContext.class);
    final Server server = mock(Server.class, new TriesToReturnSelf());
    final GrpcServerFactory factory = (p, s) -> server;

    final Map<String, Object> services = IntStream.range(0, serviceCount)
            .mapToObj(i -> mock(BindableService.class))
            .collect(Collectors.toMap(s -> UUID.randomUUID().toString(), s -> s));

    when(applicationContext.getBeansWithAnnotation(eq(GrpcService.class))).thenReturn(services);

    when(server.getPort()).thenReturn(serverPort);

    GrpcServerHost runner = new GrpcServerHost(configPort, shutdownWaitTimeInMillis, factory);
    runner.setApplicationContext(applicationContext);

    runner.start();

    assertThat(runner.getPort()).isEqualTo(serverPort);
}
项目:ibole-microservice    文件:SpringBeanServiceDefinitionLoader.java   
private void loadService() {
  LOG.info("Load service definition is starting...");
  //find and get all ServiceExporter-enabled beans
  try {
    getBeanNamesByTypeWithAnnotation(ServiceExporter.class, BindableService.class)
            .forEach(name->{
                BindableService srv = SpringContainer.getContext().getBeanFactory().getBean(name, BindableService.class);
                ServerServiceDefinition serviceDefinition = srv.bindService();
                //GRpcService gRpcServiceAnn = SpringContainer.getContext().findAnnotationOnBean(name, ServiceExporter.class);
                //serviceDefinition  = bindInterceptors(serviceDefinition,gRpcServiceAnn,globalInterceptors);
                //serverBuilder.addService(serviceDefinition);
                //log.info("'{}' service has been registered.", srv.getClass().getName());
                services.add(new GrpcServiceDefinition(serviceDefinition));
            });
  } catch (Exception e) { 
    LOG.warn("Exception happened when loading all service definitions", e);
  }
  LOG.info("Load service denifition is finished, total {} service are found.", services.size());
}
项目:spring-boot-starter-grpc    文件:AnnotationGrpcServiceDiscoverer.java   
@Override
public Collection<GrpcServiceDefinition> findGrpcServices() {
    Collection<String> beanNames = findGrpcServiceBeanNames();
    List<GrpcServiceDefinition> definitions = new ArrayList<GrpcServiceDefinition>(
            beanNames.size());
    for (String beanName : beanNames) {
        Object bean = this.applicationContext.getBean(beanName);
        Class<?> beanClazz = bean.getClass();
        if (!BindableService.class.isAssignableFrom(beanClazz)) {
            throw new IllegalStateException(beanClazz.getName() + " does not seem to extend a generated base implementation nor implements BindableService");
        }

        definitions.add(new GrpcServiceDefinition(beanName, (BindableService) bean));
    }
    return definitions;
}
项目:saluki    文件:GrpcStubServerExporter.java   
@Override
public ServerServiceDefinition export(Class<?> protocol, Object protocolImpl) {
    Object obj = protocolImpl;
    if (!(obj instanceof BindableService)) {
        throw new IllegalStateException(" Object is not io.grpc.BindableService,can not export " + obj);
    } else {
        BindableService bindableService = (BindableService) obj;
        log.info("'{}' service has been registered.", bindableService.getClass().getName());
        return bindableService.bindService();
    }
}
项目:grpc-java-contrib    文件:SimpleGrpcServerFactory.java   
@Override
public Server buildServerForServices(int port, Collection<BindableService> services) {
    ServerBuilder builder = ServerBuilder.forPort(port);
    setupServer(builder);
    services.forEach(service -> registerService(builder, service));
    return builder.build();
}
项目:grpc-java-contrib    文件:GrpcServerHost.java   
/**
 * Start the gRPC {@link Server}.
 *
 * @throws IOException if unable to bind to server address or port
 * @throws IllegalStateException if any non-{@link BindableService} classes are annotated with {@link GrpcService}
 */
public void start() throws IOException {
    if (serverFactory == null) {
        serverFactory = findServerFactory();
    }

    final Collection<BindableService> services = getServicesFromApplicationContext();

    if (services.isEmpty()) {
        throw new IOException("gRPC server not started because no services were found in the application context.");
    }

    server = serverFactory.buildServerForServices(port, services);
    server.start();
}
项目:grpc-java-contrib    文件:GrpcServerHost.java   
private Collection<BindableService> getServicesFromApplicationContext() {
    Map<String, Object> possibleServices = new HashMap<>();

    for (Class<? extends Annotation> annotation : serverFactory.forAnnotations()) {
        possibleServices.putAll(applicationContext.getBeansWithAnnotation(annotation));
    }

    Collection<String> invalidServiceNames = possibleServices.entrySet().stream()
            .filter(e -> !(e.getValue() instanceof BindableService))
            .map(Map.Entry::getKey)
            .collect(Collectors.toList());

    if (!invalidServiceNames.isEmpty()) {
        throw new IllegalStateException((format(
                "The following beans are annotated with @GrpcService, but are not BindableServices: %s",
                String.join(", ", invalidServiceNames))));
    }

    return possibleServices.values().stream().map(s -> (BindableService) s).collect(Collectors.toList());
}
项目:grpc-java-contrib    文件:GrpcServerHostTest.java   
@Test
public void startStartsServerWithServices() throws Exception {
    final int port = ThreadLocalRandom.current().nextInt(1000, 10000);
    final int serviceCount = ThreadLocalRandom.current().nextInt(5, 10);
    final long shutdownWaitTimeInMillis = ThreadLocalRandom.current().nextLong(1000, 10000);

    final ApplicationContext applicationContext = mock(ApplicationContext.class);
    final Server server = mock(Server.class, new TriesToReturnSelf());
    when(server.getPort()).thenReturn(port);

    final Map<String, Object> services = IntStream.range(0, serviceCount)
            .mapToObj(i -> mock(BindableService.class))
            .collect(Collectors.toMap(s -> UUID.randomUUID().toString(), s -> s));

    AtomicBoolean built = new AtomicBoolean(false);

    GrpcServerFactory fakeFactory = (p, s) -> {
        built.set(true);
        assertThat(p).isEqualTo(port);
        s.forEach(ss -> assertThat(services.values().contains(ss)).isTrue());
        return server;
    };

    when(applicationContext.getBeansWithAnnotation(eq(GrpcService.class))).thenReturn(services);

    GrpcServerHost runner = new GrpcServerHost(port, shutdownWaitTimeInMillis, fakeFactory);
    runner.setApplicationContext(applicationContext);

    runner.start();
    assertThat(built.get()).isTrue();

    verify(server).start();

    assertThat(runner.server()).isEqualTo(server);
}
项目:beam    文件:InProcessServerFactory.java   
@Override
public Server allocatePortAndCreate(BindableService service, ApiServiceDescriptor.Builder builder)
    throws IOException {
  String name = String.format("InProcessServer_%s", serviceNameUniqifier.getAndIncrement());
  builder.setUrl(name);
  return InProcessServerBuilder.forName(name).addService(service).build().start();
}
项目:beam    文件:InProcessServerFactory.java   
@Override
public Server create(BindableService service, ApiServiceDescriptor serviceDescriptor)
    throws IOException {
  return InProcessServerBuilder.forName(serviceDescriptor.getUrl())
      .addService(service)
      .build()
      .start();
}
项目:beam    文件:ServerFactory.java   
@Override
public Server allocatePortAndCreate(
    BindableService service, Endpoints.ApiServiceDescriptor.Builder apiServiceDescriptor)
    throws IOException {
  InetSocketAddress address = new InetSocketAddress(InetAddress.getLoopbackAddress(), 0);
  Server server = createServer(service, address);
  apiServiceDescriptor.setUrl(
      HostAndPort.fromParts(address.getHostName(), server.getPort()).toString());
  return server;
}
项目:beam    文件:ServerFactory.java   
@Override
public Server create(BindableService service, Endpoints.ApiServiceDescriptor serviceDescriptor)
    throws IOException {
  SocketAddress socketAddress = SocketAddressFactory.createFrom(serviceDescriptor.getUrl());
  checkArgument(
      socketAddress instanceof InetSocketAddress,
      "%s %s requires a host:port socket address, got %s",
      getClass().getSimpleName(), ServerFactory.class.getSimpleName(),
      serviceDescriptor.getUrl());
  return createServer(service, (InetSocketAddress) socketAddress);
}
项目:beam    文件:ServerFactory.java   
private static Server createServer(BindableService service, InetSocketAddress socket)
    throws IOException {
  Server server =
      NettyServerBuilder.forPort(socket.getPort())
          .addService(service)
          // Set the message size to max value here. The actual size is governed by the
          // buffer size in the layers above.
          .maxMessageSize(Integer.MAX_VALUE)
          .build();
  server.start();
  return server;
}
项目:dropwizard-grpc    文件:DropwizardServerBuilder.java   
@Override
public DropwizardServerBuilder addService(final BindableService bindableService) {
    // TODO configure io.grpc.ServerInterceptor to collect dropwizard metrics
    // TODO configure io.grpc.ServerInterceptor to send rpc call and exception events to logback
    origin.addService(bindableService);
    return this;
}
项目:core-java    文件:GrpcContainer.java   
/**
 * Check if the given gRPC service is scheduled for the deployment in this container.
 *
 * <p>Note, that the given gRPC service will become available to the clients,
 * once the gRPC container is started.
 *
 * <p>To find out, whether the service is already available for calls,
 * use {@link #isLive(BindableService)} method.
 *
 * @param service the gRPC service to check
 * @return {@code true}, if the given gRPC service for deployment; {@code false} otherwise
 */
public boolean isScheduledForDeployment(BindableService service) {
    final String nameOfInterest = service.bindService()
                                         .getServiceDescriptor()
                                         .getName();
    boolean serviceIsPresent = false;
    for (ServerServiceDefinition serverServiceDefinition : services) {
        final String scheduledServiceName = serverServiceDefinition.getServiceDescriptor()
                                                                   .getName();
        serviceIsPresent = serviceIsPresent || scheduledServiceName.equals(nameOfInterest);
    }
    return serviceIsPresent;
}
项目:core-java    文件:GrpcContainerShould.java   
@SuppressWarnings("MagicNumber")
@Test
public void add_and_remove_parameters_from_builder() {
    final GrpcContainer.Builder builder = GrpcContainer.newBuilder()
                                                       .setPort(8080)
                                                       .setPort(60);
    assertEquals(60, builder.getPort());

    int count = 3;
    final List<ServerServiceDefinition> definitions = new ArrayList<>(count);

    for (int i = 0; i < count; i++) {
        final BindableService mockService = mock(BindableService.class);
        final ServerServiceDefinition mockDefinition = ServerServiceDefinition
                .builder(format("service-%s", i))
                .build();
        when(mockService.bindService()).thenReturn(mockDefinition);
        definitions.add(mockDefinition);

        builder.addService(mockService);
    }

    count--;
    // Perform removal and check that the return value is builder itself.
    assertEquals(builder, builder.removeService(definitions.get(count)));

    final Set<ServerServiceDefinition> serviceSet = builder.getServices();
    assertSize(count, serviceSet);

    final GrpcContainer container = builder.build();
    assertNotNull(container);
}
项目:onos    文件:GrpcNbHostService.java   
/**
 * Register Host Service, Used for unit testing purposes.
 *
 * @return An instance of binding Host service
 */
public InProcessServer<BindableService> registerInProcessServer() {
    InProcessServer<BindableService> inprocessServer =
            new InProcessServer(HostServiceNBServerInternal.class);
    inprocessServer.addServiceToBind(getInnerInstance());

    return inprocessServer;
}
项目:onos    文件:GrpcNbApplicationService.java   
/**
 * Register Application Service, Used for unit testing purposes.
 *
 * @return An instance of binding Application service
 */
public InProcessServer<BindableService> registerInProcessServer() {
    InProcessServer<BindableService> inprocessServer =
            new InProcessServer(GrpcNbApplicationService.ApplicationServiceNbServerInternal.class);
    inprocessServer.addServiceToBind(getInnerInstance());

    return inprocessServer;
}
项目:onos    文件:GrpcNbDeviceService.java   
/**
 * Register Device Service, Used for unit testing purposes.
 *
 * @return An instance of binding Device service
 */
public InProcessServer<BindableService> registerInProcessServer() {
    InProcessServer<BindableService> inprocessServer =
            new InProcessServer(GrpcNbDeviceService.DeviceServiceNbServerInternal.class);
    inprocessServer.addServiceToBind(getInnerInstance());

    return inprocessServer;
}
项目:onos    文件:GrpcNbComponentConfigService.java   
/**
 * Register ComponentConfig Service, Used for unit testing purposes.
 *
 * @return An instance of binding ComponentConfig service
 */
public InProcessServer<BindableService> registerInProcessServer() {
    InProcessServer<BindableService> inprocessServer =
            new InProcessServer(ComponentConfigServiceNbServerInternal.class);
    inprocessServer.addServiceToBind(getInnerInstance());

    return inprocessServer;
}
项目:onos    文件:GrpcNbLinkService.java   
/**
 * Register Link Service, used for unit testing purposes.
 *
 * @return An instance of binding Link service
 */
public InProcessServer<BindableService> registerInProcessServer() {
    InProcessServer<BindableService> inprocessServer =
            new InProcessServer(LinkServiceNb.class);
    inprocessServer.addServiceToBind(getInnerInstance());

    return inprocessServer;
}
项目:onos    文件:GrpcNbRegionService.java   
/**
 * Register Region Service, used for unit testing purposes.
 *
 * @return An instance of binding Region service
 */
public InProcessServer<BindableService> registerInProcessServer() {
    InProcessServer<BindableService> inprocessServer =
            new InProcessServer(GrpcNbRegionService.RegionServiceNbServerInternal.class);
    inprocessServer.addServiceToBind(getInnerClassInstance());

    return inprocessServer;
}
项目:onos    文件:GrpcNbMastershipService.java   
/**
 * Register Mastership Service, used for unit testing purposes.
 *
 * @return an instance of binding Mastership service
 */
public InProcessServer<BindableService> registerInProcessServer() {
    InProcessServer<BindableService> inprocessServer =
            new InProcessServer(GrpcNbMastershipService.MastershipServiceNbServerInternal.class);
    inprocessServer.addServiceToBind(getInnerInstance());

    return inprocessServer;
}
项目:onos    文件:GrpcServiceRegistryImpl.java   
@Override
public boolean register(BindableService service) {
    synchronized (registeredServices) {
        if (!registeredServices.containsKey(service.getClass())) {
            registeredServices.put(service.getClass(), service);
        } else {
            log.warn("The specified class \"{}\" was not added becuase an " +
                             "instance of the class is already registered.",
                     service.getClass().toString());
            return false;
        }
    }
    return restartServer(listeningPort);
}
项目:onos    文件:GrpcServiceRegistryImpl.java   
@Override
public boolean unregister(BindableService service) {
    synchronized (registeredServices) {
        if (registeredServices.containsKey(service.getClass())) {
            registeredServices.remove(service.getClass());
        } else {
            log.warn("The specified class \"{}\" was not removed because it " +
                             "was not present.", service.getClass().toString());
            return false;
        }
    }
    return restartServer(listeningPort);
}
项目:grpc-java    文件:AbstractServerImplBuilder.java   
@Override
public final T addService(BindableService bindableService) {
  if (bindableService instanceof InternalNotifyOnServerBuild) {
    notifyOnBuildList.add((InternalNotifyOnServerBuild) bindableService);
  }
  return addService(bindableService.bindService());
}
项目:grpc-java    文件:MutableHandlerRegistryTest.java   
@Test
public void simpleLookupWithBindable() {
  BindableService bindableService =
      new BindableService() {
        @Override
        public ServerServiceDefinition bindService() {
          return basicServiceDefinition;
        }
      };

  assertNull(registry.addService(bindableService));

  ServerMethodDefinition<?, ?> method = registry.lookupMethod("basic/flow");
  assertSame(flowMethodDefinition, method);
}
项目:incubator-servicecomb-saga    文件:GrpcStartable.java   
GrpcStartable(int port, BindableService... services) {
  ServerBuilder<?> serverBuilder = ServerBuilder.forPort(port);
  Arrays.stream(services).forEach(serverBuilder::addService);
  server = serverBuilder.build();
}
项目:state-channels    文件:NodeServer.java   
public NodeServer(List<BindableService> bindableServices, ChannelServerProperties properties, EthereumConfig ethereumConfig, ContractsManagerFactory factory) {
    this.bindableServices = bindableServices;
    this.properties = properties;
    this.ethereumConfig = ethereumConfig;
    this.factory = factory;
}
项目:curiostack    文件:GrpcServiceDefinition.java   
/** The gRPC services to bind. */
List<BindableService> services();
项目:curiostack    文件:ServerModule.java   
@Multibinds
abstract Set<BindableService> grpcServices();
项目:grpc-java-contrib    文件:SimpleGrpcServerFactory.java   
/**
 * Override this method to override how a {@link BindableService} is added to the {@link ServerBuilder}.
 */
protected void registerService(ServerBuilder builder, BindableService service) {
    builder.addService(service);
}
项目:spring-boot-starter-grpc    文件:GrpcServiceDefinition.java   
public GrpcServiceDefinition(String beanName, BindableService service) {
  this.beanName = beanName;
  this.service = service;
}
项目:spring-boot-starter-grpc    文件:GrpcServiceDefinition.java   
public BindableService getService() {
  return service;
}
项目:grpc-rx    文件:IntegrationTestHelper.java   
static Server newServer(BindableService service) {
  return NettyServerBuilder
      .forPort(1234)
      .addService(service)
      .build();
}
项目:core-java    文件:GrpcContainer.java   
public Builder addService(BindableService service) {
    serviceDefinitions.add(service.bindService());
    return this;
}
项目:onos    文件:GrpcServiceRegistryImpl.java   
@Override
public boolean containsService(Class<BindableService> serviceClass) {
    return registeredServices.containsKey(serviceClass);
}
项目:grpc-java    文件:ProtoReflectionService.java   
public static BindableService newInstance() {
  return new ProtoReflectionService();
}
项目:grpc-java    文件:HealthStatusManager.java   
/**
 * Gets the health check service created in the constructor.
 */
public BindableService getHealthService() {
  return healthService;
}