In the previous blog, we discussed response compression using GZip filter for Lagom 1.3. Here, we will go over the steps we use to add similar response compression in Lagom 1.4.
The steps remain the same with minor changes due to underlying changes that came as Lagom upgraded from Play 2.5 to Play 2.6.
Step 1: The code
The first step is to write the code for our compression filter. We design a custom Filter that implements the HttpFilters interface provided by play framework as illustrated below. Let’s say we want to add GZip compression to our response before sending it to the consumer. The below snippet can be used as is in any Lagom service.
import akka.stream.Materializer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import play.filters.gzip.GzipFilter; import play.filters.gzip.GzipFilterConfig; import play.http.HttpFilters; import play.mvc.EssentialFilter; import play.mvc.Http; import play.mvc.Result; import javax.inject.Inject; import java.util.Arrays; import java.util.List; import java.util.function.BiFunction; public class GZipFilter implements HttpFilters { protected final Logger logger = LoggerFactory.getLogger(GZipFilter.class); private List filters; @Inject public GZipFilter(Materializer materializer) { GzipFilterConfig gzipFilterConfig = new GzipFilterConfig(); gzipFilterConfig = gzipFilterConfig .withShouldGzip((BiFunction<Http.RequestHeader, Result, Object>) (req, res) -> req.hasHeader("Accept-Encoding") && req.header("Accept-Encoding") .orElse("UTF-8").toLowerCase().contains("gzip")); GzipFilter gnuZIPFilter = new GzipFilter(gzipFilterConfig, materializer); filters = Arrays.asList(gnuZIPFilter.asJava()); logger.info("Filtering enabled with GZIPFilter..."); } @Override public List getFilters() { return filters; } }
The method filters() is now deprecated and is replaced by getFilters(), which returns a List of EssentialFilter. Also, The return type has been changed to List instead of an array. Other than that there is another minor change that the withShouldGzip() method of GzipFilterConfig now returns Optional of String instead of String value, making the process asynchronous.
Step 2: The configuration
In your application.conf, add the below parameters:
#Fully qualified class name of our customized HttpFilter play.http.filters = "com.example.GZipFilter" #Maximum expected size of compressed response play.filters.gzip.chunkedThreshold=300K
There is no change in the basic parameterization from Lagom 1.3 to 1.4.
And that’s it. If you have any questions, queries or suggestions, please drop a comment below and I’ll be happy to answer. And if you found this useful, do like & share this blog. Cheers. 🙂
References: