这篇文章主要讲解了“春云阿里巴巴使用假装+哨兵怎么完成熔断”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“春云阿里巴巴使用假装+哨兵怎么完成熔断”吧!
假装的使用
假装也是网飞开发的,SpringCloud使用假装非常简单,我下边演示一下:
首先服务消费者这边肯定需要一个对应的依赖:
编译(“org.springframework.cloud: spring-cloud-starter-openfeign")
需要启用假装的话,也得在启动类上面加个注解@EnableFeignClients
然后,创建一个假装的接口,像这样子
package com.skypyb.sc.feign; import com.skypyb.sc.entity.User; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @FeignClient (“sc-demo-microservice-user") public interface  UserFeignClient {=,@RequestMapping (value “/user/{id}“, method =, RequestMethod.GET) ,public User  getUser (@PathVariable (“id"), Long id); }
@FeignClient注解里边的默认属性,也就是名字属性是一个客户端的名字,如果使用了尤里卡的话,会给他自动解析为尤里卡服务器服务注册表中的服务。
要是配了丝带,也会使用默认的负载均衡策略来执行请求。
假装默认使用SpringMVC的注解声明请求,当然也可以用假装自带的注解。不过没啥必要,还需要配置东西。
,
我上边这个例子写完了,实际使用的话只需要注入该类然后调用对应的方法就完事了。非常简便。
package com.skypyb.sc.controller; import com.skypyb.sc.entity.User; import com.skypyb.sc.feign.UserFeignClient; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.client.ServiceInstance; import org.springframework.cloud.client.discovery.DiscoveryClient; import org.springframework.cloud.client.loadbalancer.LoadBalancerClient; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; import 并不知道; @RestController @RequestMapping (“/movie") public class  MovieController { ,private Logger Logger =, LoggerFactory.getLogger (MovieController.class); ,@ autowired ,private UserFeignClient  userFeignClient; ,@GetMapping (“/user/{id}“) ,public User  getUser (@PathVariable (“id"), Long id), { return 才能userFeignClient.getUser (id); ,} }
不过有几个点需要注意
在使用@FeignClient声明的假装伪装类中:
使用@PathVariable注解,必须加上参数。
得到请求无法使用对象作为入参!要不有多少参数写多少参数(每个都要加@RequestParam(“参数名”)注解),要不就用接受一个地图对象,也得加@RequestParam
文章请求可以接收对象,需要加上@RequestBody注解
,
,
假装论使用的话,其实已经差不多了。
但是还有一些相关的操作也比较重要。
,
假装的请求都是使用的默认配置,我们其实可以实现自己的配置供假装使用以实现编码,解码,日志记录,验证等等等等。
比如我可以这么定义一个配置类:
package com.skypyb.sc.config; import feign.Logger; import feign.auth.BasicAuthRequestInterceptor; import org.springframework.context.annotation.Bean; public class  FeignConfiguration { ,@ bean ,public Logger.Level  feignLog (), { return 才能;Logger.Level.FULL; ,}/* * *,才能使用指定的用户名和密码验证所有请求 *才能@return ,*/,@ bean ,public BasicAuthRequestInterceptor  basicAuthRequestInterceptor () { return 才能;new  BasicAuthRequestInterceptor (“user",“614“); ,} }
该类配置了对应的日志记录器,和一个简单的效验,以应对请求的验证。