spring boot集成open feign

spring boot集成open feign笔记

1.open feign介绍

SSpring Cloud Open Feign是一个声明式的Web Service客户端,它使得编写Web Service客户端变得更加简单。Open Feign整合了Feign,Ribbon和Hystrix。

  1. Feign:是一个声明式的Web Service客户端,让HTTP请求更加简单。通过创建一个接口并用注解来配置,它具有可插拔的注解特性,使用Feign能让HTTP API调用更加简单。Feign能通过创建接口并注解来将HTTP请求映射为方法调用,而无需自己构建HTTP请求。
  2. Ribbon:是Netflix发布的开源项目,主要功能是提供客户侧的软件负载均衡算法。Ribbon可以与Eureka、Consul等组件集成,也可以自定义实现负载均衡算法。
  3. Hystrix:是Netflix发布的容错管理框架,主要用于隔离访问远程系统、服务和第三方库的点,防止级联故障和提高容错能力。

2.集成open feign

2.1 添加依赖
 <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-openfeign</artifactId>
    </dependency>
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter</artifactId>
    </dependency>
</dependencies>

注意:本次项目集成demo 使用到的 spring cloud版本为:3.1.6. spring boot 的版本为2.7.12

2.2添加配置
1.eureka 配置

因为open feign 依赖于注册中心(本次用eureka作为注册中心),需要从注册中心获取各个服务的实际地址,因此也要加入eureka 配置

eureka:
  instance:
    lease-renewal-interval-in-seconds: 10
    #    hostname: localhost
    instance-id: ${spring.application.name}
    ip-address: localhost
  #    ip-address: 111.201.151.126
  server:
    # eureka 服务的端口
    port: 8613
    #服务端30s 定时清除操作
    eviction-interval-timer-in-ms: 30000
    enable-self-preservation: true
    sync-when-timestamp-differs: true
  client:
    service-url:
      defaultZone: http://1.15.134.32:${eureka.server.port}/eureka
    #    defaultZone: http://localhost:${eureka.server.port}/eureka
    #应用是否可以去拉取服务列表到本地
    fetch-registry: true
    # 自己是否注册服务到eureka
    register-with-eureka: true
    #间隔10秒去拉取,时间越短脏读越少,性能消耗大
    registry-fetch-interval-seconds: 30
    enabled: true
    eureka-server-read-timeout-seconds: 10
2.open feign 配置
feign:
  circuitbreaker:
    # Feign启用断路器,默认为FALSE
    enabled: true
  client:
    config:
      # 针对所有的服务
      default:
        # Feign的连接建立超时时间,默认为10秒
        connectTimeout: 5000
        # Feign的请求处理超时时间,默认为60秒
        readTimeout: 5000
        # 日志级别
        loggerLevel: full

        # 是否对404错误码解码
        # 处理逻辑详见feign.SynchronousMethodHandler#executeAndDecode
        decode404: false

  compression:
      request:
        # 开启Feign请求压缩,默认不开启
        enabled: true
        # 配置支持压缩的MIME TYPE,默认为:text/xml,application/xml,application/json
        mime-types: text/xml,application/xml,application/json
        # 触发请求数据压缩的最小Size,默认2048KB
        min-request-size: 2048
      response:
        # 开启Feign响应压缩,默认不开启
        enabled: true
        # 使用GZip解码器,默认不使用
        useGzipDecoder: false

注意:feign.circuitbreaker.enabled: true这个配置可能会因为用的版本不用有所差异

3.完整的配置文件
spring:
  application:
    name: auth
  # 服务端口配置
    # redis:
    #  host: 1.15.134.32
    # port: 6379
    # password: wz0515
    # timeout: 5000
      # jedis:
      #   pool:
      #    max-idle: 6    #最大空闲数
      #    max-active: 10 #最大连接数
      #   min-idle: 2
    #  max-wait: 1000
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3060/数据库名?useSSL=false&serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
    username: 账号
    password: 密码
    type: com.alibaba.druid.pool.DruidDataSource
    druid:
      # 连接池的配置信息
      # 初始化大小,最小,最大
      initial-size: 5
      min-idle: 5
      maxActive: 20
      # 配置获取连接等待超时的时间
      maxWait: 60000
      # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
      timeBetweenEvictionRunsMillis: 60000
      # 配置一个连接在池中最小生存的时间,单位是毫秒
      minEvictableIdleTimeMillis: 300000
      validationQuery: SELECT 1 FROM DUAL
      testWhileIdle: true
      testOnBorrow: false
      testOnReturn: false
      poolPreparedStatements: true
      maxPoolPreparedStatementPerConnectionSize: 20
      web-stat-filter:
        enabled: true
        url-pattern: "/*"  #监控哪些
        exclusions: "*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*"  #排除那些
      stat-view-servlet:
        url-pattern: "/druid/*"
        reset-enable: false
        # 登录名
        login-username: druid账号
        # 登录密码
        login-password: druid密码
  mvc:
    pathmatch:
      matching-strategy: ant_path_matcher

