通过Feign消费注册在Nacos上面的服务

Spring Boot版本:2.2.9.RELEASE Spring Cloud Alibaba版本:2.2.1.RELEASE nacos版本:1.3.1 spring-cloud-starter-openfeign版本:2.2.3.RELEASE

0 准备

首先根据 搭建注册一个discoveryServer服务。

1 引入依赖

首先引入相关依赖:

<!-- nacos服务注册与发现 -->
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>

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

<!-- 负载均衡 -->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-loadbalancer</artifactId>
</dependency>

<!-- 单元测试 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
    <exclusions>
        <exclusion>
            <groupId>org.junit.vintage</groupId>
            <artifactId>junit-vintage-engine</artifactId>
        </exclusion>
    </exclusions>
</dependency>

最主要的依赖是spring-cloud-starter-openfeign。

当然,为了能够通过服务名发现注册到Nacos的服务,所以需要引入spring-cloud-starter-alibaba-nacos-discovery;为了使用Spring官方的负载均衡器来替换Ribbon,需要引入spring-cloud-starter-loadbalancer,并添加配置spring.cloud.loadbalancer.ribbon.enabled=false;单元测试需要引入spring-boot-starter-test。

application.properties配置文件如下:

# 服务名、端口、上下文
spring.application.name=discoveryClient
server.servlet.context-path=/dc
server.port=8080

# nacos服务器的地址
spring.cloud.nacos.discovery.server-addr=192.168.225.128:8848

# 不使用RibbonLoadBalancerClient,改用BlockingLoadBalancerClient
spring.cloud.loadbalancer.ribbon.enabled=false

2 启用Feign

在启动类上添加@EnableFeignClients注解:

@EnableFeignClients
@EnableDiscoveryClient
@SpringBootApplication
public class NacosDiscoveryClientApplication {
          
   

    public static void main(String[] args) {
          
   
        SpringApplication.run(NacosDiscoveryClientApplication.class, args);
    }
}

3 编写接口

编写一个接口叫做IDiscoveryServer,代表注册到Nacos注册中心的服务discoveryServer。

@FeignClient("discoveryServer")
@RequestMapping("/ds")
public interface IDiscoveryServer {
          
   

    @GetMapping("/hello")
    String hello();
}

在这个接口里:

    使用@FeignClient注解表示这是一个Feign客户端,参数填服务名,也就是注册到Nacos中心的服务discoveryServer。 和编写web里面的Controller一样,可以使用@RequestMapping、@GetMapping这样的注解标示请求的uri。 这里的hello()方法经过Feign的处理,最后会变成http://discoveryServer/ds/hello的一个http请求。

4 验证

编写单元测试验证:

@SpringBootTest
public class MainTest {
          
   

    @Autowired
    private IDiscoveryServer discoveryServer;

    @Test
    public void hello() {
          
   
        System.out.println(discoveryServer.hello());;
    }
}

输出为:

hello, I am discoveryServer, port is [8001]
经验分享 程序员 微信小程序 职场和发展