美文网首页
spring-cloud-ribbon及其应用

spring-cloud-ribbon及其应用

作者: 轻舞凋零 | 来源:发表于2022-07-24 11:44 被阅读0次

    1 ribbon提供的功能

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

    常用的模块

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

    2 ribbon的使用

    2.1 原生使用

    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(""));
            }
    
    
        }
    }
    

    配置使用

    @Configuration
    public class RestConfig {
        @Bean
        @LoadBalanced
        public RestTemplate getRestTemplate() {
            return new RestTemplate();
        }
    }
    

    支持自定义拦截器

    MyLoadBalancerInterceptor
    
    实现ClientHttpRequestInterceptor接口
    
    自定义负载均衡实现IRule接口
    
    支持重试
    

    4 源码阅读

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

    相关文章

      网友评论

          本文标题:spring-cloud-ribbon及其应用

          本文链接:https://www.haomeiwen.com/subject/lbklirtx.html