4.SpringCloud 声明式服务调用-OpenFeign

OpenFeign

OpenFeign 全称 Spring Cloud OpenFeign,它是 Spring 官方推出的一种声明式服务调用与负载均衡组件,对 Ribbon 进行了集成,利用 Ribbon 维护了可用服务清单,并通过 Ribbon 实现了客户端的负载均衡。它的出现就是为了替代进入停更维护状态的 Feign。

OpenFeign 是 Spring Cloud 对 Feign 的二次封装,它具有 Feign 的所有功能,并在 Feign 的基础上增加了对 Spring MVC 注解的支持,例如 @RequestMapping、@GetMapping 和 @PostMapping 等。

  • @FeignClient 用于通知 OpenFeign 组件对 @RequestMapping 注解下的接口进行解析,并通过动态代理的方式产生实现类,实现负载均衡和服务调用。
  • @EnableFeignClients 用于开启 OpenFeign 功能,当 Spring Cloud 应用启动时,OpenFeign 会扫描标有 @FeignClient 注解的接口,生成代理并注册到 Spring 容器中。
  • @RequestMapping Spring MVC 注解,在 Spring MVC 中使用该注解映射请求。
  • @GetMapping Spring MVC 注解,用来映射 GET 请求。
  • @PostMapping Spring MVC 注解,用来映射 POST 请求 。

OpenFeign 基础示例

1.新建一个 Spring Boot 模块,创建时选择Web、Eureka Client、OpenFeign 依赖。

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--Eureka Client 依赖-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<!--OpenFeign 依赖-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>

2.在 application.properties 中进行配置,使项目注册到 Eureka 上:

spring.application.name=openfeign
server.port=4000
eureka.client.service-url.defaultZone=http://localhost:1111/eureka

3.在启动类上添加 @EnableFeignClients 注解,开启OpenFeign 功能:

@SpringBootApplication
@EnableFeignClients
public class OpenfeignApplication {
    public static void main(String[] args) {
        SpringApplication.run(OpenfeignApplication.class, args);
   }
}

4.在provider中使用 @FeignClient 定义接口:

@FeignClient("provider")
public interface HelloService {
    
    @GetMapping("/hello")
    String hello();//这里的方法名无所谓,随意取
}

5.在consumer中调用接口进行访问:

@RestController
public class HelloController {
    @Autowired
    HelloService helloService;
    @GetMapping("/hello")
    public String hello() {
        return helloService.hello();
   }
}

在浏览器中输入 localhost:4000/hello即可访问到 /hello接口。

OpenFeign 参数传递

和普通参数传递的区别:

  1. 参数一定要绑定参数名。
  2. 如果通过 header 来传递参数,中文必须要转码。

测试的服务端接口,继续使用 provider 提供的接口。另外,在 openfeign 中添加调用接口:

@FeignClient("provider")
public interface HelloService {

    @GetMapping("/hello")
    String hello();

    @GetMapping("/hello2")
    String hello2(@RequestParam("name") String name);

    @PostMapping("/user2")
    User addUser(@RequestBody User user);

    @DeleteMapping("/user2/{id}")
    void deleteUserById(@PathVariable("id") Integer id);

    @GetMapping("/user3")
    void getUserByName(@RequestHeader("name") String name);
}

在consumer中调用接口进行访问:

@GetMapping("/hello")
public String hello() throws UnsupportedEncodingException {
    String s = helloService.hello2("张三");
    System.out.println(s);
    User user = new User();
    user.setId(1);
    user.setUsername("zhangsan");
    user.setPassword("zhangsan");
    User u = helloService.addUser(user);
    System.out.println(u);
    helloService.deleteUserById(1);
    helloService.getUserByName(URLEncoder.encode("张三", "UTF-8"));
    return helloService.hello();
}

OpenFeign 继承特性

继承特性优缺点:

  • 代码简洁明了不易出错。服务端和消费端的代码统一。
  • 会提高服务端和消费端的耦合度。

将 provider 和 openfeign 中公共的部分提取出来,使用继承的方式。

创建maven项目,openfeign-common,添加web依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <version>2.2.4.RELEASE</version>
</dependency>

定义公共接口:

