需求描述
有三个服务A、B、C,A和B在一个注册中心,C是一个独立的SpringBoot服务。关系如下
即服务B需要同时通过注册中心访问A,和不通过注册中心访问C。使用RestTemplate
也可以做到,但是这不是我们想要的效果。既然已经集成了feign这个强大的客户端工具,就必须用起来啊。
spring cloud官方文档(http://cloud.spring.io/spring-cloud-netflix/single/spring-cloud-netflix.html#spring-cloud-ribbon-without-eureka)中的这个方法,的前提是你没有使用Eureka。
实现方法
参考资料:http://cloud.spring.io/spring-cloud-netflix/single/spring-cloud-netflix.html#netflix-ribbon-starter
使用官方提供的配置ribbon客户端的方法
@Configuration
@RibbonClient(name = "custom", configuration = CustomConfiguration.class)
public class TestConfiguration {
}
注意下面这段话
The CustomConfiguration clas must be a @Configuration class, but take care that it is not in a @ComponentScan for the main application context.
CustomConfiguration
必须有@Configuration
注解,并且不在@ComponentScan
配置的扫描包中。如果直接使用的@SpringBootApplication
那么不能和应用启动类在同一个包或其下级包下。
先写一个实例
// com.wawscm.cloud.online.Application
@SpringBootApplication(scanBasePackages = "com.wawscm.cloud.online")
@EnableTransactionManagement
@EnableWebMvc
@EnableEurekaClient
@EnableFeignClients
@MapperScan("com.wawscm.cloud.online.mapper")
@RibbonClients({
@RibbonClient(name = "custom", configuration = CustomRibbonClientConfiguration.class)
})
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
加入我们有一个服务地址是:http://localhost:8229,暴露了一个服务是"/hello",参数是name。即访问服务的地址为:http://localhost:8229/hello?name=xxx
// com.wawscm.cloud.ribbon.CustomRibbonClientConfiguration
@Configuration
public class CustomRibbonClientConfiguration{
@Bean
public ILoadBalancer ribbonLoadBalancer() {
BaseLoadBalancer balancer = new BaseLoadBalancer();
balancer.setServersList(Arrays.asList(new Server("localhost", 8229)));
return balancer;
}
}
定义一个Feign客户端。
@FeignClient(name = "custom") // 与上面配置的RibbonClient中的name一致
public interface CustomFeignClient {
@GetMapping("/hello")
String hello(@RequestParam("name") String name)
}
// 使用
@RestController
public class CustomController {
@Autowired
private CustomFeignClient client;
@GetMapping("/sayHi")
public String (String name) {
this.client.hello(name);
}
}
使用上面的方法就可以兼容注册中心服务和非注册中心服务两种模式了。在项目中服务的地址应配置在配置文件中。
RibbonClient的配置参见:http://cloud.spring.io/spring-cloud-netflix/single/spring-cloud-netflix.html#_customizing_the_ribbon_client,上面的例子中只是使用了负载均衡,其实还可以配置负载均衡的规则,客户端参数等。
扫描二维码关注公众号,回复: 5276104 查看本文章