Oleksandr Volynets
Oleksandr Volynets

Reputation: 123

Setting DNS lookup's TimeToLive in Scala Play

I am trying to set the TimeToLive setting for DNS Lookup in my Scala-Play application. I use Play 2.5.9 and Scala 2.11.8 and follow the AWS guide. I tried the following ways:

I have the following piece of test code in the application:

for (i <- 1 to 25) {
  System.out.println(java.net.InetAddress.getByName("google.com").getHostAddress())
  Thread.sleep(1000)
}

This always prints the same IP address, e.g. 216.58.212.206. To me it looks like none of the approaches specified above have any effect. However, maybe I am testing something else and not actually the value of TTL. Therefore, I have two questions:

Upvotes: 10

Views: 1376

Answers (1)

Bj&#246;rn K&#246;ster
Bj&#246;rn K&#246;ster

Reputation: 124

To change the settings for DNS cache via java.security.Security you have to provide a custom application loader.

package modules
class ApplicationLoader extends GuiceApplicationLoader {
  override protected def builder(context: Context): GuiceApplicationBuilder = {
    java.security.Security.setProperty("networkaddress.cache.ttl", "1")
    super.builder(context)
  }
}

When you build this application loader you can enable it in your application.conf

play.application.loader = "modules.ApplicationLoader"

after that you could use your code above and check if the DNS cache is behaving like you set it up. But keep in mind that your system is accessing a DNS server which is caching itself so you wont see change then. If you want to be sure that you get different addresses for google.com you should use an authority name server like ns1.google.com

If you want to write a test on that you could maybe write a test which requests the address and then waits for the specified amount of time until it resolves again. But with a DNS system out of your control like google.com this could be a problem, if you hit a DNS server with caching. If you want to write such a check you could do it with

@RunWith(classOf[JUnitRunner])
class DnsTests extends FlatSpec with Matchers {

  "DNS Cache ttl" should "refresh after 1 second" 
    in new WithApplicationLoader(new modules.ApplicationLoader) {

    // put your test code here

  }
}

As you can see you can put the custom application loader in the context of the application starting behind your test.

Upvotes: 8

Related Questions