server:
  port: 服务端口
  servlet:
    context-path: /auth
  max-http-header-size: 2MB
  # erueka 配置

eureka:
  instance:
    lease-renewal-interval-in-seconds: 10
#    hostname: localhost
    instance-id: ${spring.application.name}
    ip-address: localhost
  #    ip-address: 111.201.151.126
  server:
    # eureka 服务的端口
    port: 8613
    #服务端30s 定时清除操作
    eviction-interval-timer-in-ms: 30000
    enable-self-preservation: true
    sync-when-timestamp-differs: true
  client:
    service-url:
       defaultZone: http://1.15.134.32:${eureka.server.port}/eureka
    #      defaultZone: http://localhost:${eureka.server.port}/eureka
    #应用是否可以去拉取服务列表到本地
    fetch-registry: true
    # 自己是否注册服务到eureka
    register-with-eureka: true
    #间隔10秒去拉取,时间越短脏读越少,性能消耗大
    registry-fetch-interval-seconds: 30
    enabled: true
    eureka-server-read-timeout-seconds: 10

    # loback 日志配置文件位置
#logging:
#  config: classpath:logback/logback.xml

swagger:
  basePackage: com.wz
  title: Swagger-${spring.application.name}接口
  url: http://${eureka.instance.hostname}:${server.port}${server.servlet.context-path}/swagger-ui.html
  email: 1270821038@qq.com
  name: wz
  swagger_version: 1.0
  description: SpringCloud项目Swagger:${spring.application.name}模块接口
