我已经定义了一个REST接口,它使用不同的spring.application.name
具有不同的Spring Boot Application实现(spring.application.name
在我的业务中不能相同)。
我怎样才能定义Feign Client,并且可以访问所有SpringBootApplication REST服务?
SpringBootApplication A(spring.application.name = A)和B(spring.application.name =)有这个RestService:
@RestController
@RequestMapping(value = "/${spring.application.name}")
public class FeignRestService {
@Autowired
Environment env;
@RequestMapping(path = "/feign")
public String feign() {
return env.getProperty("server.port");
}
}
另一个SpringBootApplication C:
@FeignClient(name="SpringApplication A or B")
public interface FeignClientService {
@RequestMapping(path = "/feign")
public String feign();
}
在SpringBootApplication C中,我想使用FeignClientService来访问A和B.你有什么想法吗?
您可能已经想到了这一点,但这可能有助于任何正在寻找相同问题答案的人。您需要为使用这些服务的每个服务客户端配置Feign Client。
由于Feign客户端与您定义的服务绑定,因此无法使用相同的Feign客户端来调用不同的服务。
是的,您可以创建一个Feign客户端,并根据需要重复使用它,以便在Eureka目录中使用spring-cloud-netflix标记问题的多个命名服务。以下是您如何执行此操作的示例:
@Component
public class DynamicFeignClient {
interface MyCall {
@RequestMapping(value = "/rest-service", method = GET)
void callService();
}
FeignClientBuilder feignClientBuilder;
public DynamicFeignClient(@Autowired ApplicationContext appContext) {
this.feignClientBuilder = new FeignClientBuilder(appContext);
}
/*
* Dynamically call a service registered in the directory.
*/
public void doCall(String serviceId) {
// create a feign client
MyCall fc =
this.feignClientBuilder.forType(MyCall.class, serviceId).build();
// make the call
fc.callService();
}
}
调整调用接口以满足您的要求,然后您可以在需要使用它的bean中注入并使用DynamicFeignClient
实例。
我们几个月来一直在生产中使用这种方法来查询许多不同的服务,例如版本信息和其他有用的运行时执行器数据。