《通过 Nacos Server 和 spring-cloud-starter-alibaba-nacos-discovery 实现 服务发现 - 服务消费》

本文详细介绍了如何使用NacosServer和spring-cloud-starter-alibaba-nacos-discovery进行服务发现和服务消费。通过配置Maven依赖和Nacos属性,结合@EnableDiscoveryClient注解,实现了基于Nacos的服务注册与发现功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

《通过 Nacos Server 和 spring-cloud-starter-alibaba-nacos-discovery 实现 服务发现 - 服务消费》

1、添加依赖。
<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.live.test.MicroService</groupId>
    <artifactId>SpringCloudAlibaba-nacos-SpringCloud-config</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>com_live_test_MicroService_SpringCloudAlibaba_nacos_SpringCloud_config</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

        <spring-boot.version>2.0.4.RELEASE</spring-boot.version>
        <spring-cloud.version>Finchley.RELEASE</spring-cloud.version>

        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

    <!-- 1)parent:定义spring boot的版本 2)dependencyManagement:spring cloud的版本以及spring
        cloud alibaba的版本,由于spring cloud alibaba还未纳入spring cloud的主版本管理中,所以需要自己加入 3)dependencies:当前应用要使用的依赖内容。这里主要新加入了Nacos的配置客户端模块:spring-cloud-starter-alibaba-nacos-config。由于在dependencyManagement中已经引入了版本,所以这里就不用指定具体版本了。 -->
    <!-- 1) SpringBoot -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.4.RELEASE</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Finchley.SR1</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-alibaba-dependencies</artifactId>
                <version>0.2.2.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <!-- 3) dependencies -->
    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
            <version>0.2.1.RELEASE</version>
        </dependency>

        <!-- <dependency> <groupId>com.alibaba.nacos</groupId> <artifactId>nacos-client</artifactId>
            <version>${version}</version> </dependency> -->

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.2</version>
            <optional>true</optional>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <!-- 3、添加 SpringBoot 插件 -->
            <!-- Spring Boot的Maven插件(Spring Boot Maven plugin)能够以Maven的方式为应用提供Spring
                Boot的支持,即为Spring Boot应用提供了执行Maven操作的可能。 Spring Boot Maven plugin能够将Spring
                Boot应用打包为可执行的jar或war文件,然后以通常的方式运行Spring Boot应用。 -->
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <configuration>
                    <testFailureIgnore>true</testFailureIgnore>
                </configuration>
            </plugin>


        </plugins>
    </build>
</project>

2、bootstrap.properties 配置 Nacos
server.port=8081

spring.application.name=service-consumer

# nacos 作为注册中心
spring.cloud.nacos.discovery.server-addr=192.168.1.x:8848

3、通过 Nacos 的 @EnableDiscoveryClient 注解 开启服务发现
package com.live.test.javaee.springboot.discovery.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@Component
//@Controller
@RestController
@RequestMapping("discovery/consumer")
@EnableDiscoveryClient
public class DiscoveryConsumerController {

//    @NacosInjected
//    @Autowired
//    private NamingService namingService;
    private final RestTemplate restTemplate;

    @Autowired
    public DiscoveryConsumerController(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    @RequestMapping(value = "/echo/{str}", method = RequestMethod.GET)
    public String echo(@PathVariable String str) {
//        return restTemplate.getForObject("http://service-provider/echo/" + str, String.class);
        return restTemplate.getForObject("http://service-provider/discovery/provider/echo/" + str, String.class);
    }
}

4、测试访问 controller

### Spring Cloud Alibaba Nacos DiscoveryNacos 的对应关系 Spring Cloud Alibaba Nacos Discovery 是用于简化微服务架构下服务发现服务治理的组件之一。通过集成阿里巴巴开源的服务发现工具 Nacos,开发者可以轻松实现服务注册、发现以及配置管理等功能。 #### 关键概念解释 - **Nacos**: 动态服务发现、配置管理服务中心。它帮助构建云原生应用生态,提供易用的企业级微服务平台解决方案。 - **`spring-cloud-starter-alibaba-nacos-discovery`**: 这是一个 starter 库,旨在让基于 Spring Boot/Spring Cloud 构建的应用能够快速接入并利用 Nacos 提供的功能[^1]。 #### 配置方式 为了使应用程序能正确连接到 Nacos 并完成必要的初始化工作,在项目的 `pom.xml` 文件中需加入如下依赖: ```xml <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId> <!-- 版本号取决于所使用的 Spring Cloud Spring Boot 版本 --> </dependency> ``` 当引入上述依赖之后,框架会自动扫描并加载位于 `META-INF/spring.factories` 下指定的相关类(如 `NacosDiscoveryClientConfigServiceBootstrapConfiguration`),从而确保在应用启动期间执行相应的初始化逻辑[^3]。 #### 使用方法 一旦完成了基本设置,则无需额外编写代码来显式调用 API 或者手动处理服务注册流程;只需正常开发业务功能即可。具体来说: - 如果项目已经标注了 `@EnableDiscoveryClient` 注解,则该实例会被识别为可被其他服务发现的目标,并按照默认规则向 Nacos 注册自己; - 反之亦然,任何希望查找特定名称下的可用实例列表的操作都可以借助内置客户端接口简单几行代码搞定。 此外,对于某些特殊需求场景——比如自定义元数据上传或是调整健康状态检查机制等高级特性支持——可以通过扩展点来自由定制行为模式而不必担心破坏原有体系结构稳定性[^2]。 #### 示例代码片段展示 下面给出一段简单的 Java 代码示例,展示了如何在一个标准的 Spring Boot 工程里启用对 Nacos 的支持: ```java import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; // 开启服务发现能力 @EnableDiscoveryClient @SpringBootApplication public class MyApplication { public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); } } ``` 此段程序将会尝试联系本地运行着的一个 Nacos Server 实例来进行自我介绍(即注册)。如果一切顺利的话,那么接下来就可以像平常一样与其他已知节点交互啦!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值