自定义Ribbon负载均衡

/ 0 条评论 / 91人阅读

ribbon默认是轮询式的负载均衡,我们可以自定义为随机式负载均衡

首先编写一个自定义的规则类MyRule

package com.example.microserviceribbon8001.config;

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

@Configuration
public class MySelfRule {

    //ribbon默认是轮询式负载均衡,这里自定义为随机
    @Bean
    public IRule myRule(){
        return new RandomRule();
    }

}

然后,修改启动类

package com.example.microserviceribbon8001;

import com.example.microserviceribbon8001.config.MySelfRule;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.ribbon.RibbonClient;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
@EnableDiscoveryClient
@RibbonClient(name = "microservice-ribbon",configuration = MySelfRule.class)
public class MicroserviceRibbon8001Application {

    public static void main(String[] args) {
        SpringApplication.run(MicroserviceRibbon8001Application.class, args);
    }

    @Bean
    @LoadBalanced
    RestTemplate restTemplate() {
        return new RestTemplate();
    }

}

重点就在@RibbonClient注解上

这一个注解可以在启动时去加载我们自定义的规则类从而使配置生效,name为服务名称,configuration是规则类

效果如下

/upload/article/png/520520_20191001145731.png

/upload/article/png/520520_20191001145743.png

/upload/article/png/520520_20191001145755.png

Responses /