Exemple #1
0
  /** 基类实现消息监听接口,加上打印metaq监控日志的方法 */
  @Override
  public ConsumeConcurrentlyStatus consumeMessage(
      List<MessageExt> msgs, ConsumeConcurrentlyContext context) {
    long startTime = System.currentTimeMillis();
    logger.info("receive_message:{}", msgs.toString());
    if (msgs == null || msgs.size() < 1) {
      logger.error("receive empty msg!");
      return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
    }

    List<Serializable> msgList = new ArrayList<>();
    for (MessageExt message : msgs) {
      msgList.add(decodeMsg(message));
    }

    final int reconsumeTimes = msgs.get(0).getReconsumeTimes();
    MsgObj msgObj = new MsgObj();
    msgObj.setReconsumeTimes(reconsumeTimes);
    msgObj.setMsgList(msgList);
    msgObj.setContext(context);
    context.setDelayLevelWhenNextConsume(getDelayLevelWhenNextConsume(reconsumeTimes));

    ConsumeConcurrentlyStatus status = doConsumeMessage(msgObj);
    logger.info(
        "ConsumeConcurrentlyStatus:{}|cost:{}", status, System.currentTimeMillis() - startTime);
    return status;
  }
Exemple #2
0
  /**
   * 返回响应结果
   *
   * @param response
   * @return
   */
  public static RestResponse returnResponse(
      BaseRestRequest request,
      RestResponse response,
      RestServiceMapping serviceMapping,
      RestServiceConfiguration configuration) {

    String cmd = request.getRestRequest().getCmd();

    // 调用后置拦截器
    List<RestRequestAfterInterceptor> requestAfterInterceptors =
        configuration.getRequestAfterInterceptors();
    for (RestRequestAfterInterceptor requestInterceptor : requestAfterInterceptors) {
      String requestInterceptorName = requestInterceptor.getName();
      logger.debug(
          "REST_AFTER_INTERCEPTOR_START, cmd: {}, name: {}",
          cmd,
          requestInterceptorName + "|" + requestInterceptor.getClass().getName());
      try {
        requestInterceptor.setConfiguration(configuration);
        requestInterceptor.execute(serviceMapping, request, response);
      } catch (Exception e) {
        response.setException(e);
        logger.warn("执行拦截器 {} 失败", requestInterceptorName, e);
      }
      logger.debug(
          "REST_AFTER_INTERCEPTOR_COMPLETE, cmd: {}, name: {}",
          cmd,
          requestInterceptorName + "|" + requestInterceptor.getClass().getName());
    }
    return response;
  }
Exemple #3
0
 protected ConsumeConcurrentlyStatus exceptionConsumeConcurrentlyStatus(
     TransactionStatus status, Throwable e, MsgObj msgObj, int maxRetryCount) {
   logger.error("mq consume failed", e);
   status.setRollbackOnly();
   if (msgObj.getReconsumeTimes() >= maxRetryCount) {
     logger.error(
         "retryCount: {}, msgs: {}, context: {}", maxRetryCount, msgObj, msgObj.getContext());
     msgObj.setErrorMsg(e.getMessage());
     doLogErrorConsumeMessage(msgObj);
     return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
   } else {
     return ConsumeConcurrentlyStatus.RECONSUME_LATER;
   }
 }
Exemple #4
0
 public void destroy() {
   if (consumer != null) {
     consumer.shutdown();
     logger.info(
         "consumer shutdown! topic={0},subExpression={1},group={2}",
         topic.getTopic(), subExpression, group);
   }
 }
Exemple #5
0
 private Serializable decodeMsg(MessageExt msg) {
   if (msg == null) {
     return null;
   }
   // 1.反序列化
   try {
     return HessianUtils.decode(msg.getBody());
   } catch (IOException e) {
     logger.error("反序列化出错!" + e.getMessage(), e);
     return null;
   }
 }
