Feign简介及使用

概述

在实际开发中,我们对某些服务的调用可能不止于一处,往往一个接口会被多处调用,所以我们通常都会针对各个微服务自行封装一些客户端累来包装这些依赖服务的调用

由此,Spring Cloud Fegin在Spring Cloud Ribbon的 RestTemplate基础上做了进一步封装,

在Spring Cloud Feign的实现下,只需创建一个接口并用注解的方式来配置它,即可完成对服务提供方的接口绑定,简化了在使用Spring Cloud Ribbon时自行封装服务调用客户端的开发量

springboot中使用

服务提供者

@RestController
@RequestMapping("api")
public class ProviderController {
    
    

    @GetMapping("/user/{nanme}")
    public String getUserName(@PathVariable(value = "nanme") String nanme) {
    
    
        return "我是服务提供者==>用户name:" + inanmed;
    }
}

使用Feign实现服务消费者

引入Feign依赖

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>

添加@EnableFeignClients注解开启功能

在应用主类xxApplication中,添加@EnableFeignClients注解开启Spring Cloud Feign的支持功能。

@SpringBootApplication
@EnableFeignClients()
public class xxxApplication {
    
    
    
    public static void main(String[] args) {
    
    
        SpringApplication.run(Application.class, args);
    }
}

使用Feign绑定服务对应的接口

使用@FeignClient绑定服务

  1. url可以直接指定第三方服务地址
  2. path指定路径,
  3. 接口的方法指定接口
  4. 通过 @FeifnClient的name属性 指定目标服务名称:client-provider-servename指定这个接口所要调用的服务名称
@FeignClient(name = "client-provider-server", path = "/api",url = "http://localhost:8081")
public interface HelloServiceFeign {
    
    

    @RequestMapping(value = "/getUserName", method = RequestMethod.GET)
    public String getUserName(String name);
}

使用上面绑定的服务

在springboot中需要使用的bean中,注入上述使用@FeignClient注释的bean,便可以使用其他服务的接口

@RestController
public class RestClientController {
    
    

    @Autowired
    private HelloServiceFeign client;


    @RequestMapping(value = "/geUsertName", method = RequestMethod.GET)
    public String getHost(String name) {
    
    
        return client.getName(name);
    }
}

总结

使用feign之后,我们调用eureka 注册的其他服务,在代码中就像各个service之间相互调用那么简单

猜你喜欢

转载自blog.csdn.net/yyuggjggg/article/details/129825770