从0到1 手把手搭建spring cloud alibaba 微服务大型应用框架(六)(优化篇)开发篇-如何解决微服务开发环境请求实例转发到别人机器问题

本文涉及的产品
云原生网关 MSE Higress,422元/月
服务治理 MSE Sentinel/OpenSergo,Agent数量 不受限
注册配置 MSE Nacos/ZooKeeper,118元/月
简介: 从0到1 手把手搭建spring cloud alibaba 微服务大型应用框架(六)(优化篇)开发篇-如何解决微服务开发环境请求实例转发到别人机器问题

image.png

前言:


本篇是上一篇《从0到1 手把手搭建spring cloud alibaba 微服务大型应用框架(七) 开发环境使用轻量级在线文档解决知识分享问题》的优化篇


原来是基于下图,分散处理的,分散在各个代码层并且不是统一获取version对应的instance


1.png

本篇将集成为两个共通,统一通过client 端设置version 依次传递 下去,然后各个层通过lb获取version对应的instance,该优化是借鉴了其他一些架构,觉得不错,引入进来了,如下图


image.png

源码部分


新增两个共通模块mini-cloud-common-gateaway,mini-cloud-balancer ,目录结构如下

1.png

mini-cloud-gateaway 源码


mini-cloud-common-gateaway 代码结构以及代码明细,将作为共通被mini-cloud-gateaway 使用

1.png

pom.xml   dependencies

<dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
        </dependency>
        <!--gateway 网关依赖,内置webflux 依赖-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-gateway-core</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-jwt</artifactId>
        </dependency>
        <dependency>
            <groupId>com.nimbusds</groupId>
            <artifactId>nimbus-jose-jwt</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-loadbalancer</artifactId>
        </dependency>
    </dependencies>

EnableMiniCloudRoute.java 主要作为开启引用MiniCloudRouteAutoConfiguration 自定义路由的开关,不然是无法扫描到 MiniCloudRouteAutoConfiguration 类的

package com.minicloud.common.gateaway.annotation;
import com.minicloud.common.gateaway.config.MiniCloudRouteAutoConfiguration;
import org.springframework.context.annotation.Import;
import java.lang.annotation.*;
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@Import(MiniCloudRouteAutoConfiguration.class)
public @interface EnableMiniCloudRoute {
}

MiniCloudRouteAutoConfiguration.java 主要是注入后续源码的扫描包,便于引用项目扫面到

package com.minicloud.common.gateaway.config;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan("com.minicloud.common.gateaway")
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.REACTIVE)
public class MiniCloudRouteAutoConfiguration {
}
MiniCloudLoadBalancerClientConfiguration.java 
  如果是使用 REACTIVE 作为web引擎,则可以初始化
MiniCloudReactiveLoadBalancerClientFilter和  MiniCloudLoadBalancer 两个类 
MiniCloudReactiveLoadBalancerClientFilter :主要是重写 ReactiveLoadBalancerClientFilter 获取request中的version
VersionMiniCloudLoadBalancer: 主要是获取到version 后获取version 对应lb中的instance
import com.minicloud.common.gateaway.filter.MiniCloudReactiveLoadBalancerClientFilter;
import com.minicloud.common.gateaway.rule.MiniCloudLoadBalancer;
import com.minicloud.common.gateaway.rule.VersionMiniCloudLoadBalancer;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.gateway.config.GatewayReactiveLoadBalancerClientAutoConfiguration;
import org.springframework.cloud.gateway.config.LoadBalancerProperties;
import org.springframework.cloud.gateway.filter.ReactiveLoadBalancerClientFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@EnableConfigurationProperties(LoadBalancerProperties.class)
@AutoConfigureBefore(GatewayReactiveLoadBalancerClientAutoConfiguration.class)
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.REACTIVE)
public class MiniCloudLoadBalancerClientConfiguration {
  @Bean
  public ReactiveLoadBalancerClientFilter gatewayLoadBalancerClientFilter(MiniCloudLoadBalancer miniCloudLoadBalancer,
                                      LoadBalancerProperties properties) {
    return new MiniCloudReactiveLoadBalancerClientFilter(properties, miniCloudLoadBalancer);
  }
  @Bean
  public MiniCloudLoadBalancer grayLoadBalancer(DiscoveryClient discoveryClient) {
    return new VersionMiniCloudLoadBalancer(discoveryClient);
  }
}

