SpringCloud2023集成Nacos2.4.3

基本都是最新版,踩了两天的坑终于集成上了,实现了多环境配置。

使用版本

关键应用版本备注
Java21Oracle OpenJDK 21.0.5
Spring Boot3.2.4
Spring Cloud2023.0.1
Spring Cloud Alibaba2023.0.1.3
Nacos2.4.3单机模式

nacos安装

我学习过程使用的是windows环境,从GitHub的nacos主页下载对应的zip包。解压,修改字符编码的配置。

到$NACOS_HOME/bin目录下打开命令提示符输入:

.\startup.cmd -m standalone
PS D:\Software\Dev\nacos-server-2.4.3\nacos\bin> .\startup.cmd -m standalone
"nacos is starting with standalone"

         ,--.
       ,--.'|
   ,--,:  : |                                           Nacos 2.4.3
,`--.'`|  ' :                       ,---.               Running in stand alone mode, All function modules
|   :  :  | |                      '   ,'\   .--.--.    Port: 8848
:   |   \ | :  ,--.--.     ,---.  /   /   | /  /    '   Pid: 16740
|   : '  '; | /       \   /     \.   ; ,. :|  :  /`./   Console: http://192.168.213.1:8848/nacos/index.html
'   ' ;.    ;.--.  .-. | /    / ''   | |: :|  :  ;_
|   | | \   | \__\/: . ..    ' / '   | .; : \  \    `.      https://nacos.io
'   : |  ; .' ," .--.; |'   ; :__|   :    |  `----.   \
|   | '`--'  /  /  ,.  |'   | '.'|\   \  /  /  /`--'  /
'   : |     ;  :   .'   \   :    : `----'  '--'.     /
;   |.'     |  ,     .-./\   \  /            `--'---'
'---'        `--`---'     `----'

2024-12-25 16:33:57,344 INFO Tomcat initialized with port(s): 8848 (http)

2024-12-25 16:33:57,826 INFO Root WebApplicationContext: initialization completed in 3429 ms

2024-12-25 16:34:02,518 INFO Will secure any request with [org.springframework.security.web.session.DisableEncodeUrlFilter@b61edb9, org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@5d3ff859, org.springframework.security.web.context.SecurityContextPersistenceFilter@7ae0cc89, org.springframework.security.web.header.HeaderWriterFilter@6dd36ab6, org.springframework.security.web.csrf.CsrfFilter@294f9d50, org.springframework.security.web.authentication.logout.LogoutFilter@32ec9c90, org.springframework.security.web.savedrequest.RequestCacheAwareFilter@13e5d243, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@35ef439e, org.springframework.security.web.authentication.AnonymousAuthenticationFilter@32bb0072, org.springframework.security.web.session.SessionManagementFilter@74606204, org.springframework.security.web.access.ExceptionTranslationFilter@1d858300]

2024-12-25 16:34:02,883 INFO Adding welcome page: class path resource [static/index.html]

2024-12-25 16:34:03,281 INFO Exposing 1 endpoint(s) beneath base path '/actuator'

2024-12-25 16:34:03,296 WARN You are asking Spring Security to ignore Ant [pattern='/**']. This is not recommended -- please use permitAll via HttpSecurity#authorizeHttpRequests instead.

2024-12-25 16:34:03,297 INFO Will not secure Ant [pattern='/**']

2024-12-25 16:34:03,297 WARN You are asking Spring Security to ignore Mvc [pattern='/prometheus']. This is not recommended -- please use permitAll via HttpSecurity#authorizeHttpRequests instead.

2024-12-25 16:34:03,297 INFO Will not secure Mvc [pattern='/prometheus']

2024-12-25 16:34:03,297 WARN You are asking Spring Security to ignore Mvc [pattern='/prometheus/namespaceId/{namespaceId}']. This is not recommended -- please use permitAll via HttpSecurity#authorizeHttpRequests instead.

2024-12-25 16:34:03,297 INFO Will not secure Mvc [pattern='/prometheus/namespaceId/{namespaceId}']

2024-12-25 16:34:03,299 WARN You are asking Spring Security to ignore Mvc [pattern='/prometheus/namespaceId/{namespaceId}/service/{service}']. This is not recommended -- please use permitAll via HttpSecurity#authorizeHttpRequests instead.

