use*_*148 5 spring-boot spring-cloud-feign feign netflix-ribbon spring-cloud-netflix
我定义了一个 REST 接口,它具有不同的 Spring Boot 应用程序实现,使用不同的实现spring.application.name(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");
}
}
Run Code Online (Sandbox Code Playgroud)
另一个 SpringBootApplication C:
@FeignClient(name="SpringApplication A or B")
public interface FeignClientService {
@RequestMapping(path = "/feign")
public String feign();
}
Run Code Online (Sandbox Code Playgroud)
在SpringBootApplication C中,我想使用FeignClientService来访问A和B。你有什么想法吗?
是的,您可以创建一个 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();
}
}
Run Code Online (Sandbox Code Playgroud)
调整调用接口以满足您的要求,然后您可以将DynamicFeignClient实例注入并使用到需要使用它的 bean 中。
几个月来,我们一直在生产中使用这种方法来询问数十种不同的服务,以获取版本信息和其他有用的运行时执行器数据等内容。
| 归档时间: |
|
| 查看次数: |
6811 次 |
| 最近记录: |