• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Scala SimpleFilter类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Scala中com.twitter.finagle.SimpleFilter的典型用法代码示例。如果您正苦于以下问题:Scala SimpleFilter类的具体用法?Scala SimpleFilter怎么用?Scala SimpleFilter使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了SimpleFilter类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Scala代码示例。

示例1: RequestLoggingFilter

//设置package包名称以及导入依赖的类
package app.filter

import com.twitter.finagle.filter.LogFormatter
import com.twitter.finagle.http.Status.InternalServerError
import com.twitter.finagle.http.filter.CommonLogFormatter
import com.twitter.finagle.http.{ Request, Response }
import com.twitter.finagle.{ Service, SimpleFilter }
import com.twitter.logging.Logger
import com.twitter.util._


abstract class RequestLoggingFilter[REQ <: Request](val formatter: LogFormatter[REQ, Response])
  extends SimpleFilter[REQ, Response] {

  private val log = Logger.get(getClass)

  final def apply(request: REQ, service: Service[REQ, Response]): Future[Response] = {
    //log.info(s">>> RAW REQUEST: '${request.getContentString()}'")
    val elapsed = Stopwatch.start()
    val future = service(request)
    future.respond {
      case Return(response) => logSuccess(elapsed(), request, response)
      case Throw(error)     => logException(elapsed(), request, error)
    }
    future
  }

  final def logSuccess(replyTime: Duration, request: REQ, response: Response): Unit = {
    val line = formatter.format(request, response, replyTime)
    log.info(line)
  }

  final def logException(duration: Duration, request: REQ, error: Throwable): Unit = {
    val response = Response(request.version, InternalServerError)
    val line = formatter.format(request, response, duration)
    log.info(line)
  }
}

object RequestLoggingFilter extends RequestLoggingFilter[Request](new CommonLogFormatter) 
开发者ID:PScopelliti,项目名称:ProjectTracker,代码行数:41,代码来源:RequestLoggingFilter.scala


示例2: HandleRefusedByRateLimiterFilter

//设置package包名称以及导入依赖的类
package com.lookout.ratelimitingfilter

import com.twitter.finagle.http.{Request, Response}
import com.twitter.finagle.{Failure, Service, SimpleFilter, RefusedByRateLimiter}
import com.twitter.util.Future
import com.twitter.logging.Logger


case class HandleRefusedByRateLimiterFilter() extends SimpleFilter[Request, Response] {
  val LOG = Logger.get(getClass)

  def apply(request: Request, service: Service[Request, Response]): Future[Response] = Future {
    service(request) handle {
      case _: RefusedByRateLimiter => {
        val rateLimitedMessage = s"Request is rate limited: ${request.encodeString()}"
        LOG.info(rateLimitedMessage)
        RefusedByRateLimiterError(rateLimitedMessage).toResponse
      }
    }
  }.flatMap(identity _)
} 
开发者ID:lookout,项目名称:rate-limiting-strategy,代码行数:22,代码来源:HandleRefusedByRateLimiterFilter.scala


示例3: QueryCacheFilter

//设置package包名称以及导入依赖的类
package net.gutefrage.filter

import com.redis._
import com.redis.serialization.Parse.Implicits._
import com.twitter.finagle.{Service, SimpleFilter}
import com.twitter.util.Future
import net.gutefrage.filter.ThriftByteArray._

class QueryCacheFilter(val methodsToCache: Option[Seq[String]] = None, redisClient: RedisClient) extends SimpleFilter[Array[Byte], Array[Byte]] {

  def bytesToInt(bytes: Array[Byte]): Int = java.nio.ByteBuffer.wrap(bytes).getInt

  def apply(request: Array[Byte], service: Service[Array[Byte], Array[Byte]]): Future[Array[Byte]] = {
    val (methodName, seqId) = request.binaryProtocolMethodNameSeqId

    if (methodsToCache.isEmpty || methodsToCache.get.contains(methodName)) {
      println(s"Incoming request with method: $methodName -> Try to serve it from cache.")
      val redisKey = request.binaryProtocolChangeSeqId(Array[Byte](0, 0, 0, 0)).requestHashKey

      redisClient.get[Array[Byte]](redisKey) match {
        case Some(response) => {
          println("Data in redis found, returning from cache")
          Future.value(response)
        }
        case None => {
          println("data not in cache yet")
          service(request) map { result =>
            redisClient.setex(redisKey, 15, result)
            result
          }
        }
      }

    } else {
      println(s"Incoming request with method: $methodName -> Don't serve it from cache.")
      service(request)
    }

  }

} 
开发者ID:gutefrage,项目名称:the-finagle-docs,代码行数:42,代码来源:QueryCacheFilter.scala


示例4: WhichUserLogin

//设置package包名称以及导入依赖的类
package com.bob.reservefund.scala.Filter

import javax.inject.Inject

import com.twitter.finagle.filter.LogFormatter
import com.twitter.finagle.http.{Request, Response}
import com.twitter.finagle.{Service, SimpleFilter}
import com.twitter.inject.Logging
import com.twitter.util.{Stopwatch, Future}

case class WhichUserLogin(id: Long)

object WhichUserLoginContext {
  private val UserField = Request.Schema.newField[WhichUserLogin]()

  
class RequestAopFilter[R <: Request] @Inject()(
                                                logFormatter: LogFormatter[R, Response])
  extends SimpleFilter[R, Response] with Logging {

  override def apply(request: R, service: Service[R, Response]): Future[Response] = {
    if (!isInfoEnabled) {
      service(request)
    }
    else {
      val elapsed = Stopwatch.start()
      service(request) onSuccess { response =>
        info(response.contentString)
      } onFailure { e =>
        // should never get here since this filter is meant to be after the exception barrier
        info(logFormatter.formatException(request, e, elapsed()))
      }
    }
  }

} 
开发者ID:bobxwang,项目名称:ReserveFundService,代码行数:37,代码来源:WhichUserLoginFilter.scala


示例5: LoggingFilter

//设置package包名称以及导入依赖的类
package io.peregrine

import com.twitter.finagle.http.{Request => FinagleRequest, Response => FinagleResponse}
import com.twitter.finagle.{Service, SimpleFilter}
import com.twitter.logging.Logger
import com.twitter.util._
import com.twitter.conversions.time._

class LoggingFilter extends SimpleFilter[FinagleRequest, FinagleResponse] with LoggingFilterHelper {
  def apply(request: FinagleRequest, service: Service[FinagleRequest, FinagleResponse]): Future[FinagleResponse] = {
    applyLogging(request, req => service(req))
  }
}

trait LoggingFilterHelper extends LoggerColors {
  private val logger: Logger = PeregrineLogger.logger()

  private[peregrine] def applyLogging(request: FinagleRequest,
                                      func: FinagleRequest => Future[FinagleResponse]): Future[FinagleResponse] = {
    val elapsed = Stopwatch.start()
    func(request) map { response =>

      val duration = elapsed().inMicroseconds/1000.0
      val mColor = methodColor(response.statusCode)
      logger.info("[%s%s] %s%s %s\"%s\" %s%d %sin %s%.3fms%s",
          ANSI_RESET, request.remoteHost,
          ANSI_PURPLE, request.method,
          ANSI_BLUE, request.uri,
          mColor, response.statusCode,
          ANSI_RESET,
          ANSI_GREEN, duration,
          ANSI_RESET
      )
      response
    }
  }

