SpringCloud Feign配置应用详细介绍

来自:网络
时间:2022-12-30
阅读:
目录

前言

服务消费者调用服务提供者的时候使用RestTemplate技术

SpringCloud Feign配置应用详细介绍

存在不便之处:

  • 拼接url
  • restTmplate.getForObJect

这两处代码都比较模板化,能不能不让我我们来写这种模板化的东西,另外来说,拼接url非常的low,拼接字符串,拼接参数,很low还容易出错

1、Feign简介

Feign是Netflix开发的一个轻量级RESTful的HTTP服务客户端(用它来发起请求,远程调用的),是以Java接口注解的方式调用Http请求,而不用像Java中通过封装HTTP请求报文的方式直接调用,Feign被⼴泛应用在Spring Cloud 的解决方案中。

类似于Dubbo,服务消费者拿到服务提供者的接口,然后像调用本地接口方法一样去调用,实际发出的是远程的请求。

  • Feign可帮助我们更加便捷,优雅的调用HTTP API:不需要我们去拼接url然后呢调用restTemplate的api,在SpringCloud中,使用Feign⾮常简单,创建一个接口(在消费者--服务调用方这一端),并在接口上添加一些注解,代码就完成了
  • SpringCloud对Feign进行了增强,使Feign支持了SpringMVC注解(OpenFeign)

本质:封装了Http调用流程,更符合面向接口化的编程习惯,类似于Dubbo的服务调用

2、Feign配置应用

在服务调用者工程 (消费) 创建接口(添加注解)(效果)Feign = RestTemplate+Ribbon+Hystrix

服务消费者工程(自动投递微服务)中引入Feign依赖(或者父类工程)

   <dependencies>
        <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>
    </dependencies>

服务消费者工程(自动投递微服务)启动类使用注解@EnableFeignClients添加Feign支持

package com.lagou.edu;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients // 开启Feign客户端功能
public class AutoDeliverApplication8091 {
    public static void main(String[] args) {
        SpringApplication.run(AutoDeliverApplication8091.class, args);
    }
}

注意:此时去掉Hystrix熔断的支持注解@EnableCircuitBreaker即可包括引入的依赖,因为Feign会自动引入。

配置文件

server:
  port: 8091
# 注册到Eureka服务中心
eureka:
  client:
    service-url:
      # 注册到集群,就把多个EurekaServer地址使用逗号连接起来即可;注册到单实例(非集群模式),那就写一个
      defaultZone: http://LagouCloudEurekaServerB:8762/eureka,http://LagouCloudEurekaServerA:8761/eureka
  instance:
    prefer-ip-address: true # 服务实例中显示ip,而不是显示主机名(兼容老的Eureka版本)
    # 自定义实例显示格式,加上版本号,便于多版本管理,注意是ip-address,早期版本是ipAddress
    instance-id: ${spring.cloud.client.ipaddress}:${spring.application.name}:${server.port}:@project.version@
spring:
  application:
    name: lagou-service-autodeliver
#针对的被调用方微服务名称,不加就是全局生效
lagou-service-resume:
  ribbon:
    NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RoundRobinRule #负载策略调整
# springboot中暴露健康检查等断点接⼝
management:
  endpoints:
    web:
      exposure:
        include: "*"
# 暴露健康接⼝的细节
  endpoint:
    health:
      show-details: always

创建Feign接口

package com.lagou.edu.controller.service;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
// @FeignClient标明当前类是一个Feign客户端,value指定该客户端要请求的服务器名称(登记到注册中心上服务提供者的服务名称)
// name或value:调⽤的服务名称,和服务提供者yml⽂件中spring.application.name保持⼀致
@FeignClient(value = "lagou-service-resume")
@RequestMapping("/resume")
public interface ResumeServiceFeignClient {
    // feign要做的事情,拼装url发起请求
    // 我们调用该方法就是调用本地接口方法,那么实际上做的事远程请求
    @GetMapping("/openstate/{userId}")
    public Integer findDefaultResumeState(@PathVariable Long userId);
}

注意:

  • @FeignClient注解的name属性用于指定要调用的服务提供者名称,和服务提供者yml⽂件中spring.application.name保持一致
  • 接口中的接口方法,就好比是远程服务提供者Controller中的Hander方法(只不过如同本地调用了),那么在进行参数绑定的时,可以使用@PathVariable、@RequestParam、RequestHeader等,这也是OpenFeign对SpringMVC注解的支持,但是需要注意value必须设置,否则会抛出异常

使用接口中方法完成远程调用(注入接口即可,实际注入的是接口的实现)

package com.lagou.edu.controller;
import com.lagou.edu.controller.service.ResumeServiceFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/autodeliver")
public class AutoDeliverController {
    @Autowired
    private ResumeServiceFeignClient resumeServiceFeignClient;
    @GetMapping("/checkState/{userId}")
    public Integer findResumeOpenState(@PathVariable Long userId) {
        Integer defaultResumeState = resumeServiceFeignClient.findDefaultResumeState(userId);
        return defaultResumeState;
    }
}
返回顶部
顶部