龙哥网

龙哥网

spring cloud 集成 ribbon负载均衡的实例代码_java
2022-03-01

本文比较简单集成ribbon,如需要更详细,请查看我的更多博客内容。

首先创建两个服务提供者

服务一,集成的nacos注册中心,这块随便写一个同名接口

端口配置8301

服务二,同名接口内容修改,其他跟上一个服务一大体内容一致

端口配置成8302

创建服务消费者

RibbonConfig.java

package com.example.nacosribbonconsumers.config;

import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.RoundRobinRule;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.ribbon.RibbonClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

@Configuration
// 如果多个服务可以选择不同的策略
/*@RibbonClients({
        @RibbonClient(name = "other",configuration = OtherConfig.class),
        @RibbonClient(name = "provider",configuration = ProviderConfig.class)
})*/
@RibbonClient(name = "nacos-ribbon-provider")
public class RibbonConfig {

    //定义负载均衡规则
    @Bean
    public IRule ribbonRule(){
        return new RoundRobinRule();

        /**
         * RoundRobinRule:
         *  轮询规则
         *
         * RandomRule:
         *  随机规则
         *
         * WeightedResponseTimeRule:
         *  使用响应时间的平均或者百分比为每个服务分配权重的规则,如果没法收集响应时间信息,会默认使用轮询规则
         *
         * BestAvailableRule:
         *  会先根据断路器过滤掉处于故障的服务,然后选择并发量最小的服务
         *
         * ZoneAvoidanceRule:
         *  根据server所在Zone和其性能,选择服务器,默认规则
         *
         * AvailabilityFilteringRule:
         *  先根据断路器规则过滤掉有问题的服务,然后对剩余的服务按照轮询的策略进行访问
         *
         * RetryRule:
         *  先按照RoundRobinRule规则进行服务获取,如果调用服务失败会在指定时间内进行重试,直到获取到可用的服务。
         */
    }

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

}

RibbonTest.java

package com.example.nacosribbonconsumers.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
public class RibbonTest {

    @Autowired
    private RestTemplate restTemplate;

    @GetMapping(value = "/ribbon-consumers/ribbon-test")
    public String printProviderLog(){
        String result = restTemplate.getForObject("http://nacos-ribbon-provider/ribbon-test", String.class);
        return result;
    }

}

pom包

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

配置文件

先启动两个服务提供者,然后在启动服务消费者,浏览访问


不断刷新 发现使用的轮询方式交替执行。

免责声明
本站部分资源来源于互联网 如有侵权 请联系站长删除
龙哥网是优质的互联网科技创业资源_行业项目分享_网络知识引流变现方法的平台为广大网友提供学习互联网相关知识_内容变现的方法。