首页 > 其他分享 >spring cloud gateway根据版本过滤可用实例

spring cloud gateway根据版本过滤可用实例

时间:2024-06-21 15:36:51浏览次数:3  
标签:return get spring springframework version import org gateway cloud

根据版本过滤实例:

import cn.hutool.core.collection.CollUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.Request;
import org.springframework.cloud.client.loadbalancer.RequestDataContext;
import org.springframework.cloud.loadbalancer.core.DelegatingServiceInstanceListSupplier;
import org.springframework.cloud.loadbalancer.core.ServiceInstanceListSupplier;
import org.springframework.http.HttpHeaders;
import org.springframework.util.MultiValueMap;
import reactor.core.publisher.Flux;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
public class VersionServiceInstanceListSupplier extends DelegatingServiceInstanceListSupplier {
    private static final String VERSION = "version";

    public VersionServiceInstanceListSupplier(ServiceInstanceListSupplier delegate) {
        super(delegate);
    }


    @Override
    public Flux<List<ServiceInstance>> get() {
        return delegate.get();
    }

    @Override
    public Flux<List<ServiceInstance>> get(Request request) {
        return delegate.get(request).map(instances -> filteredByVersion(instances, getVersion(request.getContext())));
    }


    private List<ServiceInstance> filteredByVersion(List<ServiceInstance> instances, String requestVersion) {
        if(StringUtils.isEmpty(requestVersion)){
            return instances.stream()
                    .filter(instance -> StringUtils.isBlank(instance.getMetadata().get(VERSION)))
                    .collect(Collectors.toList());
        }

        log.info("request version is {}", requestVersion);
        List<ServiceInstance> filteredInstances = instances.stream()
                .filter(instance -> requestVersion.equalsIgnoreCase(instance.getMetadata().get(VERSION)))
                .collect(Collectors.toList());

        if (CollUtil.isEmpty(filteredInstances)) {
            filteredInstances = instances.stream()
                    .filter(instance -> StringUtils.isBlank(instance.getMetadata().get(VERSION)))
                    .collect(Collectors.toList());
        }
        return filteredInstances;

    }

    private String getVersion(Object requestContext) {
        if (requestContext == null) {
            return null;
        }
        String version = null;
        if (requestContext instanceof RequestDataContext) {
            version = getVersionFromHeader((RequestDataContext) requestContext);
        }
        return version;
    }

    private String getVersionFromHeader(RequestDataContext context) {
        if (context.getClientRequest() != null) {
            String version = null;
            HttpHeaders headers = context.getClientRequest().getHeaders();
            if (headers != null) {
                version = headers.getFirst(VERSION);
            }
            if (StringUtils.isBlank(version)) {
                MultiValueMap<String, String> cookies = context.getClientRequest().getCookies();
                if (cookies != null) {
                    List<String> cookieVersions = cookies.get(VERSION);
                    if (CollUtil.isNotEmpty(cookieVersions)) {
                        version = cookieVersions.get(0);
                    }
                }
            }
            return version;
        }
        return null;
    }

}

注册Bean:

import org.springframework.cloud.loadbalancer.core.ServiceInstanceListSupplier;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class VersionServiceInstanceListSupplierConfiguration {

    @Bean
    ServiceInstanceListSupplier serviceInstanceListSupplier(ConfigurableApplicationContext context) {
        ServiceInstanceListSupplier delegate = ServiceInstanceListSupplier.builder()
                .withDiscoveryClient()
                .withCaching()
                .build(context);
        return new VersionServiceInstanceListSupplier(delegate);
    }

}

启动类上加:

@LoadBalancerClients(defaultConfiguration = VersionServiceInstanceListSupplierConfiguration.class)

以nacos注册中心为例,网关加入以上代码后,业务服务配置如下:

spring:
  cloud:
    nacos:
      discovery:
        # 本地调试时修改以下信息
        metadata:
          ## 版本号,唯一  避免与其他服务冲突
          version: V123

请求接口时header带上版本号,即可路由到自己的服务

标签:return,get,spring,springframework,version,import,org,gateway,cloud
From: https://www.cnblogs.com/langty/p/18260589

