Circuit Breaker is a circuit in the protection of the safety of the switch, when the circuit has a short circuit, the circuit breaker will automatically trip, to prevent the occurrence of circuit failure.
A micro-service architecture system also requires this protection device, when the consumer calls a service, such as the current service has an exception, such as the service has been suspended, this time a circuit breaker to the current call to disconnect the service, Spring cloud integrated circuit breaker components are: Hystrix. , Hystrix can be rolled back or degraded in the event of a service failure, such as fast failure, silent failure, returning default values, assembling a return value by itself, taking advantage of a fallback type such as remote cache, primary and secondary fallback, and so on.
Downgrade fallback related information: Www.jianshu.com/p/3e11ac385c73?from=timeline
For example, call User Services in the above chapter, first implement the Java-side porting to. NET Core
1. Service call Set breaker Java version
Official document search circuit breaker in spring Cloud: Circuit breaker
Reference: Http://cloud.spring.io/spring-cloud-static/Finchley.SR1/single/spring-cloud.html#_circuit_breaker_hystrix_clients
Examples of official documents:
1.1 Adding circuit breaker dependencies
A circuit breaker is added when the consumer calls, first adding hystrix dependency on the OrderService
< Dependency > < groupId >org.springframework.cloud</groupId> < Artifactid>spring-cloud-starter-netflix-hystrix</artifactid ></dependency>
Add @enablecircuitbreaker annotations on the startup class to enable Hystrix
1.2 Specifying the call failed return method
method to add a fallback error to each method of calling the service class UserService and specify the fallback method using the @hystrixcommand annotation
@Service Public classUserService {@AutowiredPrivateresttemplate resttemplate; PrivateString serviceurl= "Http://userservice/user"; @HystrixCommand (Fallbackmethod= "Getallerror") PublicList<user>GetAll () {parameterizedtypereference<List<User>> Responsetype =NewParameterizedtypereference<list<user>>(){}; Responseentity<List<User>> resp = resttemplate.exchange (serviceurl+ "/getall", Httpmethod.get,NULL, Responsetype); List<User> list =Resp.getbody (); returnlist; } @HystrixCommand (Fallbackmethod= "Getporterror") Publicstring Getport () {string msg= Resttemplate.getforobject (serviceurl+ "/getport", String.class); returnmsg; } Publicuser Getbyname (String name) {User User= Resttemplate.getforobject (serviceurl+ "/getbyname?name=" +name, User.class); returnuser; } //GetAll Fallback Method PublicList<user>Getallerror () {return NULL; } //Getport Fallback Method PublicString Getporterror () {return"UserService service disconnected, Getport method call Error!"; }}
Stop the UserService service, call the order service to get the port method, entered the wrong method, indicating that the fallback method has been successfully set.
The call succeeds after the service is started.
1.3 Setting the time-out period
If the call has entered the fallback method, it is possible that the Hystrix has not set the timeout time, the configuration under the time-out.
Hystrix: command: default: execution: timeout: enabled:true Isolation: thread: timeoutinmilliseconds:10000 #设置超时时间 10 seconds
2. Service call set circuit breaker. NET Core Edition
2.1 Adding a circuit breaker reference
First add the Steeltoe.CircuitBreaker.HystrixCore reference in the OrderService project
2.2 Creating the command class to specify the return method
Inheriting hystrixcommand<string> on the call User Service UserService class
Official document: http://steeltoe.io/docs/steeltoe-circuitbreaker/#1 -2-8-use-commands
The. NET core version of the problem is that it is not possible to add attributes directly on the service's methods to declare the method to be rolled back, but each method uses a generic method that inherits from Hystrixcommand<>, and the generic type is the type returned by the method. Then call the method of this class, the Java version directly with the annotations or a lot more convenient.
Examples of Steeltoeoss can be consulted: github.com/steeltoeoss/samples/tree/dev/circuitbreaker/src/aspdotnetcore/fortuneteller/ Fortune-teller-ui/services
The two command classes correspond to the two methods within the service.
The command class is named after the name of the service (minus the Services) + method name +command, which makes it easy to determine which method to invoke, such as getting all the user's classes: Usergetallcommand.
usingSystem.Collections.Generic;usingSystem.Threading.Tasks;usingSteeltoe.CircuitBreaker.Hystrix;namespaceorderservice.controllers{ Public classUsergetallcommand:hystrixcommand<list<user>> { PrivateIuserservice _userservice; PublicUsergetallcommand (ihystrixcommandoptions options,iuserservice userservice):Base(options) {_userservice=UserService; isfallbackuserdefined=true; } Public AsyncTask<list<user>>GetAll () {return awaitExecuteasync (); } protected Override AsyncTask<list<user>>RunAsync () {varresult =await_userservice.getall (); returnresult; } /// <summary> ///Fallback Method/// </summary> /// <returns></returns> protected Override AsyncTask<list<user>>Runfallbackasync () {return NULL; } }}
Again, create a Getport command class, and then Configureservices in the startup class to configure the injection of the Hystrixcommand class
// Register the command class for circuit breakers using the Hystrixcommand class encapsulation UserService method Services. Addhystrixcommand<usergetallcommand> ("userservice", Configuration); Services. Addhystrixcommand<UsergetPortCommand> ("userservice", Configuration );
Instead, use the command class to invoke the UserService method in Ordercontroller.
[Route ("[Controller]")] [Apicontroller] Public classOrdercontroller:controllerbase {Private ReadOnlyIuserservice _userservice; Private ReadOnlyUsergetallcommand _usergetallcommand; Private ReadOnlyUsergetportcommand _usergetportcommand; //constructing methods to inject instances PublicOrdercontroller (Iuserservice userservice, Usergetallcommand Usergetallcommand, Usergetportcomma nd usergetportcommand) {_userservice=UserService; _usergetallcommand=Usergetallcommand; _usergetportcommand=Usergetportcommand; } [Route ("Getalluser")] [HttpGet] Public AsyncTask<list<user>>GetAll () {//list<user> List = await _userservice.getall (); varList =await_usergetallcommand.getall (); returnlist; } [Route ("Getuserserviceport")] [HttpGet] Public Asynctask<string>Getuserserviceport () {//var port = await _userservice.getport (); varPort =await_usergetportcommand.getport (); returnPort; } }
Stop the UserService service and call the fallback method successfully.
The UserService service is started and then refreshed to obtain the data successfully.
2.3 Setting the time-out period
{ "Logging": { "LogLevel": { "Default": "Warning" } }, "Allowedhosts": "*", "Spring": { "Application": { "Name": "OrderService" } }, "Eureka": { "Client": { "serviceurl": "http://localhost:8881/eureka/", "Shouldregisterwitheureka":true, "Shouldfetchregistry":true }, "Instance": { "Port": 6660 } }, "Hystrix": { "Command": { "Default": { "Execution": { "Timeout": {"Enabled":true }, "Isolation": { "Thread": {"Timeoutinmilliseconds": 10000 } } } } } }}
This circuit breaker has been added.