DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Integrate Spring With Open AI
  • Enterprise RIA With Spring 3, Flex 4 and GraniteDS
  • Distributed Tracing System (Spring Cloud Sleuth + OpenZipkin)
  • 5 DevOps Tools To Add to Your Stack in 2022

Trending

  • Simplify Authorization in Ruby on Rails With the Power of Pundit Gem
  • Java's Quiet Revolution: Thriving in the Serverless Kubernetes Era
  • Comparing SaaS vs. PaaS for Kafka and Flink Data Streaming
  • Scalability 101: How to Build, Measure, and Improve It
  1. DZone
  2. Software Design and Architecture
  3. Cloud Architecture
  4. Spring Cloud Alibaba Sentinel's Integration With Feign

Spring Cloud Alibaba Sentinel's Integration With Feign

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

By 
Andy Shi user avatar
Andy Shi
·
Jul. 10, 19 · Tutorial
Likes (3)
Comment
Save
Tweet
Share
15.4K Views

Join the DZone community and get the full member experience.

Join For Free


@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.

Spring Cloud Integration Spring Framework

Opinions expressed by DZone contributors are their own.

Related

  • Integrate Spring With Open AI
  • Enterprise RIA With Spring 3, Flex 4 and GraniteDS
  • Distributed Tracing System (Spring Cloud Sleuth + OpenZipkin)
  • 5 DevOps Tools To Add to Your Stack in 2022

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!