Feign默认集成了Ribbon,与Ribbon不同的是,通过Feign只需要定义服务绑定接口且以声明式的方法,便捷的实现了服务调用。
这里将原来Ribbon实现的服务消费者做修改,修改为通过Feign实现
加入Feign依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
<version>1.4.6.RELEASE</version>
</dependency>
编写feign接口,通过@ FeignClient(“服务名”),来指定调用哪个服务提供者
@FeignClient(value = "SPRINGCLOUD-PROVIDER-DEPT")
public interface DeptClientService {
@GetMapping("/dept/{id}")
public Dept queryById(@PathVariable("id") Long id);
@GetMapping("/dept")
public List<Dept> queryAll();
@PostMapping("/dept")
public int addDept(Dept dept);
}
启动类添加注解@EnableFeignClients开启Feign功能,可通过basePackages 指定包
@SpringBootApplication
@EnableEurekaClient
@EnableDiscoveryClient
@EnableFeignClients(basePackages = {"com.yyx.springcloud"})
public class FeignDeptConsumer_80 {
public static void main(String[] args) {
SpringApplication.run(FeignDeptConsumer_80.class,args);
}
}
controller层注入Feign客户端DeptClientService来消费服务
@RestController
public class DeptConsumerController {
@Autowired
private DeptClientService deptClientService;
@RequestMapping("/consumer/dept/add")
public int add(Dept dept){
return this.deptClientService.addDept(dept);
}
@RequestMapping("/consumer/dept/get/{deptno}")
public Dept dept(@PathVariable("deptno") Long deptno){
return this.deptClientService.queryById(deptno);
}
@RequestMapping("/consumer/dept/list")
public List<Dept> dept(){
return this.deptClientService.queryAll();
}
}
对比不同与Ribbon通过服务名来消费服务
喜欢REST风格使用Ribbon;喜欢面向接口风格使用Feign.