Skip to content

静态服务

This content is not available in your language yet.

Feat框架内置了一个高性能的静态文件服务模块(FileServer),它可以作为Nginx的替代方案,用于托管静态资源。

本文将详细介绍如何使用FileServer模块,包括基本用法、功能特性以及高级配置。

概述

FileServer模块是一个轻量级的静态资源服务器,支持以下功能:

  • 静态文件托管
  • 自动目录索引(可选)
  • 文件缓存
  • 断点续传
  • 支持大文件传输
  • 高性能IO处理

通过FileServer模块,开发者可以快速搭建一个高效的静态资源服务器,适用于以下场景:

  • 托管网站静态资源(HTML、CSS、JavaScript等)
  • 提供文件下载服务
  • 替代Nginx作为静态资源服务器

工作原理

基本用法:

public class FileServerDemo {
public static void main(String[] args) {
Feat.fileServer(opts -> opts.baseDir("./")).listen();
}
}

参数说明

baseDir

类型: String

默认值: ./

静态资源文件的存放目录,该参数为 必填项

示例:

  1. 在任意目录下创建一个 html 文件, 假设:

    • Linux:/root/static/
    • Windows: C:/static/
    • Mac: /Users/xxx/static/
    index.html
    <html lang="">
    <head>
    <title>Feat</title>
    </head>
    <body>
    <h1>Hello Feat</h1>
    <p>File Server</p>
    </body>
    </html>
  2. 以 Linux 环境为例,实现代码如下:

    public class FileServerDemo {
    public static void main(String[] args) {
    Feat.fileServer(opts -> opts.baseDir("/root/static/")).listen();
    }
    }
  3. 运行程序并打开浏览器,访问:http://localhost:8080,效果如下:

    hello world

autoIndex

类型: boolean

默认值: false

若设置为:true,则允许以目录列表的形式展现。

示例:

  1. 运行以下程序:
    public class FileServerDemo {
    public static void main(String[] args) {
    Feat.fileServer(opts -> opts.autoIndex(true)).listen();
    }
    }
  2. 打开浏览器,访问:http://localhost:8080,效果如下: hello world