Feign声明式客户端接口

目录

一、feign介绍

二、feign的使用

1、feign远程调用

(1)创建项目

(2)编辑pom

(3)编辑yml

(4)编辑主程序

(5)创建三个服务的Service层

(6)创建FeignController

(7)调用流程图示

2、feign负载均衡

3、feign超时和重试

(1)重试的默认参数

(2)编辑yml

4、feign降级

(1)编辑yml

(2)Service修改@FeignClient

(3)添加降级类

5、Feign熔断+dashborad监控仪表盘

(1)配置hystrix

(2)配置actuator

(3)启动dashborad服务


一、feign介绍

feign整合了ribbon和hystrix,不仅能进行远程调用,还具备了负载均衡,重试,降级和熔断的功能。提供了一种声明式的Web服务客户端定义的方式。

使用了我们所熟悉的spring mvc注解来对方法接口进行设置,拼接后台的服务访问路径和提交的参数。

二、feign的使用

1、feign远程调用

(1)创建项目

(2)编辑pom

添加eureka和feign依赖

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

(3)编辑yml

服务名称为:feign,使用端口:3001

spring:
  application:
    name: feign

server:
  port: 3001

eureka:
  client:
    service-url:
      defaultZone: http://eureka1:2001/eureka, http://eureka2:2002/eureka

(4)编辑主程序

添加@EnableFeignClient注解,开启Spring Cloud Feign的功能

package cn.tedu.sp09;

import ...;


@EnableFeignClients
@EnableDiscoveryClient
@SpringBootApplication
public class Sp09FeignApplication {

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

}

(5)创建三个服务的Service层

分别添加@FeignClient("微服务名称"),并添加对应的方法,其中方法上使用@RequestMapping注解拼接路径以及参数

itemService

package cn.tedu.sp09.service;

import ...;

@FeignClient("item-service")
public interface ItemFeignService {
    
    @GetMapping("/{orderId}")
    JsonResult<List<Item>> getItems(@PathVariable String orderId);

    @PostMapping("/decreaseNumber")
    JsonResult decreaseNumber(@RequestBody List<Item> items);
}

userService

package cn.tedu.sp09.service;

import ...;

@FeignClient(name="user-service",fallback = UserFeignServiceFB.class)
public interface UserFeignService {
    @GetMapping("/{userId}")
    JsonResult<User> getUser(@PathVariable Integer userId);

    // 拼接路径 /{userId}/score?score=新增积分
    //注意,如果请求参数名与方法参数名不同,@RequestParam不能省略,并且要指定请求参数名:
    //@RequestParam("score") Integer s
    @GetMapping("/{userId}/score")
    JsonResult addScore(@PathVariable Integer userId, @RequestParam Integer score);
}

orderService

package cn.tedu.sp09.service;

import ...;

@FeignClient(n
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值