ribbon客户端负载均衡

一、三种配置方式 集成eureka、注解、配置文件

1、集成erueka

在application.yml中配置(其实会默认配置好,但是最好显示配置出来)

ribbon:
  # 开启eureka与ribbon的集成
  eureka:
    enabled: true

2、注解

在启动类中添加注解

// 通过注解的方式定义了一个针对service-by-annotation服务的负载均衡器(service-by-annotation是服务的名称也是负载均衡器的名称)
@RibbonClients(value = {
        @RibbonClient(name = "service-by-annotation", configuration = ServiceByAnnontationConfiguration.class) })
@SpringBootApplication
@EnableFeignClients
// 通过注解的方式定义了一个针对service-by-annotation服务的负载均衡器(service-by-annotation是服务的名称也是负载均衡器的名称)
@RibbonClients(value = {
        @RibbonClient(name = "service-by-annotation", configuration = ServiceByAnnontationConfiguration.class) })
public class RibbonSampleApplication {

    public static void main(String[] args) {
        new SpringApplicationBuilder(RibbonSampleApplication.class).web(true).run(args);
    }

    // 这里定义 可以覆盖所有的
    // @Bean
    // public IRule ribbonRule() {
    // return new RandomRule();
    // }

}

ServiceByAnnontationConfiguration:

package com.dongnaoedu.springcloud.examples.javaconfig;

import org.springframework.cloud.netflix.ribbon.StaticServerList;
import org.springframework.context.annotation.Bean;

import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.RoundRobinRule;
import com.netflix.loadbalancer.Server;
import com.netflix.loadbalancer.ServerList;

// 注解的方式,对应RibbonSampleApplication中@RibbonClients
public class ServiceByAnnontationConfiguration {
    // 实例源
    @Bean
    public ServerList<Server> ribbonServerList() {
        // 实例列表
        String listOfServers = "http://www.csdn.net,http://www.baidu.com,http://www.dongnaoedu.com";
        String[] splits = listOfServers.split(",");
        int len = splits.length;
        if (len == 0) {
            return new StaticServerList<Server>();
        }

        Server[] servers = new Server[len];
        for (int i = 0; i < len; i++) {
            servers[i] = new Server(splits[i].trim());
        }
        // 返回这个...静态的
        return new StaticServerList<Server>(servers);
    }

    // 负载策略
    @Bean
    public IRule iniRule() {
        // 轮询
         return new RoundRobinRule();

        // 随机
//      return new RandomRule();
    }

}

3、配置文件

在application.yml文件中配置

# 定义一个针对service-by-properties服务的负载均衡器。服务实例信息来自配置文件
# 服务名
service-by-properties:
  # 服务实例列表
  listOfServers: http://www.csdn.net,http://www.baidu.com,http://www.dongnaoedu.com
  ribbon:
    # 负载策略
    NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RoundRobinRule
    # 设置它的服务实例信息来自配置文件, 如果不设置NIWSServerListClassName就会去euereka里面找
    NIWSServerListClassName: com.netflix.loadbalancer.ConfigurationBasedServerList

二、三种使用方式 feign,LoadBalancerClient,resttemplate

1、LoadBalancerClient的方式

package com.dongnaoedu.springcloud.examples.way;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

// LoadBalancerClient的方式
@RestController
@RequestMapping("/loadbalance")
public class TestLoadBalancerClientController {
    static Logger logger = LoggerFactory.getLogger(TestLoadBalancerClientController.class);
    @Autowired
    LoadBalancerClient loadbalancerClient; // spring cloud 封装的 关于负载均衡组件 ribbon的工具类

    //下面三个方法对应三种配置方式

    // properties
    @RequestMapping("/properties")
    public void properties() {
        ServiceInstance serviceInstance = loadbalancerClient.choose("service-by-properties");
        logger.warn("TestLoadBalancerClientController.properties执行结果:{}", serviceInstance.getUri());
    }

    // annotation
    @RequestMapping("/annotation")
    public void annotation() {
        ServiceInstance serviceInstance = loadbalancerClient.choose("service-by-annotation");
        logger.warn("TestLoadBalancerClientController.annotation执行结果:{}", serviceInstance.getUri());
    }

    // eureka
    @RequestMapping("/eureka")
    public void eureka() {
        ServiceInstance serviceInstance = loadbalancerClient.choose("lession-4-sms-interface");
        logger.warn("TestLoadBalancerClientController.eureka执行结果:{}", serviceInstance.getUri());
    }
}

2、resttemplate的方式

/**
 * 
 */
package com.dongnaoedu.springcloud.examples.way;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

// resttemplate的方式
@RestController
@RequestMapping("/resttemplate")
@Configuration
public class TestResttemplateController {
    static Logger logger = LoggerFactory.getLogger(TestResttemplateController.class);

