我正在学习WebFlux,我想知道如何使用WebFlux在微服务上提供静态内容,但我没有找到信息。
尝试此
RouterFunction router = resources("/**", new ClassPathResource("public/"));
更新:从外部访问URL中静态文件的名称,例如localhost:8080/index.html
胡安·麦地那(Juan Medina(是正确的。我只想使其更加清晰并提供参考链接。
实际上,您只需添加一个路由功能bean即可处理静态资源。您不必实现自己的路由功能,因为 RouterFunctions.resources("/**", new ClassPathResource("static/"));
给出了您想要的。
我要做的就是添加此代码:
@Bean
RouterFunction<ServerResponse> staticResourceRouter(){
return RouterFunctions.resources("/**", new ClassPathResource("static/"));
}
什么未录制的请求都将落入静态路由器中。
春季web流行&amp;公共静态网络资源配置
将公共静态Web资源放入
public-web-resources
文件夹:./src/main/public-web-resources
配置春季启动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>
感谢Wildloop为我提供以下属性:
spring.webflux.static-path-pattern: "/**"
spring.resources.static-locations: "classpath:/public-web-resources/"
春季启动添加以下日志行:
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
目录,它将为您提供文件。与春季Webflux并非如此。此处提到的解决方案仅在将静态文件放在resources/public
文件夹中然后构建.jar
。
我有Spring Webflux可以提供静态内容,而无需将其包含在罐中,并带有以下配置:
spring:
application:
name: spring-cloud-gateway
webflux.static-path-pattern: "/**"
resources.static-locations: "file:public/"
wit this,您可以构建WebFlux jar
,然后在部署后添加静态文件。