简介
feign是声明式的web service客户端,它让微服务之间的调用变得更简单了,类似controller调用service。Spring Cloud集成了Ribbon和Eureka,可在使用Feign时提供负载均衡的http客户端。
在springcloud中不仅可以使用Ribbo进行负载均衡,也可以使用Feign。Feign是在Ribbon的基础上进行了一次改进,采用接口的方式实现负载均衡。
使用
- 导入依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
- 编写对应的接口
@FeignClient(value = "PROVIDER-NAME")声明这是一个FeignClient,value指明需要的服务id
@FeignClient(value = "PROVIDER-NAME")
public interface DeptClientService {
// 请求的路径需与服务提供者的路径一致
@RequestMapping(value = "/dev/add")
boolean add(Dept dept);
@RequestMapping(value = "/dev/{id}")
Dept queryByID(@PathVariable("id") Long id );
@PostMapping(value = "/dev/list")
List<Dept> queryAll();
}
- 修改Controller
我们不再使用RestTemplate来获取所需的对象,而是通过之前定义的接口来获取
@RestController
public class ConsumerController {
@Autowired
private DeptClientService service;
@RequestMapping("/consumer/get/{id}")
public Dept getByID(@PathVariable("id") Long id){
return this.service.queryByID(id);
}
@RequestMapping("/consumer/add")
public boolean add(String dname){
Dept dept = new Dept();
dept.setDname(dname);
return this.service.add(dept);
}
@RequestMapping("/consumer/list")
public List<Dept> list(){
return this.service.queryAll();
}
}
- 修改启动类
@EnableFeignClients 开启Feign负载均衡
@SpringBootApplication(scanBasePackages = "com")
@EnableEurekaClient
@EnableFeignClients(basePackages = "com.service")
public class FeignApplication {
public static void main(String[] args) {
SpringApplication.run(FeignApplication.class,args);
}
}
- 对比:
Ribbon
public class ConsumerController {
@Autowired
private RestTemplate template;
private static final String url="http://PROVIDER-NAME";
@RequestMapping("/consumer/get/{id}")
public Dept getByID(@PathVariable long id){
//请求的路径,返回的对象
Dept getEntity = template.getForObject(url + "/dev/" + id, Dept.class);
return getEntity;
}
@RequestMapping("/consumer/add")
public boolean add(String dname){
Dept dept = new Dept();
dept.setDname(dname);
System.out.println(dept);
//请求的路径,传递的参数,返回的对象
return template.postForObject(url+ "/dev/add",dept,Boolean.class);
}
@RequestMapping("/consumer/list")
public List<Dept> list(){
//请求的路径,返回的对象
return template.postForObject(url+"/dev/list",void.class,List.class);
}
}
Feign
@RestController
public class ConsumerController {
@Autowired
private DeptClientService service;
@RequestMapping("/consumer/get/{id}")
public Dept getByID(@PathVariable("id") Long id){
return this.service.queryByID(id);
}
@RequestMapping("/consumer/add")
public boolean add(String dname){
Dept dept = new Dept();
dept.setDname(dname);
return this.service.add(dept);
}
@RequestMapping("/consumer/list")
public List<Dept> list(){
return this.service.queryAll();
}
}
总结
Feign的使用与Ribbon不同的地方在于
- Feign通过接口来实现,更符合我们的面向接口编程的习惯
- 在Ribbon的Controller中我们需要将url拼接,而Feign帮我们进行了拼接
以上就是SpringCloud为服务结构中的Feign的基本介绍和使用的详细内容,想要了解更多关于SpringCloud Feign的其他内容,请关注W3Cschool其它相关文章!也希望大家能够多多支持!