    @Bean
    @LoadBalanced // 这个注解一定要加,不然LoadBalancerAutoConfiguration不会对它进行处理
    RestTemplate RestTemplate() {
        // ribbon feign是一个公司开源,很好的集成
        // resttemplate是spring的
        // 这是为了设置超时
        SimpleClientHttpRequestFactory simpleClientHttpRequestFactory = new SimpleClientHttpRequestFactory();
        simpleClientHttpRequestFactory.setReadTimeout(2000);
        simpleClientHttpRequestFactory.setConnectTimeout(2000);
        return new RestTemplate(simpleClientHttpRequestFactory);
    }

    @Autowired
    RestTemplate restTemplate; // spring内置,封装了http请求的工具类
    //下面对应三种配置方式
    // properties
    @RequestMapping("/properties")
    public void properties() {
        // http://127.0.0.1:8080/sss
        // service-by-properties 通过名称 找到负载均衡器,负载均衡器会选择一个具体的实例
        String body = restTemplate.getForObject("http://service-by-properties/", String.class);
        testprint(body);// 仅仅是为了根据输出内容来判断是调用的哪个接口
    }

    // annotation
    @RequestMapping("/annotation")
    public void annotation() {
        String body = restTemplate.getForObject("http://service-by-annotation/", String.class);
        testprint(body);// 仅仅是为了根据输出内容来判断是调用的哪个接口
    }

    // eureka
    @RequestMapping("/eureka")
    public void eureka() {
        String body = restTemplate.getForObject("http://lession-4-sms-interface/sms", String.class);
        logger.warn("TestResttemplateController.eureka执行结果:{}", body);
    }

    // 仅仅是为了根据输出内容来判断是调用的哪个接口
    private void testprint(String body) {
        if (body.contains("dongnaoedu")) {
            logger.warn("根据负载均衡策略,选择实例:dongnaoedu.com");
        } else if (body.contains("csdn")) {
            logger.warn("根据负载均衡策略,选择实例:csdn.net");
        } else if (body.contains("baidu")) {
            logger.warn("根据负载均衡策略,选择实例:baidu.com");
        } else {
            logger.warn("火星....");
        }
    }

}

3、feign的方式

package com.dongnaoedu.springcloud.examples.way;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

// Feign的方式
@RestController
@RequestMapping("/feign")
public class TestFeignController {
    static Logger logger = LoggerFactory.getLogger(TestFeignController.class);
    // properties
    @Autowired
    FeignPropertiesClient feignPropertiesClient;

    @RequestMapping("/properties")
    public void properties() {
        String body = feignPropertiesClient.index();
        testprint(body);// 仅仅是为了根据输出内容来判断是调用的哪个接口
    }

    // annotation
    @Autowired
    FeignAnnotationClient feignAnnotationClient;

    @RequestMapping("/annotation")
    public void annotation() {
        String body = feignAnnotationClient.index();
        testprint(body);// 仅仅是为了根据输出内容来判断是调用的哪个接口
    }

    // eureka
    @Autowired
    FeignEurekaClient feignEurekaClient;

    @RequestMapping("/eureka")
    public void eureka() {
        String body = feignEurekaClient.index();
        logger.warn("TestFeignController.eureka执行结果:{}", body);
    }

    // 仅仅是为了根据输出内容来判断是调用的哪个接口
    private void testprint(String body) {
        if (body.contains("dongnaoedu")) {
            logger.warn("根据负载均衡策略,选择实例:dongnaoedu.com");
        } else if (body.contains("csdn")) {
            logger.warn("根据负载均衡策略,选择实例:csdn.net");
        } else if (body.contains("baidu")) {
            logger.warn("根据负载均衡策略,选择实例:baidu.com");
        } else {
            logger.warn("火星....");
        }
    }
}

@FeignClient(name = "service-by-properties")
interface FeignPropertiesClient {
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String index();
}

@FeignClient(name = "service-by-annotation")
interface FeignAnnotationClient {
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String index();
}

@FeignClient(name = "lession-4-sms-interface")
interface FeignEurekaClient {
    @RequestMapping(value = "/timeout/test", method = RequestMethod.GET)
    public String index();

}

补充:
1、eureka配置方式设置超时

ribbon:
  # 开启eureka与ribbon的集成
  eureka:
    enabled: true
  # 暂不开启熔断机制
  hystrix: 
    enabled: false
  # 配置ribbon默认的超时时间
  ConnectTimeout: 2000
  ReadTimeout: 2000
  # 是否开启重试
  OkToRetryOnAllOperations: true
  # 重试期间,实例切换次数  比如:100个实例,我只会在四个实例上面去重试
  MaxAutoRetriesNextServer: 3
  # 当前实例重试次数
  MaxAutoRetries: 2

2、resttemplate配置方式设置超时

@Bean
    @LoadBalanced // 这个注解一定要加,不然LoadBalancerAutoConfiguration不会对它进行处理
    RestTemplate RestTemplate() {
        // ribbon feign是一个公司开源,很好的集成
        // resttemplate是spring的
        // 这是为了设置超时
        SimpleClientHttpRequestFactory simpleClientHttpRequestFactory = new SimpleClientHttpRequestFactory();
        simpleClientHttpRequestFactory.setReadTimeout(2000);
        simpleClientHttpRequestFactory.setConnectTimeout(2000);
        return new RestTemplate(simpleClientHttpRequestFactory);
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值