【Feign】集成服务消费功能

本文介绍如何在Spring Cloud项目中使用Feign实现微服务间的调用,包括添加依赖、配置注解、创建Feign接口及使用示例。

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

添加依赖

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

注解开启Feign客户端功能

@EnableFeignClients注解后跟@FeignClient注解所在包名,多个包名用大括号及逗号分隔({…,…})

@SpringBootApplication
@EnableFeignClients("com.act.model.feign")
public class TestApplication {

    public static void main(String[] args) {
        SpringApplication.run(TestApplication.class, args);
    }

}

创建Feign接口

  • 通过@FeignClient注解创建客户端,value指定调用的服务名称,fallback指定调用异常后执行的方法
  • @RequestMapping注解,value指定被调用的服务路径,method指定调用类型
@FeignClient(value = "lou-nacos-service-provider", fallback = UserServiceFallback.class)
public interface Test {

    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    String hello();

    @RequestMapping(value = "/hello1", method = RequestMethod.GET)
    String hello1(@RequestParam("name") String name);
}

Feign接口使用

  • @Autowired注解将Feign接口类注入
  • 调用接口类中定义的方法即可
@Controller
@RequestMapping("/test")
public class TestController {

    @Autowired
    private Test test;

    @ResponseBody
    @RequestMapping("/hello")
    public String hello(){
        System.out.println(test.hello());
        return test.hello();
    }

    @ResponseBody
    @RequestMapping("/hello1")
    public String hello1(@RequestParam("name")String name){
        System.out.println(test.hello1(name));
        return test.hello1(name);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值