本篇适用于springcloud2020版本,2020版本之前是有Ribbon的,但是2020版本之后Springcloud把Ribbon移除了,用LoadBalancer替代了。

2020版本之前的Ribbon传送门:(23条消息) 更改Ribbon负载均衡配置规则_zuodingquan666的博客-CSDN博客

1.新建配置类

package com.myrule;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.loadbalancer.core.RandomLoadBalancer;
import org.springframework.cloud.loadbalancer.core.ReactorLoadBalancer;
import org.springframework.cloud.loadbalancer.core.ServiceInstanceListSupplier;
import org.springframework.cloud.loadbalancer.support.LoadBalancerClientFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;


public class CustomLoadBalancerConfiguration {

    @Bean
    ReactorLoadBalancer<ServiceInstance> randomLoadBalancer(Environment environment,
                                                            LoadBalancerClientFactory loadBalancerClientFactory){
        String name = environment.getProperty(LoadBalancerClientFactory.PROPERTY_NAME);
        return new RandomLoadBalancer(loadBalancerClientFactory
                .getLazyProvider(name,ServiceInstanceListSupplier.class),name);
    }
}

2.restTemplate配置

package com.cloud.config;

import com.myrule.CustomLoadBalancerConfiguration;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.loadbalancer.annotation.LoadBalancerClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;


@Configuration
@LoadBalancerClient(name = "CLOUD-PROVIDER-PAYMENT",configuration = CustomLoadBalancerConfiguration.class)
public class ApplicationContextConfig {

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

主要实现代码:

@LoadBalancerClient(name = "CLOUD-PROVIDER-PAYMENT",configuration = CustomLoadBalancerConfiguration.class)

name里面的是:服务名

configuration:里面就是我们刚刚配置的文件名

启动项目:

 运行成功

其实loadbalancer和ribbon两者之间的区别并不大,只是在写法方面有不同而已。

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