Feign是什么
feign是申明式web service客户端,让微服务之间的调用更简单。
类似controller调用service,spring cloud集成eureka和ribbon,可在使用feign时提供http请求的客户端。
Feign能干什么
- feign旨在编辑java http请求更简单
- 前面使用Ribbon+RestTemplete,利用RestTemplete对Http请求的封装,实现一套模板化的http请求方式。但是在实际开发中,对于服务依赖的调用不止一次,往往一个服务接口被多次调用,所以通常会针对某个服务封装成一个客户端类来包装这些依赖服务。所以feign做了进一步的封装,由他来帮助我们定义和实现依赖服务接口的定义。== 在feign的实现下,我们只需要创建一个接口并使用注解的方式类配置他(类似于在一个Dao接口上添加一个Mapper注解,现在是在一个接口上添加feign注解)==即可完成对服务提供方的接口绑定,简化了使用spring cloud ribbon时,封装调用客户端的代码量。
feign使用
- 1新建一个引入feign的客户端
<dependencies>
<!--feign-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
<version>1.4.6.RELEASE</version>
</dependency>
<!--Ribbon-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-ribbon</artifactId>
<version>1.4.6.RELEASE</version>
</dependency>
<!--Eureka-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
<version>1.4.6.RELEASE</version>
</dependency>
<dependency>
<groupId>com.kuang</groupId>
<artifactId>springCloud-api</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.6.7</version>
</dependency>
</dependencies>
- 2编辑启动类,注解比较
- 3在api中引入feign依赖,添加service
@Component //让spring管理
@FeignClient(value = "http://springCloud-provier-dept")//根据实际情况可能不需要 http://
public interface DeptClientService {
@GetMapping("/dept/getById/{id}") //必须和服务端路径一致
public Dept getById(@PathVariable("id") Long id);
@PostMapping("/dept/add")
public Boolean addDept(Dept dept);
@GetMapping("/dept/getDept")
public List<Dept> getAll();
}
- 4.通过接口的方式调用
@Autowired //自动装配service
private DeptClientService deptClientService ;
@RequestMapping("/customer/getDept/{id}")
public Dept getDeptById(@PathVariable("id") Long id){
System.out.println("叔叔素色宿舍");
//通过接口的方式调用,最后依然是http请求,只是代码的接口形式体现
return deptClientService.getById(id);
}
@RequestMapping("/customer/getDepts")
public List<Dept> getDept(){
System.out.println("叔叔素色宿舍");
return deptClientService.getAll();
}
@RequestMapping("/customer/add")
public Boolean addDept(Dept dept){
return deptClientService.addDept(dept);
}
- 5启动测试
启动一个注册中心,三个服务提供者,feign客户端
通过服务消费者路径访问
负载均衡依然生效