If you use Spring Cloud OpenFeign to make inter-service calls, you will normally add this annotation:

@FeignClient(name = "" ,url = "http://myapp.com",path = "")
Copy the code

You can see that the URL parameter is a string, which is configured to be “dead” in the code.

What if we want to dynamically configure this URL for different environments?

It can go like this:

First modify the annotations

@FeignClient(name = "" ,url = "${feign.client.url.TestUrl}",path = "")
Copy the code

Then add the configuration file, for example

In your application-dev.yml file

feign:
  client:
    url:
      TestUrl: http://dev:dev
Copy the code

In your application-pre-.yml file

feign:
  client:
    url:
      TestUrl: http://pre:pre
Copy the code

Using Spring’s EL expression, we can get urls dynamically based on different file values.

Alternatively, you can specify a default value for this expression

That is, give a default configuration when the configuration file does not have this configuration. In this case, our annotations should be modified to look like this:

@FeignClient(name = "" ,url = "${feign.client.url.TestUrl ? : 'http://myapp.com'}",path = "")
Copy the code

Finally, give an example of my work in a real project

@FeignClient(name = "idGenerateClient", path = "/v1/app/internal/test", url = "#{" + "('${spring.profiles.active}' eq 'local') ? " + "('${feignclient-url." + APPConstant.APPLICATION_NAME + "}' ? : 'http://${env.domain}' ): " + "'http://" + APPConstant.APPLICATION_NAME + "'" + "}", fallbackFactory = XXXClientFallback.class)Copy the code
feignclient-url:
  my-app: '127.0.0.1:8805'
Copy the code

reference

  • Stackoverflow.com/questions/4…

  • Docs. Spring. IO/spring – fram…