Nacos的基本功能以及使用Feign进行微服务间的通信

发布于:2025-07-13 ⋅ 阅读:(21) ⋅ 点赞:(0)

Nacos是Dynamic Naming and Configuration Service的缩写。What’s Nacos?

下面结合SpringBoot项目,为你介绍Nacos的基本功能以及如何使用Feign进行微服务间的通信。

一、Nacos的基本功能

Nacos是阿里巴巴开源的一个更易于构建云原生应用的动态服务发现、配置管理和服务管理平台。它的主要功能包括:

  1. 服务发现与注册:微服务可以在Nacos中注册自己,并发现其他服务。
  2. 配置管理:集中管理所有微服务的配置。
  3. 服务健康监测:检查服务的健康状态。
  4. 动态DNS服务:通过域名来访问服务。

二、依赖配置

要在SpringBoot项目中使用Nacos和Feign,需要在pom.xml中添加以下依赖:

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

<!-- 配置管理 -->
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>

<!-- Feign客户端 -->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>

<!-- Spring Cloud 依赖管理 -->
<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>Hoxton.SR12</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-alibaba-dependencies</artifactId>
            <version>2.2.9.RELEASE</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

三、配置文件

application.propertiesapplication.yml中配置Nacos服务地址:

# 应用名称
spring:
  application:
    name: service-consumer
    
  cloud:
    nacos:
      discovery:
        server-addr: 127.0.0.1:8848  # Nacos服务器地址
      config:
        server-addr: 127.0.0.1:8848  # Nacos配置中心地址
        file-extension: yaml  # 配置文件格式
        
# 端口号
server:
  port: 8080

四、代码实现

1. 服务提供者(service-provider)

首先创建一个简单的服务提供者,提供一个API接口:

package com.example.provider.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

    @GetMapping("/hello/{name}")
    public String sayHello(@PathVariable String name) {
        return "Hello, " + name + "! I'm from service-provider.";
    }
}

启动类上添加@EnableDiscoveryClient注解:

package com.example.provider;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

@SpringBootApplication
@EnableDiscoveryClient
public class ServiceProviderApplication {

    public static void main(String[] args) {
        SpringApplication.run(ServiceProviderApplication.class, args);
    }
}
2. 服务消费者(service-consumer)

创建Feign客户端接口,调用服务提供者的API:

package com.example.consumer.feign;

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

@FeignClient(name = "service-provider")  // 服务提供者的应用名称
public interface HelloFeignClient {

    @GetMapping("/hello/{name}")  // 服务提供者的API路径
    String sayHello(@PathVariable String name);
}

创建Controller,使用Feign客户端调用服务:

package com.example.consumer.controller;

import com.example.consumer.feign.HelloFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ConsumerController {

    @Autowired
    private HelloFeignClient helloFeignClient;

    @GetMapping("/call/{name}")
    public String callProvider(@PathVariable String name) {
        return helloFeignClient.sayHello(name);
    }
}

启动类上添加@EnableFeignClients注解:

package com.example.consumer;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;

@SpringBootApplication
@EnableFeignClients
public class ServiceConsumerApplication {

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

五、Nacos配置中心使用示例

创建一个配置类,读取Nacos配置中心的配置:

package com.example.consumer.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;

@Component
@RefreshScope  // 支持配置动态刷新
public class AppConfig {

    @Value("${app.name:default}")
    private String appName;

    @Value("${app.version:1.0.0}")
    private String appVersion;

    public String getAppName() {
        return appName;
    }

    public String getAppVersion() {
        return appVersion;
    }
}

创建Controller,获取配置信息:

package com.example.consumer.controller;

import com.example.consumer.config.AppConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ConfigController {

    @Autowired
    private AppConfig appConfig;

    @GetMapping("/config")
    public String getConfig() {
        return "App Name: " + appConfig.getAppName() + ", Version: " + appConfig.getAppVersion();
    }
}

在Nacos配置中心创建配置文件service-consumer.yaml

app:
  name: MyServiceConsumer
  version: 1.0.1

六、测试步骤

  1. 启动Nacos服务器(下载并解压Nacos,运行startup.sh -m standalone)。
  2. 启动服务提供者(service-provider)。
  3. 启动服务消费者(service-consumer)。
  4. 访问服务消费者的API:http://localhost:8080/call/World,会返回Hello, World! I'm from service-provider.
  5. 访问配置信息:http://localhost:8080/config,会返回Nacos配置中心的配置信息。

通过上述示例,你可以看到Nacos的服务注册与发现、配置管理功能,以及Feign如何简化微服务间的通信。


网站公告

今日签到

点亮在社区的每一天
去签到