Wednesday, May 25, 2022

Spring Data VS Spring Reactive Data

 With JPA 2.2, you no longer need to use converter it added support for the mapping of the following java.time types:


CrudRepository VS ReactiveCrudRepository

PagingAndSortingRepository VS  ReactiveSortingRepository

Flux<Person> findByLastname(Mono<String> lastname);
// insert

this.repository.save(product)
              .subscribe(p -> System.out.println("After inserting : " + p));


spring-boot-starter-data-r2dbc



@EnableTransactionManagement

@EnableJpaRepositories(basePackages = "com.baeldung.spring.data.persistence.repository")


 @Transactional annotation at the class level, which is then overridden for tRhe non-read-only methods.


Exception translation is still enabled by the use of the @Repository annotation on the DAO. This annotation enables a Spring bean postprocessor to advise all @Repository beans with all the PersistenceExceptionTranslator instances found in the container, and provide exception translation just as before.

java.time.LocalDate
java.time.LocalTime
java.time.LocalDateTime
java.time.OffsetTime
java.time.OffsetDateTime
@Column(columnDefinition = "DATE")
private LocalDate date;
@Column(columnDefinition = "TIMESTAMP")
private LocalDateTime dateTime;
@Column(columnDefinition = "TIME")
private LocalTime localTime;


@GenerateValue
@GenericGenerator

@CreationTimestamp
@UpdateTimestamp

@Entity

Logging in Microservices : Spring Boot

LEVEL

application.properties
logging.level.org.springframework=DEBUG
logging.level.com.howtodoinjava=DEBUG
 
#output to a temp_folder/file
logging.file=${java.io.tmpdir}/application.log
 
# Logging pattern for the console
logging.pattern.console= %d{yyyy-MM-dd HH:mm:ss} - %msg%n

TRACEID


ELK:



Http Client: RestTemplate, Java11-HttpClient, Apache-HttpClient, WebClient

 HTTPClient replaces the legacy HttpUrlConnection class present in the JDK since the early versions of Java.

Some of its features include:

  1. Support for HTTP/1.1, HTTP/2, and Web Socket.
  2. Support for synchronous and asynchronous programming models.
  3. Handling of request and response bodies as reactive streams.
  4. Support for cookies.
Use of HttpClient is preferred if our application is built using Java 11 and above.

sendAsync VS send


Apache HttpClient


Spring WebClient is an asynchronous, reactive HTTP client introduced in Spring 5 in the Spring WebFlux project to replace the older RestTemplate for making REST API calls in applications built with the Spring Boot framework. It supports synchronous, asynchronous, and streaming scenarios.


If you call Block- then it became synchronous. 

Spring WebClient is the preferred choice for Spring Boot applications more importantly if we are using reactive APIs.

WebClient client = WebClient.create();

  client
  .get()
  .uri(URLConstants.URL)
  .header(URLConstants.API_KEY_NAME, URLConstants.API_KEY_VALUE)
  .retrieve()
  .bodyToMono(String.class)
  .subscribe(result->System.out.println(result));


WebClient client = WebClient.create();

    String result = client
            .post()
            .uri("https://reqbin.com/echo/post/json")
            .body(BodyInserters.fromValue(prepareRequest()))
            .exchange()
            .flatMap(response -> response.bodyToMono(String.class))
            .block();
    System.out.println("result::" + result);




CloseableHttpAsyncClient client = 
      HttpAsyncClients.createDefault();) {
   client.start();
    
    final SimpleHttpRequest request = 

CloseableHttpClient httpClient = HttpClients.createDefault();
      
      CloseableHttpResponse response = httpClient.execute(httpPost)


HttpClient client = HttpClient.newBuilder()
      .version(Version.HTTP_2)
      .followRedirects(Redirect.NORMAL)
      .build();
  
  HttpRequest request = HttpRequest.newBuilder()
     .uri(new URI(URLConstants.URL))
     .GET()
     .header(URLConstants.API_KEY_NAME, URLConstants.API_KEY_VALUE)
     .timeout(Duration.ofSeconds(10))
     .build();
  
  
  client.sendAsync(request, BodyHandlers.ofString())
    .thenApply(HttpResponse::body)
    .thenAccept(System.out::println)
    .join();

Tuesday, May 24, 2022

Simple REST API using Spring Webflux, WebClient and Junit

 Dear Java Developers,

we will look into an sample REST API created using Spring Boot, Spring Webflux (Reactive) and integrated with another API using Webclient. 

Also we will add unit test cases to test Controller, Service and Webclient classes. 


OrderService - Receives inputs and checks inventory and create order.

InventoryService checks and confirms products available in inventory. Secured with JWT Token. 


@ResponseStatus



Thursday, August 5, 2021

Spring and Kafka : KafkaListenerEndpointRegistry and MessageListenerContainer

 Hi All,

Section 1: 

The message queues exist for long time and we have been using this for last 15 years. We have used Active MQ, JBoss MQ, Tomcat with Active MQ, JBoss MQ (HornetQ) and WebSphere MQ.

We have been using them a standalone MQ server or server provided MQs like WebSphereMQ and JBOSS MQ.

Now for the last 5 years we have started using RabbitMQ and Kafka which replaced all the above one.

Lets look into them in detail.

Section 2: 

2.1 Sample code for Spring Reactive Kafka Producer and Listener

2.2 Sample code for KafkaListenerEndpointRegistry and MessageListenerContainer



Rabbit MQ: VS Kafka

 

  Rabbit MQ

  Kafka

 Support for Distributed MQ

 

 

 Scalable

 

 

 Support Languages

 

 

 Publisher