Skip to content

Commit

Permalink
feat : implement jdkClient
Browse files Browse the repository at this point in the history
  • Loading branch information
rajadilipkolli committed Mar 10, 2024
1 parent ed8267b commit e4533ae
Show file tree
Hide file tree
Showing 8 changed files with 84 additions and 47 deletions.
33 changes: 22 additions & 11 deletions httpClients/boot-rest-template/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.2.3</version>
<version>3.3.0-M2</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example.rest.template</groupId>
Expand Down Expand Up @@ -331,14 +331,25 @@
</plugins>
</build>

<repositories>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<repositories>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>

</project>
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.annotation.EnableScheduling;
Expand Down Expand Up @@ -73,7 +74,7 @@ ConnectionKeepAliveStrategy connectionKeepAliveStrategy() {
Header element = headerIterator.next();
String param = element.getName();
String value = element.getValue();
if (value != null && param.equalsIgnoreCase("timeout")) {
if (value != null && param.equalsIgnoreCase(HttpHeaders.TIMEOUT)) {
return TimeValue.ofSeconds(Long.parseLong(value));
}
}
Expand All @@ -88,6 +89,9 @@ RestTemplate restTemplate(

return restTemplateBuilder
.setConnectTimeout(Duration.ofSeconds(60))
.defaultHeader(
org.springframework.http.HttpHeaders.CONTENT_TYPE,
MediaType.APPLICATION_JSON_VALUE)
.requestFactory(() -> new HttpComponentsClientHttpRequestFactory(httpClient))
.interceptors(
((request, body, execution) -> {
Expand All @@ -110,9 +114,9 @@ Runnable idleConnectionMonitor(PoolingHttpClientConnectionManager pool) {
public void run() {
// only if connection pool is initialised
if (pool != null) {
log.info("cleaning connection pool");
pool.closeExpired();
pool.closeIdle(TimeValue.ofSeconds(IDLE_CONNECTION_WAIT_TIME));
log.info("Idle connection monitor: Closing expired and idle connections");
}
}
};
Expand Down
32 changes: 16 additions & 16 deletions httpClients/boot-restclient/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.2.3</version>
<version>3.3.0-M2</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example.restclient</groupId>
Expand All @@ -18,21 +18,21 @@
<java.version>21</java.version>
<springdoc-openapi.version>2.3.0</springdoc-openapi.version>
<spotless.version>2.43.0</spotless.version>
</properties>

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.glassfish.jaxb</groupId>
<artifactId>jaxb-runtime</artifactId>
<scope>provided</scope>
</properties>

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.glassfish.jaxb</groupId>
<artifactId>jaxb-runtime</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,14 +1,45 @@
package com.example.restclient.bootrestclient.config;

import java.net.http.HttpClient;
import java.time.Duration;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.client.JdkClientHttpRequestFactory;
import org.springframework.web.client.RestClient;
import org.springframework.web.util.DefaultUriBuilderFactory;

@Configuration(proxyBeanMethods = false)
@Slf4j
public class RestClientConfiguration {

@Bean
RestClient webClient(RestClient.Builder builder) {
return builder.baseUrl("https://jsonplaceholder.typicode.com").build();
RestClient restClient(RestClient.Builder builder, HttpClient jdkClient) {
String baseUrl = "https://jsonplaceholder.typicode.com";
DefaultUriBuilderFactory factory = new DefaultUriBuilderFactory(baseUrl);
return builder.uriBuilderFactory(factory)
.defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.requestFactory(new JdkClientHttpRequestFactory(jdkClient))
.requestInterceptor(
(request, body, execution) -> {
// log the http request
log.info("URI: {}", request.getURI());
log.info("HTTP Method: {}", request.getMethod().name());
log.info("HTTP Headers: {}", request.getHeaders());

return execution.execute(request, body);
})
.build();
}

@Bean
HttpClient jdkClient() {
return HttpClient.newBuilder()
.version(HttpClient.Version.HTTP_2)
.connectTimeout(Duration.ofSeconds(30))
.followRedirects(HttpClient.Redirect.NORMAL)
.build();
}
}
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
package com.example.restclient.bootrestclient.exception;

import lombok.Getter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatusCode;

@Getter
public class MyCustomRuntimeException extends RuntimeException {
private final HttpStatusCode statusCode;
private final HttpHeaders headers;
Expand All @@ -11,12 +13,4 @@ public MyCustomRuntimeException(HttpStatusCode statusCode, HttpHeaders headers)
this.statusCode = statusCode;
this.headers = headers;
}

public HttpStatusCode getStatusCode() {
return statusCode;
}

public HttpHeaders getHeaders() {
return headers;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -71,11 +71,11 @@ public Optional<PostDto> updatePostById(Long id, PostDto postDto) {
.body(PostDto.class));
}

public PostDto deletePostById(Long id) {
public String deletePostById(Long id) {
return restClient
.delete()
.uri(uriBuilder -> uriBuilder.path("/posts/{postId}").build(id))
.retrieve()
.body(PostDto.class);
.body(String.class);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ public ResponseEntity<PostDto> updatePost(@PathVariable Long id, @RequestBody Po
}

@DeleteMapping("/{id}")
public ResponseEntity<PostDto> deletePost(@PathVariable Long id) {
public ResponseEntity<String> deletePost(@PathVariable Long id) {
return postService
.findPostById(id)
.map(postDto -> ResponseEntity.ok(postService.deletePostById(id)))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -151,12 +151,9 @@ void shouldDeletePost() throws Exception {
Long postId = 1L;
PostDto post = new PostDto(1L, postId, "Some text", "First Body");
given(postService.findPostById(postId)).willReturn(Optional.of(post));
given(postService.deletePostById(post.id())).willReturn(post);
given(postService.deletePostById(post.id())).willReturn("");

this.mockMvc
.perform(delete("/api/posts/{id}", post.id()))
.andExpect(status().isOk())
.andExpect(jsonPath("$.title", is(post.title())));
this.mockMvc.perform(delete("/api/posts/{id}", post.id())).andExpect(status().isOk());
}

@Test
Expand Down

0 comments on commit e4533ae

Please sign in to comment.