Spring Cloud 之 Feign,Hystrix 和 Gateway

Feign声明式服务调用

Feign概述

• Feign 是一个声明式的 REST 客户端,它用了基于接口的注解方式,很方便实现客户端配置。
• Feign 最初由 Netflix 公司提供,但不支持SpringMVC注解,后由SpringCloud 对其封装,支持了SpringMVC注 解,让使用者更易于接受。

  • Feign自动集成Ribbon,且默认开启相关功能
  • Feign自动集成Hystrix,但默认关闭,需要手动开启

Feign 快速入门

  1. 在消费端引入 open-feign 依赖
  2. 编写Feign调用接口
  3. 在启动类 添加 @EnableFeignClients 注解,开启Feign功能
  4. 测试调用

Feign依赖:

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

Feign调用接口:

package com.itheima.consumer.feign;

import com.itheima.consumer.FeignLogConfig;
import com.itheima.consumer.domain.Goods;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

/**
 * feign声明式接口,发起远程调用
 * String url = "http://FEIGN-PROVIDER/goods/findOne/"+id;
 * Goods goods = restTemplate.getForObject(url, Goods.class);
 *
 * 1.定义接口
 * 2.接口上添加注解,@FeignClient,设置属性为 服务提供者的 应用名称,日志级别配置类
 * 3.编写调用接口,接口的声明规则和提供方接口保持一致
 * 4.注入该接口,调用接口方法完成远程调用
 */

@FeignClient(value = "FEIGN-PROVIDER",configuration = FeignLogConfig.class)
public interface GoodsFeignClient {
   

    @GetMapping("/goods/findOne/{id}")
    public Goods findGoodsById(@PathVariable("id") int id);

}

package com.itheima.consumer.controller;


import com.itheima.consumer.domain.Goods;
import com.itheima.consumer.feign.GoodsFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
@RequestMapping("/order")
public class OrderController {
   

    @Autowired
    private RestTemplate restTemplate;
    
    @Autowired
    private GoodsFeignClient goodsFeignClient;


    @GetMapping("/goods/{id}")
    public Goods findGoodsById(@PathVariable("id") int id){
   
        
        Goods goods = goodsFeignClient.findGoodsById(id);
        return
  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值