创建提供程序以进行跟踪取决于环境变量

问题描述

我想基于配置变量创建一个多态提供者, 我做了下面的代码,但它不与错误消息一起工作:

[StaticBindings] - SQSInputMessage was bound to null

我理解问题,但是我还不知道如何克服,我想将SQSInputMessage特性绑定到某些实现,每个服务(serviceA,serviceB等)都有其他模式,我想计算模式部署文件对SQSInputMessage进行更改,因此每种服务只有一个代码库。

应用程序枚举:

sealed trait Application extends EnumEntry with CapitalHyphencase
object Application extends Enum[Application] with PlayJsonEnum[Application] {

  case object DEFAULT extends Application
  case object SERVICE_A extends Application
  case object SERVICE_B extends Application

  override def values: IndexedSeq[Application] = findValues
}

SQS输入案例分类

sealed trait SQSInputMessage {
  val transactionId: String
}


case class DefaultSQSMessage(override val transactionId: String) extends SQSInputMessage
case class ServiceASqsMessage(amount: Int,override val transactionId: String) extends SQSInputMessage
case class ServiceBSqsMessage(invoice: String,amount: Int,override val transactionId: String) extends SQSInputMessage

流:(具有多态绑定)

class RequestFlow @Inject()(conf: Configuration,taskService: TaskService)(implicit ec: ExecutionContext) extends LazyLogging with GenericFlow {
  override type Input = SQSInputMessage
  ...
  private [GenericFlow] def defaultValidation(message: Message): 
  MsgData[Input] = {
    Json.parse(message.body()).validate[Input] match {
      case JsSuccess(input,_) =>
        logger.debug(s"Input parsed successfully $input")
        parsingSuccess.increment
        MsgData(message,input)
      case JsError(ex) =>
        parsingErrorCounter.increment()
        logger.error(s"Failed to parsed message: ${message.body()},error: ",ex)
        Console println (s"Failed to parsed message: ${message.body()},ex)
        throw QueueReaderParsingException(ex.toString)
    }
  }
   ...

模块:

class StaticBindings extends AbstractModule {

  override def configure() = {
   
    bind(classOf[RequestStream]).asEagerSingleton()

    // Bind SQS Input Message:
    bind(classOf[SQSInputMessage]).toProvider(classOf[SQSInputMessageProvider]).in(classOf[Singleton])
  }
}

提供者:


object StaticBindings {

 class SQSInputMessageProvider @Inject()(
                                           configuration: Configuration
                                         ) extends Provider[SQSInputMessage] with LazyLogging {
    override def get(): SQSInputMessage = {

      def getInstanceOf[A]()(implicit t: classtag[A]): A = null.asInstanceOf[A]

      def decideByApp(app: Application): SQSInputMessage = app match {
        case Application.SERVICE_A => getInstanceOf[ServiceASqsMessage]()
        case Application.SERVICE_B => getInstanceOf[ServiceBSqsMessage]()
        case Application.DEFAULT | _ => getInstanceOf[DefaultSQSMessage]()
      }

      val res = configuration.getoptional[String]("myService.instance") match {
        case Some(appT) =>
          logger.info(s"[StaticBindings] - Trying to bind $appT...")
          decideByApp(Application.namesTovaluesMap.getorElse(appT,DEFAULT))
        case None => decideByApp(DEFAULT)
      }
      logger.info(s"[StaticBindings] - SQSInputMessage was bound to ${res}")
      res
    }
  }
}

使用play 2.7

为了快速理解:

  1. 请参阅RequestFlow类
  2. 请参见StaticBindings
  3. 按顺序查看emums和case类

谢谢!

解决方法

问题(显然)在def getInstanceOf[A]()(implicit t: ClassTag[A]): A = null.asInstanceOf[A]中。

奇怪的是,您写了整篇有关绑定的文章,却没有提到最后,您只为实例创建而苦苦挣扎。

实际上,当您具有在编译时知道的case类时,我不明白为什么需要instanceOf。只需使用构造函数即可。

def decideByApp(app: Application): SQSInputMessage = app match {
  case Application.SERVICE_A => ServiceASqsMessage(...)
  case Application.SERVICE_B => ServiceBSqsMessage(...)
  case Application.DEFAULT | _ => DefaultSQSMessage(...)
}

此外,我看到ServiceASqsMessage和其他服务根本不是服务,并且对仅用于DTO的不同案例类使用绑定并不方便。您应该在内部绑定使用相应消息类型的某种SqsMessageService的实现,并引入一些公共接口(请注意,此处 service 表示从分层体系结构而非Web服务进行OO设计的模式)。 / p>

还有其他问题吗?我建议您在这种情况下创建一个专门的问题。