2024-12-25 16:34:03,299 INFO Will not secure Mvc [pattern='/prometheus/namespaceId/{namespaceId}/service/{service}']

2024-12-25 16:34:03,344 INFO Tomcat started on port(s): 8848 (http) with context path '/nacos'

2024-12-25 16:34:03,358 INFO No TaskScheduler/ScheduledExecutorService bean found for scheduled processing

2024-12-25 16:34:03,387 INFO Nacos started successfully in stand alone mode. use embedded storage

2024-12-25 16:34:30,275 INFO Initializing Servlet 'dispatcherServlet'

2024-12-25 16:34:30,276 INFO Completed initialization in 1 ms

nacos单机模式则启动成功,登录账号和密码默认都为nacos。

创建nacos配置

当使用我这种版本的组合时,创建nacos配置时,data Id设置格式最好设为[前缀]-[运行环境].[配置格式]。

比如我设置了一个配置,前缀为micro-service。有两个环境分别是默认和开发,配置格式为yaml。

那么data Id则分别为:
默认环境:

micro-service.yaml
User:
    name: lisi
    age: 993

current:
    env: 默认环境
    config: micro-service.yaml

server:
    servlet:
        context-path: /api

开发环境:

micro-service-dev.yaml
User:
    name: laoba
    age: 837

current:
    env: 开发环境
    config: micro-service-dev.yaml

server:
    servlet:
        context-path: /dev-api

Spring Cloud部署

使用IDEA初始化一个Spring Boot的环境。

在pom里设置好各个应用的版本。

