SpringCloud-Feign搭建

本文详细介绍使用Feign实现微服务消费的过程,包括添加依赖、配置接口、设置Eureka地址等关键步骤,以及如何在消费端调用服务。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前言

Feign主要用途是消费端进行服务的消费,达到doubbo+zk那种面向接口的服务调用的效果。Feign集成了Ribbon。

1.api工程加入Feign相关依赖

 <!--引入feign相关依赖-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-feign</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-config</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

2.api工程添加接口,并添加注解@FeignClient,value值是微服务名称

/*
* 定义访问注册中心的接口
* */
@FeignClient(value = "DEPT-PROVIDER")
public interface DeptService {
    @RequestMapping(method = RequestMethod.GET, path = "dept")
    Dept findOne();
}

3.消费端的工程引入feign相关依赖

<dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-feign</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-config</artifactId>
        </dependency>
        <dependency>

4.消费端工程yml配置文件中添加Eureka地址

eureka:
  client:
    service-url:
      #指定需要做负载均衡的注册中心地址
      defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/
    register-with-eureka: false

5.消费端工程主启动类加入注解

@SpringBootApplication
@EnableEurekaClient
/*记得扫描api中的接口.feign注解要扫描,对象注入也要扫描*/
@EnableFeignClients(basePackages={"mservice.cloud.api"})
//@ComponentScan(basePackages = {"mservice.cloud.api"}) 加了这个只会扫描指定包中的,启动类下的包并不会自动扫描了
@ComponentScan(basePackages = {"mservice.cloud.api","mservice.cloud.consumer.feign.controller"})
public class ConsumerFeignMain80 {
    public static void main(String[] args) {
        SpringApplication.run(ConsumerFeignMain80.class,args);
    }
}

这里注意@EnableFeignClients和@ComponentScan两个注解,@EnableFeignClients注解扫描的路径是步骤2中加了@FeignClient的类的包,@ComponentScan也需要扫描这个包下的类才能够将类的实例注入到Spring容器中

6.消费端工程中的controller直接调用步骤2中的接口实现服务的消费

@RestController
public class DeptController {

    @Autowired
    private DeptService deptService;

    @RequestMapping(method = RequestMethod.GET,value = "dept")
    public Dept findOne(){
        return deptService.findOne();
    }

  
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值