Feign的简单使用

本文详细介绍了如何在Spring Cloud项目中使用Feign进行微服务接口调用,包括添加依赖、配置类、创建接口和服务层实现,以及默认的轮询负载均衡。Feign简化了API调用,提升开发效率。

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

springCloud提供的微服务接口调用有 Ribbon+RestTemplate和feign两种,Feign是一种负载均衡的HTTP客户端, 使用Feign调用API就像调用本地方法一样,从避免了调用目标微服务时,需要不断的解析/封装json 数据的繁琐。Feign集成了Ribbon。Ribbon+eureka是面向微服务编程,而Feign是面向接口编程。Feign同样具有负载均衡功能。

项目demo构建参考:https://blog.youkuaiyun.com/f123147/article/details/115904274
在Ppom文件中假如Feign的依赖

 <!-- 微服务组件-feign -->
      <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-openfeign</artifactId>
        <version>${spring.cloud.netflix.version}</version>
    </dependency>

在前端front工程启动类上写上@EnableFeignClients注解

package com.gmf.briup;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.openfeign.EnableFeignClients;

@EnableFeignClients
@EnableEurekaClient
@SpringBootApplication
public class FrontApplication {

    public static void main(String[] args) {

        SpringApplication.run(FrontApplication.class, args);
    }

}

在前端front工程中service层创建接口

package com.gmf.briup.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
/*
*  这是一个接口,Feign会通过动态代理,帮我们生成实现类
*/
@FeignClient(value = "order-service")  //调用哪个微服务
public interface FeignService {

    @ResponseBody
    @RequestMapping("/orderService/service/getPort")
    String getPort();
}


  

在前端接口front工程web层创建对外暴露的接口

package com.gmf.briup.controller;

import com.gmf.briup.service.FeignService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/feign")
public class FeignController {

    @Autowired
    FeignService feignService;

    @ResponseBody
    @RequestMapping(value = "/getOrderServicePort")
    public String sayHi(){
    //调用service层的方法,该方法和order-service微服务的接口绑定在一起
        String port = feignService.getPort();
         System.out.println(port);
       return port;
    }
}

在浏览器中输入front工程对外暴露的接口:http://127.0.0.1:8090/feign/getOrderServicePort
结果如下
在这里插入图片描述
从这里可以看出,Feign的负载均衡算法默认也是轮询。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值