AVt天堂网 手机版,亚洲va久久久噜噜噜久久4399,天天综合亚洲色在线精品,亚洲一级Av无码毛片久久精品

當前位置:首頁 > 科技  > 軟件

解密Spring Cloud微服務調用:如何輕松獲取請求目標方的IP和端口

來源: 責編: 時間:2023-11-28 09:37:12 248觀看
導讀目的Spring Cloud 線上微服務實例都是2個起步,如果出問題后,在沒有ELK等日志分析平臺,如何確定調用到了目標服務的那個實例,以此來排查問題圖片效果可以看到服務有幾個實例是上線,并且最終調用了那個實例圖片考慮到Spring

目的

Spring Cloud 線上微服務實例都是2個起步,如果出問題后,在沒有ELK等日志分析平臺,如何確定調用到了目標服務的那個實例,以此來排查問題2x028資訊網——每日最新資訊28at.com

圖片圖片2x028資訊網——每日最新資訊28at.com

效果

可以看到服務有幾個實例是上線,并且最終調用了那個實例2x028資訊網——每日最新資訊28at.com

圖片圖片2x028資訊網——每日最新資訊28at.com

考慮到Spring Cloud在版本升級中使用了兩種負載均衡實現,Robin和LoadBalancer,下面我們提供兩種實現方案2x028資訊網——每日最新資訊28at.com

Robin實現方案

1. 技術棧

  • Spring Cloud: Hoxton.SR6
  • Spring Boot: 2.3.1.RELEASE
  • Spring-Cloud-Openfeign: 2.2.3.RELEASE

2. 繼承RoundRobinRule,并重寫choose方法

/** * 因為調用目標機器的時候,如果目標機器本身假死或者調用目標不通無法數據返回,那么feign無法打印目標機器。這種場景下我們需要在調用失?。繕藱C器沒有返回)的時候也能把目標機器的ip打印出來,這種場景需要我們切入feign選擇機器的邏輯,注入我們自己的調度策略(默認是roundrobin),在里面打印選擇的機器即可。*/@Slf4jpublic class FeignRule extends RoundRobinRule {    @Override    public Server choose(Object key) {        Server server = super.choose(key);        if (Objects.isNull(server)) {            log.info("server is null");            return null;        }        log.info("feign rule ---> serverName:{}, choose key:{}, final server ip:{}", server.getMetaInfo().getAppName(), key, server.getHostPort());        return server;    }    @Override    public Server choose(ILoadBalancer lb, Object key) {        Server chooseServer = super.choose(lb, key);        List<Server> reachableServers = lb.getReachableServers();        List<Server> allServers = lb.getAllServers();        int upCount = reachableServers.size();        int serverCount = allServers.size();        log.info("serverName:{} upCount:{}, serverCount:{}", Objects.nonNull(chooseServer) ? chooseServer.getMetaInfo().getAppName() : "", upCount, serverCount);        for (Server server : allServers) {            if (server instanceof DiscoveryEnabledServer) {                DiscoveryEnabledServer dServer = (DiscoveryEnabledServer) server;                InstanceInfo instanceInfo = dServer.getInstanceInfo();                if (instanceInfo != null) {                    InstanceInfo.InstanceStatus status = instanceInfo.getStatus();                    if (status != null) {                        log.info("serverName:{} server:{}, status:{}", server.getMetaInfo().getAppName(), server.getHostPort(), status);                    }                }            }        }        return chooseServer;    }}

3.修改RibbonClients配置

import org.springframework.cloudflix.ribbon.RibbonClients;import org.springframework.context.annotation.Configuration;/** * @description:feign 配置 */@Configuration@RibbonClients(defaultConfiguration = {FeignRule.class})public class FeignConfig {}

LoadBalancer實現方案

1. 技術棧

  • Spring Cloud: 2021.0.4
  • Spring Boot: 2.7.17
  • Spring-Cloud-Openfeign: 3.1.4

2. 繼承ReactorServiceInstanceLoadBalancer,并實現相關方法

@Slf4jpublic class CustomRoundRobinLoadBalancer implements ReactorServiceInstanceLoadBalancer {    final AtomicInteger position;    final String serviceId;    ObjectProvider<ServiceInstanceListSupplier> serviceInstanceListSupplierProvider;    public CustomRoundRobinLoadBalancer(ObjectProvider<ServiceInstanceListSupplier> serviceInstanceListSupplierProvider, String serviceId) {        this(serviceInstanceListSupplierProvider, serviceId, (new Random()).nextInt(1000));    }    public CustomRoundRobinLoadBalancer(ObjectProvider<ServiceInstanceListSupplier> serviceInstanceListSupplierProvider, String serviceId, int seedPosition) {        this.serviceId = serviceId;        this.serviceInstanceListSupplierProvider = serviceInstanceListSupplierProvider;        this.position = new AtomicInteger(seedPosition);    }    public Mono<Response<ServiceInstance>> choose(Request request) {        ServiceInstanceListSupplier supplier = this.serviceInstanceListSupplierProvider.getIfAvailable(NoopServiceInstanceListSupplier::new);        return supplier.get(request).next().map((serviceInstances) -> {            return this.processInstanceResponse(supplier, serviceInstances);        });    }    private Response<ServiceInstance> processInstanceResponse(ServiceInstanceListSupplier supplier, List<ServiceInstance> serviceInstances) {        Response<ServiceInstance> serviceInstanceResponse = this.getInstanceResponse(serviceInstances);        if (supplier instanceof SelectedInstanceCallback && serviceInstanceResponse.hasServer()) {            ((SelectedInstanceCallback)supplier).selectedServiceInstance((ServiceInstance)serviceInstanceResponse.getServer());        }        return serviceInstanceResponse;    }    private Response<ServiceInstance> getInstanceResponse(List<ServiceInstance> instances) {        if (instances.isEmpty()) {            if (log.isWarnEnabled()) {                log.warn("No servers available for service: " + this.serviceId);            }            return new EmptyResponse();        } else {            int pos = this.position.incrementAndGet() & Integer.MAX_VALUE;            ServiceInstance instance = instances.get(pos % instances.size());            log.info("serverName:{} upCount:{}",instance.getServiceId(),instances.size());            log.info("feign rule ---> serverName:{}, final server ip:{}:{}", instance.getServiceId(), instance.getHost(),instance.getPort());            return new DefaultResponse(instance);        }    }}

