OpenFeign服务调用

学习笔记~~摸鱼时间~~

对于服务的调用,除了RestTemplate还可以使用OpenFeign,当然Feign已经停更了。

在这里我创建了两个服务提供模块(cloud-provider-payment8001\cloud-provider-payment8002),分别注册到了eureka上

首先引入OpenFeign的pom依赖

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

yml文件

server:
  port: 80
eureka:
  client:
    #false表示不向服务端注册自己
    register-with-eureka: false
    #false表示自己端就是注册中心,我的职责就是维护服务实例,并不需要去检索服务
    fetch-registry: true
    service-url:
      #设置与Eureka Server交互的地址查询服务和注册服务都需要依赖这个地址
      defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/

 

 在需要调用服务的模块中创建启动类、service的接口和controller类

启动类中要加上@EnableFeignClients注解

@SpringBootApplication
@EnableFeignClients
public class OrderFeignMain80
{
    public static void main(String[] args)
    {
        SpringApplication.run(OrderFeignMain80.class,args);
    }
}

然后就是接口和controller类的编写

PaymentFeignService接口中添加注解@FeignClient(value = "CLOUD-PAYMENT-SERVICE")

value的值就是之前在eureka上注册服务的名字

@GetMapping(value = "/better/payment/get/{id}")这个路径要和被调用服务的Mapping路径一致

@Component
@FeignClient(value = "CLOUD-PAYMENT-SERVICE")
public interface PaymentFeignService
{
    @GetMapping(value = "/better/payment/get/{id}")
    CommonResult getPaymentById(@PathVariable("id") Integer id);
}

controller类直接调用service的接口 

@RestController
@Slf4j
public class PaymentController
{
    @Resource
    private PaymentFeignService paymentFeignService;

    @GetMapping(value = "/consumer/payment/get/{id}")
    public CommonResult<Payment> getPaymentById(@PathVariable("id") Integer id)
    {
        CommonResult payment = paymentFeignService.getPaymentById(id);
        return payment;
    }
}

写好了测试一下

 

(OpenFeign也自带了轮询的调用方式)

相对于RestTemplate个人感觉OpenFeign更符合自己的编程习惯。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值