spring cloud ribbon

优质
小牛编辑
133浏览
2023-12-01

简介

ribbon用以实现负载均衡;实现软负载均衡,核心有三点:

  • 服务发现,发现依赖服务的列表
  • 服务选择规则,在多个服务中如何选择一个有效服务
  • 服务监听,检测失效的服务,高效剔除失效服务

netflix ribbon

一个简单的demo

配置文件:


# Max number of retries on the same server (excluding the first try)
sample-client.ribbon.MaxAutoRetries=1

# Max number of next servers to retry (excluding the first server)
sample-client.ribbon.MaxAutoRetriesNextServer=1

# Whether all operations can be retried for this client
sample-client.ribbon.OkToRetryOnAllOperations=true

# Interval to refresh the server list from the source
sample-client.ribbon.ServerListRefreshInterval=2000

# Connect timeout used by Apache HttpClient
sample-client.ribbon.ConnectTimeout=3000

# Read timeout used by Apache HttpClient
sample-client.ribbon.ReadTimeout=3000

# Initial list of servers, can be changed via Archaius dynamic property at runtime
sample-client.ribbon.listOfServers=www.u51.xin:80,www.baidu.com:80,www.163.com:80,www.csdn.net:80

配置格式为 clientName.spaceName.params 核心配置sample-client.ribbon.listOfServers 表明有效的服务列表

BasicTest.java

package com.lkl.springcloud.ribbon;

import com.netflix.client.ClientFactory;
import com.netflix.client.http.HttpRequest;
import com.netflix.client.http.HttpResponse;
import com.netflix.config.ConfigurationManager;
import com.netflix.loadbalancer.ZoneAwareLoadBalancer;
import com.netflix.niws.client.http.RestClient;

import java.net.URI;

/**
 * Created by liaokailin on 16/5/6.
 */
public class BasicTest {

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

        ConfigurationManager.loadPropertiesFromResources("sample-client.properties"); // 1
        System.out.println(ConfigurationManager.getConfigInstance().getProperty("sample-client.ribbon.listOfServers"));
        RestClient client = (RestClient) ClientFactory.getNamedClient("sample-client"); // 2
        HttpRequest request = HttpRequest.newBuilder().uri(new URI("/")).build(); // 3
        for (int i = 0; i < 20; i++) {
            HttpResponse response = client.executeWithLoadBalancer(request); // 4
            System.out.println("Status code for " + response.getRequestedURI() + "  :" + response.getStatus());
        }
        ZoneAwareLoadBalancer lb = (ZoneAwareLoadBalancer) client.getLoadBalancer();
        System.out.println(lb.getLoadBalancerStats());
        ConfigurationManager.getConfigInstance().setProperty("sample-client.ribbon.listOfServers",
                "www.qq.com:80,www.u51.xin"); // 5
        System.out.println("changing servers ...");
        Thread.sleep(3000); 
        for (int i = 0; i < 20; i++) {
            HttpResponse response = client.executeWithLoadBalancer(request);
            System.out.println("Status code for " + response.getRequestedURI() + "  : " + response.getStatus());
        }
        System.out.println(lb.getLoadBalancerStats()); // 6

    }
}
  • 1.通过archaius加载配置文件
  • 2.通过ClientFactory获取指定名称client,在该方法中就获取了loadBalancer
  • 3.构建请求
  • 4.执行loadBalancer,会发现调用的服务会在listOfServers列表中的数据切换
  • 5.修改可用服务列表
  • 6.获取loadBalancer状态

ribbon核心组件有三个

  • Rule - 从服务列表中如何获取一个有效服务
  • Ping - 后台运行线程用来判断服务是否可用
  • ServerList - 服务列表

spring cloud ribbon

archaius默认加载配置config.properties

ribbon配置信息

config.properties

myclient.ribbon.listOfServers=www.u51.xin:80,www.baidu.com:80,www.163.com:80,www.csdn.net:80

application.properties 配置client名称

ribbon.client.name=myclient

对应java类

package com.lkl.springcloud.ribbon;

import com.netflix.loadbalancer.Server;
import com.netflix.loadbalancer.ServerList;
import com.netflix.loadbalancer.ZoneAwareLoadBalancer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.cloud.netflix.ribbon.RibbonClients;
import org.springframework.cloud.netflix.ribbon.SpringClientFactory;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * Created by liaokailin on 16/5/6.
 */
@SpringBootApplication
@RibbonClients
@RestController
public class RibbonDefaultConfigApplication {
    @Autowired
    private SpringClientFactory clientFactory;

    @RequestMapping("/")
    public void getServerList() throws Exception {
        ZoneAwareLoadBalancer<Server> lb = (ZoneAwareLoadBalancer<Server>) clientFactory.getLoadBalancer("myclient");
        ServerList<Server> serverList = lb.getServerListImpl();


        List<Server> serverDetailList = serverList.getInitialListOfServers();
        if (!CollectionUtils.isEmpty(serverDetailList)) {
            for (Server s : serverDetailList) {
                System.out.println(s.getHost() + "," + s.getPort());
            }
        } else {
            System.out.println("no service");
        }


    }

    public static void main(String[] args) {
        SpringApplication app = new SpringApplicationBuilder(RibbonDefaultConfigApplication.class).build();
        app.run(args);
    }

}

使用@RibbonClients注解

getServerList方法中,首先获取ZoneAwareLoadBalancer,然后获取serverList,获取到serverList以后即可选择一个有效服务进行调用。

如果需要修改配置信息,可以通过@RibbonClients中的defaultConfiguration配置,例如:

@RibbonClients(defaultConfiguration=MyDefaultRibbonConfig.class) 其中MyDefaultRibbonConfig.class可以参考RibbonClientConfiguration.java