我正在学习 webflux,我想知道如何使用 webflux 在微服务上提供静态内容,但我没有找到相关信息。
5 回答
尝试这个
RouterFunction router = resources("/**", new ClassPathResource("public/"));
更新:从外部访问静态文件时,不要忘记在 URL 中指定静态文件的名称,例如localhost:8080/index.html
胡安·梅迪纳是对的。我只是想让它更清楚并提供参考链接。
实际上,您只需添加一个 RouterFunction bean 来处理静态资源。您不必实现自己的 RouterFunction,因为
RouterFunctions.resources("/**", new ClassPathResource("static/"));
它可以提供您想要的。
我所做的就是添加这段代码:
@Bean
RouterFunction<ServerResponse> staticResourceRouter(){
return RouterFunctions.resources("/**", new ClassPathResource("static/"));
}
任何无法识别的请求都将落入静态路由器。
Spring Web Flux & 公共静态 Web 资源配置
将公共静态网络资源放入
public-web-resources
文件夹:./src/main/public-web-resources
配置Spring Boot 2.0,
application.yaml
:spring.main.web-application-type: "REACTIVE" spring.webflux.static-path-pattern: "/app/**" spring.resources.static-locations: - "classpath:/public-web-resources/"
配置maven-resources-plugin,
pom.xml
:<build> <plugins> <plugin> <artifactId>maven-resources-plugin</artifactId> <version>3.0.1</version> <executions> <execution> <id>copy-resources</id> <phase>validate</phase> <goals> <goal>copy-resources</goal> </goals> <configuration> <resources> <resource> <directory>src/main/public-web-resources</directory> <filtering>true</filtering> </resource> </resources> <outputDirectory>${basedir}/target/classes/public-web-resources</outputDirectory> </configuration> </execution> </executions> </plugin> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <version>2.0.0.BUILD-SNAPSHOT</version> </plugin> </plugins> </build>
感谢 wildloop 为我工作,具有以下属性:
spring.webflux.static-path-pattern: "/**"
spring.resources.static-locations: "classpath:/public-web-resources/"
Spring Boot 添加以下日志行:
15:51:43.776 INFO Adding welcome page: class path resource [public-web-resources/index.html] - WebMvcAutoConfiguration$WelcomePageHandlerMapping.<init>
它用作http://localhost:port/myapp/的欢迎页面
希望有一种方法可以调用它/myapp/docs
我努力在.jar
可执行文件之外托管静态内容。使用spring boot mvc,您只需在public
旁边创建一个目录.jar
,它将为您提供文件。使用 spring webflux 并非如此。此处提到的解决方案仅在您将静态文件放在resources/public
文件夹中然后构建.jar
.
我得到了 spring webflux 来提供静态内容,而无需将其包含在具有以下配置的 jar 中:
spring:
application:
name: spring-cloud-gateway
webflux.static-path-pattern: "/**"
resources.static-locations: "file:public/"
有了这个,您可以构建 webfluxjar
并稍后在部署时添加静态文件。