  private[this] def methodColor(statusCode: Int) = statusCode match {
    case code if code >= 200 && code < 300 => ANSI_GREEN
    case code if code >= 400 && code < 500 => ANSI_YELLOW
    case code if code >= 500 && code < 600 => ANSI_RED
    case _                                 => ANSI_RESET
  }
} 
开发者ID:pairi,项目名称:pairi,代码行数:45,代码来源:LoggingFilter.scala


示例6: AssetsFilter

//设置package包名称以及导入依赖的类
package io.peregrine

import com.twitter.finagle.http.{Request => FinagleRequest, Response => FinagleResponse}
import com.twitter.finagle.{Service, SimpleFilter}
import com.twitter.util._

class AssetsFilter extends SimpleFilter[FinagleRequest, FinagleResponse] with LoggingFilterHelper {
  val logger = PeregrineLogger.logger()
  def apply(req: FinagleRequest, service: Service[FinagleRequest, FinagleResponse]): Future[FinagleResponse] = {
    if (req.path.startsWith("/__peregrine__/")) {
      return if (config.debugAssets()){
        applyLogging(req, request => Future(render.internal(req.path.replace("/__peregrine__", "__peregrine__"), 200).build))
      } else {
        Future(render.internal(req.path.replace("/__peregrine__", "__peregrine__"), 200).build)
      }
    }

    if (req.path.startsWith(config.assetsPathPrefix())) {
      if (config.debugAssets()) {
        applyLogging(req, request => applyAssets(request))
      } else {
        applyAssets(req)
      }
    } else {
      service(req)
    }
  }

  private[this] def applyAssets(req: FinagleRequest) = {
    val path = req.path.replace(config.assetsPathPrefix(), "")
    Try(render.static(path).build) match {
      case Return(resp) => Future(resp)
      case Throw(t)     => Future(render.notFound.build)
    }
  }

  protected def render = new ResponseBuilder()
} 
开发者ID:pairi,项目名称:pairi,代码行数:39,代码来源:AssetsFilter.scala


示例7: YaasHeadersTenantConsistentWithRouteFilter

//设置package包名称以及导入依赖的类
package me.kamkor.yaas.http.filters

import com.twitter.finagle.http.{Request, Response}
import com.twitter.finagle.{Service, SimpleFilter}
import com.twitter.util.Future
import me.kamkor.yaas.http.exceptions.ValidationException
import me.kamkor.yaas.http.filters.YaasHeadersContext._

class YaasHeadersTenantConsistentWithRouteFilter(routeParamName: String) extends SimpleFilter[Request, Response] {

  def this() = this("tenant")

  override def apply(request: Request, service: Service[Request, Response]): Future[Response] = {
    checkIfHeaderTenantConsistentWithRoute(request)
    service(request)
  }

  private def checkIfHeaderTenantConsistentWithRoute(request: Request): Unit =
    Option(request.getParam(routeParamName)) foreach { tenantRouteParam =>
      if (request.yaasHeaders.hybrisTenant != tenantRouteParam) {
        throw new ValidationException(s"'hybris-tenant' header must match route param '$routeParamName'")
      }
    }

} 
开发者ID:kamkor,项目名称:yaas-wishlist-service,代码行数:26,代码来源:YaasHeadersTenantConsistentWithRouteFilter.scala


示例8: YaasHeaders

//设置package包名称以及导入依赖的类
package me.kamkor.yaas.http.filters

import com.twitter.finagle.http.{Request, Response}
import com.twitter.finagle.{Service, SimpleFilter}
import com.twitter.util.Future

object YaasHeaders {
  val HybrisTenant = "hybris-tenant"
}

case class YaasHeaders(hybrisTenant: String)

class YaasHeadersFilter extends SimpleFilter[Request, Response] {
  override def apply(request: Request, service: Service[Request, Response]): Future[Response] = {
    YaasHeadersContext.setYaasHeaders(request)
    service(request)
  }
}

// create a context, see https://twitter.github.io/finatra/user-guide/build-new-http-server/filter.html
object YaasHeadersContext {

  private val YaasHeadersField = Request.Schema.newField[YaasHeaders]

  implicit class YaasAwareContextSyntax(val request: Request) extends AnyVal {
    def yaasHeaders: YaasHeaders = request.ctx(YaasHeadersField)
  }

  private[filters] def setYaasHeaders(request: Request): Unit = {
    val hybrisTenant = request.headerMap(YaasHeaders.HybrisTenant)
    val yaasAware = YaasHeaders(hybrisTenant)
    request.ctx.update(YaasHeadersField, yaasAware)
  }

} 
开发者ID:kamkor,项目名称:yaas-wishlist-service,代码行数:36,代码来源:YaasHeadersFilter.scala


示例9: UserFilter

//设置package包名称以及导入依赖的类
package com.example

import com.example.db.DB
import com.google.inject.Inject
import com.twitter.finagle.http.{Request, Response, Status}
import com.twitter.finagle.{Filter, Service, SimpleFilter}
import com.twitter.util.Future




class UserFilter @Inject() extends SimpleFilter[Request, Response] {
  override def apply(request: Request, service: Service[Request, Response]): Future[Response] = {
    val token = request.cookies.get("auth_token")
    DB.isValidToken(token.map(x => x.value).getOrElse("")) flatMap {
      case true => service(request)
      case false => redirectToLoginPage
    }
  }

  def redirectToLoginPage = Future {
    val response = Response(Status.TemporaryRedirect)
    response.location = "/loginform"
    response
  }
} 
开发者ID:Sergey778,项目名称:finatra_test,代码行数:27,代码来源:UserFilter.scala


示例10: ThriftServer

//设置package包名称以及导入依赖的类
package com.example

import com.twitter.finagle.example.thriftscala.Hello
import com.twitter.finagle.example.thriftscala.Hello.Hi.{Args, Result}
import com.twitter.finagle.{Service, SimpleFilter, Thrift}
import com.twitter.util.{Await, Future}

object ThriftServer {

  def main(args: Array[String]) {
    val filter = new SimpleFilter[Hello.Hi.Args, Hello.Hi.Result] {
      override def apply(request: Args, service: Service[Args, Result]): Future[Result] = {
        println("hahaha")
        service(request)
      }
    }
    val hiService = new Service[Hello.Hi.Args, Hello.Hi.Result] {
      override def apply(request: Hello.Hi.Args): Future[Hello.Hi.Result] = {
        Future(Hello.Hi.Result(Some("hi!")))
      }
    }
    val helloService = new Service[Hello.Hello.Args, Hello.Hello.Result] {
      override def apply(request: Hello.Hello.Args): Future[Hello.Hello.Result] = {
        Future(Hello.Hello.Result(Some("hello!")))
      }
    }
    val serviceImpl = Hello.ServiceIface(hi = filter andThen hiService, hello = helloService)
    val server = Thrift.serveIface("localhost:8081", Hello.MethodIfaceBuilder.newMethodIface(serviceImpl))
    Await.ready(server)
  }
} 
开发者ID:vtatai,项目名称:finagleThriftPlayground,代码行数:32,代码来源:ThriftServer.scala


示例11: ThriftClient

//设置package包名称以及导入依赖的类
package com.example

import com.twitter.finagle.{Service, SimpleFilter, Thrift}
import com.twitter.finagle.example.thriftscala.Hello
import com.twitter.finagle.thrift.{ClientId, ThriftClientRequest}
import com.twitter.util.{Await, Future}

object ThriftClient {
  def main(args: Array[String]) {
    val client = Thrift.client
      .withClientId(ClientId("CLIENT ID HARD TO MISS"))
      .filtered(new SimpleFilter[ThriftClientRequest, Array[Byte]] {
        override def apply(request: ThriftClientRequest, service: Service[ThriftClientRequest, Array[Byte]]): Future[Array[Byte]] = {
          println("Filtered")
          service(request)
        }
      })
      .newIface[Hello.FutureIface]("localhost:8081", "SPECIAL LABEL HARD TO MISS")
    println(Await.result(client.hi()))
  }
} 
开发者ID:vtatai,项目名称:finagleThriftPlayground,代码行数:22,代码来源:ThriftClient.scala


示例12: ThriftMuxGlobalServer

//设置package包名称以及导入依赖的类
package com.example

import com.twitter.finagle.example.thriftscala.Hello
import com.twitter.finagle.example.thriftscala.Hello.Hi.{Args, Result}
import com.twitter.finagle.thrift.ClientId
import com.twitter.finagle.{Service, SimpleFilter, Thrift, ThriftMux}
import com.twitter.util.{Await, Future}

object ThriftMuxGlobalServer {

  def main(args: Array[String]) {
    val iface = new Hello.FutureIface {
      def hi() = {
        println("received request")
        println(s"Client id: ${ClientId.current}")
        Future("hi there")
      }
      override def hello(): Future[String] = {
        Future("hello there")
      }
    }
    val filter = new SimpleFilter[Array[Byte], Array[Byte]] {
      override def apply(request: Array[Byte], service: Service[Array[Byte], Array[Byte]]): Future[Array[Byte]] = {
        println("filtered")
        service(request)
      }
    }
    val service = new Hello.FinagledService(iface, Thrift.protocolFactory)
    val server = ThriftMux.serve("localhost:8081", filter andThen service)
    Await.ready(server)
  }
} 
开发者ID:vtatai,项目名称:finagleThriftPlayground,代码行数:33,代码来源:ThriftMuxGlobalServer.scala


示例13: ThriftGlobalFilterServer

//设置package包名称以及导入依赖的类
package com.example

import com.twitter.finagle.example.thriftscala.Hello
import com.twitter.finagle.thrift.ClientId
import com.twitter.finagle.{Service, SimpleFilter, Thrift}
import com.twitter.util.{Await, Future}

object ThriftGlobalFilterServer {
  def main(args: Array[String]) {
    val iface = new Hello.FutureIface {
      def hi() = {
        println("received request")
        println(s"Client id: ${ClientId.current}")
        Future("hi there")
      }
      override def hello(): Future[String] = {
        Future("hello there")
      }
    }
    val filter = new SimpleFilter[Array[Byte], Array[Byte]] {
      override def apply(request: Array[Byte], service: Service[Array[Byte], Array[Byte]]): Future[Array[Byte]] = {
        println("filtered")
        service(request)
      }
    }
    val service = new Hello.FinagledService(iface, Thrift.protocolFactory)
    val server = Thrift.serve("localhost:8081", filter andThen service)
    Await.ready(server)
  }
} 
开发者ID:vtatai,项目名称:finagleThriftPlayground,代码行数:31,代码来源:ThriftGlobalFilterServer.scala


示例14: ThriftMuxServer

//设置package包名称以及导入依赖的类
package com.example

import com.twitter.finagle.example.thriftscala.Hello
import com.twitter.finagle.example.thriftscala.Hello.Hi.{Args, Result}
import com.twitter.finagle.{Service, SimpleFilter, Thrift, ThriftMux}
import com.twitter.util.{Await, Future}

object ThriftMuxServer {

