springcloud中Ribbon和RestTemplate实现服务调用与负载均衡
作者:何羡仙 发布时间:2022-06-30 14:58:45
标签:springcloud,服务调用,负载均衡
文件目录结构
文件目录结构很重要,特别注意的是rule文件要放在主启动类上一级位置,才能够扫描。
写pom
<dependencies>
<!--springboot 2.2.2-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--Spring cloud Hoxton.SR1-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!--Spring cloud alibaba 2.1.0.RELEASE-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--Eureka-Client-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
因为eureka的依赖已经整合了ribbon的依赖,所以不用额外引入新的东西。
改yml
server:
port: 80
spring:
application:
name: cloud-book-consumer
eureka:
client:
register-with-eureka: false
fetch-registry: true
service-url:
defaultZone: http://eureka7001.com:7001/eureka,http://eureka7002.com:7002/eureka
主启动
@SpringBootApplication
@EnableEurekaClient
@RibbonClient(name = "CLOUD-BOOK-SERVICE", configuration = LoadBalanceRule.class) //更换轮询算法
public class RestTemplateMain80 {
public static void main(String[] args) {
SpringApplication.run(RestTemplateMain80.class,args);
}
}
业务逻辑
rules层
在图示文件目录下新建LoadBalanceRule.class,用于更换负载均衡算法。
@Configuration
public class LoadBalanceRule {
@Bean
public IRule iRule() {
// 定义为随机
return new RandomRule();
}
}
config层
开启restTemplate负载均衡
在config文件夹下创建LoadBalanceConfig.class
@Configuration
public class LoadBalanceConfig {
@Bean
@LoadBalanced //开启负载均衡
public RestTemplate getReatTemplate(){
return new RestTemplate();
}
}
controller层
新建BookController.class
写业务代码
@RestController
@Slf4j
public class BookController {
@Resource
private RestTemplate restTemplate;
public static final String PAYMENT_URL = "http://CLOUD-BOOK-SERVICE";
@GetMapping(value = "restTemplate/book/getAllBooks")//只要json数据时
public CommonResult getAllBooks(){
return restTemplate.getForObject(PAYMENT_URL+"/book/getAllBooks",CommonResult.class);
}
@GetMapping("restTemplate/book/getAllBooks2") //需要知道更多数据时,使用getForEntity方法
public CommonResult getAllBooks2(){
ResponseEntity<CommonResult> resultResponseEntit = restTemplate.getForEntity(PAYMENT_URL+"/book/getAllBooks",CommonResult.class);
if (resultResponseEntit.getStatusCode().is2xxSuccessful()){
log.info(resultResponseEntit.getStatusCode()+"\t"+resultResponseEntit.getHeaders());
return resultResponseEntit.getBody();
}else {
return new CommonResult<>(444,"操作失败");
}
}
@GetMapping(value = "restTemplate/book/index")
public String index() {
return restTemplate.getForObject(PAYMENT_URL+"/book/index",String.class);
}
}
使用restTemplate+Ribboin实现服务调用和负载均衡完成。
手写Ribbon负载均衡算法 lb层
1.新建LoadBalancer接口,添加代码
public interface LoadBalancer {
ServiceInstance instances(List<ServiceInstance> serviceInstances);
}
2.新建实现类MyLB
@Component
public class MyLB implements LoadBalancer {
private AtomicInteger atomicInteger = new AtomicInteger(0);
//求第几次访问 自旋锁思想
public final int getAndIncrement(){
int current;
int next;
do {
current = this.atomicInteger.get();
next = current >=2147483647 ? 0 : current+1;
}while(!this.atomicInteger.compareAndSet(current,next));
System.out.println("***第几次访问next->"+next);
return next;
}
//负载均衡算法,实现roundRobin算法
@Override
public ServiceInstance instances(List<ServiceInstance> serviceInstances) {
int index = getAndIncrement() % serviceInstances.size();
return serviceInstances.get(index);
}
}
修改BookController
@RestController
@Slf4j
public class BookController {
@Resource
private RestTemplate restTemplate;
@Resource
private LoadBalancer loadBalancer;
@Resource
private DiscoveryClient discoveryClient;
public static final String PAYMENT_URL = "http://CLOUD-BOOK-SERVICE";
@GetMapping(value = "restTemplate/book/getAllBooks")//只要json数据时
public CommonResult getAllBooks(){
List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-BOOK-SERVICE");
if (instances == null || instances.size() <= 0){
return null;
}
ServiceInstance serviceInstance = loadBalancer.instances(instances);
URI uri = serviceInstance.getUri();
return restTemplate.getForObject(uri+"/book/getAllBooks",CommonResult.class);
}
@GetMapping(value = "restTemplate/book/index")
public String index() {
List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-BOOK-SERVICE");
if (instances == null || instances.size() <= 0){
return null;
}
ServiceInstance serviceInstance = loadBalancer.instances(instances);
URI uri = serviceInstance.getUri();
return restTemplate.getForObject(uri+"/book/index",String.class);
}
}
修改文件注解
删去主启动类的更换负载均衡算法注解
@RibbonClient(name = “CLOUD-BOOK-SERVICE”, configuration = LoadBalanceRule.class)
删去LoadBalanceConfig中开启负载均衡算法注解
@LoadBalanced
手写Ribbon算法并使用完成
来源:https://blog.csdn.net/super1223/article/details/115384982


