一、OpenFeign简介

1、什么是OpenFeign

OpenFeign目前是Spring Cloud 二级子项目。平时说的Feign指的是Netflix下的Feign,现在我们学习的是OpenFeign,是Spring提供的。
OpenFeign是一种声明式、模板化的HTTP客户端(仅在Application Client中使用)(称OpenFeign作用:声明式服务调用)。声明式调用是指,就像调用本地方法一样调用远程方法,无需感知操作远程http请求。学习完OpenFeign后可以不使用RestTemplate进行调用。
Spring Cloud的声明式调用, 可以做到使用 HTTP请求远程服务时能就像调用本地方法一样的体验,开发者完全感知不到这是远程方法,更感知不到这是个HTTP请求。Feign的应用,让Spring Cloud微服务中Application Client直接通过接口方法调用Application Service,而不需要通过常规的RestTemplate构造请求再解析返回数据。它解决了让开发者调用远程接口就跟调用本地方法一样,无需关注与远程的交互细节,更无需关注分布式环境开发。
使用OpenFeign时就好像在写控制器方法,OpenFeign都是写在接口中,在声明的方法上添加SpringMVC注解或声明的参数上添加SpringMVC注解就可以完成调用远程的控制器方法。

2、使用OpenFeign时程序执行流程

OpenFeign代替之前的RestTemplate代码。也是写在Application Client中。把OpenFeign接口单独放在feign包中,表示服务调用层。当需要调用其他服务时,直接注入OpenFeign接口对象就可以像调用本地方法一样调用远程服务。
整体流程说明:
1. ApplicationService 向Eureka Server 注册服务。
2. Application Client从Eureka Server中发现服务信息。
3. 在Application Client中调用OpenFeign接口中方法
4. Application Client中OpenFeign通过应用程序名调用Application Service
image.png

二、第一个OpenFeign项目

前提:
保证有Eureka Server (以单机版举例,端口为8761)

1、Application Service

新建一个项目名称任意。(示例中叫做applicationservice)

1.1 添加依赖

新建项目后,在pom.xml中添加依赖
添加了Spring Boot和Spring Cloud版本声明。
添加了web环境和eureka client依赖

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-web</artifactId>
  4. </dependency>
  5. <dependency>
  6. <groupId>org.springframework.cloud</groupId>
  7. <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
  8. </dependency>
  9. <dependency>
  10. <groupId>org.springframework.boot</groupId>
  11. <artifactId>spring-boot-starter-test</artifactId>
  12. <scope>test</scope>
  13. </dependency>

1.2 编写配置文件

在resources下新建application.yml.

  1. spring:
  2. application:
  3. name: applicationservice
  4. eureka:
  5. client:
  6. service-url:
  7. defaultZone: http://localhost:8888/eureka/
  8. server:
  9. port: 8081

1.3 编写控制器

@RestController
public class MyController {

    @RequestMapping("/demo01")
      public   String  demo01(){
          return "bjsxt111";
      }

    @RequestMapping("/demo02")
    public   String  demo02(String name,String pwd){
        System.out.println(name+"--"+pwd);
        return "bjsxt";
    }

    @RequestMapping("/demo03")
    public   String  demo03(@RequestBody User user){
        System.out.println(user);
        return "bjsxt";
    }

    @RequestMapping("/demo04/{name}/{pwd}")
    public   String  demo04(@PathVariable String name,@PathVariable String pwd){
        System.out.println(name+"--"+pwd);
        return "bjsxt";
    }

    @PostMapping("/selectAll")
    public List<User>  selectAll(){
          List<User>  list=new ArrayList<>();
          list.add(new User("zs","123"));
          list.add(new User("lisi","123"));
          list.add(new User("sxt","123"));

          return list;
    }

    @RequestMapping("/selectMore")
    public List<String> selectMore(@RequestBody List<Integer> id){
        List<String> list = new ArrayList<>();
        for (Integer s : id) {
            list.add("sxt:"+s);
        }
        return list;
    }

    @RequestMapping("/selectA")
    public  List<String>  selectA(@RequestBody List<String> list){
        System.out.println(list);
        List<String>  list1=new ArrayList<>();

        for (String s:list) {
            list1.add(s+"查询数据");
        }
        return list1;
    }

}

1.4编写启动类

@SpringBootApplication
@EnableEurekaClient
public class EurekaApplicationserverApplication {

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

}

1.5 启动项目

2 、Application Client项目(参数传递方式)

新建项目,名称任意(示例中叫做applicationclient)

2.1 添加依赖

比application service项目多了openfeign的依赖

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <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-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

2.2 新建配置文件

新建application.yml

spring:
  application:
    name: clientopenfeign
eureka:
  client:
    service-url:
      defaultZone: http://localhost:8888/eureka/
server:
  port: 9998

2.3 新建OpenFeign接口

OpenFeign接口命名:
调用应用程序+Feign
新建了com.bjsxt.feign.OpenFeignApplication
注意:
@FeignClient 参数要写调用的Application Service的应用程序名
@RequestMapping中值要和需要调用的控制器方法URL相同
方法返回值要和调用控制器方法返回值相同。
方法名称随意,没有要求。

//eureka中applicationService中名称 这个时候openFeign会根据内置负载均衡策略(Ribbon)选出一个地址
@FeignClient("APPLICATIONSERVICE")
public interface OpenFeignApplication {

