2

这是我的控制器类:

@Controller
@RequestMapping("/actuator")
public class HealthController {

    @RequestMapping(value = "/metrics", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON)
    @ResponseBody
    public HealthModel getDump() throws JsonProcessingException {
        return new HealthModel();
        //return mapper.writeValueAsString(metrics.invoke());
    }

    @RequestMapping(value = "/metrics", method = RequestMethod.GET, produces = MediaType.TEXT_PLAIN)
    @ResponseBody
    public String getHealth() {
        return "HEALTHY";
    }
}

模型

public class HealthModel {

    @JsonProperty
    private String status;
    @JsonProperty
    private int id;

    public HealthModel(){
        this.status="WARN";
        this.id=2;
    }

}

注意我已经映射/metrics到返回jsonplain-text取决于Accept Header请求中的

当我在

curl -v -H "Accept: application/json" http://localhost:8080/myapp/actuator/metrics

我在 json 中得到预期的响应 {"status":"WARN","id":2}

但是,当我尝试

curl -v -H "Accept: text/plain" http://localhost:8080/myapp/actuator/metrics

我明白了HTTP/1.1 406 Not Acceptable

编辑

@EnableWebMvc
@Configuration
public class AppMvcConfig extends WebMvcConfigurerAdapter {

   @Resource(name = "appObjectMapper")
    private ObjectMapper appObjectMapper;

    @Resource(name = "modelObjectMapper")
    private ObjectMapper modelObjectMapper;

 @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {

        final MappingJackson2HttpMessageConverter inputConverter = new MappingJackson2HttpMessageConverter();
        inputConverter.setObjectMapper(appObjectMapper);

        final MappingJackson2HttpMessageConverter outputConverter = new MappingJackson2HttpMessageConverter();
        outputConverter.setObjectMapper(modelObjectMapper);

        converters.add(new JacksonDualMapperConverter(appObjectMapper, modelObjectMapper));

        super.configureMessageConverters(converters);
    }

}
4

3 回答 3

6

以防万一有人仍然收到Type mismatch: cannot convert from MediaType to String[]错误:

解决方案是使用MediaType.APPLICATION_JSON_VALUE

代替MediaType.APPLICATION_JSON

问候

于 2017-06-15T19:56:09.480 回答
3

根据文档,@ResponseBody表示返回类型应直接写入 HTTP 响应正文(而不是放在模型中,或解释为视图名称)。所以注释应该在那里。再看一眼,您的产品注释似乎不正确。它应该是produces = MediaType.TEXT_PLAIN_VALUE而不是produces = MediaType.TEXT_PLAIN。我尝试了以下方法,它对我有用:

    @RequestMapping(value = "/metrics", method = RequestMethod.GET, produces = MediaType.TEXT_PLAIN_VALUE)
    @ResponseBody
    public String getHealth() {
        return "HEALTHY";
    }

您可能还必须添加StringHttpMessageConverter

于 2015-09-04T17:19:11.520 回答
3

由于您要添加自定义 MessageConverter configureMessageConverters,因此这会关闭默认转换器注册(请参阅 JavaDoc)。

因此,当内容协商开始时,您只有一个消息转换器(Jackson 那个),它只支持 JSON 媒体类型并且不知道如何处理text/plain.

您应该将StringHttpMessageConverter添加到列表中以支持text/plain.

converters.add(new StringHttpMessageConverter());
于 2015-09-04T18:20:52.710 回答