04.SpringCloud之Feign远程接口映射

一.简介

SpringCloud是基于Restful的远程调用框架,引入Ribbon负载均衡组件后还需要客户端使用RestTemplate调用远程接口,操作起来还显得繁琐。SpringCloud提供了远程接口映射,将远程Restful服务映射为远程接口,消费端注入远程接口即可实现方法调用。

二.流程

1.consumer-user模块中引入Feign依赖

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

2.编写映射接口

package com.vincent.consumer.feign;

import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

@FeignClient("service-user")
public interface IUserFeign {
    @GetMapping("/user/{id}")
    Object getById(@PathVariable("id") Integer id);
}

3.TestController.java注入Feign Client接口映射

package com.vincent.consumer.controller;


import com.vincent.consumer.feign.IUserFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
public class TestController {
    @Autowired
    private IUserFeign userFeign;

    @GetMapping("/getUserById")
    public Object getUserById(Integer id){
        return this.userFeign.getById(id);
    }
}

4.启动类增加@EnableFeignClients注解

package com.vincent.consumer;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.feign.EnableFeignClients;



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

}

@EnableFeignClients 定义Feign接口映射扫描包,IOC容器会自动创建接口实现类

5.访问 http://localhost:8030/getUserById?id=9

在这里插入图片描述

三.总结

Feign接口映射服务端Restful接口会自动依赖Ribbon组件,实现客户端负载均衡。使用接口调用消费端远程接口就像调用本地方法一样。

如果Feign调用的服务使用HTTP BASIC 认证,则可以在org.springframework.cloud.openfeign.FeignClient#configuration属性配置feign.RequestInterceptor 的接口Bean对象实现:

@Configuration
public class FeignConfiguration {
   @Bean
   public RequestInterceptor requestInterceptor() {
       return new BasicAuthRequestInterceptor("xxx","xxx");
   }
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值