1. 程式人生 > >feign.codec.EncodeException: class ArrayList/HashMap is not a type supported by this encoder

feign.codec.EncodeException: class ArrayList/HashMap is not a type supported by this encoder

Storm中使用Fegin,因為Storm是通過拓撲自己建立和管理Bolt的,所以在Bolt中使用到了某個FeignClient就無法通過@Service,然後通過@Autowired獲取到FeginClient的例項。

使用下面的程式碼來例項化FeginClient,

    /**
     * 初始化SanService的FeginClient
     * @param url
     * @return
     */
    public static SanService initializeSanServiceFegin(String url) {
        SanService service = Feign.builder()
                .contract(new SpringMvcContract())
                .target(SanService.class, url);

        return service;
    }

但會報下面的錯誤異常:

feign.codec.EncodeException: class is not a type supported by this encoder

因為預設的Encoder不支援List或Map,所以報錯。

如果自定義Encoder,則必須要用到Feign 依賴包中其他的類,而且需要通過@Autowired依賴注入其他類,但上面提到了,Storm中無法通過@Autowired依賴注入。

終極解決辦法:

/**
 * 初始化SanService的FeginClient
 * @param url
 * @return
 */
public static SanService initializeSanServiceFegin(String url) {
    HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter(new ObjectMapper());
    ObjectFactory<HttpMessageConverters> converter = ()-> new HttpMessageConverters(jsonConverter);
    SanService service = Feign.builder()
            .encoder(new SpringEncoder(converter))
            .decoder(new SpringDecoder(converter))
            .contract(new SpringMvcContract())
            .target(SanService.class, url);

    return service;
}