一、新建gateway项目
二、添加依赖
dependencies {
implementation 'org.springframework.cloud:spring-cloud-starter-gateway:4.0.0'
}
三、增加路由规则配置
一个web服务、一个service服务
bootstrap.yaml:
server:
port: 80
spring:
application:
name: gateway
cloud:
nacos:
discovery:
server-addr: ${NACOS_ADDR:127.0.0.1:8848}
namespace: ${NACOS_NAMESPACE:demo}
username: nacos
password: nacos
config:
#nacos配置中心服务器地址
server-addr: ${NACOS_ADDR:127.0.0.1:8848}
#nacos配置中心命名空间
namespace: ${NACOS_NAMESPACE:demo}
#文件后缀格式
file-extension: yaml
#nacos配置中心分组
group: ${spring.application.name}
username: nacos
password: nacos
#扩展文件,目前用于全局共享,下面的优先级高
ext-config:
- data-id: commom.yaml
group: common
refresh: true
application.yaml:
spring:
main:
web-application-type: reactive
cloud:
gateway:
routes:
#业务服务
- id: web_route
uri: lb://web
predicates:
- Path=/web/**
filters:
- RewritePath=/(?<segment>.*),/$\{segment}
#支撑服务
- id: service_route
uri: lb://service
predicates:
- Path=/service/**
filters:
- RewritePath=/(?<segment>.*),/$\{segment}
四、增加过滤器(可选)
比如认证、鉴权、日志打印等
例如:打印日志,用@Slf4j
注解来简化日志记录、
增加依赖
compileOnly 'org.projectlombok:lombok:1.18.24' // 使用最新版本
annotationProcessor 'org.projectlombok:lombok:1.18.24'
implementation 'org.slf4j:slf4j-api:2.0.6'
runtimeOnly 'ch.qos.logback:logback-classic:1.4.5'
代码:
@Slf4j
@Component
public class RequestLogFilter implements GlobalFilter, Ordered {
private static final String START_TIME_KEY = "startTime";
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
ServerHttpRequest request = exchange.getRequest();
String method = Objects.requireNonNull(request.getMethod()).name();
String requestURI = request.getPath().toString();
String remoteAddr = Objects.requireNonNull(request.getRemoteAddress()).getHostString();
System.out.println("method=" + method +";requestURI= "+ requestURI+ "; remoteAddr="+remoteAddr);
log.info("method=" + method +";requestURI= "+ requestURI+ "; remoteAddr="+remoteAddr);
return chain.filter(exchange);
}
@Override
public int getOrder() {
return 1;
}
}
五、增加启动类并运行测试
@SpringBootApplication(scanBasePackages = {"com.example"})
@EnableDiscoveryClient
public class GatewayApplication {
public static void main(String[] args) {
SpringApplication.run(GatewayApplication.class, args);
}
}
运行访问,用80端口
六、遇到的问题
1、启动报错
缺少依赖的包
Error starting ApplicationContext. To display the condition evaluation report re-run your application with 'debug' enabled.
2024-07-16T16:27:44.792+08:00 ERROR 9924 --- [gateway] [ main] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
Web application could not be started as there was no org.springframework.boot.web.reactive.server.ReactiveWebServerFactory bean defined in the context.
Action:
Check your application's dependencies for a supported reactive web server.
Check the configured web application type.