我正在学习WebFlux,并且想知道如何在使用WebFlux的微服务中提供静态内容,但我找不到相关信息。
我正在学习WebFlux,并且想知道如何在使用WebFlux的微服务中提供静态内容,但我找不到相关信息。
试试这个
RouterFunction router = resources("/**", new ClassPathResource("public/"));
更新: 不要忘记在从外部访问时在URL中指定静态文件的名称,例如localhost:8080/index.html
/
)结束资源路径,这样它就被视为资源树的根。也可以使用 new FileSystemResource("path/")
从用户的文件系统中提供服务。 - Yaroslav Stavnichiyresources()
在哪里?我正在自己引导,不使用Spring Boot。 - MohamedSanaullaorg.springframework.web.reactive.function.server
中找到它。 - Vladlen GladisJuan Medina是正确的。我只是想让它更清晰,并提供一个参考链接。
实际上,您只需添加一个RouterFunction bean来处理静态资源。您不必实现自己的RouterFunction,因为RouterFunctions.resources("/**", new ClassPathResource("static/"));
可以达到你想要的效果。
我所做的就是添加这段代码:
@Bean
RouterFunction<ServerResponse> staticResourceRouter(){
return RouterFunctions.resources("/**", new ClassPathResource("static/"));
}
任何未被识别的请求都会落入静态路由器中。
put public static web resources into the public-web-resources
folder:
./src/main/public-web-resources
configure 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/"
configure 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>
spring.webflux.static-path-pattern
,则不得使用 @EnableWebFlux
注释。 - Kanespring.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,您只需在.jar
旁边创建一个public
目录,它就会为您提供文件服务。但是,对于Spring WebFlux来说并非如此。这里提到的解决方案仅在您将静态文件放置在resources/public
文件夹中并构建.jar
时才有效。
我通过以下配置使Spring WebFlux无需将静态内容包含在jar中即可提供静态内容服务:
spring:
application:
name: spring-cloud-gateway
webflux.static-path-pattern: "/**"
resources.static-locations: "file:public/"
jar
文件,并在部署后添加静态文件。