源码地址:https://gitee.com/peachtec/springcloud
什么是Feign
Feign是声明式的web service 客户端,它让微服务之间的调用变得更加简单了,类似于controller调用service;SpringCloud集成了Ribbon和Eureka,可以在使用Feign时提供负载均衡的http客户端
Feign能干啥
Feign旨在编写java http客户端变得更加容易
前面在使用Ribbon+RestTemplate时,利用RestTemplate对http请求的封装处理,形成了一套模板化的调用方法;但是在实际开发中,由于对服务的调用可能不在一处,往往一个接口会被多处调用,所以通常都会针对每个微服务自行封装一些客户端类来包装这些微服务的调用,所以,Feign在此基础上做了进一步封装,由它来帮助我们定义和实现依赖服务接口的定义,在Feign的实现下,我们只需要创建一个接口并使用注解的方式来配置它(类似于以前的Dao接口标注Mapper注解,现在是在微服务接口上标注Feign注解即可);即可完成对服务提供方的接口绑定,简化了SpringCloud Ribbon时自动封装服务调用客户端的并发量。
Feign集成了Ribbon
利用Ribbon维护了微服务的服务列表信息,并通过轮询实现了客户端的负载均衡,而与Ribbon不同的是,通过Feign只需要定义服务绑定接口并且以声明式的方法,优雅而简单的实现了服务调用
使用Feign
项目代码继续引用之前的代码,只是将服务消费者模块进行重建,方便以后看的时候进行区别
- 在公共服务模块中导入Feign的jar包,并编写公共接口类,方便在其他的模块进行调用
<!-- Feign -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
//Feign客户端注解,并指服务名,在调用时会自动去找服务下面的接口
@FeignClient(value = "SPRINGCLOUD-SERVER")
@Component
public interface ClientService {
@PostMapping("/dept/add")
boolean addDept(Dept dept);
@GetMapping("/dept/get/{id}")
Dept queryById(@PathVariable("id") Integer id);
@GetMapping("/dept/get")
List<Dept> queryAll();
}
- 在服务消费者模块中,导入Feign的依赖,并重写控制层接口
<!-- Feign -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
@RestController
@RequestMapping("/dept")
public class ConsumerApi {
//通过去调用公共模块的接口的方式去访问微服务
@Autowired
private ClientService clientService;
@GetMapping("/get/{id}")
public Dept getDeptById(@PathVariable Integer id) {
return clientService.queryById(id);
}
@PostMapping("/add")
private boolean addDept(Dept dept) {
return clientService.addDept(dept);
}
@GetMapping("/get")
private List<Dept> queryAll() {
return clientService.queryAll();
}
}
- 在启动类中开启Feign,并指定要扫描的包
@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients(basePackages = {
"com.peach"})
@ComponentScan("com.peach")
public class FeignResumer_80 {
public static void main(String[] args) {
SpringApplication.run(FeignResumer_80.class, args);
}
}
- 开启测试,默认为轮训
Ribbon是基于RestFul风格的,而Feign的基于注解的,可读性可能更好,但是它的底层还是使用的是Ribbon的实现方式,相当于在外面套了一层壳,所以它的性能没有Ribbon高;在实际开发中这两种方式都可以使用。