Mastering Spring Cloud Square: A Modern Alternative to Feign for Service Calls

Spring Cloud Square, built on Retrofit and OkHttp, offers a lightweight replacement for Spring Cloud Feign, simplifying cross-service calls with declarative clients, load‑balancing support, and easy Maven integration, and this guide walks you through setup, configuration, and advanced usage examples.

macrozheng
macrozheng
macrozheng
Mastering Spring Cloud Square: A Modern Alternative to Feign for Service Calls

What is Spring Cloud Square

Spring Cloud Feign is widely known for hiding low‑level HTTP client details, but Spring Cloud Square replaces Feign by leveraging Retrofit to wrap the underlying communication libraries, providing a simpler way to make cross‑service calls.

The Spring Cloud Square project aims to replace the original Spring Cloud Feign, using Retrofit for underlying communication and is currently incubated in the spring‑cloud‑incubator repository.

Before understanding Spring Cloud Square, you need to know the following components:

OkHttp is a third‑party library that encapsulates HTTP GET, POST and other operations.

Retrofit is a RESTful HTTP client built on OkHttp; it uses annotations to configure network parameters and supports multiple data formats (Gson, JSON, XML) and RxJava.

Service calls based on Spring Cloud Square can be abstracted as shown:

Quick Start

Add Dependencies

Since spring‑cloud‑square is not officially released, configure the Spring Maven repository.

<repositories>
  <repository>
    <id>spring-milestones</id>
    <url>https://repo.spring.io/milestone</url>
  </repository>
</repositories>

Maven dependencies

<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-square-okhttp</artifactId>
  <version>${square.version}</version>
</dependency>
<dependency>
  <groupId>com.squareup.okhttp3</groupId>
  <artifactId>okhttp</artifactId>
  <version>${okhttp.version}</version>
</dependency>
<!-- Add load‑balancer support -->
<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-starter-loadbalancer</artifactId>
</dependency>

Configuration Code

@Bean
@LoadBalanced
public OkHttpClient.Builder okHttpClientBuilder() {
    return new OkHttpClient.Builder();
}

Calling Code

Similar to the original Ribbon call, very simple.

@Autowired
OkHttpClient.Builder builder;

@GetMapping
public String req() {
    Request request = new Request.Builder()
        .url("http://square-provider/req")
        .build();
    Response response = builder.build().newCall(request).execute();
    return response.body().string();
}

Advanced Usage

As a Feign replacement, Square also supports declarative clients.

Add Dependency

<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-square-retrofit</artifactId>
  <version>${square.version}</version>
</dependency>

Declare Client Interface

@RetrofitClient("square-provider")
public interface DemoService {
    @GET("/req")
    Call<String> req();
}

Enable Client Scanning

@EnableRetrofitClients

Calling Code

@Autowired
DemoService demoService;

@SneakyThrows
@GetMapping("/retrofit")
public String retrofit() {
    return demoService.req().execute().body();
}

Simplify with Custom CallAdapter

Retrofit can be extended to handle raw return types, removing the default Call wrapper.

/**
 * Processor for raw type returns, removing the default Call.
 */
@Configuration(proxyBeanMethods = false)
public class ApiCallAdapterFactory extends CallAdapter.Factory {
    @Override
    public CallAdapter<?, ?> get(@Nonnull Type returnType,
                                 @Nonnull Annotation[] annotations,
                                 @Nonnull Retrofit retrofit) {
        return new CallAdapter<>() {
            @Override
            public Type responseType() {
                return returnType;
            }
            @Override
            public Object adapt(@Nonnull Call<Object> call) {
                try {
                    return call.execute().body();
                } catch (IOException e) {
                    // custom fallback or rethrow
                    return null;
                }
            }
        };
    }
}

After adding the adapter, the client can be simplified to:

@RetrofitClient("square-provider")
public interface DemoService {
    @GET("/req")
    String req();
}
@Autowired
DemoService demoService;

@SneakyThrows
@GetMapping("/retrofit")
public String retrofit() {
    return demoService.req();
}

Summary

Because spring‑cloud‑square is built directly on Retrofit, its source code is very simple and worth reading.

The current version does not implement fallback functionality.

Source code is available at https://github.com/lltx/spring-cloud-square-demo

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

javaMicroservicesSpring CloudOkHttpRetrofitFeign alternative
macrozheng
Written by

macrozheng

Dedicated to Java tech sharing and dissecting top open-source projects. Topics include Spring Boot, Spring Cloud, Docker, Kubernetes and more. Author’s GitHub project “mall” has 50K+ stars.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.