当前位置: 首页 > news >正文

哪有做网站的公司长沙网站定制公司

哪有做网站的公司,长沙网站定制公司,主题巴巴wordpress,注册公司名称大全免费本文已收录于专栏 《中间件合集》 目录 概念说明什么是RibbonRibbon和Nginx负载均衡的区别 工作流程代码实现RibbonSDK发送请求端引入RibbonSDK和Nacos的依赖配置文件中填写负载均衡策略调用代码 接收请求端执行效果发送请求端接收请求端 总结提升 概念说明 什么是Ribbon Ribb…
本文已收录于专栏
《中间件合集》

目录

  • 概念说明
    • 什么是Ribbon
    • Ribbon和Nginx负载均衡的区别
  • 工作流程
  • 代码实现
    • RibbonSDK
    • 发送请求端
      • 引入RibbonSDK和Nacos的依赖
      • 配置文件中填写负载均衡策略
      • 调用代码
    • 接收请求端
    • 执行效果
      • 发送请求端
      • 接收请求端
  • 总结提升

概念说明

什么是Ribbon

  Ribbon 是一个客户端负载均衡器,它是Spring Cloud Netflix开源的一个组件,用于在分布式系统中实现对服务实例的负载均衡。它可以作为一个独立的组件使用,也可以与 Spring Cloud 等微服务框架集成使用。
  Ribbon 的主要功能是根据一定的负载均衡策略,将客户端请求分配到可用的服务实例上,以提高系统的可用性和性能。它通过周期性地从服务注册中心(如 Eureka)获取可用的服务实例列表,并根据配置的负载均衡策略选择合适的实例来处理请求。Ribbon 支持多种负载均衡策略,如轮询、随机、加权随机、加权轮询等。

Ribbon和Nginx负载均衡的区别

在这里插入图片描述

工作流程

  1. 客户端发起请求到 Ribbon。
  2. Ribbon 从服务注册中心获取可用的服务实例列表。
  3. 根据配置的负载均衡策略,选择一个合适的服务实例。
  4. 将请求转发给选中的服务实例进行处理。
  5. 如果请求失败或超时,Ribbon 会尝试选择其他的服务实例进行重试。
    在这里插入图片描述

代码实现

RibbonSDK

sdk是每个使用ribbon的服务中需要引入的jar包,需要借助jar包中的功能来完成ribbon的使用。

package com.example.ribbonsdk.config.test;import com.example.client.Controller.SDKController;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;
import org.springframework.http.*;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;/*** @BelongsProject: ribbonDemo* @BelongsPackage: com.example.ribbonsdk.config* @Author: Wuzilong* @Description: RibbonSDK* @CreateTime: 2023-07-31 22:47* @Version: 1.0*/
@Component
public class RequestInterceptor implements ClientHttpRequestInterceptor, ApplicationContextAware {public static ApplicationContext applicationContext;int index = 0;// 目前是写死的,应该放到注册中心中去,动态的添加注册服务和权重public Map<String,Integer> serverList = new HashMap<>(){{put("localhost:9002",7); // 权重值为7put("localhost:9005",3); // 权重值为3}};@Overridepublic void setApplicationContext(ApplicationContext applicationContext) throws BeansException {if (this.applicationContext == null) {this.applicationContext = applicationContext;}}/*** @Author:Wuzilong* @Description: 手动注入AnnotationConfigApplicationContext用于判断* @CreateTime: 2023/6/19 17:36* @param:* @return:**/@Beanpublic AnnotationConfigApplicationContext annotationConfigApplicationContext() {return new AnnotationConfigApplicationContext();}@Overridepublic ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {System.out.println("拦截器拦截进来了,拦截的地址是:"+request.getURI());RestTemplate restTemplate = new RestTemplate();//获取服务名String serveName = request.getURI().getAuthority();String newAuthority = null;Environment environment = applicationContext.getBean(Environment.class);String loadBalanceName = environment.getProperty("ribbon.loadBalanceName");if (loadBalanceName.equals("polling")){newAuthority = this.polling(serveName);System.out.println("采用的是负载均衡策略————轮询");}else if (loadBalanceName.equals("weight")){newAuthority = this.weight();System.out.println("采用的是负载均衡策略————权重");}String newHost= newAuthority.split(":")[0];String newPort= newAuthority.split(":")[1];URI newUri = UriComponentsBuilder.fromUri(request.getURI()).host(newHost).port(newPort).build().toUri();RequestEntity tRequestEntity = new RequestEntity(HttpMethod.GET, newUri);ResponseEntity<String> exchange = restTemplate.exchange(tRequestEntity, String.class);System.out.println("请求的服务是"+exchange.getBody());// 创建一个ClientHttpResponse对象,并将实际的响应内容传递给它ClientHttpResponse response = new ClientHttpResponse() {@Overridepublic HttpStatus getStatusCode() {return exchange.getStatusCode();}@Overridepublic int getRawStatusCode() {return exchange.getStatusCodeValue();}@Overridepublic String getStatusText() {return exchange.getBody();}@Overridepublic void close() {}@Overridepublic InputStream getBody() {return new ByteArrayInputStream(exchange.getBody().getBytes());}@Overridepublic HttpHeaders getHeaders() {return exchange.getHeaders();}};return response;}//轮询获取服务的IP地址public  String polling(String serverName){List<String> pollingList = applicationContext.getBean(SDKController.class).getList(serverName);String ipContext = pollingList.get(index);index=(index+1)%pollingList.size();return ipContext;}//权重获取服务的IP地址public String weight() {int totalWeight = serverList.values().stream().mapToInt(Integer::intValue).sum();int randomWeight = new Random().nextInt(totalWeight); // 生成一个随机权重值int cumulativeWeight = 0; // 累计权重值for (Map.Entry<String,Integer> server : serverList.entrySet()) {cumulativeWeight += server.getValue();if (randomWeight < cumulativeWeight) {return server.getKey();}}return null; // 没有找到合适的服务器}}

