Feign负载均衡(基于客户端)

Feign默认集成了Ribbon,与Ribbon不同的是,通过Feign只需要定义服务绑定接口且以声明式的方法,便捷的实现了服务调用。

这里将原来Ribbon实现的服务消费者做修改,修改为通过Feign实现

加入Feign依赖

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-feign</artifactId>
    <version>1.4.6.RELEASE</version>
</dependency>

编写feign接口,通过@ FeignClient(“服务名”),来指定调用哪个服务提供者

@FeignClient(value = "SPRINGCLOUD-PROVIDER-DEPT")
public interface DeptClientService {
    @GetMapping("/dept/{id}")
    public Dept queryById(@PathVariable("id") Long id);
    @GetMapping("/dept")
    public List<Dept> queryAll();
    @PostMapping("/dept")
    public int addDept(Dept dept);
}

启动类添加注解@EnableFeignClients开启Feign功能,可通过basePackages 指定包

@SpringBootApplication
@EnableEurekaClient
@EnableDiscoveryClient
@EnableFeignClients(basePackages = {"com.yyx.springcloud"})
public class FeignDeptConsumer_80 {
    public static void main(String[] args) {
        SpringApplication.run(FeignDeptConsumer_80.class,args);
    }
}

controller层注入Feign客户端DeptClientService来消费服务

@RestController
public class DeptConsumerController {

    @Autowired
    private DeptClientService deptClientService;
    @RequestMapping("/consumer/dept/add")
    public int add(Dept dept){
        return this.deptClientService.addDept(dept);
    }
    @RequestMapping("/consumer/dept/get/{deptno}")
    public Dept dept(@PathVariable("deptno") Long deptno){
        return this.deptClientService.queryById(deptno);
    }
    @RequestMapping("/consumer/dept/list")
    public List<Dept> dept(){
        return this.deptClientService.queryAll();
    }
}

对比不同与Ribbon通过服务名来消费服务
在这里插入图片描述
喜欢REST风格使用Ribbon;喜欢面向接口风格使用Feign.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

LeBron永鑫

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值