    //@RequestMapping("/demo01") 必须和applicationservice中控制单元地址保持一致
    //方法返回值和调用指定方法返回值必须一致
    //方法名称随意定义  建议:一般也和applicationservice中方法名称保持一致
    @RequestMapping("/demo01")
    String abc();

    //如果我们想要传递普通表单数据这个必须加上@RequestParam
    //如果不加@RequestParam 就会认为当前传递的数据是请求体数据
    //因为一次请求中只可以有一个请求体数据,所以再参数中绝对不会出现两个及其以上参数不加注解情况

    //如果当前接口中形参名称和applicationservice控制单元中参数名称不一致必须使用@RequestParam("zs")起别名
    // http:192.168.8.129:8081/demo02?zs=sxt&pwd=123
    @RequestMapping("/demo02")
    String demo02(@RequestParam("zs") String name,@RequestParam("pwd") String pwd);


    //User如果不加注解 代表的是传递的请求体数据@RequestBody这个注解可以省略
    //但是再applicationservice控制单元接收的时候必须加上@RequestBody
    @RequestMapping("/demo03")
    String demo03(@RequestBody User us);

    //如果我们使用Rest风格进行传递 必须加上@PathVariable
    //http:192.168.8.129:8081/demo04/bsxt/123
    @RequestMapping("/demo04/{name}/{pwd}")
    String  demo04(@PathVariable("name") String name,@PathVariable("pwd") String pwd);

    //返回集合 直接接收即可 无须处理
    @PostMapping("/selectAll")
    List<User>  selectAll();

}

2.4 新建service及实现类

新建com.bjsxt.service.ClientService及实现类。
在实现类中直接注入OpenFeign接口对象即可。没有在启动类上添加@EnableFeignClients时此处可能会报编译错误。

public interface UserService {
    String  save();
}
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private OpenFeignApplication openFeign;

    @Override
    public String save() {
        //String abc = openFeign.abc();
        //String abc = openFeign.demo02("sxt", "123");

        User  user=new User("zs","123");
        //String abc = openFeign.demo03(user);

        //String abc = openFeign.demo04("bjsxt", "123");

        List<User> list = openFeign.selectAll();
        for (User user1:list) {
            System.out.println(user1);
        }

        return "ok";
    }
}

2.5 新建控制器

新建com.bjsxt.controller.UserController

@RestController
public class UserController {
    @Autowired
    private UserService userService;
    @RequestMapping("/save")
    public  String   save(){
        return userService.save();
    }

}

2.6 新建启动类

@SpringBootApplication
//开启openfeign的服务
@EnableFeignClients
public class EurekaApplicationclientopenfeignApplication {

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

2.7 测试结果

在浏览器中输入http://localhost:9998/save

三、OpenFeign通讯优化

1、GZIP简介

  • gzip介绍:gzip是一种数据格式,采用用deflate算法压缩数据;gzip是一种流行的数据压缩算法,应用十分广泛,尤其是在Linux平台。
  • gzip能力:当Gzip压缩到一个纯文本数据时,效果是非常明显的,大约可以减少70%以上的数据大小。
  • gzip作用:网络数据经过压缩后实际上降低了网络传输的字节数,最明显的好处就是可以加快网页加载的速度。网页加载速度加快的好处不言而喻,除了节省流量,改善用户的浏览体验外,另一个潜在的好处是Gzip与搜索引擎的抓取工具有着更好的关系。例如 Google就可以通过直接读取gzip文件来比普通手工抓取更快地检索网页。

    2 、HTTP协议中关于压缩传输的规定(原理)

  • 第一:客户端向服务器请求头中带有:Accept-Encoding:gzip, deflate 字段,向服务器表示,客户端支持的压缩格式(gzip或者deflate),如果不发送该消息头,服务器是不会压缩的。

  • 第二:服务端在收到请求之后,如果发现请求头中含有Accept-Encoding字段,并且支持该类型的压缩,就对响应报文压缩之后返回给客户端,并且携带Content-Encoding:gzip消息头,表示响应报文是根据该格式压缩过的。
  • 第三:客户端接收到响应之后,先判断是否有Content-Encoding消息头,如果有,按该格式解压报文。否则按正常报文处理。

    3 、在OpenFeign技术中应用GZIP压缩

    在Spring Cloud微服务体系中,一次请求的完整流程如下:
    在整体流程中,如果使用GZIP压缩来传输数据,涉及到两次请求-应答。而这两次请求-应答的连接点是Application Client,那么我们需要在Application Client中配置开启GZIP压缩,来实现压缩数据传输。

    4 、只配置OpenFeign请求-应答的GZIP压缩

    在交互数据量级不够的时候,看不到压缩内容。
    这里只开启Feign请求-应答过程中的GZIP,也就是浏览器-Application Client之间的请求应答不开启GZIP压缩。
    在全局配置文件中,使用下述配置来实现OpenFeign请求-应答的GZIP压缩
# feign gzip
# 开启请求GZIP
feign.compression.request.enabled=true
# 开启响应GZIP
feign.compression.response.enabled=true
# 设置支持GZIP压缩的MIME类型,即请求/响应类型。
feign.compression.request.mime-types=text/html,application/xml,application/json
# 配置启动压缩数据的最小阀值,单位字节。默认为2048
feign.compression.request.min-request-size=512