【问题标题】:Disable caching of static assets in Dropwizard在 Dropwizard 中禁用静态资产缓存
【发布时间】:2014-12-03 18:18:18
【问题描述】:

我有一个带有 rest api 的 Dropwizard 网络服务器,它还提供一些静态内容,如 html、css、javascript 和 jpg 图像。不幸的是,当我更改 html 或添加另一个图像时,总是需要重新启动服务器才能使更改生效。

由于我认为这可能是缓存的问题,我探索了bazaarvoice's Configurable Assets Bundle

这就是我添加到配置类的内容:

@Valid
@NotNull
@JsonProperty
private final AssetsConfiguration assets = new AssetsConfiguration();

在主类中

@Override
public void initialize(Bootstrap<MyConfiguration> bootstrap) {
    // ...
    CacheBuilderSpec cacheBuilderSpec = CacheBuilderSpec.disableCaching();
    bootstrap.addBundle(new ConfiguredAssetsBundle("/html", cacheBuilderSpec, "/", "index.html", "Static assets"));
}

@Override
public void run(MyConfiguration config, Environment env) {
    env.jersey().setUrlPattern("/api/*");
    // ...
}

yaml 配置没有变化。

静态文件位于 src/main/resources/html。 如何禁用缓存以便 Dropwizard 立即显示更改?

第二个问题,如何让 Dropwizard 跟随资产目录中的符号链接?

更新

我在 ConfiguredAssetsBundle 源代码中找到了这个:

// Let the cache spec from the configuration override the one specified in the code
CacheBuilderSpec spec = (config.getCacheSpec() != null)
    ? CacheBuilderSpec.parse(config.getCacheSpec())
    : cacheBuilderSpec;

这肯定会覆盖使用 yaml 文件中的配置在代码中设置的缓存构建器规范。追加后

assets:
  cacheSpec: maximumSize=0

对于配置,调试器显示最大大小现在为 0。但是,行为没有改变。

【问题讨论】:

    标签: java caching assets cache-control dropwizard


    【解决方案1】:

    静态内容不会改变不是因为你需要重新启动,而是因为运行的服务器实际上是在为目标目录下的文件提供服务。更改此目录中的文件只会使事情变得混乱(因此它不是真正的解决方案),但更改几行并等待一秒钟以验证服务器现在无需重新启动即可提供修改后的文件。

    作为一种解决方案,我更喜欢在 Eclipse 中将 dropwizard 项目作为 maven 项目打开,并使用 exec-maven-plugin 在终端上使用 mvn exec:java 运行该项目。 Eclipse 会在文件更改时更新目标目录,但这需要几秒钟,具体取决于项目的大小。

    【讨论】: