什么是Feign
Feign是Spring Cloud提供的一个声明式的伪Http客户端, 它使得调用远程服务就像调用本地服务一样简单, 只需要创建一个接口并添加一个注解即可。
Nacos很好的兼容了Feign, Feign默认集成了 Ribbon, 所以在Nacos下使用Fegin默认就实现了负载均衡的效果。

Feign的使用

一、添加依赖


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

二、入口类添加 @EnableFeignClients 注解:



@SpringBootApplication
@EnableFeignClients // 开启Fegin
public class IndexApplication {

三、创建一个UserService, 并使用Fegin实现微服务调用:



package com.temp.index.service;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable; @Service
@FeignClient("nacos-user") // 声明调用的提供者的name
public interface UserService {
   /*
    * 指定调用提供者的哪个方法;
    * 
    * @FeignClient+@GetMapping 就是一个完整的请求路径 http://nacos-user/user/{id}
    */
   @GetMapping(value = "/user/{id}")
   String getUser(@PathVariable("id") Integer id);
}