【Nacos系列第一篇】-Nacos之Spring Discovery(第一篇.系列.Nacos.Spring.Discovery...)

wufei123 发布于 2025-09-11 阅读(1)

作者:毕来生 微信:878799579

前言

个人比较看好Spring Cloud Alibaba家族。此系列以Nacos为主题,从Spring、Spring boot、Spring Cloud多个方面逐步进行演示,源码解读。目前来看官方文档还有待完善。网络上除了官网外缺少Nacos系列文章。都是零零散散的知识点。如此系列文章哪里写的有不周全,错误之处。欢迎大家指正。谢谢。

因公众号排版问题,可能会有代码显示不完整,请使用电脑版微信内置浏览器/复制链接到浏览器中。

1、Nacos是什么?服务发现和服务健康监测动态配置服务动态 DNS 服务服务及其元数据管理Nacos架构图【Nacos系列第一篇】-Nacos之Spring Discovery2、准备工作

工具:IDEA2018.3 、JDK: 1.8、Maven:3.5(通用配置。后续不在提及此部分。均已此版本演示)

Nacos:0.7.0(写此文章时最新版本,如后续更新。以最新版本给大家演示)

环境:Windows(演示用,后续更新完成后会有一章在linux下演示。有坑,但原理一样。不多赘述。)

Nacos稳定版本:https://github.com/alibaba/nacos/releases

Linux下请下载tar后解压。Windows下请下载zip。

代码语言:javascript代码运行次数:0运行复制
<pre class="brush:php;toolbar:false;">unzip nacos-server-$version.zip 或者 tar -xvf nacos-server-$version.tar.gz

下载后启动Nacos。Nacos默认启动端口为8848,意为珠穆朗玛峰高度。如启动有端口冲突,请自行调整端口。

3、工程结构

上面说了那么多,现在先整理来看一下我们的工程结构

【Nacos系列第一篇】-Nacos之Spring Discovery

附上关键部分代码。

