SpringCloud之Feign(简化客户端的服务调用)***

Feign:假装、伪装的意思

  Feign可以把HTTP 的请求进行隐藏,伪装成类似 SpringMVC 的 Controller一样。你不用再自己拼接 url,拼接参数等等操作,一切都交给 Feign 去做。  

  提供一个接口, 封装服务提供方的服务接口(url),便于Controller的调用, 谁需要调用服务, 在谁添加Feign, 

内嵌ribbon,不需要导入ribbon的依赖

使用 Feign 替代 RestTemplate 发送 HTTP请求。(在服务消费方添加如下配置)

1、导入Feign依赖

<!-- feign的支持  内嵌ribbon依赖-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>

2、添加注解, 在启动类添加@EnableFeignClients, 开启FeignClient

@SpringBootApplication
//表示这个项目是一个Eureka-client(服务)
@EnableEurekaClient
//开启FeignClient
@EnableFeignClients
public class SpringCloudUserApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringCloudUserApplication.class, args);
    }

3、在application.yml配置文件中添加配置

#ribbon.eureka.enabled=true
ribbon:
  eureka:
    enabled: true

4、服务提供方的接口

@RestController
@RequestMapping(path = "master",produces = "application/json;charset=utf-8")
public class helloController {

    @Value("${server.port}")
    private int port;
    
    @GetMapping("sayHello/{word}")
    public String sayHello(@PathVariable("word")String word)  throws  Exception{
        System.out.println("master"+port);
        return "hello:"+word;
    }

5、在服务消费方:编写Feign的接口,创建Feign客户端

//创建一个client文件夹
//表示连接服务消费方的服务名
@FeignClient("springCould-master")
//提供相同的窄化请求路径
@RequestMapping("master")
public interface MasterService {

    //接口输入参数、输出参数必须与服务提供方一致
    @GetMapping("sayHello/{word}")
    public String sayHello(@PathVariable("word")String word)  throws  Exception;
}

6、使用Feign客户端

@RestController
@RequestMapping(path = "user",produces = "application/json;charset=utf-8")
public class helloController {
    //注入Feign客户端接口
    @Autowired
    private MasterService masterService;

    @GetMapping("hello/{word}")
    public String sayHello(@PathVariable("word")String word)  throws  Exception{
        //直接调用方法获取服务提供方数据
        return masterService.sayHello(word);
    }
}

启动两个服务提供方服务。多次执行访问接口。显示客户端不一致说明 Feign 默认是集成了 Ribbon 的轮询方案。

原文地址:https://www.cnblogs.com/64Byte/p/13282868.html