How to custom @FeignClient Expander to convert param?

本秂侑毒 提交于 2019-12-20 02:54:59

问题


Feign default expander to convert param:

final class ToStringExpander implements Expander {

    @Override
    public String expand(Object value) {
      return value.toString();
    }
  }

I want custom it to convert user to support GET param, like this

@FeignClient("xx")
interface UserService{

   @RequestMapping(value="/users",method=GET)
   public List<User> findBy(@ModelAttribute User user);
}

userService.findBy(user);

What can i do?


回答1:


First,you must write a expander like ToJsonExpander:

public class ToJsonExpander implements Param.Expander {

  private static ObjectMapper objectMapper = new ObjectMapper();

  public String expand(Object value) {
    try {
      return objectMapper.writeValueAsString(value);
    } catch (JsonProcessingException e) {
      throw new ExpanderException(e);
    }
  }
}

Second, write a AnnotatedParameterProcessor like JsonArgumentParameterProcessor to add expander for your processor.

public class JsonArgumentParameterProcessor implements AnnotatedParameterProcessor {

  private static final Class<JsonArgument> ANNOTATION = JsonArgument.class;

  public Class<? extends Annotation> getAnnotationType() {
    return ANNOTATION;
  }

  public boolean processArgument(AnnotatedParameterContext context, Annotation annotation) {
    MethodMetadata data = context.getMethodMetadata();
    String name = ANNOTATION.cast(annotation).value();
    String method = data.template().method();

    Util.checkState(Util.emptyToNull(name) != null,
        "JsonArgument.value() was empty on parameter %s", context.getParameterIndex());

    context.setParameterName(name);

    if (method != null && (HttpMethod.POST.matches(method) || HttpMethod.PUT.matches(method) || HttpMethod.DELETE.matches(method))) {
      data.formParams().add(name);
    } else {
      `data.indexToExpanderClass().put(context.getParameterIndex(), ToJsonExpander.class);`
      Collection<String> query = context.setTemplateParameter(name, data.template().queries().get(name));
      data.template().query(name, query);
    }

    return true;
  }
}

Third,add it to Feign configuration.

  @Bean
  public Contract feignContract(){
    List<AnnotatedParameterProcessor> processors = new ArrayList<>();
    processors.add(new JsonArgumentParameterProcessor());
    processors.add(new PathVariableParameterProcessor());
    processors.add(new RequestHeaderParameterProcessor());
    processors.add(new RequestParamParameterProcessor());
    return new SpringMvcContract(processors);
  }

Now, you can use @JsonArgument to send model argument like:

public void saveV10(@JsonArgument("session") Session session);



回答2:


I don't know what @ModelAttribute does but I was looking for a way to convert @RequestParam values.

import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.i18n.phonenumbers.Phonenumber;
import org.springframework.cloud.netflix.feign.FeignFormatterRegistrar;
import org.springframework.format.FormatterRegistry;
import org.springframework.stereotype.Component;

import static com.google.i18n.phonenumbers.PhoneNumberUtil.PhoneNumberFormat.E164;

@Component
public class PhoneNumberFeignFormatterRegistrar implements FeignFormatterRegistrar {
    private final PhoneNumberUtil phoneNumberUtil;

    public PhoneNumberFeignFormatterRegistrar(PhoneNumberUtil phoneNumberUtil) {
        this.phoneNumberUtil = phoneNumberUtil;
    }

    @Override
    public void registerFormatters(FormatterRegistry registry) {
        registry.addConverter(Phonenumber.PhoneNumber.class, String.class, source -> phoneNumberUtil.format(source, E164));
    }
}

Now stuff like the following works

import com.google.i18n.phonenumbers.Phonenumber;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.hateoas.Resource;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

@FeignClient("data-service")
public interface DataClient {
    @RequestMapping(method = RequestMethod.GET, value = "/phoneNumbers/search/findByPhoneNumber")
    Resource<PhoneNumberRecord> getPhoneNumber(@RequestParam("phoneNumber") Phonenumber.PhoneNumber phoneNumber);
}



回答3:


As the open feign issue and spring doc say:

The OpenFeign @QueryMap annotation provides support for POJOs to be used as GET parameter maps.

Spring Cloud OpenFeign provides an equivalent @SpringQueryMap annotation, which is used to annotate a POJO or Map parameter as a query parameter map since 2.1.0.

You can use it like this:

    @GetMapping("user")
    String getUser(@SpringQueryMap User user);
public class User {
    private String name;
    private int age;
    ...
}


来源:https://stackoverflow.com/questions/35621062/how-to-custom-feignclient-expander-to-convert-param

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!