public interface IUserService {
    @GetMapping("/hello")
    String hello();

    @GetMapping("/hello2")
    String hello2(@RequestParam("name") String name);

    @PostMapping("/user2")
    User addUser(@RequestBody User user);

    @DeleteMapping("/user2/{id}")
    void deleteUserById(@PathVariable("id") Integer id);

    @GetMapping("/user3")
    void getUserByName(@RequestHeader("name") String name);
}

公共接口定义完成后,接下来,在 provider 和 openfeign 中,分别引用该模块,并分别实现接口:

<dependency>
    <groupId>com.example</groupId>
    <artifactId>openfeign-common</artifactId>
    <version>1.0-SNAPSHOT</version>
</dependency>

在 provider 中实现该接口:

@RestController
public class HelloController implements IUserService {
    @Value("${server.port}")
    Integer port;

    @Override
    public String hello() {
        return "hello javaboy:" + port;
    }

    @Override
    public String hello2(String name) {
        System.out.println(new Date() + ">>>" + name);
        return "hello " + name;
    }

    @PostMapping("/user1")
    public User addUser1(User user) {
        return user;
    }

    @Override
    public User addUser2(@RequestBody User user) {
        return user;
    }

    @PutMapping("/user1")
    public void updateUser1(User user) {
        System.out.println(user);
    }

    @PutMapping("/user2")
    public void updateUser2(@RequestBody User user) {
        System.out.println(user);
    }

    @DeleteMapping("/user1")
    public void deleteUser1(Integer id) {
        System.out.println(id);
    }

    @Override
    public void deleteUser2(@PathVariable Integer id) {
        System.out.println(id);
    }

    @Override
    public void getUserByName(@RequestHeader String name) throws UnsupportedEncodingException {
        System.out.println(URLDecoder.decode(name, "UTF-8"));
    }
}

在 openfeign 中,定义接口继承自公共接口:

@FeignClient("provider")
public interface HelloService extends IUserService {
}

OpenFeign 日志记录

OpenFeign 中,我们可以通过配置日志,来查看整个请求的调用过程。日志级别一共分为四种:

  • NONE:不开启日志,默认
  • BASIC:记录请求方法、URL、响应状态码、执行时间
  • HEADERS:在 BASIC 的基础上,加载请求/响应头
  • FULL:在 HEADERS 基础上,再增加 body 以及请求元数据

四种级别,可以通过 Bean 来配置:

@SpringBootApplication
@EnableFeignClients //开启OpenFeign 功能
public class OpenfeignApplication {

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

	// 配置日志记录级别
    @Bean
    Logger.Level loggerLevel() {
        return Logger.Level.FULL;
    }
}

在 application.properties 中开启日志级别:

logging.level.com.example.openfeign.HelloService=debug

OpenFeign 数据压缩

# 开启请求的数据压缩
feign.compression.request.enabled=true
# 开启响应的数据压缩
feign.compression.response.enabled=true
# 压缩的数据类型
feign.compression.request.mime-types=text/html,application/json
# 压缩的数据下限,2048 表示当要传输的数据大于 2048 时,才会进行数据压缩
feign.compression.request.min-request-size=2048

OpenFeign 服务降级

Hystrix 中的容错、服务降级等功能,在 OpenFeign 中一样使用。

1.在application.properties 中开启 Hystrix功能:

# 开启 Hystrix功能
feign.hystrix.enabled=true

2.定义服务降级的方法:

@Component
@RequestMapping("/serviceDegradation")// 添加映射路径,防止请求地址重复
public class HelloServiceFallback implements HelloService {
    @Override
    public String hello() {
        return "error";
    }

    @Override
    public String hello2(String name) {
        return "error2";
    }

    @Override
    public User addUser2(User user) {
        return null;
    }

    @Override
    public void deleteUser2(Integer id) {

    }

    @Override
    public void getUserByName(String name) throws UnsupportedEncodingException {

    }
}

3.在 provider 中配置这个服务降级类:

@FeignClient(value = "provider",fallback = HelloServiceFallback.class)
public interface HelloService extends IUserService {
}

参考文章:http://itboyhub.com/2021/01/31/spring-cloud-openfeign/

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值