Spring Webflux 源码阅读之 resource包

支持为静态资源提供服务的类。

HttpResource

HttpResource diagram:

httpResource.jpg

将资源写入HTTP响应的扩展接口。

HTTP头将被提供给服务当前资源的HTTP响应。返回HttpHeaders


public interface HttpResource extends Resource {

    /**
     * The HTTP headers to be contributed to the HTTP response
     * that serves the current resource.
     * @return the HTTP response headers
     */
    HttpHeaders getResponseHeaders();
}

ResourceResolver

![resourceTransform.jpg](http://upload-images.jianshu.io/upload_images/8565418-7323e094de2c1538.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

解决对服务器端资源的请求的策略。

提供解决传入请求到实际资源的机制,以及获取客户端在请求资源时应该使用的公共URL路径。

public interface ResourceResolver {

将提供的请求和请求路径解析为存在于其中一个给定资源位置下的资源。

Mono<Resource> resolveResource(@Nullable ServerWebExchange exchange, String requestPath,
        List<? extends Resource> locations, ResourceResolverChain chain);

解析面向外部的公用URL路径,供客户端用来访问位于给定内部资源路径的资源。在向客户端呈现URL链接时这很有用。

Mono<String> resolveUrlPath(String resourcePath, List<? extends Resource> locations,
        ResourceResolverChain chain);

}

ResourceResolverChain

调用ResourceResolvers链的协定,其中每个解析器都被赋予一个引用链,允许它在必要时进行委托。

public interface ResourceResolverChain {

将提供的请求和请求路径解析为存在于其中一个给定资源位置下的资源。

Mono<Resource> resolveResource(@Nullable ServerWebExchange exchange, String requestPath,
        List<? extends Resource> locations);

解析面向外部的公用URL路径,供客户端用来访问位于给定内部资源路径的资源。
Mono<String> resolveUrlPath(String resourcePath, List<? extends Resource> locations);

}

ResourceTransformer

resourceTransform.jpg

转换资源内容的抽象。

转换给定的资源。

@FunctionalInterface
public interface ResourceTransformer {

    /**
     * Transform the given resource.
     * @param exchange the current exchange
     * @param resource the resource to transform
     * @param transformerChain the chain of remaining transformers to delegate to
     * @return the transformed resource (never empty)
     */
    Mono<Resource> transform(ServerWebExchange exchange, Resource resource,
            ResourceTransformerChain transformerChain);

}

ResourceTransformerChain

一个调用ResourceTransformers链的协议,每个解析器都被赋予一个链,让它在必要时进行委托。

  • getResolverChain() 返回用于解析正在转换的资源的ResourceResolverChain。这可能需要解析相关的资源,例如链接到其他资源。
  • transform(ServerWebExchange exchange, Resource resource) 转换给定的资源。


public interface ResourceTransformerChain {

    /**
     * Return the {@code ResourceResolverChain} that was used to resolve the
     * {@code Resource} being transformed. This may be needed for resolving
     * related resources, e.g. links to other resources.
     */
    ResourceResolverChain getResolverChain();

    /**
     * Transform the given resource.
     * @param exchange the current exchange
     * @param resource the candidate resource to transform
     * @return the transformed or the same resource, never empty
     */
    Mono<Resource> transform(ServerWebExchange exchange, Resource resource);

}


@FunctionalInterface
protected static interface CssLinkResourceTransformer.LinkParser

提取表示链接的内容块。

@FunctionalInterface
protected interface LinkParser {

    void parse(String cssContent, SortedSet<ContentChunkInfo> result);

}

AbstractResourceResolver

基于 ResourceResolver提供一致的日志记录。

public abstract class AbstractResourceResolver implements ResourceResolver {

protected final Log logger = LogFactory.getLog(getClass());

将提供的请求和请求路径解析为存在于其中一个给定资源位置下的资源。

@Override
public Mono<Resource> resolveResource(@Nullable ServerWebExchange exchange, String requestPath,
        List<? extends Resource> locations, ResourceResolverChain chain) {

    if (logger.isTraceEnabled()) {
        logger.trace("Resolving resource for request path \"" + requestPath + "\"");
    }
    return resolveResourceInternal(exchange, requestPath, locations, chain);
}

解析面向外部的公用URL路径,供客户端用来访问位于给定内部资源路径的资源。

@Override
public Mono<String> resolveUrlPath(String resourceUrlPath, List<? extends Resource> locations,
        ResourceResolverChain chain) {

    if (logger.isTraceEnabled()) {
        logger.trace("Resolving public URL for resource path \"" + resourceUrlPath + "\"");
    }

    return resolveUrlPathInternal(resourceUrlPath, locations, chain);
}


protected abstract Mono<Resource> resolveResourceInternal(@Nullable ServerWebExchange exchange,
        String requestPath, List<? extends Resource> locations, ResourceResolverChain chain);

protected abstract Mono<String> resolveUrlPathInternal(String resourceUrlPath,
        List<? extends Resource> locations, ResourceResolverChain chain);

}

VersionStrategy

VersionStrategy.jpg

确定静态资源的版本并应用and/or从URL路径中提取的策略。

public interface VersionStrategy {

从请求路径中提取资源版本。

@Nullable
String extractVersion(String requestPath);

从请求路径中删除版本。假定给定的版本是通过extractVersion(String)提取的。

String removeVersion(String requestPath, String version);

给给定的请求路径添加一个版本。

String addVersion(String requestPath, String version);

确定给定资源的版本

Mono<String> getResourceVersion(Resource resource);

}

VersionStrategy 的实现类:

AbstractFileNameVersionStrategy

基于文件名后缀的抽象基类,基于VersionStrategy实现,例如“static/ myresource-version.js”

protected final Log logger = LogFactory.getLog(getClass());

private static final Pattern pattern = Pattern.compile("-(\\S*)\\.");

从请求路径中提取资源版本。

@Override
public String extractVersion(String requestPath) {
    Matcher matcher = pattern.matcher(requestPath);
    if (matcher.find()) {
        String match = matcher.group(1);
        return (match.contains("-") ? match.substring(match.lastIndexOf('-') + 1) : match);
    }
    else {
        return null;
    }
}

从请求路径中删除版本

@Override
public String removeVersion(String requestPath, String version) {
    return StringUtils.delete(requestPath, "-" + version);
}

给给定的请求路径添加一个版本。

@Override
public String addVersion(String requestPath, String version) {
    String baseFilename = StringUtils.stripFilenameExtension(requestPath);
    String extension = StringUtils.getFilenameExtension(requestPath);
    return (baseFilename + '-' + version + '.' + extension);
}

AbstractPrefixVersionStrategy

用于在URL路径中插入前缀的版本策略实现的抽象基类。例如:“version/static/myresource.js”。

protected final Log logger = LogFactory.getLog(getClass());


private final String prefix;


protected AbstractPrefixVersionStrategy(String version) {
    Assert.hasText(version, "'version' must not be empty");
    this.prefix = version;
}


@Override
public String extractVersion(String requestPath) {
    return requestPath.startsWith(this.prefix) ? this.prefix : null;
}

@Override
public String removeVersion(String requestPath, String version) {
    return requestPath.substring(this.prefix.length());
}

@Override
public String addVersion(String path, String version) {
    if (path.startsWith(".")) {
        return path;
    }
    else if (this.prefix.endsWith("/") || path.startsWith("/")) {
        return this.prefix + path;
    }
    else {
        return this.prefix + '/' + path;
    }
}

具体实现类 ContentVersionStrategy

从资源的内容中计算Hex MD5散列的版本策略,并将其附加到文件名。“styles/ main-e36d2e05253c6c7085a91522ce43a0b4.css”。

public class ContentVersionStrategy extends AbstractFileNameVersionStrategy {

private static final DataBufferFactory dataBufferFactory = new DefaultDataBufferFactory();

确定给定资源的版本。

@Override
public Mono<String> getResourceVersion(Resource resource) {
    return DataBufferUtils.read(resource, dataBufferFactory, StreamUtils.BUFFER_SIZE)
            .reduce(DataBuffer::write)
            .map(buffer -> {
                byte[] result = new byte[buffer.readableByteCount()];
                buffer.read(result);
                DataBufferUtils.release(buffer);
                return DigestUtils.md5DigestAsHex(result);
            });
}

}

具体实现类 FixedVersionStrategy

依赖于固定版本作为请求路径前缀的VersionStrategy,例如减少SHA,版本名称,发布日期等

例如当ContentVersionStrategy无法使用时,例如使用负责加载JavaScript资源并需要知道其相对路径的JavaScript模块加载器时,这非常有用。


public class FixedVersionStrategy extends AbstractPrefixVersionStrategy {

    private final Mono<String> versionMono;


    /**
     * Create a new FixedVersionStrategy with the given version string.
     * @param version the fixed version string to use
     */
    public FixedVersionStrategy(String version) {
        super(version);
        this.versionMono = Mono.just(version);
    }


    @Override
    public Mono<String> getResourceVersion(Resource resource) {
        return this.versionMono;
    }

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 157,198评论 4 359
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 66,663评论 1 290
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 106,985评论 0 237
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,673评论 0 202
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 51,994评论 3 285
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,399评论 1 211
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,717评论 2 310
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,407评论 0 194
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,112评论 1 239
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,371评论 2 241
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,891评论 1 256
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,255评论 2 250
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,881评论 3 233
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,010评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,764评论 0 192
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,412评论 2 269
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,299评论 2 260

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,087评论 18 139
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 46,301评论 6 344
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 11,596评论 4 59
  • 译者说 Tornado 4.3于2015年11月6日发布,该版本正式支持Python3.5的async/await...
    TaoBeier阅读 3,002评论 0 10
  • 一说到REST,我想大家的第一反应就是“啊,就是那种前后台通信方式。”但是在要求详细讲述它所提出的各个约束,以及如...
    时待吾阅读 3,339评论 0 19