27 Şubat 2023 Pazartesi

SpringMVC @GetExchange Anotasyonu - OpenFeign Yerine Kullanılır

Giriş
Şu satırı dahil ederiz
import org.springframework.web.service.annotation.GetExchange;
Açıklaması şöyle
Why do you need Spring Reactive Web dependencies
When creating the project above, the dependency of Spring Reactive Web was introduced, and the WebClient type was used when creating the service object of the proxy. This is because HTTP Interface currently only has built-in implementation of WebClient, which belongs to the category of Reactive Web. Spring will launch a RestTemplate-based implementation in subsequent versions.
Örnek
Şöyle yaparız
interface UsersClient {
@GetExchange("/users") User findByFirstName(@RequestParam("firstName") String firstName); }
Örnek
Elimizde şöyle bir REST kodu olsun
public class User implements Serializable {
  ...
}

@GetMapping("/users")
public List<User> list() {
    return IntStream.rangeClosed(1, 10)
            .mapToObj(i -> new User(i, "User" + i))
            .collect(Collectors.toList());
}
Şöyle yaparız
public interface UserApiService {
   @GetExchange("/users")
   List<User> getUsers();
}

@Test
void getUsers() {
   WebClient client = WebClient.builder()
    .baseUrl("http://localhost:8080/")
    .build();

  HttpServiceProxyFactory factory = HttpServiceProxyFactory
    .builder(WebClientAdapter.forClient(client))
    .build();

   UserApiService service = factory.createClient(UserApiService.class);
   List<User> users = service.getUsers();
   for (User user : users) {
      System.out.println(user);
   }
}

Hiç yorum yok:

Yorum Gönder