云计算、AI、云原生、大数据等一站式技术学习平台

网站首页 > 教程文章 正文

SpringBoot应用中使用拦截器实现路由转发

jxf315 2025-05-22 11:11:54 教程文章 14 ℃

1、背景

项目中有一个SpringBoot开发的微服务,经过业务多年的演进,代码已经累积到令人恐怖的规模,亟需重构,将之拆解成多个微服务。该微服务的接口庞大,调用关系非常复杂,且实施重构的人员大部分不是原开发者,慎重起见,要求开发人员先实施一个改动尽量少又可以验证拆解出来的新服务的功能的版本,该版本在试运行的过程中,用户请求可以允许切换回旧服务进行处理,兼容某些遗漏的场景,以保证业务的稳定正常运行,提高容错性。

基于以上背景,最终决定,在原有服务中,使用过滤器或拦截器开发一个简单的路由功能来实现上述需求。该路由功能将维护一个URL对象列表(请求url、是否转发标识、目标url等)。前端请求接口地址不变,依然向原服务发起请求。当请求进入到过滤器或拦截器时,从URL对象列表中匹配当前请求url,如果匹配到,则根据url的是否转发标识将请求路由给目标url(即原有请求url拆分到新服务后的请求url地址)处理。运行过程中,如果发现新服务接口异常,可以通过刷新接口对应url的转发标识为“不转发”来将请求继续交由原服务处理,待新服务问题修复后,下个版本再切换。

以下是使用Spring MVC的拦截器HandlerInterceptor + RestTemplate实现的基础版本。

RestTemplate 是 Spring 框架中用于同步调用 RESTful 服务的核心组件,它提供了一个简单且方便的方式来与 RESTful API 进行交互。

2、创建拦截器

拦截器负责拦截请求,并根据请求的 HTTP 方法调用RestTemplate的相应方法进行转发。

import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.util.StreamUtils;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.HandlerMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;

/**
 * 使用拦截器实现的简单的路由转发器
 *
 * @author Bruce.CH
 * @since 2025年03月06日
 */
public class SimpleRouter implements HandlerInterceptor, ApplicationListener<ApplicationReadyEvent> {

    // 定义路由规则:应用启动是初始化,然后使用定时任务间隔5分钟刷新一次
    private static final Map<String, UrlMapping> ROUTING_RULES = new HashMap<>();

    // 创建RestTemplate实例:实际开发中,应从容器中注入
    private final RestTemplate restTemplate = new RestTemplate();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 当前匹配url
        String currentPattern = currentPattern(request);

        // 获取当前请求url的路由规则
        UrlMapping urlMapping = ROUTING_RULES.get(currentPattern);

        // 如果存在路由规则,且标识了转发,则路由到目标url进行处理
        if (Objects.nonNull(urlMapping) && urlMapping.isForward()) {
            forwardRequest(request, response, urlMapping);
            return false;
        }

