spring cloud——feign声明式服务调用

什么是Feign

Feign是Spring Cloud Netflix组件中的一个轻量级RESTFUL和HTTP服务客户端,实现了负载均衡和Rest调用的开源框架,封装了Ribbon和RestTemplate,实现了web Service的面向接口编程,进一步降低了项目的耦合度。
是一种声明式,模板化的HTTP客户端(仅在Consumer中使用),使用Feign的注解定义接口,调用这个接口,就可以调用服务注册中心的服务

Feign解决了什么问题

像调用本地方法一样调用远程方法,无感知远程HTTP请求,使用Feign实现负载均衡是首选方案,只需要创建一个接口,然后在上面添加注解即可。

Feign VS OpenFeign

OpenFeign 是spring cloud在Feign的基础上支持了Spring MVC注解,如@RequestMapping,@Pathvariable。OpenFeign的@FeignClient可以解析SpringMVC的@RequestMapping注解下的接口,并通过动态代理的方式生产实现类,实现类中做负载均衡并调用服务

Feign入门案例

使用的是前面的springcloud的Eureka中的两个provider,以及注册中心,这里consumer的使用,需要注意,需要单独写一个service,表示请求服务的接口名称
需要调用的服务为service-provider,调用的接口就是selectAll接口,在接口上面要注解调用服务的请求地址

import org.springframework.cloud.openfeign.FeignClient
import org.springframework.web.bind.annotation.GetMapping

@FeignClient("service-provider")
interface ProductService {


    @GetMapping("/product/test")
    fun selectAll():String
}

build.gradle.kts

import org.jetbrains.kotlin.gradle.tasks.KotlinCompile

plugins {
    id("org.springframework.boot") version "2.3.7.RELEASE"
    id("io.spring.dependency-management") version "1.0.10.RELEASE"
    kotlin("jvm") version "1.3.72"
    kotlin("plugin.spring") version "1.3.72"
}

group = "com"
version = "0.0.1-SNAPSHOT"
java.sourceCompatibility = JavaVersion.VERSION_1_8

repositories {
    mavenCentral()
}

dependencies {
    implementation("org.springframework.boot:spring-boot-starter-web")
    implementation("com.fasterxml.jackson.module:jackson-module-kotlin")
    implementation("org.jetbrains.kotlin:kotlin-reflect")
    implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8")
    testImplementation("org.springframework.boot:spring-boot-starter-test") {
        exclude(group = "org.junit.vintage", module = "junit-vintage-engine")
    }
    // https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-dependencies
    implementation("org.springframework.cloud:spring-cloud-dependencies:Hoxton.SR12")
    // https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-netflix-eureka-client
    implementation("org.springframework.cloud:spring-cloud-starter-netflix-eureka-client:2.2.10.RELEASE")
    // https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-openfeign
    implementation("org.springframework.cloud:spring-cloud-starter-openfeign:2.2.10.RELEASE")

}

tasks.withType<Test> {
    useJUnitPlatform()
}

tasks.withType<KotlinCompile> {
    kotlinOptions {
        freeCompilerArgs = listOf("-Xjsr305=strict")
        jvmTarget = "1.8"
    }
}

application.yml

server:
  port: 9091

spring:
  application:
    name: service-consumer

eureka:
  client:
    register-with-eureka: false
    registry-fetch-interval-seconds: 10
    service-url:
      service-url:
        defaultZone: http://localhost:8761/eureka/

#局部的负载均衡策略
#service-provider 为调用的服务的名称
service-provider:
  ribbon:
    NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule

启动文件

import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
import org.springframework.cloud.openfeign.EnableFeignClients

@SpringBootApplication
@EnableFeignClients
class ServiceConsumerApplication

fun main(args: Array<String>) {
    runApplication<ServiceConsumerApplication>(*args)
}

consumer接口的实现层

import com.service_consumer.service.ProductService
import com.service_consumer.service.TestService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Repository

@Repository
class TestServiceImpl :TestService{

    @Autowired
    lateinit var productService: ProductService

    override fun hello(id: String): String {
        return productService.selectAll()+" "+id
    }
}

项目结构
在这里插入图片描述

Feign负载均衡

可以使用配置文件注解的方式进行全局配置,也可以在application.yml中,根据服务名进行单独配置

import com.netflix.loadbalancer.RandomRule
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration

@Configuration
class RibbonConfig {

    @Bean
    fun randomRule(): RandomRule {
        return RandomRule()
    }
}

Feign请求传参

get方式的传递

    @GetMapping("/product/{id}")
    fun selectById(@PathVariable("id") id:String) : String

然后调用正常调用consumer接口就可以了
post方法传参,在服务中就是@RequstBody注解

    @PostMapping("/product/save")
    fun saveOne(user:Product):R<*>

Feign性能优化

gzip压缩,大约可以减少70%以上的文件大小
局部配置
只要配置Consumer通过Feign到Provider的请求与相应的Gzip压缩

feign:
  compression:
    request:
      mime-types: text/xml,application/xml,application/json #配置压缩支持的类型
      min-request-size: 512          #配置压缩数据大小的最小阈值,默认2048
      enabled: true      #请求是否开启
    response:
      enabled: true      #响应是否开启

全局配置

server:
  port: 9091
  compression:
    enabled: true
    mime-types: application/json,application/xml,text/html,text/xml,text/plain

HTTP连接池
使用HttpClient,它封装了HTTP的请求头,参数,内容体,响应等等,不仅使客户端发送HTTP请求变得容易,而且也方便了开发人员测试接口(基于HTTP协议的)
需要进入如下依赖(一般需要导入第一个,第一个以及集成在了新版的SpringCloud中)

// https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient
implementation("org.apache.httpcomponents:httpclient:4.5.13")
// https://mvnrepository.com/artifact/io.github.openfeign/feign-httpclient
implementation("io.github.openfeign:feign-httpclient:11.8")

需要在consumer的配置文件中,声明使用HTTPClient

feign:
  httpclient:
    enabled: true

状态查看
需要在resources中添加日志文件logback.xml

请求超时

全局的

ribbon:
  ConnectTimeout: 5000 #默认时间是1秒
  ReadTimeout: 5000 #请求处理的超时时间

局部的,可以根据不同的微服务的名称进行配置

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值