相关文章

  • 基于springboot地方废物回收机构管理系统
    收藏关注不迷路||项目不适合可以浏览博主其他项目文章项目源码||毕设定制||远程支持||可联系博主---------------同类型文章链接--------------------------java项目设计专栏1项目基于springboot地方废物回收机构管理系统本系统的核心价值观在于为用户打造一个便......
  • Spring Boot 实现优雅的参数校验
    前言在日常的Web开发中,请求参数校验是一个非常基础且重要的环节。通过校验,我们可以确保每次接口请求中,入参的数据是有效、安全且合规的,避免数据库中出现脏数据。手动校验参数原始的手动校验参数代码如下:@PostMapping("/test")@ApiOperationLog(description="测试......
  • Spring常用注解,自动扫描装配Bean
    1引入context命名空间(在Spring的配置文件中),配置文件如下:Xml代码xmlns:context="http://www.springframework.org/schema/context"http://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-2.5.xsd......
  • 计算机Java项目|SpringBoot在线宠物用品交易网站
    作者主页:编程指南针作者简介:Java领域优质创作者、CSDN博客专家、CSDN内容合伙人、掘金特邀作者、阿里云博客专家、51CTO特邀作者、多年架构师设计经验、腾讯课堂常驻讲师主要内容:Java项目、Python项目、前端项目、人工智能与大数据、简历模板、学习资料、面试题库、技术互......
  • spring整合openAI大模型之Spring AI
    文章目录一、SpringAI简介1.什么是SpringAI2.SpringAI支持的大模型类型(1)聊天模型(2)文本到图像模型(3)转录(音频到文本)模型(4)嵌入模型(5)矢量数据库3.SpringAI版本二、SpringAI框架使用,对接OpenAI1.环境信息2.初始化3.配置文件(1)application.yml(2)pom文件4.聊天代码测试(1)聊天接......
  • 「Java开发指南」如何使用Spring注释器实现Spring控制器?(二)
    本教程将引导您使用SpringAnnotator实现Spring控制器,标准Java类被添加到搭建项目中,SpringAnnotatorSpring启用Java类。虽然本教程的重点是Spring控制器,但是SpringAnnotator也可以用于Spring服务、组件和存储库。在本教程中,您将学习如何:创建一个Java类将类配置为Spring控制......
  • springMVC域对象共享数据
    目录五、域对象共享数据5.1、使用ServletAPI向request域对象共享数据5.2、使用ModelAndView向request域对象共享数据5.3、使用Model向request域对象共享数据5.4、使用map向request域对象共享数据5.5、使用ModelMap向request域对象共享数据5.6Model、ModelMap、Map的关系5.7、向se......
  • Springboot+Vue+Mybatis-Plus+Easyexcel实现文件导入+导出的excel单元格下拉列表
    引言文件的导入与导出功能扮演着至关重要的角色,特别是在处理大量数据和复杂的表格时。通过整合SpringBoot、Vue、Mybatis-Plus和Easyexcel等先进技术,我们可以构建一个高效、灵活的文件处理系统。其中,Excel作为广泛使用的电子表格软件,其单元格下拉列表功能对于数据录入和校验......
  • 云VR(CloudVR)服务与传统VR技术对比
    虚拟现实(VirtualReality,简称VR)是一种利用计算机技术模拟产生一个三维空间的虚拟世界,让用户通过视觉、听觉、触觉等感官,获得与现实世界类似或超越的体验。VR技术发展历程可追溯至上世纪,经历概念提出、设备研制以及应用拓展等多阶段。随着计算机图形学、传感器技术、网络技术等领域......
  • 阿里云Apsara Clouder专项技能认证——弹性计算Clouder认证:ECS快速入门(实验、考试操
    前言证书特点:免费!免费!免费!多一个证书有啥不好呢!!!证书名称:阿里ECS专项认证证书有效期:2年培训需求:免费培训,阿里提供课程发证机构:阿里巴巴考试时间:随时,线上直接考考试语言:中文考试费用:0考试难度:★★☆☆☆社会认可度:★★☆☆☆性价比:★★★★★(因为免费,性价比拉满)技术......