1.Ribbon, Feign related presentations
ribbon is load balancing processor, ribbon is a component part of springcloud when we microService to pull the communication list through the registry, you can access other micro server through the communication address, but if other micro servers do cluster, then there a plurality of micro-services, which we in the end micro-services access it, if all went to visit a micro-service, then the service will be accessed micro because too many threads that might access the server and explosion, while other servers but idle, so this is we need to load balancer to help us deal with these requests, help us a reasonable allocation of these requests, ribbon is this role, ribbon default is polling request processing, as well as others such as random, consistent hashing, weighted manner requested distribution.
feign also load balancing processor is based on the ribbon, Ribbon is a tool based load balancing HTTP and TCP clients.
It can be configured in the client RibbonServerList (server list), or using HttpClient RestTemplate analog http request, steps, is rather cumbersome.
The Feign
Feign is an improvement on the basis of the Ribbon, it is more convenient to use a HTTP client.
By way of an interface, only you need to create an interface, then you can add annotations above, the method will need to call other services is defined as abstract methods, do not need to build their own http request.
Then call the method itself works like a calling, and feel is to call a remote method, the client makes writing very easy.
Step 2. The code implementation ribbon
1. Import dependence
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-ribbon</artifactId> </dependency>
2. Notes @LoadBalanced marked on the return restTemplate the bean's method, the annotation gives the ability to have load balancing restTemplate
@Configuration public class {BeanConfig / ** after * @LoadBalanced hit the notes will have a ribbon restTemplate load balancing capabilities * @return * / @Bean @LoadBalanced public RestTemplate restTemplate () { return new new RestTemplate (); } }
Modify the controller call the method of
@GetMapping("/order/{id}") public JsonResult queryById(@PathVariable Long id){ //使用restTemplate发送http协议 String url = "http://user-client/userclient/user/"+id; User user = template.getForObject(url, User.class); JsonResult jsonResult = new JsonResult(); jsonResult.setData(user); return jsonResult; }
Step 3. The code for feign
1. Import dependence
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency>
2. Write feign interface
/ ** * Write feign interface user-client, registration centers registered application name * / @FeignClient (value = "the User-Client" ) public interface UserFeignClient { / ** * @PathVariable ( "the above mentioned id") there must be written "id" otherwise, the injection can not UserFeignClient * @param ID * @return * / userclient / User / {ID}, the server path resources need to call server * / @GetMapping ( "/ userclient / User / {ID}" ) queryById the User (@PathVariable ( "ID" ) Long ID); }
3. Open the main configuration class feign @ EnableFeignClients ( "cn.learn.springcloud.feignclient")
/** * @EnableFeignClients("cn.learn.springcloud.feignclient")主配置类开启fenign */ @SpringBootApplication @EnableFeignClients("cn.learn.springcloud.feignclient") public class OrderClientApplication { public static void main(String[] args) { SpringApplication.run(OrderClientApplication.class); } }
4.controller injection layer interface to invoke a method
@RestController @RequestMapping("/orderclient") public class UserController { @Autowired private UserFeignClient userFeignClient; @GetMapping("/order/{id}") public User queryById(@PathVariable Long id){ //调用feign的接口的方法 User user = userFeignClient.queryById(id); return user; } }
3.Hystrix related presentations
hystrix is a framework used for fusing mechanism, but also belong to the components springcloud when our poor service to access other services through micro registry when the service if other micro-hang, not to visit, it will cause the avalanche effect, causing paralysis of other servers, such a paralysis caused by the phenomenon of micro-services paralysis of the other services we call it micro avalanche effect, in order to solve this problem springcloud introduced the fuse mechanism hystrix help us solve this problem, when a server hangs after, if you want to access the server is hang up, do not have access to, we return to a normal friendly tips, tell the micro service, this server is out of order, like when to hang up this server is isolated, then no It can cause paralysis of the server you want to access, and to ensure that a server hang up, the other server uptime.
3.1 Integration in the ribbon hystrix
1. Import dependence
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-hystrix</artifactId> </dependency>
2. The primary fuse mechanism open configuration class @EnableCircuitBreaker
/** * @EnableCircuitBreaker开启熔断机制 */ @SpringBootApplication @EnableCircuitBreaker public class OrderClientApplication { public static void main(String[] args) { SpringApplication.run(OrderClientApplication.class); } }
3. Return to jsonResult way a friendly hint, if there is no access to data services, we return to drag the bottom of the method returns the results, playing notes on methods @HystrixCommand (fallbackMethod = "getUserByIdFallback" )
Note: The parameters underpinning method and returns the result to the original and consistent method
@RestController @RequestMapping ( "/ OrderClient" ) public class the UserController { @Autowired Private RestTemplate Template; / ** * @HystrixCommand (fallbackMethod = "getUserByIdFallback"), bottom drag methods tab marked * @param ID * @return * / @HystrixCommand (fallbackMethod = "getUserByIdFallback" ) @GetMapping ( "/ Order / {ID}" ) public a JsonResult queryById (Long @PathVariable ID) { // use http protocol to transmit restTemplate String url = "http: // userclient / userclient / user / "+ID; the User User = template.getForObject (URL, the User. class ); a JsonResult JsonResult = new new a JsonResult (); jsonResult.setData (User); return JsonResult; } / ** * downgrade method, if no access to the user-client drag bottom data return method * / public a JsonResult getUserByIdFallback (Long @PathVariable ID) { a JsonResult JsonResult = new new a JsonResult (); jsonResult.setSuccess ( to false ); jsonResult.setMsg ( "I'm sorry server system is busy, please try again later" ); jsonResult.setData ( null ); return jsonResult; } }
3.2 integrated hystrix in feign in
1. Import dependence
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-hystrix</artifactId> </dependency>
2. Modify feign client interface @FeignClient (value = "user-client", fallback = UserFeignClientFallback.class), fallback = UserFeignClientFallback.class a rear access failure
Method Invocation UserFeignClientFallback this class return information friendship
3. Write UserFeignClientFallback, achieve feign interface, the interface method feign override (drag the bottom to achieve)
@Component public class UserFeignClientFallback the implements UserFeignClient { @Override public the User queryById (Long ID) { return new new the User (-1L, "I'm sorry, the server is not available", 0 ); } }
4.yml configuration file to enable fusing mechanism, feign fuse mechanism is disabled by default
ureka:
Client:
serviceUrl:
defaultzone: HTTP: // peer0: 1000 / Eureka /, HTTP: // peer1: 1001 / Eureka /
instance:
the prefer-ip-address: # define to true ip to the registry registration
instance-id: order -client: 2001
Server:
Port: 2001
the Spring:
the Application:
name: the Order-Client-2001
Feign:
hystrix:
Enabled: blown open support to true #