pom文件如下:

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.2.4</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>org.example</groupId>
    <artifactId>micro-service01</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>micro-service01</name>
    <description>micro-service01</description>
    <url/>
    <licenses>
        <license/>
    </licenses>
    <developers>
        <developer/>
    </developers>
    <scm>
        <connection/>
        <developerConnection/>
        <tag/>
        <url/>
    </scm>
    <properties>
        <java.version>21</java.version>
        <spring-boot.version>3.2.4</spring-boot.version>
        <spring-cloud-alibaba.version>2023.0.1.3</spring-cloud-alibaba.version>
        <spring-cloud.version>2023.0.1</spring-cloud.version>
        <spring-webmvc.version>6.1.16</spring-webmvc.version> <!-- 或者更高版本 -->
        <lombok>1.18.30</lombok>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
            <version>1.18.30</version>
            <scope>provided</scope>
        </dependency>

        <!-- Nacos 服务配置 -->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
        </dependency>
        <!-- Nacos 服务发现 -->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <!-- 服务发现: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>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>${spring-boot.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <dependency>
                <groupId>com.alibaba.cloud</groupId>
                <artifactId>spring-cloud-alibaba-dependencies</artifactId>
                <version>${spring-cloud-alibaba.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

Spring Cloud集成nacos

application.xml配置:

# SpringBoot Configuration
server:
    port: 8080

spring:
    profiles:
    	# 此处可为空,为空和default等价
    	# 通过修改active的值来修改运行的环境配置
        active: dev
    # 应用名可以自定义
    application:
        name: micro-service01
    # 使用字符串填充的方式设置要读取的配置
    config:
        import:
            - nacos:${spring.cloud.nacos.config.prefix}.${spring.cloud.nacos.config.file-extension}?refreshEnabled=true
            - nacos:${spring.cloud.nacos.config.prefix}-${spring.profiles.active}.${spring.cloud.nacos.config.file-extension}?refreshEnabled=true
    cloud:
        nacos:
        	# nacos的ip、登录账号以及密码可统一设置,或者在 config以及discovery中单独设置
            username: nacos
            password: nacos
            server-addr: 127.0.0.1:8848
            # config设置要读取的nacos配置
            config:
                enabled: true
                namespace: learn-cloud
                # 设置要读取的nacos配置的格式
                file-extension: yaml
                prefix: micro-service
            # discovery设置服务被发现的设置,比如此处设置服务在learn-cloud的命名空间被发现
            discovery:
                namespace: learn-cloud
                register-enabled: true

management:
    endpoint:
        health:
            show-details: always
    endpoints:
        web:
            exposure:
                include: "*"

logging:
    level:
        com.alibaba.cloud.nacos.configdata: debug

在Spring Boot启动类获取一下使用的环境配置,然后修改spring.profiles.active的值来验证一下是否成功切换配置。


/*
 * @EnableDiscoveryClient 开启服务注册发现的功能
 */
@SpringBootApplication
@EnableDiscoveryClient
public class MicroService01Application {

    public static void main(String[] args) throws InterruptedException {
        ConfigurableApplicationContext applicationContext = SpringApplication.run(MicroService01Application.class, args);
        while (true) {
            String userName = applicationContext.getEnvironment().getProperty("User.name");
            String userAge = applicationContext.getEnvironment().getProperty("User.age");
            //获取当前部署的环境
            String currentEnv = applicationContext.getEnvironment().getProperty("current.env");
            String currentConfig = applicationContext.getEnvironment().getProperty("current.config");
            System.err.println("in "+currentEnv+" environment; "+"Config:"+ currentConfig +"; Username :" + userName + "; Age: " + userAge);
            TimeUnit.SECONDS.sleep(1);
        }
    }
}

--------------------------------------------------------2025.03.26-----------------------------------------------------------------
今天在云服务器上配置了nacos,发现服务居然注册不上,折腾了好久才知道需要在安全组的入方向额外开放9848和9849这两个端口

### Nacos 2.4.3 整合 Spring Boot 使用教程 #### 准备工作 为了使NacosSpring Boot顺利集成,需先获取并编译Nacos源码。这可以通过Fork的方式拉取指定版本的源码来实现: ```bash git clone https://github.com/alibaba/nacos.git cd nacos git checkout -b 2.4.3-analysis 2.4.3 mvn clean install -Dmaven.test.skip=true ``` 上述命令用于克隆仓库至本地,并切换到`2.4.3`标签创建的新分支上进行编译操作[^2]。 #### 创建父项目及子模块 构建一个多模块Maven工程作为基础框架,在此之上分别定义提供者(`provider`)和服务消费者(`consumer`)两个角色的具体应用实例。确保所使用的Spring Boot和Spring Cloud版本相互兼容非常重要[^3]。 ##### 父项目的pom.xml文件配置如下所示: ```xml <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.7.0</version><!-- 版本号应根据实际情况调整 --> <relativePath/> <!-- lookup parent from repository --> </parent> <dependencyManagement> <dependencies> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-alibaba-dependencies</artifactId> <version>${alibaba.spring.version}</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> ``` #### 子模块配置 对于每一个子模块而言,除了继承自父POM外还需要单独引入必要的依赖项以便能够访问Nacos的服务发现功能以及配置中心特性。 ##### `nacos-provider` 配置样例 在`application.yml`中加入以下内容以启用服务注册能力: ```yaml server: port: 8081 spring: application: name: nacos-provider management: endpoints: web: exposure: include: "*" cloud: nacos: discovery: server-addr: localhost:8848 # Nacos服务器地址 ``` ##### `nacos-consumer` 配置样例 同样地,在另一个微服务的应用程序属性文件里设置相应的客户端参数从而允许其查找其他已知的服务列表并向它们发起请求: ```yaml server: port: 8082 spring: application: name: nacos-consumer feign: hystrix: enabled: false ribbon: ReadTimeout: 30000 ConnectTimeout: 30000 cloud: nacos: discovery: server-addr: localhost:8848 # 同样的Nacos服务器地址 ``` #### 实现Controller接口 为了让整个系统运转起来,还需开发若干RESTful API端点供外部调用;这里简单给出一个基于Feign声明式的HTTP客户端例子用来展示跨进程间通信的过程。 ##### Provider中的控制器方法 ```java @RestController @RequestMapping("/api/v1/provider") public class HelloController { @GetMapping("/hello/{name}") public String hello(@PathVariable(value = "name") final String name){ return "Hello," + name; } } ``` ##### Consumer中的FeignClient定义 ```java @FeignClient(name="nacos-provider", fallbackFactory=HelloServiceFallback.class) public interface HelloService { @RequestMapping(method = RequestMethod.GET,value="/api/v1/provider/hello/{name}") String sayHiFromProvider(@PathVariable("name")String name); } ``` 最后一步就是启动所有的应用程序组件并通过浏览器或其他工具验证一切正常运作了!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

PABL01

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值