Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Spring Cloud Alibaba Sentinel's Integration With Feign

DZone 's Guide to

Spring Cloud Alibaba Sentinel's Integration With Feign

Let's explore Spring Cloud Alibaba Sentinel's integration with Feign.

· Integration Zone ·
Free Resource


@FeignClient(name = "service-provider")
public interface EchoService {
  @RequestMapping(value = "/echo/{str}", method = RequestMethod.GET)
  String echo(@PathVariable("str") String str);
}

What Is Sentinel

Sentinel is an open source circuit breaker. It can be part of Spring Cloud Alibaba or as an individual package.

What Is Feign

Feign is a Java to HTTP client binder. It’s aiming to simplify the REST API process.

Feign emphasizes on the definition of the interfaces. There is 1:1 mapping between the methods in an interface to a REST API. This is vastly different from HttpClient or OkHttp.

How Does Feign work

First, we need to use @EnableFeignClients to turn on the features

@SpringBootApplication
@EnableFeignClients 
public class MyApplication {
  ...
}

Then we use @FeignClient to generate a proxy class

Once that’s done, it will be injected into ApplicationContext and can be auto wired to use.

How to Use Feign Client

Before that let’s dig deeper of the proxy class by looking at the sequence diagram of registering a Feign client:

Image title

Here is some explanation of the chart:

 @FeignClient  annotated interface will be translated into a  FactoryBean named  FeignClientFactoryBean, within which the  getObject()  method will eventually return a Proxy.

During the generation of Proxy, it has to utilize the information from  org.springframework.cloud.openfeign.Targeter  interface. It will also invoke  feign.Feign.Builder  to build an instance of feign.Feign.

Once the feign.Feign instance is created, the  newInstance() method will return a Proxy.

Let’s keep looking at the code on the newInstance() part:

public <T> T newInstance(Target<T> target) {
    Map<String, MethodHandler> nameToHandler = targetToHandlersByName.apply(target);
    Map<Method, MethodHandler> methodToHandler = new LinkedHashMap<Method, MethodHandler>();
    List<DefaultMethodHandler> defaultMethodHandlers = new LinkedList<DefaultMethodHandler>();

    for (Method method : target.type().getMethods()) {
      if (method.getDeclaringClass() == Object.class) {
        continue;
      } else if(Util.isDefault(method)) {
        DefaultMethodHandler handler = new DefaultMethodHandler(method);
        defaultMethodHandlers.add(handler);
        methodToHandler.put(method, handler);
      } else {
        methodToHandler.put(method, nameToHandler.get(Feign.configKey(target.type(), method)));
      }
    }

    InvocationHandler handler = factory.create(target, methodToHandler);

    T proxy = (T) Proxy.newProxyInstance(target.type().getClassLoader(), new Class<?>[]{target.type()}, handler);

    for(DefaultMethodHandler defaultMethodHandler : defaultMethodHandlers) {
      defaultMethodHandler.bindTo(proxy);
    }
    return proxy;
  }

In this part of the code, InvocationHandlerFactory is the most important piece to remember.

Integrate Sentinel With Feign

A word of caution is that there are package-level interfaces. These interfaces are not accessible from outside the package, which means we shall not change that.

If you look carefully at the sequence diagram, you might notice Hystrix in the process. Yes, Hystrix and Feign are closely tied. Sentinel plays a similar role as Hystrix. One major difference is it’s still under active development.

spring-cloud-starter-openfeign has a dependency on feign-hystrix. As a result, the default  InvocationHandlerFactory  in the previous code snippet will return a HystrixInvocationHandler. And that’s where we are changing. We implemented SentinelInvocationHandler to swap out the Hystrix logic and inject Sentinel’s version.

Here is an example with Sentinel and Feign:

@FeignClient(name = "test-service")
public interface TestService {
  @RequestMapping(value = "/echo/{str}", method = RequestMethod.GET)
  String echo(@PathVariable("str") String str);

  @RequestMapping(value = "/divide", method = RequestMethod.GET)
  String divide(@RequestParam("a") Integer a, @RequestParam("b") Integer b);
}

Users won't notice the changes behind the scene.

Summary

Feign provides flexibility to RESTful APIs in Spring Cloud, and it’s getting popular. As a good RESTful solution, it also provides circuit breaker integration. Sentinel is now integrated with Feign and can provide the same functionalities as Hystrix does.

Topics:
spring cloud ,feign client ,sentinel ,tutorial ,integration ,alibaba ,rest api process

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}