猜你喜欢
- 本文实例讲述了java实现单词搜索迷宫游戏。分享给大家供大家参考。具体分析如下:我们在杂志上,经常能够看到找单词的小游戏,在一个二维表格中,
- 由于Android课程项目需要,特地查阅了okHttp的使用,发现网上找的大多和自己的需求不一样。所以就着团队项目需要,自己简单封装了一个o
- 本文实例讲述了Android中资源文件用法。分享给大家供大家参考,具体如下:一、XML文件间资源文件的使用引用格式:attribute=&q
- 1.JWT定义JWT(Json Web Token)是一种用于双方之间传递安全信息的简洁的、URL安全的表述性声明规范。JWT作为一个开放的
- 定义 1、如果注解中有属性,那么必须给属性赋值。package com.lxc.Test;// 定义一个注解public @int
- 本文介绍spring-rest接口中的LocalDateTime日期类型转时间戳的方法。具体的代码参照示例项目 https://github
- 最近项目中需要根据模板生成word文档,模板文件也是word文档。当时思考一下想用POI API来做,但是觉得用起来相对复杂。后来又找了一种
- Mybatis-plus官网地址:https://baomidou.com/配置mysql在配置文件连接mysqlspring.dataso
- 最近项目中用到了文字图标的按钮,需要居中显示,如果用TextView实现的方式,必须同时设置padding和drawablePadding。
- 写应用程序的过程中,弹窗是个避免不了的功能,显示中,假设弹窗背景色和主窗口背景色相差不多,甚至是一样的时候,就会存在一个比较严重的人机交互和
- ArrayList就是传说中的动态数组,它提供了如下一些好处:动态的增加和减少元素实现了ICollection和IList接口灵活的设置数组
- 前言自从用了SpringBoot,个人最喜欢的就是SpringBoot的配置文件了,和Spring比起SpringBoot更加灵活,修改的某
- 1、cookie是啥?随手百度了网友的说说简单的说,Cookie就是服务器暂存放在你计算机上的一笔资料,好让服务器用来辨认你的计算机。当你在
- 前言最近发现公司的微服务项目中没有统一的批量新增方法,公司用的是MP插件,遇到批量新增都是单独去去编写xml实现,费时费力,而MP自带的批插
- 1、多个线程对同一个队列进行读写操作,要注意进行读写控制,某个线程在读取的时候,不允许其它线程读、写;某个线程在写的时候,不允许其它线程进行
- 对称加密算法是应用较早的加密算法,技术成熟。在对称加密算法中,数据发信方将明文(原始数据)和加密密钥(mi yue)一起经过特殊加密算法处理
- 一、微信官方文档微信支付开发流程(公众号支付)首先我们到微信支付的官方文档的开发步骤部分查看一下需要的设置。[图片上传失败...(image
- ELK是三款软件的简称,分别是Elasticsearch、Logstash、Kibana组成,在发展的过程中,又有新成员Beats的加入,所
- 连接操作redisSpring Boot中操作redis还是需要使用相关的启动器<dependency><groupId&
- 前段时间接到一个Web应用自动生成Word的需求,现整理了下一些关键步骤拿来分享一下。思路:(注:这里只针对WORD2003版本,其它版本大