Feign的介绍与使用

  1. 什么是Feign?

    Feign是声明式Web Service客户端,它让微服务之间的调用变得更简单。

  2. 为什么使用Feign?

    • Feign旨在使编写Java Http客户端变得更容易;
    • 之前在使用Ribbon + RestTemplate时,利用RestTemplate对Http请求的封装处理,形成了一套模板化的调用方法。但是在实际开发中,由于对服务依赖的调用可能不止一处,往往一个接口会被多处调用,所以通常都会针对每个微服务自行封装一个客户端类来包装这些依赖服务的调用。所以,Feign在此基础上做了进一步的封装,由他来帮助我们定义和实现依赖服务接口的定义,在Feign的实现下,我们只需要创建一个接口并使用注解的方式来配置它 (类似以前Dao接口上标注Mapper注解,现在是一个微服务接口上面标注一个Feign注解即可),即可完成对服务提供方的接口绑定,简化了使用Spring Cloud Ribbon 时,自动封装服务调用客户端的开发量;
    • Feign默认集成了Ribbon。
  3. Feign的使用步骤

    • 导入依赖
    <!-- Feign -->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-feign</artifactId>
    </dependency>
    
    • Feign实现消费者模块调用服务提供者模块的原理和原来的Dubbo+zookeeper类似,即需要使用注解实现远程注入,所以我们直接在springcould-api模块中添加一个接口DeptClientService,这个接口中的方法定义自己随意,只是方法上面要像controller一样写上@RequestMapping或者它的变体@GetMapping、@PostMapping等,但是这个接口上面不需要使用注解@Controller或@RestController

    • 这个接口上面需要使用注解@FeignClient(value = “服务集群在注册中心中的名称”)和注解@Component或者它的变体@Service;其中注解@FeignClient+value属性用于指定注册中心中哪一个服务中的

    @Component //被spring托管/装配到spring容器中
    //@FeignClient:微服务客户端注解,value:指定微服务的名字,这样就可以使Feign客户端直接找到对应的微服务
    @FeignClient(name="user-provider")
    public interface UserFeignClient {
        @GetMapping("/user/{id}")
        User getById(@PathVariable("id") Integer id);
    }
    
    • 修改Controller
    @RestController
    public class MovieController {
        @Autowired
        private UserFeignClient userFeignClient;
    
        @GetMapping("/user/{id}")
        public User findById(@PathVariable Integer id) {
            return userFeignClient.getById(id);
        }
    
    }
    
    • 修改启动类
    @SpringBootApplication
    @EnableFeignClients
    public class MovieApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(MovieApplication.class, args);
        }
    }
    
posted @   Hanyta  阅读(33)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
点击右上角即可分享
微信分享提示