本项目的笔记和资料的Download,请点击这一句话自行获取。html
day01-springboot(理论篇) ;day01-springboot(实践篇)git
day02-springcloud(理论篇一) ;day02-springcloud(理论篇二) ;day02-springcloud(理论篇三) ;day02-springcloud(理论篇四) ;github
day03-springcloud(Hystix,Feign) ;day03-springcloud(Zuul网关)
spring
Hystix,即熔断器。json
主页:https://github.com/Netflix/Hystrix/springboot
Hystix是一个延迟和容错库,用于隔离访问远程服务、第三方库,防止出现级联失败。mybatis
正常工做的状况下,客户端请求调用服务API接口:app
当有服务出现异常时,直接进行失败回滚,服务降级处理: 负载均衡
当服务繁忙时,若是服务出现异常,不是粗暴的直接报错,而是返回一个友好的提示,虽然拒绝了用户的访问,可是会返回一个结果。dom
这就比如去买鱼,日常超市买鱼会额外赠送杀鱼的服务。等到逢年过节,超时繁忙时,可能就不提供杀鱼服务了,这就是服务的降级。
系统特别繁忙时,一些次要服务暂时中断,优先保证主要服务的畅通,一切资源优先让给主要服务来使用,在双11、618时,京东天猫都会采用这样的策略。
首先在user-consumer中引入Hystix依赖:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
咱们改造user-consumer,添加一个用来访问的user服务的DAO,而且声明一个失败时的回滚处理函数:
@Component public class UserDao { @Autowired private RestTemplate restTemplate; private static final Logger logger = LoggerFactory.getLogger(UserDao.class); @HystrixCommand(fallbackMethod = "queryUserByIdFallback") public User queryUserById(Long id){ long begin = System.currentTimeMillis(); String url = "http://user-service/user/" + id; User user = this.restTemplate.getForObject(url, User.class); long end = System.currentTimeMillis(); // 记录访问用时: logger.info("访问用时:{}", end - begin); return user; } public User queryUserByIdFallback(Long id){ User user = new User(); user.setId(id); user.setName("用户信息查询出现异常!"); return user; } }
@HystrixCommand(fallbackMethod="queryUserByIdFallback")
:声明一个失败回滚处理函数queryUserByIdFallback,当queryUserById执行超时(默认是1000毫秒),就会执行fallback函数,返回错误提示。在原来的业务逻辑中调用这个DAO:
@Service public class UserService { @Autowired private UserDao userDao; public List<User> queryUserByIds(List<Long> ids) { List<User> users = new ArrayList<>(); ids.forEach(id -> { // 咱们测试屡次查询, users.add(this.userDao.queryUserById(id)); }); return users; } }
改造服务提供者,随机休眠一段时间,以触发熔断:
@Service public class UserService { @Autowired private UserMapper userMapper; public User queryById(Long id) throws InterruptedException { // 为了演示超时现象,咱们在这里然线程休眠,时间随机 0~2000毫秒 Thread.sleep(new Random().nextInt(2000)); return this.userMapper.selectByPrimaryKey(id); } }
而后运行并查看日志:
id为九、十、11的访问时间分别是:
id为12的访问时间:
所以,只有12是正常访问,其它都会触发熔断,咱们来查看结果:
虽然熔断实现了,可是咱们的重试机制彷佛没有生效,是这样吗?
其实这里是由于咱们的Ribbon超时时间设置的是1000ms:
而Hystix的超时时间默认也是1000ms,所以重试机制没有被触发,而是先触发了熔断。
因此,Ribbon的超时时间必定要小于Hystix的超时时间。
咱们能够经过hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds
来设置Hystrix超时时间。
hystrix: command: default: execution: isolation: thread: timeoutInMillisecond: 6000 # 设置hystrix的超时时间为6000ms
在前面的学习中,咱们使用了Ribbon的负载均衡功能,大大简化了远程调用时的代码:
String baseUrl = "http://user-service/user/"; User user = this.restTemplate.getForObject(baseUrl + id, User.class)
若是就学到这里,你可能之后须要编写相似的大量重复代码,格式基本相同,无非参数不同。有没有更优雅的方式,来对这些代码再次优化呢?
这就是咱们接下来要学的Feign的功能了。
有道词典的英文解释:
为何叫假装?
Feign能够把Rest的请求进行隐藏,假装成相似SpringMVC的Controller同样。你不用再本身拼接url,拼接参数等等操做,一切都交给Feign去作。
项目主页:https://github.com/OpenFeign/feign
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency>
@FeignClient("user-service") public interface UserFeignClient { @GetMapping("/user/{id}") User queryUserById(@PathVariable("id") Long id); }
@FeignClient
,声明这是一个Feign客户端,相似@Mapper
注解。同时经过value
属性指定服务名称改造原来的调用逻辑,再也不调用UserDao:
@Service public class UserService { @Autowired private UserFeignClient userFeignClient; public List<User> queryUserByIds(List<Long> ids) { List<User> users = new ArrayList<>(); ids.forEach(id -> { // 咱们测试屡次查询, users.add(this.userFeignClient.queryUserById(id)); }); return users; } }
咱们在启动类上,添加注解,开启Feign功能
@SpringBootApplication @EnableDiscoveryClient @EnableHystrix @EnableFeignClients // 开启Feign功能 public class UserConsumerDemoApplication { public static void main(String[] args) { SpringApplication.run(UserConsumerDemoApplication.class, args); } }
访问接口:
Feign中自己已经集成了Ribbon依赖和自动配置:
所以咱们不须要额外引入依赖,也不须要再注册RestTemplate
对象。
另外,咱们能够像上节课中讲的那样去配置Ribbon,能够经过ribbon.xx
来进行全局配置。也能够经过服务名.ribbon.xx
来对指定服务配置:
user-service: ribbon: ConnectTimeout: 250 # 链接超时时间(ms) ReadTimeout: 1000 # 通讯超时时间(ms) OkToRetryOnAllOperations: true # 是否对全部操做重试 MaxAutoRetriesNextServer: 1 # 同一服务不一样实例的重试次数 MaxAutoRetries: 1 # 同一实例的重试次数
Feign默认也有对Hystix的集成:
只不过,默认状况下是关闭的。咱们须要经过下面的参数来开启:
feign: hystrix: enabled: true # 开启Feign的熔断功能
可是,Feign中的Fallback配置不像Ribbon中那样简单了。
1)首先,咱们要定义一个类,实现刚才编写的UserFeignClient(接口),做为fallback的处理类。
@Component public class UserFeignClientFallback implements UserFeignClient { @Override public User queryUserById(Long id) { User user = new User(); user.setId(id); user.setName("用户查询出现异常!"); return user; } }
2)而后在UserFeignClient中,指定刚才编写的实现类
@FeignClient(value = "user-service", fallback = UserFeignClientFallback.class) public interface UserFeignClient { @GetMapping("/user/{id}") User queryUserById(@PathVariable("id") Long id); }
3)重启测试:
咱们关闭user-service服务,而后在页面访问:
Spring Cloud Feign 支持对请求和响应进行GZIP压缩,以减小通讯过程当中的性能损耗。经过下面的参数便可开启请求与响应的压缩功能:
feign: compression: request: enabled: true # 开启请求压缩 response: enabled: true # 开启响应压缩
同时,咱们也能够对请求的数据类型,以及触发压缩的大小下限进行设置:
feign: compression: request: enabled: true # 开启请求压缩 mime-types: text/html,application/xml,application/json # 设置压缩的数据类型 min-request-size: 2048 # 设置触发压缩的大小下限
注:上面的数据类型、压缩大小下限均为默认值。
前面讲过,经过logging.level.xx=debug
来设置日志级别。然而这个对Fegin客户端而言不会产生效果。由于@FeignClient
注解修改的客户端在被代理时,都会建立一个新的Fegin.Logger实例。咱们须要额外指定这个日志的级别才能够。
1)设置com.leyou包下的日志级别都为debug
logging: level: com.leyou: debug
2)编写配置类,定义日志级别
@Configuration public class FeignConfig { @Bean Logger.Level feignLoggerLevel(){ return Logger.Level.FULL; } }
这里指定的Level级别是FULL,Feign支持4种级别:
3)在FeignClient中指定配置类:
@FeignClient(value = "user-service", fallback = UserFeignClientFallback.class, configuration = FeignConfig.class) public interface UserFeignClient { @GetMapping("/user/{id}") User queryUserById(@PathVariable("id") Long id); }
4)重启项目,便可看到每次访问的日志:
=============================================
参考资料:
Spring Cloud升级最新Finchley版本的全部坑
end