您的位置:首页 > 编程语言 > Java开发

06.Spring Cloud OpenFeign:基于 Ribbon 和 Hystrix 的声明式服务调用

2020-01-11 18:11 1306 查看

Spring Cloud OpenFeign:基于 Ribbon 和 Hystrix 的声明式服务调用

Spring Cloud OpenFeign 是声明式的服务调用工具,它整合了 Ribbon 和 Hystrix,拥有负载均衡和服务容错功能,本文将对其用法进行详细介绍。

1.Feign 简介

Feign 是声明式的服务调用工具,我们只需创建一个接口并用注解的方式来配置它,就可以实现对某个服务接口的调用,简化了直接使用 RestTemplate 来调用服务接口的开发量。Feign 具备可插拔的注解支持,同时支持 Feign 注解、JAX-RS 注解及 SpringMvc 注解。当使用 Feign 时,Spring Cloud 集成了 Ribbon 和 Eureka 以提供负载均衡的服务调用及基于 Hystrix 的服务容错保护功能。

2.创建一个 feign-service 模块

这里我们创建一个 feign-service 模块来演示 feign 的常用功能。

2.1 在 pom.xml 中添加相关依赖

<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

2.2 在 application.yml 中进行配置

server:
port: 8701
spring:
application:
name: feign-service
eureka:
client:
register-with-eureka: true
fetch-registry: true
service-url:
defaultZone: http://localhost:8001/eureka/

2.3 在启动类上添加@EnableFeignClients 注解来启用 Feign 的客户端功能

@EnableFeignClients
@EnableDiscoveryClient
@SpringBootApplication
public class FeignServiceApplication {

public static void main(String[] args) {
SpringApplication.run(FeignServiceApplication.class, args);
}

}

2.4 添加 UserService 接口完成对 user-service 服务的接口绑定

我们通过@FeignClient 注解实现了一个 Feign 客户端,其中的 value 为 user-service 表示这是对 user-service 服务的接口调用客户端。我们可以回想下 user-service 中的 UserController,只需将其改为接口,保留原来的 SpringMvc 注释即可。

@FeignClient(value = "user-service")
public interface UserService {
@PostMapping("/user/create")
CommonResult create(@RequestBody User user);

@GetMapping("/user/{id}")
CommonResult<User> getUser(@PathVariable Long id);

@GetMapping("/user/getByUsername")
CommonResult<User> getByUsername(@RequestParam String username);

@PostMapping("/user/update")
CommonResult update(@RequestBody User user);

@PostMapping("/user/delete/{id}")
CommonResult delete(@PathVariable Long id);
}

2.5 添加 UserFeignController 调用 UserService 实现服务调用

@RestController
@RequestMapping("/user")
public class UserFeignController {
@Autowired
private UserService userService;

@GetMapping("/{id}")
public CommonResult getUser(@PathVariable Long id) {
return userService.getUser(id);
}

@GetMapping("/getByUsername")
public CommonResult getByUsername(@RequestParam String username) {
return userService.getByUsername(username);
}

@PostMapping("/create")
public CommonResult create(@RequestBody User user) {
return userService.create(user);
}

@PostMapping("/update")
public CommonResult update(@RequestBody User user) {
return userService.update(user);
}

@PostMapping("/delete/{id}")
public CommonResult delete(@PathVariable Long id) {
return userService.delete(id);
}
}

3.负载均衡功能演示

3.1 启动 eureka-service,两个 user-service,feign-service 服务,启动后注册中心显示如下:

3.2 多次调用http://localhost:8701/user/1进行测试,可以发现运行在 8201 和 8202 的 user-service 服务交替打印如下信息:

2019-11-02 13:08:48.998 INFO 10680 — [nio-8201-exec-3] c.allan.cloud.controller.UserController : 根据id获取用户信息,用户名称为:yanglin
2019-11-02 13:08:53.277 INFO 10680 — [nio-8201-exec-7] c.allan.cloud.controller.UserController : 根据id获取用户信息,用户名称为:yanglin
2019-11-02 13:09:15.519 INFO 10680 — [nio-8201-exec-9] c.allan.cloud.controller.UserController : 根据id获取用户信息,用户名称为:yanglin
2019-11-02 13:09:16.073 INFO 10680 — [nio-8201-exec-4] c.allan.cloud.controller.UserController : 根据id获取用户信息,用户名称为:yanglin
2019-11-02 13:09:16.627 INFO 10680 — [nio-8201-exec-8] c.allan.cloud.controller.UserController : 根据id获取用户信息,用户名称为:yanglin

4.Feign 中的服务降级

Feign 中的服务降级使用起来非常方便,只需要为 Feign 客户端定义的接口添加一个服务降级处理的实现类即可,下面我们为 UserService 接口添加一个服务降级实现类。

4.1 添加服务降级实现类 UserFallbackService

需要注意的是它实现了 UserService 接口,并且对接口中的每个实现方法进行了服务降级逻辑的实现。

