public static void main(String[] args) throws InterruptedException { // Create a channel ManagedChannel channel = ManagedChannelBuilder.forAddress(HOST, PORT) .usePlaintext(true) .build(); // Create a blocking stub with the channel GreetingServiceGrpc.GreetingServiceBlockingStub stub = GreetingServiceGrpc.newBlockingStub(channel); // Create a request HelloRequest request = HelloRequest.newBuilder() .setName("Mete - on Java") .setAge(34) .setSentiment(Sentiment.HAPPY) .build(); // Send the request using the stub System.out.println("GreeterClient sending request"); HelloResponse helloResponse = stub.greeting(request); System.out.println("GreeterClient received response: " + helloResponse.getGreeting()); //channel.shutdown(); }
public AssistantClient(OAuthCredentials oAuthCredentials, AssistantConf assistantConf, DeviceModel deviceModel, Device device) { this.assistantConf = assistantConf; this.deviceModel = deviceModel; this.device = device; this.currentConversationState = ByteString.EMPTY; // Create a channel to the test service. ManagedChannel channel = ManagedChannelBuilder.forAddress(assistantConf.getAssistantApiEndpoint(), 443) .build(); // Create a stub with credential embeddedAssistantStub = EmbeddedAssistantGrpc.newStub(channel); updateCredentials(oAuthCredentials); }
public void greet(String name, String message) { if (discoveryClient == null) { logger.info("Discovery client is null"); } else { logger.info("Discovery client is not null"); try { List<ServiceInstance> servers = discoveryClient.getInstances("service-account"); for (ServiceInstance server : servers) { String hostName = server.getHost(); int gRpcPort = Integer.parseInt(server.getMetadata().get("grpc.port")); logger.info("=====>> " + hostName + " ---- " + gRpcPort); final ManagedChannel channel = ManagedChannelBuilder.forAddress(hostName, gRpcPort) .usePlaintext(true) .build(); final GreetingGrpc.GreetingFutureStub stub = GreetingGrpc.newFutureStub(channel); stub.sayHi(HelloRequest.newBuilder().setName(name).setMessage(message).build()); } } catch (Exception e) { e.printStackTrace(); } } }
private void fetchAccessToken() { ManagedChannel channel = ManagedChannelBuilder.forTarget(HOSTNAME).build(); try { mApi = EmbeddedAssistantGrpc.newStub(channel) .withCallCredentials(MoreCallCredentials.from( Credentials_.fromResource(getApplicationContext(), R.raw.credentials) )); } catch (IOException|JSONException e) { Log.e(TAG, "error creating assistant service:", e); } for (Listener listener : mListeners) { listener. onCredentioalSuccess(); } }
public synchronized ManagedChannel getChannel(String addressStr) { ManagedChannel channel = connPool.get(addressStr); if (channel == null) { HostAndPort address; try { address = HostAndPort.fromString(addressStr); } catch (Exception e) { throw new IllegalArgumentException("failed to form address"); } // Channel should be lazy without actual connection until first call // So a coarse grain lock is ok here channel = ManagedChannelBuilder.forAddress(address.getHostText(), address.getPort()) .maxInboundMessageSize(conf.getMaxFrameSize()) .usePlaintext(true) .idleTimeout(60, TimeUnit.SECONDS) .build(); connPool.put(addressStr, channel); } return channel; }
@Test public void getMessage(){ ManagedChannel channel = ManagedChannelBuilder .forAddress("127.0.0.1",50051) .usePlaintext(true) .build(); GreeterGrpc.GreeterBlockingStub blockingStub = GreeterGrpc.newBlockingStub(channel); HelloRequest request = HelloRequest.newBuilder().setName("gggg").build(); HelloReply response; blockingStub.sayHello(request); try { channel.shutdown().awaitTermination(5, TimeUnit.SECONDS); } catch (InterruptedException e) { e.printStackTrace(); } }
public static void main(String[] args) throws Exception { String host = args[0]; int port = Integer.parseInt(args[1]); String abstractName = "mesh://timeService"; // Open a channel to the server Channel channel = ManagedChannelBuilder .forTarget(abstractName) .nameResolverFactory(StaticResolver.factory(new InetSocketAddress(host, port))) .usePlaintext(true) .build(); // Create a CompletableFuture-based stub TimeServiceGrpc8.TimeServiceCompletableFutureStub stub = TimeServiceGrpc8.newCompletableFutureStub(channel); // Call the service CompletableFuture<TimeReply> completableFuture = stub.getTime(Empty.getDefaultInstance()); TimeReply timeReply = completableFuture.get(); // Convert to JDK8 types Instant now = MoreTimestamps.toInstantUtc(timeReply.getTime()); System.out.println("The time is " + now); }
public static ManagedChannel getChannel(String serviceName) { HostInfo hostInfo=LoadBalance.getHostInfo(serviceName); if(hostInfo==null) return null; synchronized (ChannelFactory.class) { if(serviceChannels.get(hostInfo)!=null) { return serviceChannels.get(hostInfo); } else { ManagedChannel channel=ManagedChannelBuilder.forAddress(hostInfo.getIp(), Integer.valueOf(hostInfo.getPort())) .usePlaintext(true) .build(); serviceChannels.put(hostInfo, channel); return channel; } } }
/** * if the config is rollback the config of dbleAppender should be rollback too */ public static void rollbackConfig() { if (stub == null && (grpcUrlOld == null && "".equals(grpcUrlOld))) { grpcUrl = grpcUrlOld; serverId = serverIdOld; alertComponentId = alertComponentIdOld; port = portOld; grpcUrl = grpcUrlOld; grpcLevel = grpcLevelOld; return; } else { grpcUrl = grpcUrlOld; serverId = serverIdOld; alertComponentId = alertComponentIdOld; port = portOld; grpcUrl = grpcUrlOld; try { Channel channel = ManagedChannelBuilder.forAddress(grpcUrl, port).usePlaintext(true).build(); stub = UcoreGrpc.newBlockingStub(channel); } catch (Exception e) { return; } } }
private ManagedChannelBuilder<?> defaultChannelBuilder() { NettyChannelBuilder channelBuilder = NettyChannelBuilder.forTarget("etcd"); if (builder.sslContext() != null) { channelBuilder.sslContext(builder.sslContext()); } else { channelBuilder.usePlaintext(true); } channelBuilder.nameResolverFactory( forEndpoints( Optional.ofNullable(builder.authority()).orElse("etcd"), builder.endpoints(), Optional.ofNullable(builder.uriResolverLoader()) .orElseGet(URIResolverLoader::defaultLoader) ) ); if (builder.loadBalancerFactory() != null) { channelBuilder.loadBalancerFactory(builder.loadBalancerFactory()); } channelBuilder.intercept(new AuthTokenInterceptor()); return channelBuilder; }
/** * Construct the client connecting to server at {@code host:port}. */ public ClientApp(String host, int port) { final TypeUrl orderTypeUrl = TypeUrl.from(Order.getDescriptor()); final Target.Builder target = Target.newBuilder() .setType(orderTypeUrl.getTypeName()); orderTopic = Topic.newBuilder() .setTarget(target) .build(); commandFactory = CommandFactory.newBuilder() .setActor(newUserId(Identifiers.newUuid())) .setZoneOffset(ZoneOffsets.UTC) .build(); channel = ManagedChannelBuilder .forAddress(host, port) .usePlaintext(true) .build(); blockingClient = CommandServiceGrpc.newBlockingStub(channel); nonBlockingClient = SubscriptionServiceGrpc.newStub(channel); }
@BeforeClass public void beforeClass() throws IOException, DuplicateSessionException { /* create and start service */ final int port = 8080; final ServiceRunner service = new ServiceRunner.Builder() .setSessionProvider(sessionProvider) .setPort(port) .build(); thread = new Thread(service); thread.start(); /* create client */ final Channel channel = ManagedChannelBuilder.forAddress("127.0.0.1", port) .usePlaintext(true).build(); client = DigestServiceGrpc.newBlockingStub(channel); /* register session id */ sessionId = sessionProvider.createSession(userId); }
public static void main(String[] args) throws InterruptedException, UnknownHostException { String host = System.getenv("ECHO_SERVICE_HOST"); String port = System.getenv("ECHO_SERVICE_PORT"); final ManagedChannel channel = ManagedChannelBuilder.forAddress(host, Integer.valueOf(port)) .usePlaintext(true) .build(); final String self = InetAddress.getLocalHost().getHostName(); ExecutorService executorService = Executors.newFixedThreadPool(THREADS); for (int i = 0; i < THREADS; i++) { EchoServiceGrpc.EchoServiceBlockingStub stub = EchoServiceGrpc.newBlockingStub(channel); executorService.submit(() -> { while (true) { EchoResponse response = stub.echo(EchoRequest.newBuilder() .setMessage(self + ": " + Thread.currentThread().getName()) .build()); System.out.println(response.getFrom() + " echoed"); Thread.sleep(RANDOM.nextInt(700)); } }); } }
public static void main(String[] args) throws InterruptedException { ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", 8080) .usePlaintext(true) .build(); GreetingServiceGrpc.GreetingServiceBlockingStub stub = GreetingServiceGrpc.newBlockingStub(channel); HelloResponse helloResponse = stub.greeting( HelloRequest.newBuilder() .setName("Ray") .setAge(18) .setSentiment(Sentiment.HAPPY) .build()); System.out.println(helloResponse); channel.shutdown(); }
/** * Build an AsyncDiscovery wrapper from Host and Port * * @param _host The server host * @param _port The server port * @return An Observable stream containing the newly built AsyncDiscovery wrapper */ public static Observable<AsyncDiscovery> from(String _host, int _port) { return Observable .create((Subscriber<? super AsyncDiscovery> t) -> { try { ManagedChannel ch = ManagedChannelBuilder .forAddress(_host, _port) .usePlaintext(true) .build(); DiscoveryGrpc.DiscoveryFutureStub stub1 = DiscoveryGrpc.newFutureStub(ch); t.onNext(new AsyncDiscovery(stub1)); t.onCompleted(); } catch (Exception ex) { t.onError(ex); } }); }
@Override public void login(String host, int port, String name) { channel = ManagedChannelBuilder.forAddress(host, port) .usePlaintext(true) .build(); blockingStub = ChatGrpc.newBlockingStub(channel); asyncStub = ChatGrpc.newStub(channel); id = toSHA1(InetAddress.getLoopbackAddress().getHostName() + "-" + System.nanoTime()); asyncStub.login(Login.newBuilder() .setName(name) .setId(id) .build(), new StreamObserverAdapter<Response>() { @Override public void onNext(Response value) { clientDispatcher.dispatch(asCommand(value)); } @Override public void onError(Throwable throwable) { eventBus.publishAsync(new ThrowableEvent(throwable)); } }); }
/** Construct client connecting to HelloWorld server at {@code host:port}. */ BatchGreeterClient(TimerRequest request, StreamObserver<BatchResponse> observer) { Preconditions.checkNotNull(request, "request required"); Preconditions.checkNotNull(observer, "response observer required"); Preconditions.checkArgument(request.getHost().length() > 0, "hostname required"); Preconditions.checkArgument(request.getPort() > 0, "grpc port required"); Preconditions.checkArgument(port > 0, "grpc port must be greater than zero"); Preconditions.checkArgument( request.getTotalSize() > 0, "total request count must be greater than zero"); Preconditions.checkArgument( request.getBatchSize() > 0, "batch request size must be greater than zero"); this.request = request; this.observer = observer; this.channel = ManagedChannelBuilder.forAddress(request.getHost(), request.getPort()) .usePlaintext(true) .build(); this.blockingStub = GreeterGrpc.newBlockingStub(channel); }
private void initSession(RpcSessionCreateRequestMsg msg) { log.info("[{}] Initializing session", context().self()); ServerAddress remoteServer = msg.getRemoteAddress(); listener = new BasicRpcSessionListener(systemContext, context().parent(), context().self()); if (msg.getRemoteAddress() == null) { // Server session session = new GrpcSession(listener); session.setOutputStream(msg.getResponseObserver()); session.initInputStream(); session.initOutputStream(); systemContext.getRpcService().onSessionCreated(msg.getMsgUid(), session.getInputStream()); } else { // Client session Channel channel = ManagedChannelBuilder.forAddress(remoteServer.getHost(), remoteServer.getPort()).usePlaintext(true).build(); session = new GrpcSession(remoteServer, listener); session.initInputStream(); ClusterRpcServiceGrpc.ClusterRpcServiceStub stub = ClusterRpcServiceGrpc.newStub(channel); StreamObserver<ClusterAPIProtos.ToRpcServerMessage> outputStream = stub.handlePluginMsgs(session.getInputStream()); session.setOutputStream(outputStream); session.initOutputStream(); outputStream.onNext(toConnectMsg()); } }
@Test public void sayHelloEndpointReturnsExpectedResponse() { final String name = UUID.randomUUID().toString(); final ManagedChannel channel = ManagedChannelBuilder .forAddress("localhost", applicationTestRule.application().port()) .usePlaintext(true) .build(); final GreeterGrpc.GreeterBlockingStub blockingStub = GreeterGrpc.newBlockingStub(channel); HelloRequest request = HelloRequest.newBuilder() .setName(name) .build(); HelloResponse response = blockingStub.sayHello(request); assertThat(response.getMessage()).isEqualTo("Hello " + name); }
@SuppressWarnings("unchecked") @Override protected <T> T doRefer(Class<T> type, URL url) throws JahhanException { String name = type.getName(); final ManagedChannel channel = ManagedChannelBuilder.forAddress(url.getHost(), url.getPort()).usePlaintext(true) .build(); try { String substring = name.substring(name.lastIndexOf(".") + 1, name.indexOf(BaseConfiguration.INTERFACE_SUFFIX)); String grpcImplName; if (name.startsWith(BaseConfiguration.SERVICE_PATH)) { grpcImplName = BaseConfiguration.SERVICE_PATH + packageName + substring + "GrpcInvoker"; } else if (name.startsWith(BaseConfiguration.FRAMEWORK_PATH)) { grpcImplName =BaseConfiguration.FRAMEWORK_PATH + packageName + substring + "GrpcInvoker"; } else { grpcImplName = "com" + packageName + substring + "GrpcInvoker"; } Class<?> grpcImplClass = Class.forName(grpcImplName); GrpcAbstractInvoker newInstance = (GrpcAbstractInvoker) BaseContext.CTX.getInjector().getInstance(grpcImplClass); newInstance.setChannel(channel); return (T) newInstance; } catch (Exception e) { throw new JahhanException(e.getMessage(), e); } }
public static void main(String[] args) { ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", 11800).usePlaintext(true).build(); JVMMetricsServiceGrpc.JVMMetricsServiceBlockingStub blockingStub = JVMMetricsServiceGrpc.newBlockingStub(channel); JVMMetrics.Builder builder = JVMMetrics.newBuilder(); builder.setApplicationInstanceId(2); JVMMetric.Builder metricBuilder = JVMMetric.newBuilder(); metricBuilder.setTime(System.currentTimeMillis()); buildCPUMetric(metricBuilder); buildGCMetric(metricBuilder); buildMemoryMetric(metricBuilder); buildMemoryPoolMetric(metricBuilder); builder.addMetrics(metricBuilder.build()); blockingStub.collect(builder.build()); }
public void open(boolean compressedConnection) throws IOException { ManagedChannelBuilder<?> managedChannelBuilder = ManagedChannelBuilder.forAddress(member.getServerAddress(), member.getExternalPort()) .maxInboundMessageSize(256 * 1024 * 1024).usePlaintext(true); channel = managedChannelBuilder.build(); blockingStub = ExternalServiceGrpc.newBlockingStub(channel); if (compressedConnection) { blockingStub = blockingStub.withCompression("gzip"); } asyncStub = ExternalServiceGrpc.newStub(channel); if (compressedConnection) { asyncStub = asyncStub.withCompression("gzip"); } System.err.println("INFO: Connecting to <" + member.getServerAddress() + ">"); }
/** * Create a P4Runtime client for this device. Returns true if the operation was successful, false otherwise. * * @return true if successful, false otherwise */ protected boolean createClient() { deviceId = handler().data().deviceId(); controller = handler().get(P4RuntimeController.class); String serverAddr = this.data().value(P4RUNTIME_SERVER_ADDR_KEY); String serverPortString = this.data().value(P4RUNTIME_SERVER_PORT_KEY); String p4DeviceIdString = this.data().value(P4RUNTIME_DEVICE_ID_KEY); if (serverAddr == null || serverPortString == null || p4DeviceIdString == null) { log.warn("Unable to create client for {}, missing driver data key (required is {}, {}, and {})", deviceId, P4RUNTIME_SERVER_ADDR_KEY, P4RUNTIME_SERVER_PORT_KEY, P4RUNTIME_DEVICE_ID_KEY); return false; } ManagedChannelBuilder channelBuilder = NettyChannelBuilder .forAddress(serverAddr, Integer.valueOf(serverPortString)) .usePlaintext(true); if (!controller.createClient(deviceId, Long.parseUnsignedLong(p4DeviceIdString), channelBuilder)) { log.warn("Unable to create client for {}, aborting operation", deviceId); return false; } return true; }
@Override public boolean createClient(DeviceId deviceId, long p4DeviceId, ManagedChannelBuilder channelBuilder) { checkNotNull(deviceId); checkNotNull(channelBuilder); deviceLocks.getUnchecked(deviceId).writeLock().lock(); log.info("Creating client for {} (with internal device id {})...", deviceId, p4DeviceId); try { if (clients.containsKey(deviceId)) { throw new IllegalStateException(format("A client already exists for %s", deviceId)); } else { return doCreateClient(deviceId, p4DeviceId, channelBuilder); } } finally { deviceLocks.getUnchecked(deviceId).writeLock().unlock(); } }
private boolean doCreateClient(DeviceId deviceId, long p4DeviceId, ManagedChannelBuilder channelBuilder) { GrpcChannelId channelId = GrpcChannelId.of(deviceId, "p4runtime"); // Channel defaults. channelBuilder.nameResolverFactory(nameResolverProvider); ManagedChannel channel; try { channel = grpcController.connectChannel(channelId, channelBuilder); } catch (IOException e) { log.warn("Unable to connect to gRPC server of {}: {}", deviceId, e.getMessage()); return false; } P4RuntimeClient client = new P4RuntimeClientImpl(deviceId, p4DeviceId, channel, this); channelIds.put(deviceId, channelId); clients.put(deviceId, client); return true; }
@Override public ManagedChannel connectChannel(GrpcChannelId channelId, ManagedChannelBuilder<?> channelBuilder) throws IOException { checkNotNull(channelId); checkNotNull(channelBuilder); Lock lock = channelLocks.computeIfAbsent(channelId, k -> new ReentrantLock()); lock.lock(); try { if (enableMessageLog) { channelBuilder.intercept(new InternalLogChannelInterceptor(channelId)); } ManagedChannel channel = channelBuilder.build(); // Forced connection not yet implemented. Use workaround... // channel.getState(true); doDummyMessage(channel); channels.put(channelId, channel); return channel; } finally { lock.unlock(); } }
@Override protected ManagedChannel createChannel() { assertEquals( "jdk7 required", "1.7", System.getProperty("java.specification.version")); assertEquals( "Can not run in dev servers because they lack org.conscrypt.OpenSSLProvider support", "Production", System.getProperty("com.google.appengine.runtime.environment")); ManagedChannelBuilder<?> builder = ManagedChannelBuilder.forTarget(INTEROP_TEST_ADDRESS) .maxInboundMessageSize(AbstractInteropTest.MAX_MESSAGE_SIZE); assertTrue(builder instanceof OkHttpChannelBuilder); return builder.build(); }
void run() throws Exception { // Port 0 means that the operating system will pick an available port to use. Server server = ServerBuilder.forPort(0).addService(new GreeterGrpc.GreeterImplBase() { @Override public void sayHello(HelloRequest request, StreamObserver<HelloReply> responseObserver) { responseObserver.onError(Status.INTERNAL .withDescription("Eggplant Xerxes Crybaby Overbite Narwhal").asRuntimeException()); } }).build().start(); channel = ManagedChannelBuilder.forAddress("localhost", server.getPort()).usePlaintext(true).build(); blockingCall(); futureCallDirect(); futureCallCallback(); asyncCall(); advancedAsyncCall(); channel.shutdown(); server.shutdown(); channel.awaitTermination(1, TimeUnit.SECONDS); server.awaitTermination(); }
void run() throws Exception { Server server = ServerBuilder.forPort(0).addService(new GreeterGrpc.GreeterImplBase() { @Override public void sayHello(HelloRequest request, StreamObserver<HelloReply> responseObserver) { Metadata trailers = new Metadata(); trailers.put(DEBUG_INFO_TRAILER_KEY, DEBUG_INFO); responseObserver.onError(Status.INTERNAL.withDescription(DEBUG_DESC) .asRuntimeException(trailers)); } }).build().start(); channel = ManagedChannelBuilder.forAddress("localhost", server.getPort()).usePlaintext(true).build(); blockingCall(); futureCallDirect(); futureCallCallback(); asyncCall(); advancedAsyncCall(); channel.shutdown(); server.shutdown(); channel.awaitTermination(1, TimeUnit.SECONDS); server.awaitTermination(); }
@Override protected String doInBackground(String... params) { String host = params[0]; String message = params[1]; String portStr = params[2]; int port = TextUtils.isEmpty(portStr) ? 0 : Integer.valueOf(portStr); try { channel = ManagedChannelBuilder.forAddress(host, port).usePlaintext(true).build(); GreeterGrpc.GreeterBlockingStub stub = GreeterGrpc.newBlockingStub(channel); HelloRequest request = HelloRequest.newBuilder().setName(message).build(); HelloReply reply = stub.sayHello(request); return reply.getMessage(); } catch (Exception e) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); pw.flush(); return String.format("Failed... : %n%s", sw); } }
public static ManagedChannel build(String host, int port, @Nullable String serverHostOverride, boolean useTls, @Nullable InputStream testCa, @Nullable String androidSocketFactoryTls) { ManagedChannelBuilder<?> channelBuilder = ManagedChannelBuilder.forAddress(host, port) .maxInboundMessageSize(16 * 1024 * 1024); if (serverHostOverride != null) { // Force the hostname to match the cert the server uses. channelBuilder.overrideAuthority(serverHostOverride); } if (useTls) { try { SSLSocketFactory factory; if (androidSocketFactoryTls != null) { factory = getSslCertificateSocketFactory(testCa, androidSocketFactoryTls); } else { factory = getSslSocketFactory(testCa); } ((OkHttpChannelBuilder) channelBuilder).negotiationType(NegotiationType.TLS); ((OkHttpChannelBuilder) channelBuilder).sslSocketFactory(factory); } catch (Exception e) { throw new RuntimeException(e); } } else { channelBuilder.usePlaintext(true); } return channelBuilder.build(); }
@Before public void setUp() throws Exception { final int port = NetUtil.findUnusedPort(); this.server = ServerBuilder.forPort(port) .executor(this.exec) .addService(new HelloService()) .build() .start(); this.channel = ManagedChannelBuilder.forAddress("127.0.0.1", port) .executor(this.exec) .usePlaintext(true) .build(); }
@Setup(Level.Trial) public void prepare() throws Exception { ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", 9999) // Channels are secure by default (via SSL/TLS). For the example we disable TLS to avoid // needing certificates. .usePlaintext(true) .build(); blockingStub = Neo4jQueryGrpc.newBlockingStub(channel); driver = GraphDatabase.driver( "bolt://localhost:7687", AuthTokens.basic( "neo4j", "swordfish" ) ); }
@Before public void setup() throws Exception { ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", 9999) // Channels are secure by default (via SSL/TLS). For the example we disable TLS to avoid // needing certificates. .usePlaintext(true) .build(); blockingStub = Neo4jQueryGrpc.newBlockingStub(channel); }
@Override protected void configure() { ManagedChannel channel = ManagedChannelBuilder.forAddress(HOST, PORT).usePlaintext(true).build(); bind(StreamingGreeterGrpc.StreamingGreeterStub.class) .toInstance(StreamingGreeterGrpc.newStub(channel)); }
@Override protected void configure() { ManagedChannel channel = ManagedChannelBuilder.forAddress(HOST, PORT).usePlaintext(true).build(); bind(BookServiceGrpc.BookServiceFutureStub.class) .toInstance(BookServiceGrpc.newFutureStub(channel)); bind(BookServiceGrpc.BookServiceBlockingStub.class) .toInstance(BookServiceGrpc.newBlockingStub(channel)); }
@Override protected void configure() { ManagedChannel channel = ManagedChannelBuilder.forAddress(HOST, PORT).usePlaintext(true).build(); bind(ShelfServiceGrpc.ShelfServiceFutureStub.class) .toInstance(ShelfServiceGrpc.newFutureStub(channel)); bind(ShelfServiceGrpc.ShelfServiceBlockingStub.class) .toInstance(ShelfServiceGrpc.newBlockingStub(channel)); }
public LoadBalancedClusterMessageSender(String[] addresses, MessageSerializer serializer, MessageDeserializer deserializer, ServiceConfig serviceConfig, MessageHandler handler, int reconnectDelay) { if (addresses.length == 0) { throw new IllegalArgumentException("No reachable cluster address provided"); } channels = new ArrayList<>(addresses.length); for (String address : addresses) { ManagedChannel channel = ManagedChannelBuilder.forTarget(address) .usePlaintext(true) .build(); channels.add(channel); senders.put( new GrpcClientMessageSender( address, channel, serializer, deserializer, serviceConfig, errorHandlerFactory(), handler), 0L); } scheduleReconnectTask(reconnectDelay); }
public MetaClient(String host, int port) { this(ManagedChannelBuilder.forAddress(host, port) // Channels are secure by default (via SSL/TLS). For the example we disable TLS to avoid // needing certificates. .usePlaintext(true) .build()); }
@Override public void afterPropertiesSet() { super.afterPropertiesSet(); if (getServiceInterface() == null) { throw new IllegalArgumentException("Property 'serviceInterface' is required"); } this.serviceProxy = new ProxyFactory(getServiceInterface(), this).getProxy(getBeanClassLoader()); channel = ManagedChannelBuilder.forTarget(getServiceUrl()).usePlaintext(true).build(); remotingServiceBlockingStub = RemotingServiceGrpc.newBlockingStub(channel); }