scala – Finch:方法’toService’的论据不够
我使用Finch和Finagle做了一个非常简单的休息方法:
val getUsers:Endpoint[List[User]] = get("users") {Ok(getAllUsers())} Http.serve(":8080",getUsers.toService) 并得到此错误: Error:(50,32) not enough arguments for method toService: (implicit ts: io.finch.internal.ToService[List[DAL.Instances.User.User]])com.twitter.finagle.Service[com.twitter.finagle.http.Request,com.twitter.finagle.http.Response]. Unspecified value parameter ts. Http.serve(":8080",getUsers.toService) ^ 有关如何解决它的任何想法? 解决方法
在最新版本的Finch(0.10)中,编译器错误稍微好一些.如果我们有以下构建配置:
scalaVersion := "2.11.7" libraryDependencies += "com.github.finagle" %% "finch-core" % "0.10.0" 这个设置: import com.twitter.finagle.Http import io.finch._ case class User(id: String,name: String) def getAllUsers(): List[User] = List(User("111","Foo McBar")) val getUsers: Endpoint[List[User]] = get("users") { Ok(getAllUsers()) } 然后当我们尝试使用toService时,我们得到以下内容: <console>:18: error: You can only convert a router into a Finagle service if the result type of the router is one of the following: * A Response * A value of a type with an EncodeResponse instance * A coproduct made up of some combination of the above List[User] does not satisfy the requirement. You may need to provide an EncodeResponse instance for List[User] (or for some part of List[User]). Http.serve(":8080",getUsers.toService) ^ 问题是您没有告诉Finch如何将您的用户类型的实例转换为HTTP响应. Finch的EncodeResponse是type class的一个例子,它是一种广泛用于Scala(包括标准库)和许多其他静态类型函数式编程语言的多态性方法. 提供适当的EncodeResponse实例的最简单方法是将Finch的Circe兼容性模块添加到您的构建中: libraryDependencies ++= Seq( "io.circe" %% "circe-generic" % "0.3.0","com.github.finagle" %% "finch-circe" % "0.10.0" ) 然后您需要的是以下导入: import io.finch.circe._,io.circe.generic.auto._ 并且toService将正常工作: scala> Http.serve(":8080",getUsers.toService) Feb 26,2016 8:32:24 AM com.twitter.finagle.Init$$anonfun$1 apply$mcV$sp INFO: Finagle version 6.33.0 (rev=21d0ee8b5070b735eda5c84d7aa6fbf1ba7b1635) built at 20160203-202859 res2: com.twitter.finagle.ListeningServer = Group(/0:0:0:0:0:0:0:0:8080) 现在,如果你去http:// localhost:8080 / users,你会看到以下内容: [{"id":"111","name":"Foo McBar"}] 这看起来很神奇,但正在发生的事情是相当有原则的. Circe是一个JSON库,提供通用编解码器派生,在编译时计算出如何将您的案例类表示为JSON值(有关更多上下文,请参阅我的博客文章here). Finch cookbook是学习更多类似问题的绝佳资源,第一部分详细介绍了提供服务需求的EncoderResponse实例的其他方法.如果您有任何其他问题或上述任何问题不明确,请随时在此处或Gitter询问. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |