Skip to content

Instantly share code, notes, and snippets.

@saltukalakus
Created February 9, 2021 12:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save saltukalakus/eca7f6722f95237f4a09033360262d14 to your computer and use it in GitHub Desktop.
Save saltukalakus/eca7f6722f95237f4a09033360262d14 to your computer and use it in GitHub Desktop.
Java sample to reset connections every 30 seconds
object PoolingHttpClientFactory {
private val poolingConnectionManager = PoolingHttpClientConnectionManager().apply {
maxTotal = 40
defaultMaxPerRoute = 40
}
// called every 30 seconds from a scheduled task
fun cleanupConnections() {
poolingConnectionManager.closeExpiredConnections()
poolingConnectionManager.closeIdleConnections(2, MINUTES)
}
fun create(): HttpClient {
val requestConfig = RequestConfig.custom()
.setConnectTimeout(SECONDS.toMillis(15).toInt())
.setConnectionRequestTimeout(SECONDS.toMillis(15).toInt())
.setSocketTimeout(SECONDS.toMillis(60).toInt())
.build()
return HttpClients.custom()
.setDefaultRequestConfig(requestConfig)
.setConnectionManager(poolingConnectionManager)
.build()
}
}
@Configuration
class ClientHttpRequestFactoryConfiguration {
private val logger = LoggerFactory.getLogger(this::class.java)
@Bean
fun clientHttpRequestFactory() = HttpComponentsClientHttpRequestFactory(PoolingHttpClientFactory.create())
@Scheduled(initialDelay = 30_000, fixedDelay = 30_000)
fun cleanupConnections() {
logger.info("cleanup connections")
PoolingHttpClientFactory.cleanupConnections()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment