本文整理汇总了Scala中io.netty.channel.ChannelHandler.Sharable类的典型用法代码示例。如果您正苦于以下问题:Scala Sharable类的具体用法?Scala Sharable怎么用?Scala Sharable使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Sharable类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: RespondToExpectContinue
//设置package包名称以及导入依赖的类
package com.twitter.finagle.netty4.http.handler
import io.netty.buffer.Unpooled
import io.netty.channel.ChannelHandler.Sharable
import io.netty.channel.{ChannelHandlerContext, ChannelInboundHandlerAdapter}
import io.netty.handler.codec.http._
@Sharable
private[http] object RespondToExpectContinue extends ChannelInboundHandlerAdapter {
def newContinue(): FullHttpResponse =
new DefaultFullHttpResponse(
HttpVersion.HTTP_1_1,
HttpResponseStatus.CONTINUE,
Unpooled.EMPTY_BUFFER)
override def channelRead(ctx: ChannelHandlerContext, msg: Any): Unit = {
msg match {
case http: HttpMessage if HttpUtil.is100ContinueExpected(http) =>
ctx.writeAndFlush(newContinue())
http.headers.remove(HttpHeaderNames.EXPECT)
case _ =>
}
super.channelRead(ctx, msg)
}
}
示例2: ThriftClientArrayToByteBufEncoder
//设置package包名称以及导入依赖的类
package com.twitter.finagle.thrift.transport.netty4
import com.twitter.finagle.thrift.ThriftClientRequest
import com.twitter.finagle.thrift.transport.ExceptionFactory
import io.netty.buffer.Unpooled
import io.netty.channel.ChannelHandler.Sharable
import io.netty.channel.{
ChannelHandler, ChannelHandlerContext, ChannelOutboundHandlerAdapter,
ChannelPromise, CombinedChannelDuplexHandler}
@Sharable
private object ThriftClientArrayToByteBufEncoder extends ChannelOutboundHandlerAdapter {
override def write(ctx: ChannelHandlerContext, msg: Any, promise: ChannelPromise): Unit = msg match {
case request: ThriftClientRequest =>
val buf = Unpooled.wrappedBuffer(request.message)
ctx.writeAndFlush(buf, promise)
case other =>
val ex = ExceptionFactory.wrongClientWriteType(other)
promise.setFailure(ex)
throw ex
}
}
}
示例3: ThriftByteBufToArrayDecoder
//设置package包名称以及导入依赖的类
package com.twitter.finagle.thrift.transport.netty4
import io.netty.buffer.ByteBuf
import io.netty.channel.ChannelHandler.Sharable
import io.netty.channel.{ChannelHandlerContext, ChannelInboundHandlerAdapter}
@Sharable
private[netty4] object ThriftByteBufToArrayDecoder extends ChannelInboundHandlerAdapter {
override def channelRead(
ctx: ChannelHandlerContext,
msg: scala.Any
): Unit = msg match {
case buffer: ByteBuf =>
// toArray takes ownership of the buffer
val array = toArray(buffer)
ctx.fireChannelRead(array)
case _ => throw new IllegalArgumentException("no byte buffer")
}
// takes ownership of the passed `ByteBuf`
private def toArray(buffer: ByteBuf): Array[Byte] = {
val array = new Array[Byte](buffer.readableBytes())
buffer.readBytes(array)
buffer.release() // If you love it, set it free.
array
}
}
示例4: ServerByteBufCodec
//设置package包名称以及导入依赖的类
package com.twitter.finagle.thrift.transport.netty4
import com.twitter.finagle.thrift.transport.ExceptionFactory
import io.netty.buffer.Unpooled
import io.netty.channel.{
ChannelHandler, ChannelHandlerContext, ChannelOutboundHandlerAdapter,
ChannelPromise, CombinedChannelDuplexHandler}
import io.netty.channel.ChannelHandler.Sharable
private[netty4] object ServerByteBufCodec {
def apply(): ChannelHandler = {
val encoder = ThriftServerArrayToByteBufEncoder
val decoder = ThriftByteBufToArrayDecoder
new CombinedChannelDuplexHandler(decoder, encoder)
}
@Sharable
private object ThriftServerArrayToByteBufEncoder extends ChannelOutboundHandlerAdapter {
override def write(ctx: ChannelHandlerContext, msg: Any, promise: ChannelPromise): Unit =
msg match {
case array: Array[Byte] =>
val buf = Unpooled.wrappedBuffer(array)
ctx.writeAndFlush(buf, promise)
case other =>
val ex = ExceptionFactory.wrongServerWriteType(other)
promise.setFailure(ex)
throw ex
}
}
}
示例5: ServerBridge
//设置package包名称以及导入依赖的类
package com.twitter.finagle.netty4.channel
import com.twitter.finagle.transport.Transport
import io.netty.channel.{ChannelInitializer, Channel}
import io.netty.channel.ChannelHandler.Sharable
@Sharable
private[netty4] class ServerBridge[In, Out](
transportFac: Channel => Transport[In, Out],
serveTransport: Transport[In, Out] => Unit)
extends ChannelInitializer[Channel] {
def initChannel(ch: Channel): Unit = {
val transport: Transport[In, Out] = transportFac(ch)
serveTransport(transport)
}
}
示例6: DirectToHeapInboundHandler
//设置package包名称以及导入依赖的类
package com.twitter.finagle.netty4.channel
import io.netty.buffer.ByteBuf
import io.netty.channel.ChannelHandler.Sharable
import io.netty.channel.{ChannelHandlerContext, ChannelInboundHandlerAdapter}
@Sharable
object DirectToHeapInboundHandler extends ChannelInboundHandlerAdapter {
override def channelRead(ctx: ChannelHandlerContext, msg: Any): Unit = msg match {
case bb: ByteBuf if bb.isDirect =>
val heapBuf = ctx.alloc().heapBuffer(bb.readableBytes, bb.capacity)
heapBuf.writeBytes(bb)
bb.release()
ctx.fireChannelRead(heapBuf)
case _ => ctx.fireChannelRead(msg)
}
}
示例7: ChannelRequestStatsHandler
//设置package包名称以及导入依赖的类
package com.twitter.finagle.netty4.channel
import com.twitter.finagle.stats.StatsReceiver
import io.netty.channel._
import io.netty.channel.ChannelHandler.Sharable
import io.netty.util.AttributeKey
import java.util.concurrent.atomic.AtomicInteger
private[finagle] object ChannelRequestStatsHandler {
private[channel] val ConnectionRequestsKey: AttributeKey[AtomicInteger] =
AttributeKey.valueOf("ChannelRequestStatsHandler.connection_requests")
}
@Sharable
private[finagle] class ChannelRequestStatsHandler(statsReceiver: StatsReceiver)
extends ChannelInboundHandlerAdapter
{
import ChannelRequestStatsHandler.ConnectionRequestsKey
private[this] val requestCount = statsReceiver.stat("connection_requests")
override def handlerAdded(ctx: ChannelHandlerContext): Unit = {
ctx.channel.attr(ConnectionRequestsKey).set(new AtomicInteger(0))
super.handlerAdded(ctx)
}
override def channelInactive(ctx: ChannelHandlerContext): Unit = {
requestCount.add(ctx.channel.attr(ConnectionRequestsKey).get.get)
super.channelInactive(ctx)
}
override def channelRead(ctx: ChannelHandlerContext, msg: Any): Unit = {
val readCount = ctx.channel.attr(ConnectionRequestsKey).get
readCount.incrementAndGet()
super.channelRead(ctx, msg)
}
}
示例8: RecvBufferSizeStatsHandler
//设置package包名称以及导入依赖的类
package com.twitter.finagle.netty4.channel
import com.twitter.finagle.stats.StatsReceiver
import io.netty.buffer.ByteBuf
import io.netty.channel.ChannelHandler.Sharable
import io.netty.channel.{ChannelHandlerContext, ChannelInboundHandlerAdapter}
@Sharable
private[netty4] class RecvBufferSizeStatsHandler(stats: StatsReceiver)
extends ChannelInboundHandlerAdapter {
private[this] val receiveBufferBytes = stats.stat("receive_buffer_bytes")
override def channelRead(ctx: ChannelHandlerContext, msg: Any): Unit = {
msg match {
case bb: ByteBuf => receiveBufferBytes.add(bb.readableBytes().toFloat)
case _ => // NOOP
}
ctx.fireChannelRead(msg)
}
}
示例9: HistoryReplier
//设置package包名称以及导入依赖的类
package com.wavesplatform.network
import io.netty.channel.ChannelHandler.Sharable
import io.netty.channel.{ChannelHandlerContext, ChannelInboundHandlerAdapter}
import scorex.transaction.{History}
import scorex.utils.ScorexLogging
@Sharable
class HistoryReplier(history: History, maxChainLength: Int) extends ChannelInboundHandlerAdapter with ScorexLogging {
override def channelRead(ctx: ChannelHandlerContext, msg: AnyRef): Unit = msg match {
case GetSignatures(otherSigs) =>
otherSigs.view
.map(parent => parent -> history.blockIdsAfter(parent, maxChainLength))
.find(_._2.nonEmpty) match {
case Some((parent, extension)) =>
log.debug(s"${id(ctx)} Got GetSignatures with ${otherSigs.length}, found common parent $parent and sending ${extension.length} more signatures")
ctx.writeAndFlush(Signatures(parent +: extension))
case None if otherSigs.length == 1 && otherSigs.head == history.lastBlock.get.uniqueId =>
// this is the special case when both nodes only have genesis block
log.debug(s"${id(ctx)} Both local and remote nodes only have genesis block")
ctx.writeAndFlush(Signatures(otherSigs))
case _ =>
log.debug(s"${id(ctx)} Got GetSignatures with ${otherSigs.length} signatures, but could not find an extension")
}
case GetBlock(sig) =>
for (h <- history.heightOf(sig); bytes <- history.blockBytes(h)) {
ctx.writeAndFlush(RawBytes(BlockMessageSpec.messageCode, bytes))
}
case _: Handshake =>
ctx.writeAndFlush(LocalScoreChanged(history.score()))
case _ => super.channelRead(ctx, msg)
}
}
示例10: InboundConnectionFilter
//设置package包名称以及导入依赖的类
package com.wavesplatform.network
import java.net.{InetAddress, InetSocketAddress}
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.atomic.AtomicInteger
import io.netty.channel.ChannelHandler.Sharable
import io.netty.channel.{ChannelFuture, ChannelHandlerContext}
import io.netty.handler.ipfilter.AbstractRemoteAddressFilter
import scorex.utils.ScorexLogging
@Sharable
class InboundConnectionFilter(peerDatabase: PeerDatabase, maxInboundConnections: Int, maxConnectionsPerHost: Int)
extends AbstractRemoteAddressFilter[InetSocketAddress] with ScorexLogging {
private val inboundConnectionCount = new AtomicInteger(0)
private val perHostConnectionCount = new ConcurrentHashMap[InetAddress, Int]
private def dec(remoteAddress: InetAddress) = {
inboundConnectionCount.decrementAndGet()
perHostConnectionCount.compute(remoteAddress, (_, cnt) => cnt - 1)
null.asInstanceOf[ChannelFuture]
}
override def accept(ctx: ChannelHandlerContext, remoteAddress: InetSocketAddress) = {
val newTotal = inboundConnectionCount.incrementAndGet()
val newCountPerHost = perHostConnectionCount.compute(remoteAddress.getAddress, (_, cnt) => Option(cnt).fold(1)(_ + 1))
val isBlacklisted = peerDatabase.blacklistedHosts.contains(remoteAddress.getAddress)
log.trace(s"Check inbound connection from $remoteAddress: new inbound total = $newTotal, " +
s"connections with this host = $newCountPerHost, address ${if (isBlacklisted) "IS" else "is not"} blacklisted")
newTotal <= maxInboundConnections &&
newCountPerHost <= maxConnectionsPerHost &&
!isBlacklisted
}
override def channelAccepted(ctx: ChannelHandlerContext, remoteAddress: InetSocketAddress) =
ctx.channel().closeFuture().addListener((_: ChannelFuture) => dec(remoteAddress.getAddress))
override def channelRejected(ctx: ChannelHandlerContext, remoteAddress: InetSocketAddress) =
dec(remoteAddress.getAddress)
}
示例11: MessageCodec
//设置package包名称以及导入依赖的类
package com.wavesplatform.network
import java.util
import io.netty.channel.ChannelHandler.Sharable
import io.netty.channel.ChannelHandlerContext
import io.netty.handler.codec.MessageToMessageCodec
import scorex.network.message._
import scorex.utils.ScorexLogging
@Sharable
class MessageCodec extends MessageToMessageCodec[RawBytes, Message] with ScorexLogging {
private val specs: Map[Byte, MessageSpec[_ <: AnyRef]] = BasicMessagesRepo.specs.map(s => s.messageCode -> s).toMap
override def encode(ctx: ChannelHandlerContext, msg: Message, out: util.List[AnyRef]) = msg match {
case LocalScoreChanged(score) => out.add(RawBytes(ScoreMessageSpec.messageCode, ScoreMessageSpec.serializeData(score)))
case GetPeers => out.add(RawBytes(GetPeersSpec.messageCode, Array[Byte]()))
case k: KnownPeers => out.add(RawBytes(PeersSpec.messageCode, PeersSpec.serializeData(k)))
case gs: GetSignatures => out.add(RawBytes(GetSignaturesSpec.messageCode, GetSignaturesSpec.serializeData(gs)))
case s: Signatures => out.add(RawBytes(SignaturesSpec.messageCode, SignaturesSpec.serializeData(s)))
case g: GetBlock => out.add(RawBytes(GetBlockSpec.messageCode, GetBlockSpec.serializeData(g)))
case BlockForged(b) => out.add(RawBytes(BlockMessageSpec.messageCode, b.bytes))
case r: RawBytes => out.add(r)
}
override def decode(ctx: ChannelHandlerContext, msg: RawBytes, out: util.List[AnyRef]) =
out.add(specs(msg.code).deserializeData(msg.data).get)
}
示例12: UtxPoolSynchronizer
//设置package包名称以及导入依赖的类
package com.wavesplatform.network
import java.util.concurrent.Executors
import akka.dispatch.ExecutionContexts
import com.wavesplatform.UtxPool
import com.wavesplatform.state2.diffs.TransactionDiffer.TransactionValidationError
import io.netty.channel.ChannelHandler.Sharable
import io.netty.channel.group.ChannelGroup
import io.netty.channel.{ChannelHandlerContext, ChannelInboundHandlerAdapter}
import scorex.transaction.Transaction
import scorex.utils.ScorexLogging
import scala.concurrent.Future
@Sharable
class UtxPoolSynchronizer(utx: UtxPool, allChannels: ChannelGroup)
extends ChannelInboundHandlerAdapter with ScorexLogging {
private implicit val executor = ExecutionContexts.fromExecutor(Executors.newSingleThreadExecutor())
override def channelRead(ctx: ChannelHandlerContext, msg: AnyRef): Unit = msg match {
case t: Transaction => Future(utx.putIfNew(t) match {
case Left(TransactionValidationError(e, _)) =>
log.debug(s"${id(ctx)} Error processing transaction ${t.id}: $e")
case Left(e) =>
log.debug(s"${id(ctx)} Error processing transaction ${t.id}: $e")
case Right(_) =>
allChannels.broadcast(RawBytes(TransactionMessageSpec.messageCode, t.bytes), Some(ctx.channel()))
log.trace(s"${id(ctx)} Added transaction ${t.id} to UTX pool")
})
case _ => super.channelRead(ctx, msg)
}
}
示例13: UnpoolHandler
//设置package包名称以及导入依赖的类
package com.twitter.finagle.buoyant.h2
package netty4
import io.netty.buffer.{ByteBuf, ByteBufHolder, EmptyByteBuf, Unpooled}
import io.netty.channel.ChannelHandler.Sharable
import io.netty.channel.{ChannelHandlerContext, ChannelInboundHandlerAdapter}
@Sharable
object UnpoolHandler extends ChannelInboundHandlerAdapter {
private[this] final def copyOnHeapAndRelease(bb: ByteBuf): ByteBuf = {
try {
if (bb.readableBytes > 0) Unpooled.buffer(bb.readableBytes, bb.capacity).writeBytes(bb)
else Unpooled.EMPTY_BUFFER
} finally {
val _ = bb.release()
}
}
override def channelRead(ctx: ChannelHandlerContext, msg: Any): Unit = msg match {
case bb: ByteBuf =>
val _ = ctx.fireChannelRead(copyOnHeapAndRelease(bb))
// This case is special since it helps to avoid unnecessary `replace`
// when the underlying content is already `EmptyByteBuffer`.
case bbh: ByteBufHolder if bbh.content.isInstanceOf[EmptyByteBuf] =>
val _ = ctx.fireChannelRead(bbh)
case bbh: ByteBufHolder =>
val onHeapContent = copyOnHeapAndRelease(bbh.content)
val _ = ctx.fireChannelRead(bbh.replace(onHeapContent))
case _ =>
val _ = ctx.fireChannelRead(msg)
}
}
示例14: PretentCreditCardService
//设置package包名称以及导入依赖的类
package com.packt.masteringakka.bookstore.server
import io.netty.channel.ChannelHandler.Sharable
import unfiltered.netty.ServerErrorResponse
import unfiltered.request._
import java.util.Date
import org.json4s._
import org.json4s.native.Serialization
import org.json4s.native.Serialization.{read, write}
import unfiltered.response._
@Sharable
object PretentCreditCardService extends unfiltered.netty.async.Plan with ServerErrorResponse{
case class ChargeRequest(cardHolder:String, cardType:String, cardNumber:String, expiration:Date, amount:Double)
case class ChargeResponse(confirmationCode:String)
implicit val formats = Serialization.formats(NoTypeHints)
def intent = {
case req @ POST(Path(Seg("credit" :: "charge" :: Nil))) =>
val body = Body.string(req)
val request = read[ChargeRequest](body)
val resp = write(ChargeResponse(java.util.UUID.randomUUID().toString))
req.respond(JsonContent ~> ResponseString(resp))
}
}
示例15: PretentCreditCardService
//设置package包名称以及导入依赖的类
package com.packt.masteringakka.bookstore.common
import io.netty.channel.ChannelHandler.Sharable
import unfiltered.netty.ServerErrorResponse
import unfiltered.request._
import java.util.Date
import org.json4s._
import org.json4s.native.Serialization
import org.json4s.native.Serialization.{read, write}
import unfiltered.response._
@Sharable
object PretentCreditCardService extends unfiltered.netty.async.Plan with ServerErrorResponse{
case class ChargeRequest(cardHolder:String, cardType:String, cardNumber:String, expiration:Date, amount:Double)
case class ChargeResponse(confirmationCode:String)
implicit val formats = Serialization.formats(NoTypeHints)
def intent = {
case req @ POST(Path(Seg("credit" :: "charge" :: Nil))) =>
val body = Body.string(req)
val request = read[ChargeRequest](body)
val resp = write(ChargeResponse(java.util.UUID.randomUUID().toString))
req.respond(JsonContent ~> ResponseString(resp))
}
}