programing

스프링 부트 액추에이터 엔드포인트의 응답 MIME 유형

lastcode 2023. 2. 9. 21:57
반응형

스프링 부트 액추에이터 엔드포인트의 응답 MIME 유형

Spring Boot 어플리케이션을 1.4.x에서 1.5.1로 업데이트하면 Spring Actuator 엔드포인트는 다른 MIME 유형을 반환합니다.

예를들면,/health지금이다application/vnd.spring-boot.actuator.v1+json그 대신 간단하게application/json.

어떻게 하면 다시 바꿀 수 있나요?

엔드포인트는 클라이언트의 요청을 수락할 수 있다고 하는 내용을 지원하는 콘텐츠유형을 반환합니다.당신은 그것을 얻을 것입니다.application/json클라이언트에 의한 응답Accept다음을 요구하는 헤더:

Accept: application/json

https://stackoverflow.com/users/2952093/kap의 코멘트에 대한 대응(코멘트를 작성하기에는 평판이 낮습니다): Firefox를 사용하여 JSON을 반환하는 엔드포인트를 확인할 때는 Add-on JSONView를 사용합니다.설정에서 대체 JSON 콘텐츠 유형을 지정하는 옵션이 있습니다.application/vnd.spring-boot.actuator.v1+json반환된 JSON이 브라우저 안에 예쁜 글씨로 표시됩니다.

1.5.x에서는 액튜에이터의 콘텐츠 타입이 변경되었습니다.

"Accept:" 헤더에 "application/json"을 입력하면 일반적인 content-type을 얻을 수 있습니다.

그러나 클라이언트를 수정할 방법이 없는 경우 이 스니펫은 상태(상세 없음)와 원본 컨텐츠 유형(1.4.x 방법)을 반환합니다.

@RestController
@RequestMapping(value = "/health", produces = MediaType.APPLICATION_JSON_VALUE)
public class HealthController {

    @Inject
    HealthEndpoint healthEndpoint;
    @RequestMapping(method = RequestMethod.GET)
    public ResponseEntity<Health > health() throws IOException {
        Health health = healthEndpoint.health();
        Health nonSensitiveHealthResult = Health.status(health.getStatus()).build();
        if (health.getStatus().equals(Status.UP)) {
            return ResponseEntity.status(HttpStatus.OK).body(nonSensitiveHealthResult);
        } else {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(nonSensitiveHealthResult);
        }
    }
}

구성(기존 상태 제거)

endpoints.health.path: internal/health

https://github.com/spring-projects/spring-boot/issues/2449의 코드(동작하지만 새로운 타입은 완전히 삭제)에 근거해 생각해 낸 것입니다.

@Component
public class ActuatorCustomizer implements EndpointHandlerMappingCustomizer {

    static class Fix extends HandlerInterceptorAdapter {


        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
                throws Exception {
            Object attribute = request.getAttribute(HandlerMapping.PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE);
            if (attribute instanceof LinkedHashSet) {
                @SuppressWarnings("unchecked")
                LinkedHashSet<MediaType> lhs = (LinkedHashSet<MediaType>) attribute;
                if (lhs.remove(ActuatorMediaTypes.APPLICATION_ACTUATOR_V1_JSON)) {
                    lhs.add(ActuatorMediaTypes.APPLICATION_ACTUATOR_V1_JSON);
                }
            }
            return true;
        }

    }

    @Override
    public void customize(EndpointHandlerMapping mapping) {
        mapping.setInterceptors(new Object[] {new Fix()});
    }
}

새로운 벤더 미디어 타입을 마지막에 배치하여application/json모든 액튜에이터 엔드포인트(지정되어 있지 않은 경우)에 적용됩니다.

스프링 부트 1.5.3으로 테스트 완료

SpringBoot 2.0.x 이후 권장되는 솔루션은EndpointHandlerMappingCustomizer더 이상 작동하지 않습니다.

좋은 소식은 이제 해결 방법이 더 간단해졌다는 것입니다.

더 빈EndpointMediaTypes를 제공해야 합니다.SpringBoot 클래스에서 제공됩니다.WebEndpointAutoConfiguration디폴트입니다.

자신의 것을 제공하는 방법은 다음과 같습니다.

@Configuration
public class ActuatorEndpointConfig {

    private static final List<String> MEDIA_TYPES = Arrays
        .asList("application/json", ActuatorMediaType.V2_JSON);

    @Bean
    public EndpointMediaTypes endpointMediaTypes() {
        return new EndpointMediaTypes(MEDIA_TYPES, MEDIA_TYPES);
    }
}

서포트하다application/vnd.spring-boot.actuator.v1+jsonFirefox의 내장 JSON 뷰어에 json-content-type-override라는 애드온을 설치할 수 있습니다."json"을 포함하는 콘텐츠 유형을 "application/json"으로 변환합니다.

업데이트: Firefox 58+는 이러한 MIME 유형을 기본적으로 지원하므로 추가 기능은 더 이상 필요하지 않습니다.https://bugzilla.mozilla.org/show_bug.cgi?id=1388335 를 참조해 주세요.

언급URL : https://stackoverflow.com/questions/42343314/response-mime-type-for-spring-boot-actuator-endpoints

반응형