As you can see, all we did was replace the @HystrixCommand annotation with @SentinelResource. Thevalueattribute labels the method we would like to apply to the circuit breaker. And thefallbackattribute points out the fallbackMethod function. Then. we add thefallbackfunction reliable(). The function does the same as in the example.

So far, it has been pretty close to what Hystrix is doing. However, as mentioned in the previous article, Hystrix dictates the circuit breaker behavior. Once you point out the resource, the condition to trigger the circuit breaker is taken care of.

Sentinel, on the other hand, gives that control to the user, which means that the user has to create a rule to define that condition. Let’s do that and add the rule. It can be appended to the end of the file.

We just created a DegradeRule, setting the mode to be exception ratio, the threshold to 0.5 (1 out of 2), and the recovery time to 10 seconds. The DegradeRuleManagerwill load this rule to take effect.

Let’s try it out: We only start the Reading Service but not the Bookstore service. So, every time a request comes in, it will fail. After two attempts (and two failures), we shall see the fallback function kick in:

Cloud Native Java (O'Reilly)

Now, let’s start the Bookstore service. After 10 seconds, we shall see the normal response:

In a production environment, it is actually easier to use the Sentienl dashboard to configure this rule than adding the rule via code. Here is a screenshot:

Wait, There's More

So far, we’ve looked at the same feature as Hystrix has performed. And actually, Sentinel needs one more step. But here is the justification: users can achieve more with that flexibility. Now, let's see an example.

Sentinel allows rules to be based on different metrics. In this example, we are using QPS.

We added a @SentinelResource, but instead of the fallbackfunction, we use theblockHandler function. This function will simply print out a message showing “Sentinel in Action.” Now, we need to add a new rule when this function will be triggered:

However, if we generate more than 1 request in one second, we shall see the blockHandler function kick in:

Sentinel in Action

And after 1 second, we can see the normal response again.

Again, in a real production environment, users can use the dashboard to configure and monitor the traffic.

Summary

Sentinel aims to provide users with multiple options to control the flow into their services. By doing so, it requires users to define the rules via GUI or code. Other than QPS, users can control the number of threads, or even create a white list for access control. With the growing complexity of distributed services, this model will better serve the user’s requirements.