mybatis-plus:
  mapper-locations: classpath:mapper/*.xml
  type-aliases-package: com.wz.${spring.application.name}.entity

  global-config:
    db-config:
      id-type: auto
      #表名前缀为tb_,表名为前缀拼接类名(小写)
      #table-prefix: tb_

  configuration:
    #类属性与表字段的驼峰映射,mybatiplus默认true开启,mybatis需要手动配置
    map-underscore-to-camel-case: false
    cache-enabled: false

feign:
  circuitbreaker:
    # Feign启用断路器,默认为FALSE
    enabled: true
  client:
    config:
      # 针对所有的服务
      default:
        # Feign的连接建立超时时间,默认为10秒
        connectTimeout: 5000
        # Feign的请求处理超时时间,默认为60秒
        readTimeout: 5000
        # 日志级别
        loggerLevel: full

        # 是否对404错误码解码
        # 处理逻辑详见feign.SynchronousMethodHandler#executeAndDecode
        decode404: false

  compression:
      request:
        # 开启Feign请求压缩,默认不开启
        enabled: true
        # 配置支持压缩的MIME TYPE,默认为:text/xml,application/xml,application/json
        mime-types: text/xml,application/xml,application/json
        # 触发请求数据压缩的最小Size,默认2048KB
        min-request-size: 2048
      response:
        # 开启Feign响应压缩,默认不开启
        enabled: true
        # 使用GZip解码器,默认不使用
        useGzipDecoder: false


2.3启动类

启动类要在该服务java包下,因为集成了eureka 需要添加 @EnableEurekaClient @EnableDiscoveryClient 这两个注解,一遍服务能够被eureka 服务端发现并注册到上面

@EnableFeignClients  // 集成open feign需要加这个注解
@SpringBootApplication // spring boot 启动类注解
@EnableDiscoveryClient // 服务被发现
@EnableEurekaClient //开启eureka 客户端
@ComponentScan("com.wz") //包扫描
public class authApplication {
    public static void main(String[] args) {
        SpringApplication.run(authApplication.class,args);
    }
}

3.eureka 服务端配置

3.1添加依赖
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter</artifactId>
    </dependency>
</dependencies>

注意:本次项目集成demo 使用到的 spring cloud版本为:3.1.6. spring boot 的版本为2.7.12 spring boot starter test 可以不加

3.2 添加eureka service配置文件
eureka:
  instance:
    lease-renewal-interval-in-seconds: 10
    hostname: localhost
    instance-id: ${spring.application.name}
  server:
    # eureka 服务的端口
    port: ${server.port}
    #服务端30s 定时清除操作
    eviction-interval-timer-in-ms: 30000
    enable-self-preservation: true
    sync-when-timestamp-differs: true
  client:
    service-url:
      defaultZone: http://${eureka.instance.hostname}:${eureka.server.port}/eureka
    #应用是否可以去拉取服务列表到本地
    fetch-registry: true
    # 自己是否注册服务到eureka
    register-with-eureka: false
    #间隔10秒去拉取,时间越短脏读越少,性能消耗大
    registry-fetch-interval-seconds: 30
    enabled: true
    eureka-server-read-timeout-seconds: 10

3.3完整eureka service 服务配置文件

spring:
  application:
    name: eureka
server:
  port: 8613
eureka:
  instance:
    lease-renewal-interval-in-seconds: 10
    hostname: localhost
    instance-id: ${spring.application.name}
  server:
    # eureka 服务的端口
    port: ${server.port}
    #服务端30s 定时清除操作
    eviction-interval-timer-in-ms: 30000
    enable-self-preservation: true
    sync-when-timestamp-differs: true
  client:
    service-url:
      defaultZone: http://${eureka.instance.hostname}:${eureka.server.port}/eureka
    #应用是否可以去拉取服务列表到本地
    fetch-registry: true
    # 自己是否注册服务到eureka
    register-with-eureka: false
    #间隔10秒去拉取,时间越短脏读越少,性能消耗大
    registry-fetch-interval-seconds: 30
    enabled: true
    eureka-server-read-timeout-seconds: 10
3.4启动类
@EnableEurekaServer // eureka 服务端的注解是这个
@EnableDiscoveryClient
@SpringBootApplication
public class eurekaApplication {
    public static void main(String[] args) {
        SpringApplication.run(eurekaApplication.class, args);
    }
}

eureka 服务的的web 界面 为 服务地址:端口 eg: localhost:8613 打开就能看的eureka web端的界面
在这里插入图片描述

上面是服务地址 , 左下红框为注册成功的服务。

4.使用open feign

4.1准备一个测试接口

本次demo 在query模块下 有一个查询接口
在这里插入图片描述

该接口完整的请求路径为:

http://localhost:8082/qury/user/query?id=10001&name= (为了方便就用了一个查询参数)

在这里插入图片描述

4.2准备接口

在服务调用方准备需要的接口
在这里插入图片描述

1.在该接口类使用 @FeignClient注解 @FeignClient(value = “qury”, path = “/qury/user”) value 为eureka注册中心 的服务名 path是该请求的路径,例如:该请求完整路径为: /qury/user/query 为了书写方便可以把前面相同的路径写在path上。

2.该接口的请求方式, 请求参数 ,返回对象的类型一定要和服务提供方相同

3.如果请求找不到(你感觉都对,没有什么问题的情况下) 有可能是服务名太长导致, eureka 注册中心超过4个字符找不到服务(不知道原因)这个可能是eureka有延迟,又可以请求成功了0.0 ,建议eureka刷新 调小点 例如10s刷新,或者服务刚启动不要太急进行请求.

4.如果服务名 太长 多个单词拼接的 建议使用 - 分割,不建议下划线(_)

4.3 controller调用服务

在这里插入图片描述

注入写的open feign 接口,调用方法

5测试

启动相关服务,本次服务的端口为8081如果我想通过open feign转发去请求query 模块的服务(http://localhost:8082/qury/user/query?id=10001&name= (为了方便就用了一个查询参数)) 则只需要调用上面controller层中的接口就好。

http://localhost:8081/auth/test/a?id=10001&name
在这里插入图片描述

服务经过open feign 寻找到正确的服务,请求成功!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Spring Boot Feign是一个基于HTTP的轻量级Java库,用于简化使用HTTP客户端进行远程过程调用(RPC)的开发。它提供了一种简单的方式来定义和使用基于接口的HTTP客户端。 在Spring Boot Feign中,我们可以使用注解来定义一个HTTP客户端接口。通过在接口的方法上添加注解,我们可以指定用于发送HTTP请求的URL、请求方法、请求参数、请求头等信息。Feign会根据这些注解的配置,自动生成具体的HTTP请求。 与传统的RPC相比,Spring Boot Feign具有以下优点: 1. 简化开发:使用Feign,我们可以将HTTP请求的细节抽象成接口方法,无需手动处理HTTP请求、序列化和反序列化等操作,开发起来更加简单快捷。 2. 标准化接口:通过标准化接口的形式,我们可以更好地定义和管理服务间的通信协议,提高接口的重用性和可维护性。 3. 自动化配置:Spring Boot提供了自动化配置的支持,通过简单的配置,我们可以快速地将Feign集成Spring Boot应用中。 4. 可扩展性:借助Spring的依赖注入和AOP等特性,我们可以很方便地实现自定义的拦截器、错误处理器和负载均衡等功能,提升系统的可扩展性。 总体而言,Spring Boot Feign是一个简单、灵活且功能强大的远程过程调用(RPC)工具,适用于构建微服务架构的应用程序。通过它,我们可以轻松地实现服务间的通信,提高系统的可维护性和扩展性。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值