MiniCloudReactiveLoadBalancerClientFilter.java

@Slf4j
public class MiniCloudReactiveLoadBalancerClientFilter extends ReactiveLoadBalancerClientFilter {
  private static final int LOAD_BALANCER_CLIENT_FILTER_ORDER = 10150;
  private LoadBalancerProperties properties;
  private MiniCloudLoadBalancer miniCloudLoadBalancer;
  public MiniCloudReactiveLoadBalancerClientFilter(LoadBalancerProperties properties, MiniCloudLoadBalancer miniCloudLoadBalancer) {
    super(null, properties);
    this.properties = properties;
    this.miniCloudLoadBalancer = miniCloudLoadBalancer;
  }
  @Override
  public int getOrder() {
    return LOAD_BALANCER_CLIENT_FILTER_ORDER;
  }
  @Override
  public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
    URI url = exchange.getAttribute(ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR);
    String schemePrefix = exchange.getAttribute(ServerWebExchangeUtils.GATEWAY_SCHEME_PREFIX_ATTR);
    if (url == null
        || (!"lb".equals(url.getScheme()) && !"lb".equals(schemePrefix))) {
      return chain.filter(exchange);
    }
    // preserve the original url
    ServerWebExchangeUtils.addOriginalRequestUrl(exchange, url);
    if (log.isTraceEnabled()) {
      log.trace(ReactiveLoadBalancerClientFilter.class.getSimpleName()
          + " url before: " + url);
    }
    return choose(exchange).doOnNext(response -> {
      if (!response.hasServer()) {
        throw NotFoundException.create(properties.isUse404(),
            "Unable to find instance for " + url.getHost());
      }
      URI uri = exchange.getRequest().getURI();
      // if the `lb:<scheme>` mechanism was used, use `<scheme>` as the default,
      // if the loadbalancer doesn't provide one.
      String overrideScheme = null;
      if (schemePrefix != null) {
        overrideScheme = url.getScheme();
      }
      DelegatingServiceInstance serviceInstance = new DelegatingServiceInstance(
          response.getServer(), overrideScheme);
      URI requestUrl = LoadBalancerUriTools.reconstructURI(serviceInstance, uri);
      if (log.isTraceEnabled()) {
        log.trace("LoadBalancerClientFilter url chosen: " + requestUrl);
      }
      exchange.getAttributes().put(ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR, requestUrl);
    }).then(chain.filter(exchange));
  }
  private Mono<Response<ServiceInstance>> choose(ServerWebExchange exchange) {
    URI uri = exchange.getAttribute(ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR);
    ServiceInstance serviceInstance = miniCloudLoadBalancer.choose(uri.getHost(),exchange.getRequest());
    return Mono.just(new DefaultResponse(serviceInstance));
  }

MiniCloudLoadBalancer

package com.minicloud.common.gateaway.rule;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.http.server.reactive.ServerHttpRequest;
public interface MiniCloudLoadBalancer {
  ServiceInstance choose(String serviceId, ServerHttpRequest request);
}

VersionMiniCloudLoadBalancer.java

@Slf4j
@AllArgsConstructor
public class VersionMiniCloudLoadBalancer implements MiniCloudLoadBalancer {
  private DiscoveryClient discoveryClient;
  @Override
  public ServiceInstance choose(String serviceId, ServerHttpRequest request) {
    List<ServiceInstance> instances = discoveryClient.getInstances(serviceId);
    //注册中心无实例 抛出异常
    if (CollUtil.isEmpty(instances)) {
      log.warn("No instance available for {}", serviceId);
      throw new NotFoundException("No instance available for " + serviceId);
    }
    // 获取请求version,无则随机返回可用实例
    String reqVersion = request.getHeaders().getFirst("version");
    if (StrUtil.isBlank(reqVersion)) {
      return instances.get(RandomUtil.randomInt(instances.size()));
    }
    // 遍历可以实例元数据,若匹配则返回此实例
    for (ServiceInstance instance : instances) {
      Map<String, String> metadata = instance.getMetadata();
      String targetVersion = MapUtil.getStr(metadata, "version");
      if (reqVersion.equalsIgnoreCase(targetVersion)) {
        log.info("gray requst match success :{} {}", reqVersion, instance);
        return instance;
      }
    }
    return instances.get(RandomUtil.randomInt(instances.size()));
  }
}

