一.简介
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");
}
}