Using ribbon and feign without eureka or both

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/jaune161/article/details/83145996

需求描述

有三个服务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,上面的例子中只是使用了负载均衡,其实还可以配置负载均衡的规则,客户端参数等。

猜你喜欢

转载自blog.csdn.net/jaune161/article/details/83145996
今日推荐