Apitore blog

Apitoreを運営していた元起業家のブログ

Spring-bootのウェブサービスを多少高速化した

はじめに

Googleが提供するPageSpeed InsightsでApitoreの速度を測った所、モバイルのスコアが50点台と悪かったので、キャッシング等々して高速化を図りました。結果、70点にはなったので、その情報をシェアします。 amarec (20161003-221839)

Spring-boot側の設定

正確にはSpring Securityです。こんな感じにして静的ファイルをキャッシュできるようにします。

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
  // 中略
  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http
      // 中略
      .and()
        .headers()
        .cacheControl();
  }
}
@Configuration
public class WebMvcConfiguration extends WebMvcConfigurerAdapter {
  @Override
  public void addResourceHandlers(final ResourceHandlerRegistry registry) {
      registry.addResourceHandler("/js/**").setCachePeriod(31556926);
      registry.addResourceHandler("/css/**").setCachePeriod(31556926);
      registry.addResourceHandler("/img/**").setCachePeriod(31556926);
  }
}

nginxの設定

以下の記述を追加して、コンテンツを圧縮します。

server {
    # 中略
    gzip             on;
    gzip_min_length  1000;
    gzip_proxied     expired no-cache no-store private auth;
    gzip_types       text/plain application/xml text/css text/javascript;
    gzip_vary        on;
    expires          30d;

おわりに

あと残すところはレンダリングブロックCSSを何とかすることなのですが、これは結構めんどくさいのでやめました。一度にCSS読み込んでいるので遅くなっているようです。必要に応じて読み込むようにすれば良いのですが、管理がめんどくさいのでとりあえず放置しました。以上の工夫で、多少はモバイルでも高速にレンダリングできるようになったはずです。