mini-cloud-common-balancer 源码


mini-cloud-common-balancer 代码结构以及代码明细,将作为共通被各个业务端使用

1.png

pom.xml

 <dependencies>
        <dependency>
            <groupId>org.mini-cloud</groupId>
            <artifactId>mini-cloud-common-core</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>
        <dependency>
            <groupId>io.github.openfeign</groupId>
            <artifactId>feign-core</artifactId>
        </dependency>
    </dependencies>

spring.factories spring-boot 约定文件,也就是传说的“约定大于配置”

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
  com.minicloud.common.balancer.config.MiniCloudRibbonLoadBalancerConfiguration

MiniCloudRibbonLoadBalancerConfiguration.java

主要为了注入bean: MiniCloudRibbonLoadBalancerRule ,RequestInterceptor

import com.minicloud.common.balancer.fegin.MiniCloudFeignRequestInterceptor;
import com.minicloud.common.balancer.rule.MiniCloudRibbonLoadBalancerRule;
import feign.RequestInterceptor;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
@Configuration
public class MiniCloudRibbonLoadBalancerConfiguration {
  @Bean
  @ConditionalOnMissingBean
  @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
  public MiniCloudRibbonLoadBalancerRule ribbonLoadBalancerRule() {
    return new MiniCloudRibbonLoadBalancerRule();
  }
  @Bean
  public RequestInterceptor grayFeignRequestInterceptor() {
    return new MiniCloudFeignRequestInterceptor();
  }
}

MiniCloudFeignRequestInterceptor.java 为了拦截fegin请求并设置上游发来的 version