  def main(args: Array[String]) {
    val filter = new SimpleFilter[Hello.Hi.Args, Hello.Hi.Result] {
      override def apply(request: Args, service: Service[Args, Result]): Future[Result] = {
        println("hahaha")
        service(request)
      }
    }
    val hiService = new Service[Hello.Hi.Args, Hello.Hi.Result] {
      override def apply(request: Hello.Hi.Args): Future[Hello.Hi.Result] = {
        Future(Hello.Hi.Result(Some("hi!")))
      }
    }
    val helloService = new Service[Hello.Hello.Args, Hello.Hello.Result] {
      override def apply(request: Hello.Hello.Args): Future[Hello.Hello.Result] = {
        Future(Hello.Hello.Result(Some("hello!")))
      }
    }
    val serviceImpl = Hello.ServiceIface(hi = filter andThen hiService, hello = helloService)
    val server = ThriftMux.serveIface("localhost:8081", Hello.MethodIfaceBuilder.newMethodIface(serviceImpl))
    Await.ready(server)
  }
} 
开发者ID:vtatai,项目名称:finagleThriftPlayground,代码行数:32,代码来源:ThriftMuxServer.scala


示例15: HawkAuthenticateRequestFilter

//设置package包名称以及导入依赖的类
package com.redbubble.hawk

import cats.syntax.either._
import com.redbubble.hawk.HawkAuthenticate.authenticateRequest
import com.redbubble.hawk.RequestContextBuilder.buildContext
import com.redbubble.hawk.validate.Credentials
import com.redbubble.util.http.ResponseOps._
import com.redbubble.util.http.{ApiError, AuthenticationFailedError}
import com.redbubble.util.metrics.StatsReceiver
import com.twitter.finagle.http.{Request, Response}
import com.twitter.finagle.{Service, SimpleFilter}
import com.twitter.util.Future

abstract class HawkAuthenticateRequestFilter(
    credentials: Credentials,
    whitelistedPaths: Seq[String],
    statsReceiver: StatsReceiver)
    extends SimpleFilter[Request, Response] {

  private val stats = statsReceiver.scope("hawk_auth")
  private val failureCounter = stats.counter("failure")
  private val successCounter = stats.counter("success")

  final override def apply(request: Request, continue: Service[Request, Response]): Future[Response] =
    if (whitelistedPaths.exists(p => request.path.startsWith(p))) {
      continue(request)
    } else {
      authenticate(request).fold(
        e => {
          failureCounter.incr()
          unauthorised(e.getMessage)
        },
        _ => {
          successCounter.incr()
          continue(request)
        }
      )
    }

  private def authenticate(request: Request): Either[ApiError, RequestValid] = {
    val valid = buildContext(request).map { context =>
      authenticateRequest(credentials, context)
    }.getOrElse(errorE(s"Missing authentication header '$AuthorisationHttpHeader'"))
    valid.leftMap(e => AuthenticationFailedError("Request is not authorised", Some(e)))
  }
} 
开发者ID:redbubble,项目名称:finagle-hawk,代码行数:47,代码来源:HawkAuthenticateRequestFilter.scala


示例16: format

//设置package包名称以及导入依赖的类
package com.twitter.finagle.filter

import com.twitter.util.{Duration, Return, Throw, Stopwatch, Future}
import com.twitter.finagle.{SimpleFilter, Service}
import com.twitter.logging.Logger

trait LogFormatter[-Req, Rep] {
  def format(request: Req, reply: Rep, replyTime: Duration): String

  def formatException(request: Req, throwable: Throwable, replyTime: Duration): String
}


trait LoggingFilter[Req, Rep] extends SimpleFilter[Req, Rep] {
  val log: Logger
  val formatter: LogFormatter[Req, Rep]

  def apply(request: Req, service: Service[Req, Rep]): Future[Rep] = {
    val elapsed = Stopwatch.start()
    val future = service(request)
    future respond {
      case Return(reply) =>
        log(elapsed(), request, reply)
      case Throw(throwable) =>
        logException(elapsed(), request, throwable)
    }
    future
  }

  protected def log(replyTime: Duration, request: Req, reply: Rep) {
    val line = formatter.format(request, reply, replyTime)
    log.info(line)
  }

