<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<includeSystemScope>true</includeSystemScope>
</configuration>
<!--指定打包时候将依赖一起打包-->
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>11</source>
<target>11</target>
<skip>true</skip>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<configuration>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
spring:
# ...
config:
import:
- optional:nacos:serviceB.yml?group=DEFAULT_GROUP&refreshEnabled=true
@Slf4j
public class ForwardInterceptor implements HandlerInterceptor {
private String prefix;
public ForwardInterceptor(String prefix) {
this.prefix = prefix;
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String requestURI = request.getRequestURI();
// path修正为去掉context-path之后的真实uri
String newURI = requestURI.replaceFirst(prefix + "/serviceB", "");
log.debug("ForwardInterceptor.preHandle, prefix={}, requestURI: {}, newURI={}", prefix, request.getRequestURI(), newURI);
// 转发
request.getRequestDispatcher(newURI).forward(request, response);
return false; // 转发完请求就结束了,这里一定要返回false
}
}
@Slf4j
@Configuration
public class InfInterceptorConfig implements WebMvcConfigurer {
@Value("${spring.application.name}")
private String application;
@Value("${server.servlet.context-path}")
private String contextPath;
public static final String STATIC_CONTENT = "/static/file/**";
private static final String ORIGIN_APPLICATION = "serviceB";
@Override
public void addInterceptors(InterceptorRegistry registry) {
// 这里做兼容,如果serviceB回退为spring boot fat jar时,不做任何处理
if (ORIGIN_APPLICATION.equalsIgnoreCase(application)) {
return;
}
log.info("forward interceptor add, application={}, context-path={}", application, contextPath);
// 配置需要的转发路径
registry.addInterceptor(new ForwardInterceptor(contextPath))
.addPathPatterns("/serviceB/**");
}
}
spring:
gateway:
routes:
- id: serviceA
uri: lb://serviceA # serviceA
predicates:
- Path=/api/serviceA/**
filters:
- StripPrefix=1
- id: serviceB
uri: lb://serviceA # 注意这里需要改成serviceB
predicates:
- Path=/api/serviceB/**
filters:
# 这里需要做一个url rewrite
- RewritePath=/api/serviceB/?(?<segment>.*), /api/ticket/serviceB/$\{segment}
- StripPrefix=1
@FeignClient(name = "serviceA", contextId = "serviceB", path = "/serviceA", fallbackFactory = InfrastructureFeignClientFallbackFactory.class)
public interface ServiceBFeignClient {
// ...
}