springcloud学习实战(四)Ribbon

一.Ribbon介绍

Spring Cloud Ribbon是一个基于HTTP和TCP的客户端负载均衡工具,它基于Netflix Ribbon实现。通过Spring Cloud的封装,可以让我们轻松地将面向服务的REST模版请求自动转换成客户端负载均衡的服务调用。Spring Cloud Ribbon虽然只是一个工具类框架,它不像服务注册中心、配置中心、API网关那样需要独立部署,但是它几乎存在于每一个Spring Cloud构建的微服务和基础设施中。因为微服务间的调用,API网关的请求转发等内容,实际上都是通过Ribbon来实现的,包括后续我们将要介绍的Feign,它也是基于Ribbon实现的工具。所以,对Spring Cloud Ribbon的理解和使用,对于我们使用Spring Cloud来构建微服务非常重要。

实现负载均衡的算法。

 		<dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>

这个依赖中包含了Ribbon

下面方法中的@LoadBalanced就是使用Ribbon默认的轮询实现负载均衡

package com.dxf.springcloud.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

/**
 * @author dxf
 * @create 2020-03-27 13:12
 */
@Configuration
public class ApplicationContextConfig {
    /*使用restTemplate访问restful接口非常的简单粗暴,(
    url、requestMap、ResponseBean.class)这三个参数
    分别代表REST请求地址、请求参数、HTTP响应转换被转换成的对象类型。

    //LoadBalanced注解开启RestTemplate负载均衡功能。
    */

    @Bean
    //@LoadBalanced(注释则使用自己写的负载均衡)
    public RestTemplate getRestTemplate(){
        return new RestTemplate();
    }
}

二.替换默认轮询

首先注释 //@LoadBalanced(注释则使用自己写的负载均衡)

package com.dxf.myrule;


import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.RandomRule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author dxf
 * @create 2020-03-28 16:15
 * 不能与主启动类在同一个包下!
 */

@Configuration
public class MySelfRule {

    /**
     * 负载均衡轮询算法 :rest接口第几次请求次数 % 服务器集群总数量 =
     * 实际调用服务器位置下标,每次服务器重启后,rest接口计数从1开始。
     *
     */

    @Bean
    public IRule myRule() {
        //定义为随机
        return new RandomRule();
    }
}

主启动类添加注释:(注册中心服务名,负载均衡方法)

@RibbonClient(name = "CLOUD-PAYMENT-SERVICE", configuration = MySelfRule.class)

三.自定义轮询算法

LoadBalancer接口:

package com.dxf.springcloud.lib;

import org.springframework.cloud.client.ServiceInstance;

import java.util.List;

/**
 * @Author: dxf
 * @Description:
 * @Date: Created in 2020-03-28 17:39
 * @Modified By:
 */
public interface LoadBalancer {
    ServiceInstance instances(List<ServiceInstance> serviceInstances);
}

实现类:

package com.dxf.springcloud.lib;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author: dxf
 * @Description: 自己的轮询算法
 * @Date: Created in 2020-03-28 17:42
 * @Modified By:
 */
@Component
public class MyLB implements LoadBalancer {

    private AtomicInteger atomicInteger = new AtomicInteger(0);

    public final int getAndIncrement() {
        int current;
        int next;

        do {
            current = this.atomicInteger.get();
            next = current >= Integer.MAX_VALUE ? 0 : current + 1;
        } while (!this.atomicInteger.compareAndSet(current, next));
        //第几次访问
        System.out.println("****next: " + next);
        return next;
    }

    //负载均衡轮询算法 :rest接口第几次请求次数 % 服务器集群总数量 =
    // 实际调用服务器位置下标,每次服务器重启后,rest接口计数从1开始。
    @Override
    public ServiceInstance instances(List<ServiceInstance> serviceInstances) {
        int index = getAndIncrement() % serviceInstances.size();
        return serviceInstances.get(index);
    }
}

针对某个服务使用

//使用自己的轮询实现负载均衡
    @GetMapping("/consumer/payment/lb")
    public String getPaymentLB() {
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PROVIDER-SERVICE");
        if (instances == null || instances.size() <= 0) {
            return null;
        }
        ServiceInstance serviceInstance = loadBalance.instances(instances);
        URI uri = serviceInstance.getUri();

        return restTemplate.getForObject(uri + "/payment/lb", String.class);
    }
发布了15 篇原创文章 · 获赞 2 · 访问量 1042

猜你喜欢

转载自blog.csdn.net/weixin_42408648/article/details/105188693