2Feign 入门 · SpringCloud微服务实战 · 看云

导航


本节代码地址


1.新建项目

在项目根目录下新建mudule fw-cloud-feign-client
11787ab2ae131badd034691926b4929a_MD5.webp

1.1 maven 配置

Spring Cloud 已经为我们封装好了Feign 的包,使用的时候直接加入依赖即可。pom.xml依赖如下

<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-actuator</artifactId>
    </dependency>

1.2 新建启动类

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

在启动类上加入@EnableFeignClients注解,如果Feign的定义跟启动类不在一个包名下,还需要制定路径,如@EnableFeignClients(basePackages = "con.fwcloud.xxx.xxx")

1.3 项目配置

server:
  port: 8771
spring:
  application:
    name: fw-feign
eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka/

指定项目名称和Eureka的地址

1.4 定义Feign 请求的接口

这里我们配合前面Eureka的例子,做一次远程调用

@FeignClient(value = "fw-register-eureka-client")
public interface EurekaFeignService {
    
    @GetMapping("/hello")
    String hello();
}

@FeignClient(value = "fw-register-eureka-client")里面配置的value 就是服务的名称
这里有几点需要注意

  1. 如果你在项目里面设置了同意的请求路径(server.servlet.context-path),需要将@FeignClient注解调整@FeignClient(value = "fw-register-eureka-client",path = "xxx")
  2. Feign 里面定义的接口,有多个@RequestParam,但只能有不超过一个@RequestBody
  3. 在定义接口的时候,如果返回的是用户自定义的实体,建议抽取出来,在Controller中实现接口,将抽取出来的接口单独打包,需要调用的项目依赖此包即可,每个项目不用重新定义一遍

1.5 定义控制层

@RestController
@Slf4j
public class EurekaFeignController {

    @Resource
    private EurekaFeignService eurekaFeignService;

    @GetMapping("/feignInfo")
    public String feignInfo() {
        String message = eurekaFeignService.hello();
        log.info(message);
        return message;
    }
}

1.6启动项目

由于需要配合的项目是fw-cloud-client-eureka,因此我们仍然按照之前的方式启动项目,Idea设置为允许并行启动。启动两个端点分别为8763、8764
5d8b69936bb7d9ebefd840dbd31a6139_MD5.png

接着启动fw-cloud-feign-client项目,并在postman 中测试接口http://localhost:8771/feignInfo
4670e64406203efb3c248ae98b79d3fa_MD5.png

获取到的结果也是轮询的显示8763、8764端口

到此Ribbon 的入门使用已经完成

总结

通过本例,相信你对Feign 的基本使用已经了解,可以独立开发一个基础Feign 的HTTP的请求调用。