        // 否则,由原服务继续处理请求
        return true;
    }

    private String currentPattern(HttpServletRequest request) {
        Object bestMatchingPattern = request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
        return Optional.ofNullable(bestMatchingPattern).orElse("").toString();
    }

    private void forwardRequest(HttpServletRequest request, HttpServletResponse response, UrlMapping urlMapping) throws IOException {
        // 构造请求url
        String url = getUrl(request, urlMapping);

        // 透传请求头
        HttpHeaders headers = getHttpHeaders(request);

        // 请求方法
        HttpMethod method = getMethod(request);

        // 请求体
        byte[] body = getRequestBody(request);
        HttpEntity<byte[]> entity = new HttpEntity<>(body, headers);

        // 响应流
        Class<byte[]> responseType = byte[].class;

        // 路径变量:在getUrl方法中拼接赋值,这里空即可
        Map<String, ?> uriVariables = new HashMap<>();

        // 发送请求并获取响应
        ResponseEntity<byte[]> exchange = restTemplate.exchange(url, method, entity, responseType, uriVariables);

        // 设置响应头
        HttpHeaders responseHeaders = exchange.getHeaders();
        responseHeaders.forEach((name, values) -> values.forEach(value -> response.addHeader(name, value)));

        // 设置响应体
        byte[] responseBody = exchange.getBody();
        if (Objects.nonNull(responseBody)) {
            response.getOutputStream().write(responseBody);
        }
    }

    private byte[] getRequestBody(HttpServletRequest request) throws IOException {
        try (InputStream inputStream = request.getInputStream()) {
            return StreamUtils.copyToByteArray(inputStream);
        }
    }

    private HttpMethod getMethod(HttpServletRequest request) {
        String method = request.getMethod();
        switch (method) {
            case "GET":
                return HttpMethod.GET;
            case "POST":
                return HttpMethod.POST;
            case "PUT":
                return HttpMethod.PUT;
            case "DELETE":
                return HttpMethod.DELETE;
            case "PATCH":
                return HttpMethod.PATCH;
            case "HEAD":
                return HttpMethod.HEAD;
            case "OPTIONS":
                return HttpMethod.OPTIONS;
            default:
                throw new IllegalArgumentException("Unsupported HTTP method: " + method);
        }
    }

    private HttpHeaders getHttpHeaders(HttpServletRequest request) {
        HttpHeaders headers = new HttpHeaders();
        Enumeration<String> headerNames = request.getHeaderNames();
        // 透传请求头:遍历headerNames,根据headerName将请求中的请求头复制到headers中
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            Enumeration<String> headerValues = request.getHeaders(headerName);
            while (headerValues.hasMoreElements()) {
                String headerValue = headerValues.nextElement();
                headers.add(headerName, headerValue);
            }
        }
        return headers;
    }

    private String getUrl(HttpServletRequest request, UrlMapping urlMapping) {
        // 返回urlMapping的目标请求地址:实际开发中,拼接目标请求url的主机地址 + request请求中路径以及参数即可
        return urlMapping.getTargetUrl();
    }

    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        // 初始化路由规则
        refreshRoutingRules();
    }

    /**
     * 每5分钟刷新路由规则
     */
    @Scheduled(fixedRate = 300000)
    public void refreshRoutingRules() {
        // 实际开发中从数据库表或配置中加载
        UrlMapping mockService1 = new UrlMapping("/api/service1", "http://new-service1.example.com/api/service1");
        UrlMapping mockService2 = new UrlMapping("/api/service2", "http://new-service2.example.com/api/service2");
        UrlMapping mockService3 = new UrlMapping("/api/service3", "http://new-service3.example.com/api/service3");
        ROUTING_RULES.put(mockService1.getSourceUrl(), mockService1);
        ROUTING_RULES.put(mockService2.getSourceUrl(), mockService2);
        ROUTING_RULES.put(mockService3.getSourceUrl(), mockService3);
    }
}

上述代码中,preHandle方法在请求处理前进行拦截。获取当前请求的 URL 模式,检查是否有匹配的路由规则。如果存在匹配路由规则且设置了转发标识,则构造新的请求,将请求头、请求方法、请求体等信息透传到新的目标 URL,并将新服务的响应结果返回给客户端;如果没有匹配规则或未设置转发标识,则由原服务继续处理该请求。

  • UrlMapping

Url映射类

import lombok.Getter;
import lombok.Setter;

/**
 * url的映射对象
 *
 * @author Bruce.CH
 * @since 2025年03月06日
 */
@Getter
@Setter
public class UrlMapping {
    /**
     * 构造方法
     *
     * @param sourceUrl 源url
     * @param targetUrl 目标请求url
     */
    public UrlMapping (String sourceUrl, String targetUrl) {
        this.sourceUrl = sourceUrl;
        this.targetUrl = targetUrl;
    }

    /**
     * 源url:对应controller中定义的完整路径,比如/api/service1
     */
    private String sourceUrl;

    /**
     * 目标请求url:新服务的完整请求地址,比如http://new-service1.example.com/api/service1
     */
    private String targetUrl;

    /**
     * 默认转发到目标url处理请求,false为不转发即还是由源服务处理请求
     */
    private boolean forward = true;
}

3、注册拦截器

创建一个配置类,将拦截器注册到 Spring MVC 中。

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new SimpleRouter())
              .addPathPatterns("/api/**");
    }
}

在上述配置类中,addPathPatterns("/api/**") 表示拦截所有以 /api 开头的请求路径。

4、开启任务调度

在 Spring Boot 应用的主类上添加 @EnableScheduling 注解,以启用定时任务功能,定时刷新路由规则。

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
@EnableScheduling
public class YourApplication {
    public static void main(String[] args) {
        SpringApplication.run(YourApplication.class, args);
    }
}

5、总结

通过以上步骤,可以在 Spring Boot 应用中用拦截器和RestTemplate实现简单的路由转发功能。

上述代码实现了基本的转发功能,还有很多待改进的地方,比如在forwardRequest方法中,目前没有处理restTemplate.exchange可能抛出的异常,比如文件上传请求的处理,还有待继续的细化和完善。

Tags:

最近发表
标签列表