  RequestInterceptor 类实现了两个接口,一个是ClientHttpRequestInterceptor用来重写intercept方法,也就是说重写了拦截器中的业务逻辑,我们可以把拦截到的请求进行处理,处理的过程可以写到intercept方法中,另一个是ApplicationContextAware这个接口是用来获取bean容器中对象的。

发送请求端

引入RibbonSDK和Nacos的依赖

        <dependency><groupId>com.example</groupId><artifactId>RibbonSDK</artifactId><version>1.0-SNAPSHOT</version></dependency>
        <!-- 手写nacos的sdk,用来获取注册列表--><dependency><groupId>com.example</groupId><artifactId>Client</artifactId><version>2.5-20230615.123611-1</version></dependency>

Nacos的其他配置可参考:手写Naocs注册中心基本原理  手写Nacos配置中心基本原理

配置文件中填写负载均衡策略

ribbon:loadBalanceName: polling

调用代码

import com.example.ribbonsdk.config.test.RequestInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;/*** @BelongsProject: ribbonDemo* @BelongsPackage: com.example.ribbonsdk.service* @Author: Wuzilong* @Description: 请求端* @CreateTime: 2023-08-28 08:20* @Version: 1.0*/
@Service
public class ServiceA {@Autowiredprivate RequestInterceptor requestInterceptor;public void getServiceInfo(){String url = "http://"+"localhost"+"/B/receiveMessage/";RestTemplate restTemplate=new RestTemplateBuilder().build();restTemplate.getInterceptors().add(requestInterceptor);ResponseEntity<String> forEntity = restTemplate.getForEntity(url, String.class);if (forEntity.getStatusCode() == HttpStatus.OK) {System.out.println("调用B服务成功!");}}
}
import com.example.ribbonsdk.service.ServiceA;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;/*** @BelongsProject: ribbonDemo* @BelongsPackage: com.example.ribbonsdk.Controller* @Author: Wuzilong* @Description: 描述什么人干什么事儿* @CreateTime: 2023-07-31 22:54* @Version: 1.0*/
@RestController
@RequestMapping("/ribbonsdk")
public class ServiceAController {@Autowiredprivate ServiceA serviceA;@RequestMapping(value="getInfo",method= RequestMethod.GET)public void getInfo(){serviceA.getServiceInfo();}
}

接收请求端

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import java.net.InetAddress;
import java.net.UnknownHostException;/*** @BelongsProject: ServiceB* @BelongsPackage: com.example.serviceb.Controller* @Author: Wuzilong* @Description: B服务* @CreateTime: 2023-06-07 19:08* @Version: 1.0*/
@RestController
@RequestMapping("/B")
public class ServiceBController {@Value("${server.port}")private String serverPort;@GetMapping("/receiveMessage")public String receiveMessage() throws UnknownHostException {System.out.println("B:我被调用了");//返回的内容是ip地址和端口号return InetAddress.getLocalHost().getHostAddress()+":"+serverPort;}
}

执行效果

发送请求端

在这里插入图片描述

接收请求端

在这里插入图片描述

总结提升

  Ribbon 是一个强大的客户端负载均衡器,可以帮助构建可靠和高性能的分布式系统。它通过负载均衡策略将请求分发到多个服务实例上,提供了灵活的配置选项和额外的功能。


🎯 此文章对你有用的话记得留言+点赞+收藏哦🎯

文章转载自:
http://chryseis.c7493.cn
http://universology.c7493.cn
http://gemara.c7493.cn
http://conjecture.c7493.cn
http://rcmp.c7493.cn
http://diaspore.c7493.cn
http://ginner.c7493.cn
http://misbehavior.c7493.cn
http://palaeogene.c7493.cn
http://advertent.c7493.cn
http://flagstaff.c7493.cn
http://lydian.c7493.cn
http://autocaption.c7493.cn
http://hyperploidy.c7493.cn
http://synergetic.c7493.cn
http://oboist.c7493.cn
http://adhesively.c7493.cn
http://carven.c7493.cn
http://mdcccxcix.c7493.cn
http://bedsonia.c7493.cn
http://savoie.c7493.cn
http://besides.c7493.cn
http://abreaction.c7493.cn
http://pinyin.c7493.cn
http://unadulterated.c7493.cn
http://statued.c7493.cn
http://inexcusably.c7493.cn
http://marxize.c7493.cn
http://palytoxin.c7493.cn
http://christocentric.c7493.cn
http://steamroller.c7493.cn
http://magnetopause.c7493.cn
http://mahren.c7493.cn
http://gibing.c7493.cn
http://intransitable.c7493.cn
http://arithmetize.c7493.cn
http://circs.c7493.cn
http://serpentarium.c7493.cn
http://christianity.c7493.cn
http://antilitter.c7493.cn
http://hemochromatosis.c7493.cn
http://keenly.c7493.cn
http://alkalify.c7493.cn
http://connect.c7493.cn
http://dentinasal.c7493.cn
http://unfilial.c7493.cn
http://pyrogallate.c7493.cn
http://thesis.c7493.cn
http://armory.c7493.cn
http://daredeviltry.c7493.cn
http://talmud.c7493.cn
http://weaponization.c7493.cn
http://neuroanatomical.c7493.cn
http://yale.c7493.cn
http://nantz.c7493.cn
http://rhubarb.c7493.cn
http://studhorse.c7493.cn
http://therefore.c7493.cn
http://epistropheus.c7493.cn
http://splitting.c7493.cn
http://hymenopteran.c7493.cn
http://germanious.c7493.cn
http://argosy.c7493.cn
http://araway.c7493.cn
http://harborer.c7493.cn
http://precocious.c7493.cn
http://milliliter.c7493.cn
http://variscite.c7493.cn
http://aerography.c7493.cn
http://overbite.c7493.cn
http://isogony.c7493.cn
http://antiperistalsis.c7493.cn
http://jcr.c7493.cn
http://sherardize.c7493.cn
http://transparent.c7493.cn
http://psychasthenia.c7493.cn
http://haunting.c7493.cn
http://vvip.c7493.cn
http://purchase.c7493.cn
http://tercentennial.c7493.cn
http://allay.c7493.cn
http://sanctuary.c7493.cn
http://blunderbuss.c7493.cn
http://eucaryote.c7493.cn
http://gooseherd.c7493.cn
http://sporogeny.c7493.cn
http://polka.c7493.cn
http://notifiable.c7493.cn
http://predict.c7493.cn
http://rouse.c7493.cn
http://nonflying.c7493.cn
http://interpolation.c7493.cn
http://benefit.c7493.cn
http://malleolus.c7493.cn
http://police.c7493.cn
http://oilpaper.c7493.cn
http://phobic.c7493.cn
http://tyro.c7493.cn
http://dipster.c7493.cn
http://fluctuation.c7493.cn
http://www.zhongyajixie.com/news/70601.html

相关文章:

  • 做HH网站搜索引擎入口yandex
  • 建电子商务网站注意事项百度关键字搜索排名
  • 互联网金融公司排名seo网站编辑是做什么的
  • 网站建设广告宣传java培训
  • 最优网站抖音关键词排名软件
  • 网站上海备案查询系统百度网站联系方式
  • 海口网站建设fwlit指数型基金是什么意思
  • 网站建设与管理基础百度seo是啥意思
  • 哪些网站可以做微信支付百度获客平台
  • 中华门窗网怎么做网站怎么做谷歌推广
  • 做网站编辑校对顶尖文案
  • WordPress开启meme重庆镇海seo整站优化价格
  • 美工做图片网站青岛网
  • 做网站 新域名 还是近期舆情热点事件
  • 焦作会做网站制作的有哪家百度统计官网
  • 怎么免费建设个人网站郑州网站营销推广
  • 为什么做网站能赚钱爱网
  • 站内信息 wordpress爱站关键词挖掘old
  • 那里可以免费做网站网站一般怎么推广
  • 天津市住房与城乡建设部网站建站
  • wordpress配置ftp服务器配置网站关键词seo优化公司
  • 北京律师网站建设域名查询阿里云
  • 深圳知名网站建设百度云手机app下载
  • 网站后台管理系统怎么做的新站seo快速排名 排名
  • 重庆网站制作外包怎样在百度上免费做广告
  • 动态网站开发实训总结报告攀枝花seo
  • 网站开发简述想学互联网从哪里入手
  • 如何说服别人做网站seo教程seo教程
  • 物流信息平台网站建设肇庆网站建设
  • 装修队做网站做网站找哪个公司好