Медленное время отклика на плохие запросы (исключения из службы) при начальной загрузке с zuul - PullRequest
2 голосов
/ 03 апреля 2020

У меня развернуты загрузочные микро-сервисы с zuul gateway и Eureka, которые работают нормально, но я замечаю, что когда запрос отправляет неверный запрос, который фактически выдает исключение из класса обслуживания (неверный идентификатор пользователя / клиента) соответствующего Ответ об ошибке занял более 2 секунд. Сценарий успеха ios работает нормально с приемлемым временем отклика. Как вы можете видеть в журнале ниже, ОШИБКА заняла больше времени. Эти сервисы размещены в AWS, но они прекрасно работали в локальной среде без интеграции с zuul.

2020-04-03 04:14:38.102 DEBUG 14156 --- [nio-8084-exec-9] c.t.book.filter.AuthorizationFilter  : Auth UserId in filter: uid-b7e9d6f7-f5bf-4e74-9ac1-1d1120ceb43f
2020-04-03 04:14:38.103 DEBUG 14156 --- [nio-8084-exec-9] c.t.t.controller.TransactionController   : Create transaction inputs: {"bookId":"bid-1","customerId":"cid-8","transactionType":"credit","amount":5000.0,"note":"date validation test","dueDate":1585026193934,"imageUrl":"http://123.com","customerBookType":null,"requiredAvailable":true}, timeZone: Asia/Colombo
2020-04-03 04:14:39.884 ERROR 14156 --- [nio-8084-exec-9] c.t.t.controller.TransactionController   : Invalid customer id for the transaction: {"bookId":"bid-1","","transactionType":"credit","amount":5000.0,"note":"date validation test","dueDate":1585026193934,"imageUrl":"http://123.com","customerBookType":null,"requiredAvailable":true}

com.book.exception.InvalidUserException: Invalid customer id

Также я попытался отправить запрос напрямую, минуя zuul, но и здесь я получаю задержку. Пожалуйста, посмотрите на это, если вам нужна дополнительная информация, дайте мне знать.

Обновлено

Я замечаю, что это происходит с перерывами, как первый звонок и второй вызов занимает более 2 секунд, затем следующие 4-5 запросов занимают обычное время, затем снова один запрос занимает больше времени. Но в местной среде такого поведения нет. (Как я упоминал ранее, это происходит только для ошибки ERROR ios)

Код

Класс обслуживания

public Customer updateCustomer(CustomerUpdateRequestDto customerUpdateRequestDto) {
        try {
            String customerId = customerUpdateRequestDto.getCustomerId().trim();
            Optional<Customer> customerOptional = customerRepository
                    .findById(customerId);
            if (customerOptional.isPresent()) {
                Customer customer = customerOptional.get();
                customer.setDisplayName(customerUpdateRequestDto.getName().trim());
                customer.setImageUrl(customerUpdateRequestDto.getImageUrl() == null ?
                        null : customerUpdateRequestDto.getImageUrl().trim());
                customer.setMobileNo(customerUpdateRequestDto.getMobileNo().getDisplayNumber());
                customer.setUpdatedAt(new Date());
                customerRepository.save(customer);
                return customer;
            } else {
                throw new InvalidUserException(INVALID_CUSTOMER_ID);
            }
        } catch (DataAccessException e) {
            throw new BookException(FAILED_UPDATE_CUSTOMER, e);
        }

    }

Вызов метода из контроллера

    private ResponseEntity<ResponseWrapper> updateCustomerIfValid(CustomerUpdateRequestDto customerUpdateRequestDto) {
        try {
            Customer customer = customerService.updateCustomer(customerUpdateRequestDto);
            CustomerResponseDto customerResponseDto = new CustomerResponseDto(customer);
            log.debug("Updating customer: {} was successful", customerResponseDto.toLogJson());
            ResponseWrapper responseWrapper =
                    new ResponseWrapper(ResponseStatusType.SUCCESS, SUCCESS_MESSAGE_UPDATE, customerResponseDto);
            return new ResponseEntity<>(responseWrapper, HttpStatus.OK);
        } catch (InvalidUserException e) {
            log.error("Updating customer was failed for customer: {}", customerUpdateRequestDto.toLogJson(), e);
            return getBadRequestError(ErrorResponseStatusType.INVALID_CUSTOMER_ID);
        }
    }

    protected ResponseEntity<ResponseWrapper> getBadRequestError(ErrorResponseStatusType errorResponseStatusType) {
        ResponseWrapper responseWrapper =
                new ErrorResponseWrapper(errorResponseStatusType, null);
        return new ResponseEntity<>(responseWrapper, HttpStatus.BAD_REQUEST);
    }

Спасибо

1 Ответ

1 голос
/ 03 апреля 2020

Я идентифицировал проблему, расширение вышеупомянутого микро-сервиса было .war, и я не заметил этого, после преобразования его в банку, задержка больше не была их. В любом случае нужно проверить, почему это произошло для расширения .war.

...