@Component
public class UserFallbackService implements UserService {
@Override
public CommonResult create(User user) {
User defaultUser = new User(-1L, "defaultUser", "123456");
return new CommonResult<>(defaultUser);
}

@Override
public CommonResult<User> getUser(Long id) {
User defaultUser = new User(-1L, "defaultUser", "123456");
return new CommonResult<>(defaultUser);
}

@Override
public CommonResult<User> getByUsername(String username) {
User defaultUser = new User(-1L, "defaultUser", "123456");
return new CommonResult<>(defaultUser);
}

@Override
public CommonResult update(User user) {
return new CommonResult("调用失败,服务被降级",500);
}

@Override
public CommonResult delete(Long id) {
return new CommonResult("调用失败,服务被降级",500);
}
}

4.2 修改 UserService 接口,设置服务降级处理类为 UserFallbackService

修改@FeignClient 注解中的参数,设置 fallback 为 UserFallbackService.class 即可。

@FeignClient(value = "user-service",fallback = UserFallbackService.class)
public interface UserService {
}

4.3 修改 application.yml,开启 Hystrix 功能

feign:
hystrix:
enabled: true #在Feign中开启Hystrix

5.服务降级功能演示

5.1 关闭两个 user-service 服务,重新启动 feign-service;

5.2 调用http://localhost:8701/user/1进行测试,可以发现返回了服务降级信息。

6.日志打印功能

Feign 提供了日志打印功能,我们可以通过配置来调整日志级别,从而了解 Feign 中 Http 请求的细节。

6.1 日志级别

  • NONE:默认的,不显示任何日志;

  • BASIC:仅记录请求方法、URL、响应状态码及执行时间;

  • HEADERS:除了 BASIC 中定义的信息之外,还有请求和响应的头信息;

  • FULL:除了 HEADERS 中定义的信息之外,还有请求和响应的正文及元数据。

6.2 通过配置开启更为详细的日志

我们通过 java 配置来使 Feign 打印最详细的 Http 请求日志信息。

@Configuration
public class FeignConfig {
@Bean
Logger.Level feignLoggerLevel() {
return Logger.Level.FULL;
}
}

6.3 在 application.yml 中配置需要开启日志的 Feign 客户端

配置 UserService 的日志级别为 debug。

logging:
level:
com.allan.cloud.service.UserService: debug

6.4 查看日志

调用http://localhost:8701/user/1进行测试,可以看到以下日志。

2019-11-02 13:14:15.741 DEBUG 24240 — [user-service-10] com.allan.cloud.service.UserService : [UserService#getUser] —> GET http://user-service/user/1 HTTP/1.1
2019-11-02 13:14:15.742 DEBUG 24240 — [user-service-10] com.allan.cloud.service.UserService : [UserService#getUser] —> END HTTP (0-byte body)
2019-11-02 13:14:16.760 DEBUG 24240 — [user-service-10] com.allan.cloud.service.UserService : [UserService#getUser] <— HTTP/1.1 200 (1018ms)
2019-11-02 13:14:16.760 DEBUG 24240 — [user-service-10] com.allan.cloud.service.UserService : [UserService#getUser] content-type: application/json;charset=UTF-8
2019-11-02 13:14:16.761 DEBUG 24240 — [user-service-10] com.allan.cloud.service.UserService : [UserService#getUser] date: Sat, 02 Nov 2019 05:14:16 GMT
2019-11-02 13:14:16.761 DEBUG 24240 — [user-service-10] com.allan.cloud.service.UserService : [UserService#getUser] transfer-encoding: chunked
2019-11-02 13:14:16.761 DEBUG 24240 — [user-service-10] com.allan.cloud.service.UserService : [UserService#getUser]
2019-11-02 13:14:16.766 DEBUG 24240 — [user-service-10] com.allan.cloud.service.UserService : [UserService#getUser] {“data”:{“id”:1,“username”:“yanglin”,“password”:“123456”},“message”:“操作成功”,“code”:200}
2019-11-02 13:14:16.766 DEBUG 24240 — [user-service-10] com.allan.cloud.service.UserService : [UserService#getUser] <— END HTTP (94-byte body)

7.Feign 的常用配置

7.1 Feign 自己的配置。

feign:
hystrix:
enabled: true #在Feign中开启Hystrixcompression:
request:
enabled: false #是否对请求进行GZIP压缩
mime-types: text/xml,application/xml,application/json #指定压缩的请求数据类型
min-request-size: 2048 #超过该大小的请求会被压缩
response:
enabled: false #是否对响应进行GZIP压缩
logging:
level: #修改日志级别
com.allan.cloud.service.UserService: debug

7.2 Feign 中的 Ribbon 配置

在 Feign 中配置 Ribbon 可以直接使用 Ribbon 的配置,具体可以参考Spring Cloud Ribbon:负载均衡的服务调用

7.3 Feign 中的 Hystrix 配置

在 Feign 中配置 Hystrix 可以直接使用 Hystrix 的配置,具体可以参考Spring Cloud Hystrix:服务容错保护

8.使用到的模块

Spring-Cloud-Greenwich
├── eureka-server – eureka注册中心
├── user-service – 提供User对象CRUD接口的服务
└── feign-service – feign服务调用测试服务

9.项目源码地址

https://github.com/yanglin1501804006/spring-cloud-vGreenwich.SR3

  • 点赞
  • 收藏
  • 分享
  • 文章举报
站内首发文章 Spring的思念 发布了37 篇原创文章 · 获赞 2 · 访问量 1609 私信 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: