将以下配置添加到Akka Http服务器的application.conf中:
akka.http.server {
# Enabling CORS support
cors {
# If enabled, all origins will be allowed. This setting overrides `allowedOrigins`.
allow-all-origins = true
# List of origins that are allowed to make requests to the server.
allowedOrigins = ["*"]
# List of HTTP headers that should be allowed.
allowedHeaders = []
# List of HTTP methods that should be allowed.
allowedMethods = []
# If enabled, cookies can be included in CORS requests.
allowCredentials = true
}
}
在启动Akka Http服务器之前,还需要添加以下依赖关系:
libraryDependencies += "com.typesafe.akka" %% "akka-http-cors" % "1.1.1"
使用akka-grpc-client来调用gRPC服务的示例代码:
val system = ActorSystem("MySystem")
implicit val mat = ActorMaterializer.create(system)
implicit val ec = system.dispatcher
val clientSettings = GrpcClientSettings.connectToServiceAt("localhost", 8080).withTls(false)
val client = AkkaGrpcClient(clientSettings)
val responseFuture: Future[MyResponse] = client.myService.myMethod(MyRequest())
responseFuture.onComplete {
case Success(response) => println(s"Received response: $response")
case Failure(e) => e.printStackTrace()
}
使用Akka HTTP来调用gRPC服务的示例代码:
val system = ActorSystem("MySystem")
implicit val mat = ActorMaterializer.create(system)
implicit val ec = system.dispatcher
val responseFuture: Future[HttpResponse] =
Http().singleRequest(HttpRequest(
method = HttpMethods.POST,
uri = "http://localhost:8080/myService/myMethod",
entity = HttpEntity(ContentTypes.`application/grpc+proto`, MyRequest().toByteArray),
headers = List(RawHeader("te", "trailers"))
))
responseFuture.flatMap { response =>
val unmarshalPromise = Promise[MyResponse]()
response.entity.dataBytes
.via(Grpc.grpcFramingDecoder)
.map(_.bytes)