SpringCloud :feign接口方式调用服务

feign:佛儿gin

1,feign是什么、

  feign是声明式的web service客户端,他让微服务之间的调用看上去更简单了(代码可读性强),

  它是集成了Ribbon,同时又封装了一层接口,因此性能没有Ribbon高,以为微服务调用时舍弃了Resttemplate,用的是面向接口调用的思想,所以可读性上增强了相比Ribbon

 

Ribbon对比Feign小总结:

  1.微服务名字:【ribbon】

  2.接口+注解:【feign】 

 

 

 

实现:

1.导入依赖,消费者+api(公用区域)

       <!--feign-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-feign</artifactId>
            <version>1.4.6.RELEASE</version>
        </dependency>

 

2,在api或者服务端写一个接口,用来接收(绑定)微服务服务

@Component  //注册到spring容器里
@FeignClient(value = "SPRINGCLOUD-PROVIDER-DEPT") //被服务直接调用
public interface DeptClientService {

     @GetMapping("/dept/get/{id}")
     Dept queryById(@PathVariable("id") Long id);

     @GetMapping("/dept/list")
     List<Dept> queryAll();

     @PostMapping("/dept/add")
     Boolean addDept(String dname);

}

 

3.服务消费者调用接口

@RestController
public class FeignDeptConsumerController {

    //调用api的接口
    //这里报错,但没有错
    @Autowired
    private DeptClientService service = null; //null,因为调用的是接口没有实现类,不可为false,空指针异常

    @RequestMapping("/consumer/dept/add/{dname}")
    public Boolean add(@PathVariable("dname") String dname){
        return this.service.addDept(dname);
    }

    @RequestMapping("/consumer/dept/get/{id}")
    public Dept get(@PathVariable("id")Long id){
        return this.service.queryById(id);
    }

    @RequestMapping("/consumer/dept/list")
    public List<Dept> list(){
        return this.service.queryAll();
    }


}

 

最后!消费者著启动类开启feigon功能,绑定接口

@EnableFeignClients(basePackages = {"com.king.springcloud"})//指定路径扫描(feign),数组
@SpringBootApplication
//Ribbon和Eureka整合,客户端可以直接调用,不用关心ip地址
@EnableEurekaClient
@EnableFeignClients(basePackages = {"com.king.springcloud"})//指定路径扫描(feign),数组
public class FeignDeptConsumer_80 {
    public static void main(String[] args) {
        SpringApplication.run(FeignDeptConsumer_80.class,args);
    }
}

 

 

 

posted @ 2021-01-27 19:33  凸然猿  阅读(510)  评论(0编辑  收藏  举报