springcloud中使用openfeign来优化接口调用

简单介绍在springcloud中使用openfeign来优化接口调用

一、引入依赖

        <!--添加openFeign依赖-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>

二、为服务提供者编写openfeign接口

如需要调用的远程Controller接口如下(服务提供者接口)

@RestController
@RequestMapping("/stock")
public class StockController {

    @Value("${server.port}")
    String port;

    @GetMapping("/reduce")
    public String reduce(){
        System.out.println("扣减库存:"+port);
        return "扣减库存:"+port;
    }
}

需要编写的openfeign接口如下(服务消费者openfeign接口)

/**
 * name 指定调用rest接口所对应的服务名
 * path 指定调用rest接口所在的RequestMapping路径
 */
@FeignClient(name = "stock-service",path = "/stock")
public interface StockFeignService {
    // 声明需要调用rest接口对应的方法
    @GetMapping("/reduce")
    String reduce();
}

三、服务消费者调用定义的openfeign接口

随后在服务消费者Controller接口中调用定义的openfeign接口,达到像调用本地接口一样调用远程接口

@RestController
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private StockFeignService stockFeignService;

    @GetMapping("/addOrder")
    public String addOrder(){
        System.out.println("下单成功");
// String msg = restTemplate.getForObject("http://stock-service/stock/reduce", String.class);
        String msg = stockFeignService.reduce();
        return "hello feign !"+msg;
    }
}

四、项目结构

在这里插入图片描述

五、日志级别配置

在服务消费者端往往需要查看调用服务提供者接口的日志信息,包括接口地址,接口返回参数等等,因此需要对openfeign日志进行配置,以下提供三种配置方式

1、通过配置类进行全局配置

定义一个配置类

@Configuration
public class FeignConfig {
    @Bean
    public Logger.Level feignLoggerLevel(){
        return Logger.Level.FULL;
    }
}

需要在yml配置文件中开启日志

# springboot默认的日志级别为info,feign的debug日志级别就不会输入,所以需要修改feign目录下对应的日志级别为debug
logging:
  level:
    com.tuling.order.feign: debug

该方式会作用于所有的服务提供者,即调用所有的服务提供者都会打印相应级别的日志

2、通过配置类进行局部配置

将配置类FeignConfig中的@Configuration注解去掉

public class FeignConfig {
    @Bean
    public Logger.Level feignLoggerLevel(){
        return Logger.Level.FULL;
    }
}

随后修改对应的FeignService中@FeignClient注解,加上configuration = FeignConfig.class

@FeignClient(name = "stock-service",path = "/stock",configuration = FeignConfig.class)
public interface StockFeignService {
    // 声明需要调用rest接口对应的方法
    @GetMapping("/reduce")
    String reduce();
}

最后注意同样需要在yml配置文件中开启日志
这样的方式可以通过编辑服务提供者对应的FeignService来自定义开启哪些服务提供者的日志

3、通过配置文件配置

# springboot默认的日志级别为info,feign的debug日志级别就不会输入,所以需要修改feign目录下对应的日志级别为debug
logging:
  level:
    com.tuling.order.feign: debug

feign:
  client:
    config:
      stock-service:
        logger-level: BASIC

其中stock-service为服务提供者对应的服务名

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值