基本都是最新版,踩了两天的坑终于集成上了,实现了多环境配置。
使用版本
关键应用 | 版本 | 备注 |
---|---|---|
Java | 21 | Oracle OpenJDK 21.0.5 |
Spring Boot | 3.2.4 | |
Spring Cloud | 2023.0.1 | |
Spring Cloud Alibaba | 2023.0.1.3 | |
Nacos | 2.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这两个端口