kbastani/event-sourcing-microservices-example

Error when adding new friend relationship

Closed this issue · 1 comments

Adding a new friend relationship results in a null pointer exception without any detail provided. When a friend is added, the friend-service uses a load balanced WebClient, to make sure that the two users exist before a friend relationship can be made. The resulting error is due to the WebClient not being properly configured at startup.

@Bean
@LoadBalanced
public WebClient.Builder userWebClient() {
   return WebClient.builder();
}

To properly configure the reactive load balanced client to use the discovery service or service registry, the bean must not directly instantiate the WebClient, rather it must instantiate and replace the autoconfigured WebClient.Builder bean.

To make service-to-service reactive calls that use client-side load balancing, you would then need to inject the WebClient.Builder bean into your component class. See the example below.

@Service
public class UserClient {

   private final WebClient.Builder userWebClient;

   public UserClient(WebClient.Builder userWebClient) {
      this.userWebClient = userWebClient;
   }

   public Mono<User> getUser(Long userId) {

      Mono<User> user;

      try {
         // You must build the client using the service name in the registry
         user = userWebClient.baseUrl("http://user-service/").build().get()
               .uri("v1/users/{userId}", userId)
               .accept(MediaType.APPLICATION_JSON)
               .retrieve()
               .bodyToMono(User.class)
               .single()
               .log();
      } catch (Exception ex) {
         throw new RuntimeException("Could not retrieve user", ex);
      }

      return user;
   }
}