每天二十分钟spring-cloud的ribbon的使用

2022-07-24 11:41:35 浏览数 (2)

1 ribbon提供的功能

项目地址: https://github.com/Netflix/ribbon

常用的模块

  • ribbon-loadbalancer
  • ribbon-eureka
  • ribbon-transport
  • ribbon-httpclient
  • ribbon-example
  • ribbon-core

2 ribbon的使用

2.1 原生使用

代码语言:java复制
public class NativeRibbon {

    private final ILoadBalancer loadBalancer;
    
    private final RetryHandler retryHandler = new DefaultLoadBalancerRetryHandler(0, 1, true);


    public NativeRibbon(List<Server> serverList) {
        loadBalancer = LoadBalancerBuilder.newBuilder().buildFixedServerListLoadBalancer(serverList);
    }


    /**
     * 获取服务端ip
     *
     * @return String
     */
    public String getServerIp(String path) throws Exception {
        return LoadBalancerCommand.<String>builder().withLoadBalancer(loadBalancer).withRetryHandler(retryHandler).build().submit(
                new ServerOperation<String>() {
                    @Override
                    public rx.Observable<String> call(Server server) {
                        URL url;
                        try {
                            url = new URL("http://"   server.getHost()   ":"   server.getPort()   path);
                            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                            return Observable.just(conn.getResponseMessage());
                        } catch (Exception e) {
                            return Observable.error(e);
                        }
                    }
                }
        ).toBlocking().first();
    }

    public LoadBalancerStats getLoadBalancerStats() {
        return ((BaseLoadBalancer) loadBalancer).getLoadBalancerStats();
    }

    public static void main(String[] args) throws Exception {

        List<Server> serverList = Arrays.asList(new Server("baidu.com", 80), new Server("sina.com.cn", 80));
        NativeRibbon nativeRibbon = new NativeRibbon(serverList);

        for (int times = 0; times < 10; times  ) {
            System.out.println(nativeRibbon.getServerIp(""));
        }


    }
}

配置使用

代码语言:java复制
@Configuration
public class RestConfig {
    @Bean
    @LoadBalanced
    public RestTemplate getRestTemplate() {
        return new RestTemplate();
    }
}

支持自定义拦截器

代码语言:txt复制
MyLoadBalancerInterceptor

实现ClientHttpRequestInterceptor接口

自定义负载均衡实现IRule接口

支持重试

4 源码阅读

ribbon的抽象在core模块,核心在loadbalance

image.pngimage.png
image.pngimage.png

0 人点赞