Exemple #6
0
  protected static void recordToErrorCounter(String cmd) {

    String today = DateUtil.format(new Date(), "yyyyMMdd");
    try {

      RedisUtil.incr(ERROR_COUNT_KEY + today);

    } catch (Exception e) {

      logger.warn("记录api返回错误请求的次数失败, today: {}", today, e);
    }

    try {

      RedisUtil.incr(ERROR_COUNT_KEY + today + ":cmd:" + cmd);

    } catch (Exception e) {

      logger.warn("记录cmd: {}, today: {} 返回错误请求的次数失败", cmd, today, e);
    }
  }
Exemple #7
0
  public static void handleException(RestRequest request, RestResponse response, Throwable ex) {

    Throwable rootCause = ExceptionUtils.getRootCause(ex);
    rootCause = rootCause == null ? ex : rootCause;

    logger.error("捕获到Rest异常:request={}", request, rootCause);
    RestError restError = new RestError();
    restError.setErrorCode(2);

    if (ex instanceof RestServiceException) {

      RestServiceException rse = (RestServiceException) ex;

      if (rse.getErrorCode() != 0) {

        restError.setErrorCode(rse.getErrorCode());
      }

      restError.setErrorInfo(rse.getMessage());

    } else {

      restError.setErrorInfo(RestApiConstants.DEFAULT_ERROR_INFO);

      if (request.isDebug()) {

        String stackTrace = ExceptionUtils.getStackTrace(rootCause);
        // 截取有用的部分
        stackTrace = StringUtils.substringBefore(stackTrace, RestApiConstants.STACK_TRACE_BEFORE);
        response.setDebugInfo(stackTrace);
      }

      // 统计响应结果
      recordToErrorCounter(request.getCmd());
    }

    response.setStatusCode(500);
    response.setError(restError);
    response.setResponseTime(new Date());
  }
Exemple #8
0
  public void init() throws MQClientException {
    nameServer = PropertyFileUtil.get("rocketmq.namesrv.domain");

    if (StringUtils.isBlank(nameServer)) {

      logger.warn("【MQ init】property rocketmq.namesrv.domain not found");

      return;
    }

    if ("localTest".equals(nameServer)) {

      logger.warn("【MQ init】localTest");

      return;
    }

    if (StringUtils.isBlank(System.getProperty("rocketmq.namesrv.domain"))) {
      System.setProperty("rocketmq.namesrv.domain", nameServer);
    }
    topicType = getTopic();
    topic = RocketMqUtils.getTopic(topicType);

    if (StringUtils.isBlank(group)) {
      group = "S_" + topic.getTopic() + "_" + topic.getTags();
    }
    consumer = new DefaultMQPushConsumer(group);
    consumer.setNamesrvAddr(nameServer);
    consumer.setMessageModel(getMessageModel());
    consumer.setConsumeThreadMin(minConsumeThread);
    consumer.setConsumeThreadMax(maxConsumeThread);
    // 可以不设置 设置后可以起多个 消费端
    try {
      consumer.setInstanceName("DEFAULT_CONSUMER-" + InetAddress.getLocalHost().getHostName());
    } catch (UnknownHostException e) {
      logger.error("getHostName error", e);
    }
    // 设置订阅的topic 设置订阅过滤表达式
    if (StringUtils.isBlank(subExpression)) {
      subExpression = topic.getTags();
      consumer.subscribe(topic.getTopic(), subExpression);
    } else {
      consumer.subscribe(topic.getTopic(), subExpression);
    }
    try {
      consumer.registerMessageListener(this);
      consumer.start();
    } catch (MQClientException e) {
      logger.error(
          "consumer start error!topic={},subExpression={},group={}",
          topic.getTopic(),
          subExpression,
          group,
          e);
    }
    logger.info(
        "consumer start! topic={},subExpression={},group={}",
        topic.getTopic(),
        subExpression,
        group);
  }