NacosConfiguration代码语言:javascript代码运行次数:0运行复制
<pre class="brush:php;toolbar:false;">package org.nacos.spring;import com.alibaba.nacos.api.annotation.NacosProperties;import com.alibaba.nacos.spring.context.annotation.config.NacosPropertySource;import com.alibaba.nacos.spring.context.annotation.discovery.EnableNacosDiscovery;import org.springframework.beans.factory.annotation.Configurable;/** * @Author: bilaisheng * @Wechat: 878799579 * @Date: 2019/1/13 19:28 * @Todo: NacosConfiguration,用以注册以及测试Service Name : nacos-spring * @Version : JDK8  , IDEA2018 */@Configurable@EnableNacosConfig(globalProperties = @NacosProperties(serverAddr = "127.0.0.1:8848"))@NacosPropertySource(dataId = "nacos-spring", autoRefreshed = true)public class NacosConfiguration {}
@EnableNacosConfig
注解启用 Nacos Spring 的配置管理服务。@NacosPropertySource
加载了
dataId
nacos-spring`的配置源,并开启自动更新。对 Nacos Spring 的用户来说,在自身应用中就只是设置 “autoRefreshed” 的一个布尔值。然后在需要修改配置的时候,调用 Nacos 修改配置的接口,或使用 Nacos 的控制台去修改,配置发生变更后, Nacos 就会把最新的配置推送到该应用的所有机器上。NacosDiscoveryController代码语言:javascript代码运行次数:0运行复制
<pre class="brush:php;toolbar:false;">package org.nacos.spring.controller;import com.alibaba.nacos.api.annotation.NacosInjected;import com.alibaba.nacos.api.config.annotation.NacosValue;import com.alibaba.nacos.api.exception.NacosException;import com.alibaba.nacos.api.naming.NamingService;import com.alibaba.nacos.api.naming.pojo.Instance;import com.alibaba.nacos.spring.context.annotation.discovery.EnableNacosDiscovery;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.ResponseBody;import java.util.Date;import java.util.List;import static org.springframework.web.bind.annotation.RequestMethod.GET;/** * @Author: bilaisheng * @Wechat: 878799579 * @Date: 2019/1/13 19:29 * @Todo: NacosDisCoveryTest * @Version : JDK8  , IDEA2018 */@Controller@RequestMapping("nacos")public class NacosDiscoveryController {    @NacosInjected    private NamingService namingService;    @NacosValue(value = "${useLocalCache:false}", autoRefreshed = true)    private boolean useLocalCache;    @RequestMapping("/{str}")    public String helloNacos(@PathVariable String str){        return new Date() + "Hello Nacos " + str;    }    @RequestMapping("/instance")    @ResponseBody    public List<Instance> getInstance(@PathVariable  String serviceName) throws NacosException {        return namingService.getAllInstances(serviceName);    }    @RequestMapping(value = "/get", method = GET)    @ResponseBody    public boolean get() {        return useLocalCache;    }}

此文件为普通Spring映射控制器,话说Nacos Spring还是小马哥@mercyblitz亲自操刀。大家可以不用怀疑质量啦。相信很多同学都快被小马哥逼的要劝退了。

着重说明一下,这个也是Nacos中常用的方法之一。

代码语言:javascript代码运行次数:0运行复制
<pre class="brush:php;toolbar:false;">@RequestMapping("/instance")    @ResponseBody    public List<Instance> getInstance(@PathVariable  String serviceName) throws NacosException {        return namingService.getAllInstances(serviceName);    }
代码语言:javascript代码运行次数:0运行复制
<pre class="brush:php;toolbar:false;">List<Instance> getAllInstances(String serviceName) throws NacosException;List<Instance> getAllInstances(String serviceName, List<String> clusters) throws NacosException;

请求参数

名称

类型

描述

serviceName

字符串

服务名

clusters

List

集群列表

返回参数

List 实例列表。

PIA PIA

全面的AI聚合平台,一站式访问所有顶级AI模型

PIA226 查看详情 PIA

描述

用于服务启动的时候从 Nacos 获取配置。

代码语言:javascript代码运行次数:0运行复制
<pre class="brush:php;toolbar:false;">public String getConfig(String dataId, String group, long timeoutMs) throws NacosException

请求参数

参数名

参数类型

描述

dataId

string

配置 ID,采用类似 package.class(如com.taobao.tc.refund.log.level)的命名规则保证全局唯一性,class 部分建议是配置的业务含义。全部字符小写。只允许英文字符和 4 种特殊字符("."、":"、"-"、"_"),不超过 256 字节。

group

string

配置分组,建议填写产品名:模块名(Nacos:Test)保证唯一性,只允许英文字符和4种特殊字符("."、":"、"-"、"_"),不超过128字节。

timeout

long

读取配置超时时间,单位 ms,推荐值 3000。

返回值

参数类型

描述

string

配置值

请求示例

代码语言:javascript代码运行次数:0运行复制
<pre class="brush:php;toolbar:false;">try {    String serverAddr = "{serverAddr}";    String dataId = "{dataId}";    String group = "{group}";    Properties properties = new Properties();    properties.put("serverAddr", serverAddr);    ConfigService configService = NacosFactory.createConfigService(properties);    String content = configService.getConfig(dataId, group, 5000);    System.out.println(content);} catch (NacosException e) {    // TODO Auto-generated catch block    e.printStackTrace();}

上述两个文件中关于Nacos使用,请参考官网NacosSDK。里面详细标注了每个方法以及对应参数以及测试案例。

父pom.xml代码语言:javascript代码运行次数:0运行复制
<pre class="brush:php;toolbar:false;"><?xml version="1.0" encoding="UTF-8"?><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>org.bilaisheng.nacos</groupId>  <artifactId>nacos-spring-examples</artifactId>  <packaging>pom</packaging>  <version>1.0-SNAPSHOT</version>  <modules>    <module>nacos-spring-discvoery</module>  </modules>  <name>nacos-spring-examples</name>  <properties>    <maven.compiler.source>1.8</maven.compiler.source>    <maven.compiler.target>1.8</maven.compiler.target>    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>    <spring.framework.version>5.1.3.RELEASE</spring.framework.version>    <servlet-api.version>4.0.1</servlet-api.version>    <nacos-spring-context.version>0.2.2-RC1</nacos-spring-context.version>  </properties>  <dependencyManagement>    <dependencies>      <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->      <dependency>        <groupId>javax.servlet</groupId>        <artifactId>javax.servlet-api</artifactId>        <version>${servlet-api.version}</version>        <scope>provided</scope>      </dependency>      <!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->      <dependency>        <groupId>org.springframework</groupId>        <artifactId>spring-core</artifactId>        <version>${spring.framework.version}</version>      </dependency>      <!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->      <dependency>        <groupId>org.springframework</groupId>        <artifactId>spring-context</artifactId>        <version>${spring.framework.version}</version>      </dependency>      <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->      <dependency>        <groupId>org.springframework</groupId>        <artifactId>spring-webmvc</artifactId>        <version>${spring.framework.version}</version>      </dependency>      <!-- https://mvnrepository.com/artifact/com.alibaba.nacos/nacos-spring-context -->      <dependency>        <groupId>com.alibaba.nacos</groupId>        <artifactId>nacos-spring-context</artifactId>        <version>${nacos-spring-context.version}</version>      </dependency>    </dependencies>  </dependencyManagement></project>
本工程pom.xml代码语言:javascript代码运行次数:0运行复制
<pre class="brush:php;toolbar:false;"><?xml version="1.0" encoding="UTF-8"?><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">    <parent>        <artifactId>nacos-spring-examples</artifactId>        <groupId>org.bilaisheng.nacos</groupId>        <version>1.0-SNAPSHOT</version>    </parent>    <modelVersion>4.0.0</modelVersion>    <artifactId>nacos-spring-discvoery</artifactId>    <dependencies>        <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->        <dependency>            <groupId>javax.servlet</groupId>            <artifactId>javax.servlet-api</artifactId>        </dependency>        <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->        <dependency>            <groupId>org.springframework</groupId>            <artifactId>spring-webmvc</artifactId>        </dependency>        <!-- https://mvnrepository.com/artifact/com.alibaba.nacos/nacos-spring-context -->        <dependency>            <groupId>com.alibaba.nacos</groupId>            <artifactId>nacos-spring-context</artifactId>        </dependency>    </dependencies></project>
页面请求

页面请求同普通Spring相同,启动后根据http://ip:端口/controller/xxx。

以上就是【Nacos系列第一篇】-Nacos之Spring Discovery的详细内容,更多请关注知识资源分享宝库其它相关文章!

相关标签: linux javascript java git windows idea github 微信 浏览器 JavaScript spring spring boot 架构 spring cloud maven String xml 字符串 接口 class 值参数 github windows http https linux 大家都在看: Spring Boot入门教程1、使用Spring Boot构建第一个Web应用程序 Linux Mint 19体验学习笔记 Linux 学习_ssh(secure shell) WSL 2正式支持CUDA/GPU啦!微软将Linux GUI引入Windows 10 Windows10上安装Linux子系统(WSL2,Ubuntu),配合Windows Terminal使用,还要什么自行车

标签:  第一篇 系列 Nacos 

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。