【发布时间】:2021-04-20 08:00:10
【问题描述】:
我在 AWS ECS 上运行了多个微服务,我想试用 AWS X-Ray。在this developer guide 之后,我添加了一个带有跟踪过滤器的WebConfig.java 文件。
向build.gradle添加行:
implementation "javax.servlet:javax.servlet-api:4.0.1"
implementation "com.amazonaws:aws-xray-recorder-sdk-core:2.8.0"
新文件WebConfig.java:
import com.amazonaws.xray.javax.servlet.AWSXRayServletFilter;
import javax.servlet.Filter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class WebConfig {
@Bean
public Filter tracingFilter() {
return new AWSXRayServletFilter("ordermicroservice");
}
}
但是,我不认为这是正确的,主要是因为我必须为 javax.servlet.Filter 添加额外的依赖项。我认为这是因为我使用的是 spring-boot-webflux 而不是 spring-boot-web。所以我有一个 Netty 网络服务器,而不是 Tomcat 网络服务器。
我的问题是:
- 如何向 servlet 过滤器添加日志记录,以确保每个传入的 HTTP 请求都正确地通过过滤器?
- 在使用 Netty 而不是 Tomcat 的 spring-boot-webflux 项目中编写 Web 过滤器的正确方法是什么?
编辑: 到目前为止,我想出了如何使用 Spring Boot WebFlux 编写过滤器。我将在此处将其添加到问题中以供将来参考:
import org.springframework.stereotype.Component
import org.springframework.web.server.ServerWebExchange
import org.springframework.web.server.WebFilter
import org.springframework.web.server.WebFilterChain
import reactor.core.publisher.Mono
@Component
class MyCustomWebFilter : WebFilter {
override fun filter(webExchange: ServerWebExchange, chain: WebFilterChain): Mono<Void> {
print("Successfully reached the WebFilter.\n")
val request = webExchange.request
val response = webExchange.response
// TODO: Do the actual filtering by looking at the request and modifying the response
return chain.filter(webExchange)
}
}
【问题讨论】:
-
你是对的。当您使用 webflux 时,servlet 过滤器将不起作用。与 webflux 中的 servlet 过滤器等效的是 WebFilter。您需要做的就是创建 WebFilter 接口的新实现并向其添加组件注释。 docs.spring.io/spring-framework/docs/current/javadoc-api/org/…
标签: spring-boot netty spring-webflux servlet-filters aws-xray