io.grpc.Server Scala Examples
The following examples show how to use io.grpc.Server.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
Example 1
Source File: DEXExtension.scala From matcher with MIT License | 5 votes |
package com.wavesplatform.dex.grpc.integration import java.net.InetSocketAddress import java.util.concurrent.TimeUnit import com.wavesplatform.dex.grpc.integration.services._ import com.wavesplatform.dex.grpc.integration.settings.DEXExtensionSettings import com.wavesplatform.extensions.{Extension, Context => ExtensionContext} import com.wavesplatform.utils.ScorexLogging import io.grpc.Server import io.grpc.netty.NettyServerBuilder import monix.execution.{ExecutionModel, Scheduler} import net.ceedubs.ficus.Ficus._ import net.ceedubs.ficus.readers.ArbitraryTypeReader._ import net.ceedubs.ficus.readers.NameMapper import scala.concurrent.Future class DEXExtension(context: ExtensionContext) extends Extension with ScorexLogging { @volatile private var server: Server = _ private var apiService: WavesBlockchainApiGrpcService = _ implicit val chosenCase: NameMapper = net.ceedubs.ficus.readers.namemappers.implicits.hyphenCase implicit private val apiScheduler: Scheduler = Scheduler( ec = context.actorSystem.dispatchers.lookup("akka.actor.waves-dex-grpc-scheduler"), executionModel = ExecutionModel.AlwaysAsyncExecution ) override def start(): Unit = { val settings = context.settings.config.as[DEXExtensionSettings]("waves.dex.grpc.integration") val bindAddress = new InetSocketAddress(settings.host, settings.port) apiService = new WavesBlockchainApiGrpcService(context, settings.balanceChangesBatchLinger) server = NettyServerBuilder .forAddress(bindAddress) .permitKeepAliveWithoutCalls(true) .permitKeepAliveTime(500, TimeUnit.MILLISECONDS) .addService(WavesBlockchainApiGrpc.bindService(apiService, apiScheduler)) .build() .start() log.info(s"gRPC DEX extension was bound to $bindAddress") } override def shutdown(): Future[Unit] = { log.info("Shutting down gRPC DEX extension") if (server != null) server.shutdownNow() Future.successful(()) } }
Example 2
Source File: GrpcSpec.scala From mleap with Apache License 2.0 | 5 votes |
package ml.combust.mleap.grpc.server import akka.actor.ActorSystem import akka.stream.{ActorMaterializer, Materializer} import akka.testkit.TestKit import io.grpc.{ManagedChannel, Server} import ml.combust.mleap.executor.service.TransformService import ml.combust.mleap.executor.testkit.TransformServiceSpec import org.scalatest.{BeforeAndAfterAll, BeforeAndAfterEach} import org.scalatest.concurrent.ScalaFutures import scala.concurrent.duration._ import ml.combust.mleap.grpc.server.TestUtil._ class GrpcSpec extends TestKit(ActorSystem("grpc-server-test")) with TransformServiceSpec with BeforeAndAfterEach with BeforeAndAfterAll with ScalaFutures { private lazy val server = createServer(system) private lazy val channel = inProcessChannel private lazy val client = createClient(channel) override lazy val transformService: TransformService = { server client } override implicit def materializer: Materializer = ActorMaterializer()(system) override protected def afterAll(): Unit = { server.shutdown() channel.shutdown() TestKit.shutdownActorSystem(system, 5.seconds, verifySystemShutdown = true) } }
Example 3
Source File: TestUtil.scala From mleap with Apache License 2.0 | 5 votes |
package ml.combust.mleap.grpc.server import java.io.File import java.net.URI import akka.actor.ActorSystem import akka.stream.ActorMaterializer import com.typesafe.config.ConfigFactory import io.grpc.{ManagedChannel, Server} import io.grpc.inprocess.{InProcessChannelBuilder, InProcessServerBuilder} import ml.combust.mleap.executor.MleapExecutor import ml.combust.mleap.grpc.GrpcClient import ml.combust.mleap.pb.MleapGrpc import ml.combust.mleap.pb.MleapGrpc.MleapStub import ml.combust.mleap.runtime.frame.DefaultLeapFrame import ml.combust.mleap.runtime.serialization.FrameReader import scala.concurrent.ExecutionContext import ExecutionContext.Implicits.global import scala.util.Try object TestUtil { lazy val lrUri: URI = URI.create(getClass.getClassLoader.getResource("models/airbnb.model.lr.zip").toURI.toString) lazy val frame: Try[DefaultLeapFrame] = FrameReader().read(new File(getClass.getClassLoader.getResource("leap_frame/frame.airbnb.json").getFile)) lazy val uniqueServerName : String = "in-process server for " + getClass def createServer(system: ActorSystem) : Server = { val config = new GrpcServerConfig(ConfigFactory.load().getConfig("ml.combust.mleap.grpc.server.default")) val ssd = MleapGrpc.bindService(new GrpcServer(MleapExecutor(system), config)(global, ActorMaterializer.create(system)), global) val builder = InProcessServerBuilder.forName(uniqueServerName) builder.directExecutor().addService(ssd).intercept(new ErrorInterceptor) val server = builder.build server.start() server } def createClient(channel: ManagedChannel): GrpcClient = new GrpcClient(new MleapStub(channel)) def inProcessChannel : ManagedChannel = InProcessChannelBuilder.forName(uniqueServerName).directExecutor.build }
Example 4
Source File: ServerBuilderSyntax.scala From fs2-grpc with MIT License | 5 votes |
package org.lyranthe.fs2_grpc package java_runtime package syntax import cats.effect._ import fs2.Stream import io.grpc.{Server, ServerBuilder} import java.util.concurrent.TimeUnit import scala.concurrent._ trait ServerBuilderSyntax { implicit final def fs2GrpcSyntaxServerBuilder(builder: ServerBuilder[_]): ServerBuilderOps = new ServerBuilderOps(builder) } final class ServerBuilderOps(val builder: ServerBuilder[_]) extends AnyVal { def streamWithShutdown[F[_]](shutdown: Server => F[Unit])(implicit F: Sync[F]): Stream[F, Server] = Stream.resource(resourceWithShutdown(shutdown)) }
Example 5
Source File: GRPCServer.scala From NSDb with Apache License 2.0 | 5 votes |
package io.radicalbit.nsdb.client.rpc import java.net.InetSocketAddress import com.google.common.net.InetAddresses import io.grpc.Server import io.grpc.netty.NettyServerBuilder import io.radicalbit.nsdb.rpc.health.HealthGrpc import io.radicalbit.nsdb.rpc.health.HealthGrpc.Health import io.radicalbit.nsdb.rpc.init.InitMetricGrpc import io.radicalbit.nsdb.rpc.init.InitMetricGrpc.InitMetric import io.radicalbit.nsdb.rpc.restore.RestoreGrpc import io.radicalbit.nsdb.rpc.restore.RestoreGrpc.Restore import io.radicalbit.nsdb.rpc.service.NSDBServiceCommandGrpc.NSDBServiceCommand import io.radicalbit.nsdb.rpc.service.NSDBServiceSQLGrpc.NSDBServiceSQL import io.radicalbit.nsdb.rpc.service.{NSDBServiceCommandGrpc, NSDBServiceSQLGrpc} import io.radicalbit.nsdb.sql.parser.SQLStatementParser import scala.concurrent.ExecutionContext import scala.util.Try trait GRPCServer { protected[this] def executionContextExecutor: ExecutionContext protected[this] def interface: String protected[this] def port: Int protected[this] def serviceSQL: NSDBServiceSQL protected[this] def serviceCommand: NSDBServiceCommand protected[this] def initMetricService: InitMetric protected[this] def health: Health protected[this] def restore: Restore protected[this] def parserSQL: SQLStatementParser sys.addShutdownHook { if (!server.isTerminated) { System.err.println(s"Shutting down gRPC server at interface $interface and port $port since JVM is shutting down") stop() System.err.println(s"Server at interface $interface and port $port shut down") } } lazy val server: Server = NettyServerBuilder .forAddress(new InetSocketAddress(InetAddresses.forString(interface), port)) .addService(NSDBServiceSQLGrpc.bindService(serviceSQL, executionContextExecutor)) .addService(NSDBServiceCommandGrpc.bindService(serviceCommand, executionContextExecutor)) .addService(InitMetricGrpc.bindService(initMetricService, executionContextExecutor)) .addService(HealthGrpc.bindService(health, executionContextExecutor)) .addService(RestoreGrpc.bindService(restore, executionContextExecutor)) .build def start(): Try[Server] = Try(server.start()) def stop(): Unit = server.shutdownNow().awaitTermination() }
Example 6
Source File: KsmGrpcServer.scala From kafka-security-manager with MIT License | 5 votes |
package com.github.simplesteph.ksm.grpc import com.github.simplesteph.ksm.AclSynchronizer import com.security.kafka.pb.ksm.{KsmServiceGrpc, KsmServiceHandler} import grpcgateway.server.{GrpcGatewayServer, GrpcGatewayServerBuilder} import io.grpc.protobuf.services.ProtoReflectionService import io.grpc.{ManagedChannelBuilder, Server, ServerBuilder} import org.slf4j.LoggerFactory import scala.concurrent.ExecutionContext class KsmGrpcServer( aclSynchronizer: AclSynchronizer, port: Int, gatewayPort: Int, enabled: Boolean ) { val log = LoggerFactory.getLogger(KsmServiceGrpc.getClass) private[this] var server: Server = _ private[this] var gateway: GrpcGatewayServer = _ private val ec = ExecutionContext.global def start(): Unit = { if (enabled) { log.info("Starting gRPC Server") server = ServerBuilder .forPort(port) .addService(ProtoReflectionService.newInstance()) .addService( KsmServiceGrpc.bindService(new KsmServiceImpl(aclSynchronizer), ec) ) .build() server.start() log.info(s"gRPC Server started on port $port") log.info("Starting gRPC Gateway") // internal client for gateway val channel = ManagedChannelBuilder .forAddress("localhost", port) .usePlaintext() .build() // gateway (REST) gateway = GrpcGatewayServerBuilder .forPort(gatewayPort) .addService(new KsmServiceHandler(channel)(ec)) .build() gateway.start() log.info(s"gRPC Server started on port $gatewayPort") } } def stop(): Unit = { if (enabled) { server.shutdown() gateway.shutdown() } } }
Example 7
Source File: RouteGuideServer.scala From grpcexample with MIT License | 5 votes |
package io.grpc.routeguide import java.util.logging.Logger import akka.actor.ActorSystem import akka.stream.ActorMaterializer import io.grpc.{Server, ServerBuilder} class RouteGuideServer(server: Server) { val logger: Logger = Logger.getLogger(classOf[RouteGuideServer].getName) def start(): Unit = { server.start() logger.info(s"Server started, listening on ${server.getPort}") sys.addShutdownHook { // Use stderr here since the logger may has been reset by its JVM shutdown hook. System.err.println("*** shutting down gRPC server since JVM is shutting down") stop() System.err.println("*** server shut down") } () } def stop(): Unit = { server.shutdown() } def blockUntilShutdown(): Unit = { server.awaitTermination() } } object RouteGuideServer extends App { val features = RouteGuidePersistence.parseFeatures( Thread.currentThread.getContextClassLoader.getResource("route_guide.json") ) val server = new RouteGuideServer( ServerBuilder .forPort(8980) .addService( RouteGuideGrpc.bindService( new RouteGuideService(features), scala.concurrent.ExecutionContext.global ) ) .build() ) server.start() server.blockUntilShutdown() } object RouteGuideMonixServer extends App { val features = RouteGuidePersistence.parseFeatures( Thread.currentThread.getContextClassLoader.getResource("route_guide.json") ) val server = new RouteGuideServer( ServerBuilder .forPort(8980) .addService( RouteGuideGrpcMonix.bindService( new RouteGuideMonixService(features), monix.execution.Scheduler.global ) ) .build() ) server.start() server.blockUntilShutdown() } object RouteGuideAkkaStreamServer extends App { val features = RouteGuidePersistence.parseFeatures( Thread.currentThread.getContextClassLoader.getResource("route_guide.json") ) val system = ActorSystem("RouteGuideAkkaStreamServer") implicit val materializer = ActorMaterializer.create(system) val server = new RouteGuideServer( ServerBuilder .forPort(8980) .addService( RouteGuideGrpcAkkaStream.bindService( new RouteGuideAkkaStreamService(features) ) ) .build() ) server.start() server.blockUntilShutdown() system.terminate() }
Example 8
Source File: GRPCServerExtension.scala From Waves with MIT License | 5 votes |
package com.wavesplatform.api.grpc import java.net.InetSocketAddress import com.wavesplatform.extensions.{Extension, Context => ExtensionContext} import com.wavesplatform.settings.GRPCSettings import com.wavesplatform.utils.ScorexLogging import io.grpc.Server import io.grpc.netty.NettyServerBuilder import monix.execution.Scheduler import net.ceedubs.ficus.Ficus._ import net.ceedubs.ficus.readers.ArbitraryTypeReader._ import scala.concurrent.Future class GRPCServerExtension(context: ExtensionContext) extends Extension with ScorexLogging { @volatile var server: Server = _ override def start(): Unit = { val settings = context.settings.config.as[GRPCSettings]("waves.grpc") this.server = startServer(settings) } override def shutdown(): Future[Unit] = { log.debug("Shutting down gRPC server") if (server != null) { server.shutdown() Future(server.awaitTermination())(context.actorSystem.dispatcher) } else { Future.successful(()) } } private[this] def startServer(settings: GRPCSettings): Server = { implicit val apiScheduler: Scheduler = Scheduler(context.actorSystem.dispatcher) val bindAddress = new InetSocketAddress(settings.host, settings.port) val server: Server = NettyServerBuilder .forAddress(bindAddress) .addService(TransactionsApiGrpc.bindService(new TransactionsApiGrpcImpl(context.transactionsApi), apiScheduler)) .addService(BlocksApiGrpc.bindService(new BlocksApiGrpcImpl(context.blocksApi), apiScheduler)) .addService(AccountsApiGrpc.bindService(new AccountsApiGrpcImpl(context.accountsApi), apiScheduler)) .addService(AssetsApiGrpc.bindService(new AssetsApiGrpcImpl(context.assetsApi, context.accountsApi), apiScheduler)) .addService(BlockchainApiGrpc.bindService(new BlockchainApiGrpcImpl(context.blockchain, context.settings.featuresSettings), apiScheduler)) .build() .start() log.info(s"gRPC API was bound to $bindAddress") server } }
Example 9
Source File: HelloWorldServer.scala From grpc-scala-sample with BSD 3-Clause "New" or "Revised" License | 5 votes |
package io.grpc.examples.helloworld import java.util.logging.Logger import io.grpc.{Server, ServerBuilder} import io.grpc.examples.helloworld.helloworld.{GreeterGrpc, HelloRequest, HelloReply} import scala.concurrent.{ExecutionContext, Future} object HelloWorldServer { private val logger = Logger.getLogger(classOf[HelloWorldServer].getName) def main(args: Array[String]): Unit = { val server = new HelloWorldServer(ExecutionContext.global) server.start() server.blockUntilShutdown() } private val port = 50051 } class HelloWorldServer(executionContext: ExecutionContext) { self => private[this] var server: Server = null private def start(): Unit = { server = ServerBuilder.forPort(HelloWorldServer.port).addService(GreeterGrpc.bindService(new GreeterImpl, executionContext)).build.start HelloWorldServer.logger.info("Server started, listening on " + HelloWorldServer.port) sys.addShutdownHook { System.err.println("*** shutting down gRPC server since JVM is shutting down") self.stop() System.err.println("*** server shut down") } } private def stop(): Unit = { if (server != null) { server.shutdown() } } private def blockUntilShutdown(): Unit = { if (server != null) { server.awaitTermination() } } private class GreeterImpl extends GreeterGrpc.Greeter { override def sayHello(req: HelloRequest) = { val reply = HelloReply(message = "Hello " + req.name) Future.successful(reply) } } }
Example 10
Source File: GrpcServerModule.scala From scala-server-toolkit with MIT License | 5 votes |
package com.avast.sst.grpc.server import java.util.concurrent.TimeUnit import cats.effect.{Resource, Sync} import io.grpc.{Server, ServerBuilder, ServerInterceptor, ServerServiceDefinition} import scala.collection.immutable.Seq import scala.concurrent.ExecutionContext object GrpcServerModule { def make[F[_]: Sync]( config: GrpcServerConfig, services: Seq[ServerServiceDefinition], executionContext: ExecutionContext, interceptors: Seq[ServerInterceptor] = List.empty ): Resource[F, Server] = Resource.make { Sync[F].delay { val builder = ServerBuilder .forPort(config.port) .handshakeTimeout(config.handshakeTimeout.toMillis, TimeUnit.MILLISECONDS) .maxInboundMessageSize(config.maxInboundMessageSize) .maxInboundMetadataSize(config.maxInboundMetadataSize) .executor(executionContext.execute) services.foreach(builder.addService) interceptors.foreach(builder.intercept) builder.build.start() } } { s => Sync[F].delay { s.shutdown().awaitTermination(config.serverShutdownTimeout.toMillis, TimeUnit.MILLISECONDS) () } } }