springcloud集成ribbon负载均衡的实例代码 本文比较简单集成ribbon,如需要更详细,请查看我的更多博客内容. 首先创建两个服务提供者 服务一,集成的nacos注册中心,这块随便写一个同名接口 端口配置8301 服务二,同名接口内容修改,其他跟上一个服务一大
本文比较简单集成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>
配置文件
先启动两个服务提供者,然后在启动服务消费者,浏览访问
不断刷新 发现使用的轮询方式交替执行。
到此这篇关于spring cloud 集成 ribbon负载均衡的文章就介绍到这了,更多相关spring cloud ribbon负载均衡内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!
织梦狗教程
本文标题为:spring cloud 集成 ribbon负载均衡的实例代码


基础教程推荐
猜你喜欢
- 全局记录Feign的请求和响应日志方式 2023-01-09
- Java File类的概述及常用方法使用详解 2023-05-18
- 一文了解Java 线程池的正确使用姿势 2023-06-17
- 用java实现扫雷游戏 2022-12-06
- 工厂方法在Spring框架中的运用 2023-06-23
- Java去掉小数点后面无效0的方案与建议 2023-02-18
- Java使用EasyExcel进行单元格合并的问题详解 2023-01-18
- JVM分析之类加载机制详解 2023-04-06
- SpringBoot配置文件中密码属性加密的实现 2023-03-11
- Project Reactor源码解析publishOn使用示例 2023-04-12