16 Şubat 2023 Perşembe

SpringCloud Retrofit Kullanımı

Giriş
Refrofit kütüphanesi OpenFeign yerine tercih edilebilir

Gradle
Şöyle yaparız
implementation ‘org.springframework.cloud:spring-cloud-square-retrofit:0.4.1’
implementation ‘org.springframework.cloud:spring-cloud-square-okhttp:0.4.1’
Örnek
Şöyle yaparız
@EnableRetrofitClients(basePackages = "com.oguzderici.retrofitdemo.clients")
@Configuration
public class RetrofitConfiguration {

  @Bean
  @LoadBalanced
  public OkHttpClient.Builder okHttpClientBuilder() {
    return new OkHttpClient.Builder()
      .addInterceptor(new HttpLoggingInterceptor()
                        .setLevel(HttpLoggingInterceptor.Level.BASIC));
    }
}
Arayüzler için şöyle yaparız
@RetrofitClient(name = "welcome-service", configuration = AuthenticationConfig.class)
public interface WelcomeRetrofitClient {
  @GET("/v1/whoiam")
  Call<WelcomeResponse> callName(@Query("name") String name);

  @POST("/v1/welcome")
  Call<WelcomeResponse> callSuccess(@Body WelcomeRequest welcomeRequest);

  @PUT("/v1/welcome/{id}")
  Call<WelcomeResponse> callWithFail(@Path("id") String id,
     @Body WelcomeRequest welcomeRequest);

  @DELETE("/v1/welcome/{id}")
  Call<Void> deleteWelcomeRequest(@Path("id") String id);
}

@RequiredArgsConstructor
@Configuration
public class AuthenticationConfig {
  private final TokenInterceptor tokenInterceptor;
  private final AuthenticatorInterceptor authenticatorInterceptor;
  private final HeaderInterceptor headerInterceptor;

  @Bean
  @LoadBalanced
  public OkHttpClient.Builder okHttpClientBuilder() {
    return new OkHttpClient.Builder()
      .addInterceptor(tokenInterceptor)
      .addInterceptor(headerInterceptor)
      .authenticator(authenticatorInterceptor);
  }
}



Hiç yorum yok:

Yorum Gönder