Created
February 9, 2021 12:59
-
-
Save saltukalakus/eca7f6722f95237f4a09033360262d14 to your computer and use it in GitHub Desktop.
Java sample to reset connections every 30 seconds
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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