spring cloud 集成 ribbon负载均衡的实例代码

网友投稿 652 2022-11-18

spring cloud 集成 ribbon负载均衡的实例代码

spring cloud 集成 ribbon负载均衡的实例代码

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

首先创建两个服务提供者

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

端口配置8301

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

端口配置成8302

创建服务消费者

RibbonConfig.java

package com.example.nacosribbonconsumers.config;

import com-flix.loadbalancer.IRule;

import com-flix.loadbalancer.RoundRobinRule;

import org.springframework.cloud.client.loadbalancer.LoadBalanced;

import org.springframework.cloud-flix.ribbon.RibbonClient;

import org.springframework.context.annotation.Bean;

ihttp://mport 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包

org.springframework.cloud

spring-cloud-starter-netflix-ribbon

配置文件

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

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

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:100 MySQL_5 _DDL数据表操作【重点】
下一篇:133 文件操作
相关文章

 发表评论

暂时没有评论,来抢沙发吧~