【问题标题】:Is it possible to share pure FP state between multiple http requests on http4s server?是否可以在 http4s 服务器上的多个 http 请求之间共享纯 FP 状态?
【发布时间】:2020-07-05 21:55:40
【问题描述】:

我正在尝试在 http4s 服务器上的多个 http 请求之间共享状态。

这就是我尝试过的:

for {
     state  <- Ref[F].of(0)
 
    _ <- BlazeServerBuilder[F]
         .bindHttp(port, host)
         .withHttpApp( ... httpApp that has link to "state" ... )
         .serve.compile.lastOrError

} yield  () 

在http请求中更改后状态保持不变。

是否可以使用Ref 或来自Fs2 的东西以纯FP 风格共享“状态”?

更新:问题出在我的应用程序内部。与我如何通过参考无关。我的错。

【问题讨论】:

    标签: scala scala-cats fs2 http4s


    【解决方案1】:

    您可以在 HTTP 请求中很好地修改状态。副作用是 IO monad 的重点,而可变状态是 Ref 的用途。下面是一个计算被调用次数的路由示例:

      def countRoutes[F[_]: Defer: Monad](ref: Ref[F, Int]): HttpRoutes[F] = {
        val dsl = new Http4sDsl[F]{}
        import dsl._
        HttpRoutes.of[F] {
          case GET -> Root / "count" =>
            for {
              current  <- ref.updateAndGet(_ + 1)
              resp <- Ok(current.toString)
            } yield resp
        }
      }
    
    

    不过,您的初始化代码看起来很奇怪。应该是这样的:

    for {
        state  <- Ref[IO].of(0)
        exitCode <- BlazeServerBuilder[F]
               .bindHttp(port, host)
               .withHttpApp( ... httpApp that has link to "state" ... )
               .serve.compile.lastOrError
    } yield exitCode
    

    【讨论】:

    • 我遇到了几乎同样的问题。是否可以使用Ref,以防每个请求分配一些Resource,然后将它们组合在一起以释放?我的意思是Ref[F, Resource[F, Unit]]
    猜你喜欢
    • 1970-01-01
    • 2011-05-07
    • 2020-10-30
    • 2012-11-28
    • 1970-01-01
    • 1970-01-01
    • 2016-03-07
    • 2010-12-23
    • 1970-01-01
    相关资源
    最近更新 更多