How can I change the feign URL during the runtime?

liucyu picture liucyu · May 2, 2017 · Viewed 25.3k times · Source

@FeignClient(name = "test", url="http://xxxx")

How can I change the feign URL (url="http://xxxx") during the runtime? because the URL can only be determined at run time.

Answer

Sandip Nirmal picture Sandip Nirmal · Jul 18, 2018

Feign has a way to provide the dynamic URLs and endpoints at runtime.

The following steps have to be followed:

  1. In the FeignClient interface we have to remove the URL parameter. We have to use @RequestLine annotation to mention the REST method (GET, PUT, POST, etc.):
@FeignClient(name="customerProfileAdapter")
public interface CustomerProfileAdaptor {

    // @RequestMapping(method=RequestMethod.GET, value="/get_all")
    @RequestLine("GET")
    public List<Customer> getAllCustomers(URI baseUri); 

    // @RequestMapping(method=RequestMethod.POST, value="/add")
    @RequestLine("POST")
    public ResponseEntity<CustomerProfileResponse> addCustomer(URI baseUri, Customer customer);

    @RequestLine("DELETE")
    public ResponseEntity<CustomerProfileResponse> deleteCustomer(URI baseUri, String mobile);
}
  1. In RestController you have to import FeignClientConfiguration
  2. You have to write one RestController constructor with encoder and decoder as parameters.
  3. You need to build the FeignClient with the encoder, decoder.
  4. While calling the FeignClient methods, provide the URI (BaserUrl + endpoint) along with rest call parameters if any.
@RestController
@Import(FeignClientsConfiguration.class)
public class FeignDemoController {

    CustomerProfileAdaptor customerProfileAdaptor;

    @Autowired
    public FeignDemoController(Decoder decoder, Encoder encoder) {
        customerProfileAdaptor = Feign.builder().encoder(encoder).decoder(decoder) 
           .target(Target.EmptyTarget.create(CustomerProfileAdaptor.class));
    }

    @RequestMapping(value = "/get_all", method = RequestMethod.GET)
    public List<Customer> getAllCustomers() throws URISyntaxException {
        return customerProfileAdaptor
            .getAllCustomers(new URI("http://localhost:8090/customer-profile/get_all"));
    }

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public ResponseEntity<CustomerProfileResponse> addCustomer(@RequestBody Customer customer) 
            throws URISyntaxException {
        return customerProfileAdaptor
            .addCustomer(new URI("http://localhost:8090/customer-profile/add"), customer);
    }

    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public ResponseEntity<CustomerProfileResponse> deleteCustomer(@RequestBody String mobile)
            throws URISyntaxException {
        return customerProfileAdaptor
            .deleteCustomer(new URI("http://localhost:8090/customer-profile/delete"), mobile);
    }
}