openFeign学习记录

openFeign是什么

 openFeign是一个声明式的web service客户端。以前我们需要用ribbon+restTemplate实现远程http调用,如果我们使用feign,只需要声明一个接口,在接口上加上注解@FeignClient(value="服务的名称")就可以实现远程http调用,更好的面向接口编程。OpenFeign同时支持SpringMVC注解

openFeign官网

 springcloud openFeign的官网

openFeign的使用

 引入maven依赖

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

主启动类加上@EnableFeignClients注解开启feign

创建Service接口,我们将在接口中调用远程服务

package com.atguigu.springcloud.service;

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import com.atguigu.springcloud.entities.CommonResult;
import com.atguigu.springcloud.entities.Payment;

@Component 
@FeignClient(value = "CLOUD-PAYMENT-SERVICE")
public interface ConsumerFeignService {

	@GetMapping("/payment/{id}")
	CommonResult<Payment> getPaymentById(@PathVariable(value = "id")Long id);
	
	//feign默认超时等待1s,接口调用超过1s报错connect time out,如果是集群服务,本来是轮训,此时eureka会将这个超时的服务移除,不在提供服务
	@GetMapping("/payment/wait/{id}")
	public CommonResult<Payment> waitGetPaymentById(@PathVariable(value = "id")Long id);
}

注意:

Service接口上要加上@Component注解,不然spring不会注入bean

在Service接口加上注解@FeignClient(value="远程服务的名称")

Service接口中加上方法,加上注解@GetMapping,@PostMapping注解指定访问路径

注意:

当调用参数为基本类型的封装类时,必须加上@PathVariable或者@RequestParam注解

创建controller调用Service接口

package com.atguigu.springcloud.controller;

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 com.atguigu.springcloud.entities.CommonResult;
import com.atguigu.springcloud.entities.Payment;
import com.atguigu.springcloud.service.ConsumerFeignService;

@RestController
@RequestMapping()
public class ConsumerFeignController {

	@Autowired
	private ConsumerFeignService consumerFeignService;
	
	@GetMapping("/consumer/payment/get/{id}")
	public CommonResult<Payment> getPayment(@PathVariable(value = "id")Long id){
		return consumerFeignService.getPaymentById(id);
	}
	
	@GetMapping("/consumer/payment/wait/{id}")
	public CommonResult<Payment> waitGetPaymentById(@PathVariable(value = "id")Long id){
		return consumerFeignService.waitGetPaymentById(id);
	}
}

启动项目,测试

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值