@Slf4j
public class MiniCloudFeignRequestInterceptor implements RequestInterceptor {
  @Override
  public void apply(RequestTemplate template) {
    String reqVersion = WebUtils.getRequest() != null
        ? WebUtils.getRequest().getHeader("version") : null;
    if (StrUtil.isNotBlank(reqVersion)) {
      log.debug("feign gray add header version :{}", reqVersion);
      template.header("version", reqVersion);
    }
  }

MiniCloudRibbonLoadBalancerRule.java 自定义使用端ribbon loadbalance 路由

@Slf4j
public class MiniCloudRibbonLoadBalancerRule extends AbstractLoadBalancerRule {
  @Override
  public void initWithNiwsConfig(IClientConfig iClientConfig) {
  }
  @Override
  public Server choose(Object key) {
    return choose(getLoadBalancer(), key);
  }
  public Server choose(ILoadBalancer lb, Object key) {
    List<Server> reachableServers = lb.getReachableServers();
    //注册中心无可用实例 抛出异常
    if (CollUtil.isEmpty(reachableServers)) {
      log.warn("No instance available for {}", key);
      return null;
    }
    // 获取请求version,无则随机返回可用实例
    String reqVersion = WebUtils.getRequest() != null
        ? WebUtils.getRequest().getHeader("version") : null;
    if (StrUtil.isBlank(reqVersion)) {
      return reachableServers.get(RandomUtil.randomInt(reachableServers.size()));
    }
    // 遍历可以实例元数据,若匹配则返回此实例
    for (Server server : reachableServers) {
      NacosServer nacosServer = (NacosServer) server;
      Map<String, String> metadata = nacosServer.getMetadata();
      String targetVersion = MapUtil.getStr(metadata,"version");
      if (reqVersion.equalsIgnoreCase(targetVersion)) {
        log.debug("gray requst match success :{} {}", reqVersion, nacosServer);
        return nacosServer;
      }
    }
    return reachableServers.get(RandomUtil.randomInt(reachableServers.size()));
  }
}


相关实践学习
SLB负载均衡实践
本场景通过使用阿里云负载均衡 SLB 以及对负载均衡 SLB 后端服务器 ECS 的权重进行修改,快速解决服务器响应速度慢的问题
负载均衡入门与产品使用指南
负载均衡(Server Load Balancer)是对多台云服务器进行流量分发的负载均衡服务,可以通过流量分发扩展应用系统对外的服务能力,通过消除单点故障提升应用系统的可用性。 本课程主要介绍负载均衡的相关技术以及阿里云负载均衡产品的使用方法。
相关文章
|
20天前
|
人工智能 前端开发 Java
Spring AI Alibaba + 通义千问,开发AI应用如此简单!!!
本文介绍了如何使用Spring AI Alibaba开发一个简单的AI对话应用。通过引入`spring-ai-alibaba-starter`依赖和配置API密钥,结合Spring Boot项目,只需几行代码即可实现与AI模型的交互。具体步骤包括创建Spring Boot项目、编写Controller处理对话请求以及前端页面展示对话内容。此外,文章还介绍了如何通过添加对话记忆功能,使AI能够理解上下文并进行连贯对话。最后,总结了Spring AI为Java开发者带来的便利,简化了AI应用的开发流程。
265 0
|
1月前
|
XML Java 数据格式
Spring Core核心类库的功能与应用实践分析
【12月更文挑战第1天】大家好,今天我们来聊聊Spring Core这个强大的核心类库。Spring Core作为Spring框架的基础,提供了控制反转(IOC)和依赖注入(DI)等核心功能,以及企业级功能,如JNDI和定时任务等。通过本文,我们将从概述、功能点、背景、业务点、底层原理等多个方面深入剖析Spring Core,并通过多个Java示例展示其应用实践,同时指出对应实践的优缺点。
60 14
|
1月前
|
消息中间件 监控 Java
如何将Spring Boot + RabbitMQ应用程序部署到Pivotal Cloud Foundry (PCF)
如何将Spring Boot + RabbitMQ应用程序部署到Pivotal Cloud Foundry (PCF)
39 6
|
1月前
|
XML 前端开发 安全
Spring MVC:深入理解与应用实践
Spring MVC是Spring框架提供的一个用于构建Web应用程序的Model-View-Controller(MVC)实现。它通过分离业务逻辑、数据、显示来组织代码,使得Web应用程序的开发变得更加简洁和高效。本文将从概述、功能点、背景、业务点、底层原理等多个方面深入剖析Spring MVC,并通过多个Java示例展示其应用实践,同时指出对应实践的优缺点。
85 2
|
1月前
|
Java 关系型数据库 MySQL
如何将Spring Boot + MySQL应用程序部署到Pivotal Cloud Foundry (PCF)
如何将Spring Boot + MySQL应用程序部署到Pivotal Cloud Foundry (PCF)
63 5
|
1月前
|
缓存 监控 Java
如何将Spring Boot应用程序部署到Pivotal Cloud Foundry (PCF)
如何将Spring Boot应用程序部署到Pivotal Cloud Foundry (PCF)
45 5
|
2月前
|
消息中间件 Java Kafka
Spring Boot 与 Apache Kafka 集成详解:构建高效消息驱动应用
Spring Boot 与 Apache Kafka 集成详解:构建高效消息驱动应用
64 1
|
2月前
|
设计模式 Java API
微服务架构演变与架构设计深度解析
【11月更文挑战第14天】在当今的IT行业中,微服务架构已经成为构建大型、复杂系统的重要范式。本文将从微服务架构的背景、业务场景、功能点、底层原理、实战、设计模式等多个方面进行深度解析,并结合京东电商的案例,探讨微服务架构在实际应用中的实施与效果。
154 6
|
2月前
|
设计模式 Java API
微服务架构演变与架构设计深度解析
【11月更文挑战第14天】在当今的IT行业中,微服务架构已经成为构建大型、复杂系统的重要范式。本文将从微服务架构的背景、业务场景、功能点、底层原理、实战、设计模式等多个方面进行深度解析,并结合京东电商的案例,探讨微服务架构在实际应用中的实施与效果。
61 1
|
1月前
|
Java 开发者 微服务
从单体到微服务:如何借助 Spring Cloud 实现架构转型
**Spring Cloud** 是一套基于 Spring 框架的**微服务架构解决方案**,它提供了一系列的工具和组件,帮助开发者快速构建分布式系统,尤其是微服务架构。
191 69
从单体到微服务:如何借助 Spring Cloud 实现架构转型