3.修改LoadBalancerClients配置

@Configuration@LoadBalancerClients(defaultConfiguration = CustomLoadBalancerConfiguration.class)public class CustomLoadBalancerConfig {}@Configurationclass CustomLoadBalancerConfiguration {    /**     * 參考默認實現     * @see org.springframework.cloud.loadbalancer.annotation.LoadBalancerClientConfiguration#reactorServiceInstanceLoadBalancer     * @return     */    @Bean    public ReactorLoadBalancer<ServiceInstance> reactorServiceInstanceLoadBalancer(Environment environment, LoadBalancerClientFactory loadBalancerClientFactory) {        String name = environment.getProperty(LoadBalancerClientFactory.PROPERTY_NAME);        return new CustomRoundRobinLoadBalancer(loadBalancerClientFactory.getLazyProvider(name, ServiceInstanceListSupplier.class), name);    }}

以上兩部完成大功告成!2x028資訊網——每日最新資訊28at.com

源碼下載:https://github.com/dongweizhao/spring-cloud-example/tree/SR6-OpenFeign https://github.com/dongweizhao/spring-cloud-example/tree/EurekaOpenFeign2x028資訊網——每日最新資訊28at.com

2x028資訊網——每日最新資訊28at.com

本文鏈接:http://www.tebozhan.com/showinfo-26-34679-0.html解密Spring Cloud微服務調用:如何輕松獲取請求目標方的IP和端口

聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。郵件:2376512515@qq.com

上一篇: 超高效,使用Terraform創建Docker鏡像和容器

下一篇: Javascript的閉包有哪些應用?你學會了嗎?

標簽:
  • 熱門焦點
  • 小米平板5 Pro 12.4簡評:多專多能 兼顧影音娛樂的大屏利器

    疫情帶來了網課,網課盤活了安卓平板,安卓平板市場雖然中途停滯了幾年,但好的一點就是停滯的這幾年行業又有了新的發展方向,例如超窄邊框、高刷新率、多攝鏡頭組合等,這就讓安卓
  • 6月安卓手機性能榜:vivo/iQOO霸占旗艦排行榜前三

    2023年上半年已經正式過去了,我們也迎來了安兔兔V10版本,在新的驍龍8Gen3和天璣9300發布之前,性能榜的榜單大體會以驍龍8Gen2和天璣9200+為主,至于那顆3.36GHz的驍龍8Gen2領先
  • SpringBoot中使用Cache提升接口性能詳解

    環境:springboot2.3.12.RELEASE + JSR107 + Ehcache + JPASpring 框架從 3.1 開始,對 Spring 應用程序提供了透明式添加緩存的支持。和事務支持一樣,抽象緩存允許一致地使用各
  • 一篇聊聊Go錯誤封裝機制

    %w 是用于錯誤包裝(Error Wrapping)的格式化動詞。它是用于 fmt.Errorf 和 fmt.Sprintf 函數中的一個特殊格式化動詞,用于將一個錯誤(或其他可打印的值)包裝在一個新的錯誤中。使
  • 微博大門常打開,迎接海外畫師漂洋東渡

    作者:互聯網那些事&ldquo;起猛了,我能看得懂日語了&rdquo;。&ldquo;為什么日本人說話我能聽懂?&rdquo;&ldquo;中文不像中文,日語不像日語,但是我竟然看懂了&rdquo;&hellip;&hell
  • OPPO K11樣張首曝:千元機影像“卷”得真不錯!

    一直以來,OPPO K系列機型都保持著較為均衡的產品體驗,歷來都是2K價位的明星機型,去年推出的OPPO K10和OPPO K10 Pro兩款機型憑借各自的出色配置,堪稱有
  • 蘋果140W USB-C充電器:采用氮化鎵技術

    據10 月 30 日 9to5 Mac 消息報道,當蘋果推出新的 MacBook Pro 2021 時,該公司還推出了新的 140W USB-C 充電器,附贈在 MacBook Pro 16 英寸機型的盒子里,也支
  • 電博會與軟博會實現"線下+云端"的雙線融合

    在本次“電博會”與“軟博會”雙展會利好條件的加持下,既可以發揮展會拉動人流、信息流、資金流實現快速交互流動的作用,繼而推動區域經濟良性發展;又可以聚
  • 榮耀Magic4 至臻版 首創智慧隱私通話 強勁影音系統

    2022年第一季度臨近尾聲,在該季度內,許多品牌陸續發布自己的最新產品,讓大家從全新的角度來了解當今的手機技術。手機是電子設備中,更新迭代十分迅速的一款產品,基
Top