  protected def logException(replyTime: Duration, request: Req, throwable: Throwable) {
    val line = formatter.formatException(request, throwable, replyTime)
    log.info(throwable, line)
  }

} 
开发者ID:wenkeyang,项目名称:finagle,代码行数:41,代码来源:LoggingFilter.scala


示例17: ExceptionSourceFilter

//设置package包名称以及导入依赖的类
package com.twitter.finagle.filter

import com.twitter.finagle.{param, SimpleFilter, Service,
  ServiceFactory, SourcedException, Stack, Stackable, Failure}
import com.twitter.util.Future

private[finagle] object ExceptionSourceFilter {
  val role = Stack.Role("ExceptionSource")

  
class ExceptionSourceFilter[Req, Rep](serviceName: String) extends SimpleFilter[Req, Rep] {

  private[this] val addExceptionSource: PartialFunction[Throwable, Future[Rep]] = {
    case f: Failure =>
      Future.exception(f.withSource(Failure.Source.Service, serviceName))
    case e: SourcedException =>
      e.serviceName = serviceName
      Future.exception(e)
  }

  def apply(request: Req, service: Service[Req, Rep]): Future[Rep] =
    service(request).rescue(addExceptionSource)
} 
开发者ID:wenkeyang,项目名称:finagle,代码行数:24,代码来源:ExceptionSourceFilter.scala


示例18: ServerStatsFilter

//设置package包名称以及导入依赖的类
package com.twitter.finagle.filter

import com.twitter.finagle.stats.StatsReceiver
import com.twitter.finagle.{param, Service, ServiceFactory, SimpleFilter, Stack, Stackable}
import com.twitter.util.{Future, Stopwatch}
import java.util.concurrent.TimeUnit

private[finagle] object ServerStatsFilter {
  val role = Stack.Role("ServerStats")

  
private[finagle] class ServerStatsFilter[Req, Rep](statsReceiver: StatsReceiver, nowNanos: () => Long)
  extends SimpleFilter[Req, Rep]
{
  def this(statsReceiver: StatsReceiver) = this(statsReceiver, Stopwatch.systemNanos)

  private[this] val handletime = statsReceiver.stat("handletime_us")

  def apply(request: Req, service: Service[Req, Rep]): Future[Rep] = {
    val startAt = nowNanos()
    try service(request)
    finally {
      val elapsedNs = nowNanos() - startAt
      handletime.add(TimeUnit.MICROSECONDS.convert(elapsedNs, TimeUnit.NANOSECONDS))
    }
  }
} 
开发者ID:wenkeyang,项目名称:finagle,代码行数:28,代码来源:ServerStatsFilter.scala


示例19: RequestMeterFilter

//设置package包名称以及导入依赖的类
package com.twitter.finagle.filter

import com.twitter.concurrent.AsyncMeter
import com.twitter.finagle.{Failure, Service, SimpleFilter}
import com.twitter.util.{Future, Throw}

import java.util.concurrent.RejectedExecutionException


class RequestMeterFilter[Req, Rep](meter: AsyncMeter) extends SimpleFilter[Req, Rep] {
  def apply(request: Req, service: Service[Req, Rep]) = {
    meter.await(1).transform {
      case Throw(noPermit) => noPermit match {
        case e: RejectedExecutionException =>
          Future.exception(Failure.rejected(noPermit))
        case e => Future.exception(e)
      }
      case _ => service(request)
    }
  }
} 
开发者ID:wenkeyang,项目名称:finagle,代码行数:22,代码来源:RequestMeterFilter.scala


示例20: MkJvmFilter

//设置package包名称以及导入依赖的类
package com.twitter.finagle.filter

import com.twitter.util.{Time, Future}
import com.twitter.jvm.Jvm
import com.twitter.finagle.{Service, SimpleFilter}
import com.twitter.finagle.tracing.{Trace, Record, Annotation}
import com.twitter.conversions.time._


class MkJvmFilter(jvm: Jvm) {
  private[this] val buffer = jvm.monitorGcs(1.minute)

  def apply[Req, Rep](): SimpleFilter[Req, Rep] = new SimpleFilter[Req, Rep] {
    def apply(req: Req, service: Service[Req, Rep]): Future[Rep] = {
      val begin = Time.now
      if (Trace.isActivelyTracing) {
        service(req) ensure {
          buffer(begin) foreach { gc =>
            Trace.record {
              Record(Trace.id, gc.timestamp, Annotation.Message(gc.toString), Some(gc.duration))
            }
          }
        }
      }
      else
        service(req)
    }
  }
} 
开发者ID:wenkeyang,项目名称:finagle,代码行数:30,代码来源:JvmFilter.scala



注:本文中的com.twitter.finagle.SimpleFilter类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Scala HttpService类代码示例发布时间:2022-05-23
下一篇:
Scala AlertDialog类代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap