从0到1搭建Spring-Cloud项目
...About 12 min
文本基于Spring-Boot 2.7.10版本搭建,使用的SpringCloud版本为2021.0.5, 使用nacos作为注册中心和配置中心。
服务版本说明
由于Spring Boot 3.0,SpringBoot 2.7~2.4 和 SpringBoot 2.4以下版本之间变化较大比较大,所以存在以下三个对应关系:
SpringCloud 2022.x 分支
SpringBoot版本 | SpringCloud版本 | SpringCloud Alibaba版本 |
---|---|---|
3.0.0 | Spring Cloud 2022.0.0 | 2022.0.0.0-RC* |
SpringCloud 2021.x 分支
SpringBoot版本 | SpringCloud版本 | SpringCloud Alibaba版本 |
---|---|---|
2.6.13 | Spring Cloud 2021.0.5 | 2021.0.5.0* |
2.6.11 | Spring Cloud 2021.0.4 | 2021.0.4.0 |
2.6.3 | Spring Cloud 2021.0.1 | 2021.0.1.0 |
2.4.2 | Spring Cloud 2020.0.1 | 2021.1 |
SpringBoot 2.2.x 分支
SpringBoot版本 | SpringCloud版本 | SpringCloud Alibaba版本 |
---|---|---|
2.3.12.RELEASE | Spring Cloud Hoxton.SR12 | 2.2.10-RC1* |
2.3.12.RELEASE | Spring Cloud Hoxton.SR12 | 2.2.9.RELEAS |
2.3.12.RELEASE | Spring Cloud Hoxton.SR12 | 2.2.8.RELEAS |
2.3.12.RELEASE | Spring Cloud Hoxton.SR12 | 2.2.7.RELEASE |
2.3.2.RELEASE | Spring Cloud Hoxton.SR9 | 2.2.6.RELEASE |
2.2.5.RELEASE | Spring Cloud Hoxton.SR3 | 2.2.1.RELEASE |
2.2.X.RELEASE | Spring Cloud Hoxton.RELEASE | 2.2.0.RELEASE |
2.1.13.RELEASE | Spring Cloud Greenwich.SR6 | 2.1.4.RELEASE |
2.1.X.RELEASE | Spring Cloud Greenwich | 2.1.2.RELEASE |
各版本最新对应关系请查看:
- https://github.com/alibaba/spring-cloud-alibaba/wiki/版本说明
- https://docs.spring.io/spring-cloud/docs/current/reference/html/
搭建项目公共的parent
parent初始化
pom.xml文件
<?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>2.7.10</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>cn.moremind</groupId>
<artifactId>moremind-example-boot-starter-parent</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>moremind-example-boot-starter-parent</name>
<packaging>pom</packaging>
<description>moremind-example-boot-starter-parent</description>
<properties>
<java.version>1.8</java.version>
<spring-boot.version>2.7.10</spring-boot.version>
<spring-cloud-alibaba.version>2021.0.5.0</spring-cloud-alibaba.version>
<spring-cloud.version>2021.0.5</spring-cloud.version>
<commons-lang3.version>3.12.0</commons-lang3.version>
<hutool.version>5.8.15</hutool.version>
<commons-collections4.version>4.4</commons-collections4.version>
<commons-io.version>2.11.0</commons-io.version>
</properties>
<!-- 申明依赖 -->
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>${spring-boot.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>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- 通用工具类 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>${hutool.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>${commons-collections4.version}</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<!-- 发布地址 -->
<distributionManagement>
<repository>
<id>nexus-releases</id>
<url>https://domain/nexus/content/repositories/releases/</url>
</repository>
<snapshotRepository>
<id>nexus-snapshots</id>
<url>https://domain/nexus/content/repositories/snapshots/</url>
</snapshotRepository>
</distributionManagement>
<repositories>
<!-- internal repository -->
<repository>
<id>nexus</id>
<name>Nexus Snapshot Repository</name>
<url>https://domain/nexus/content/groups/public/</url>
<layout>default</layout>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
<repository>
<id>aliyun-releases</id>
<name>Aliyun Repository</name>
<url>https://maven.aliyun.com/repository/public</url>
</repository>
<repository>
<id>central</id>
<name>Central Repository</name>
<url>https://repo.maven.apache.org/maven2</url>
<layout>backup</layout>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<!-- 配置从哪个仓库中下载构件,即jar包 -->
<pluginRepositories>
<pluginRepository>
<id>nexus</id>
<name>Nexus Snapshot Repository</name>
<url>https://domain/nexus/content/groups/public/</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>false</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
</project>
打包安装到本地
执行命令mvn clean install
打包到本地
新建moremind-example-module1
moremind-example-module1初始化
pom.xml文件配置
<?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>cn.moremind</groupId>
<artifactId>moremind-example-boot-starter-parent</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath/>
</parent>
<artifactId>moremind-example-module1</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>pom</packaging>
<name>moremind-example-module1</name>
<description>moremind-example-module1</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
删除无用文件
删除src目录/.mvn目录以及其他无用文件
新建moremind-example-module1-api模块
moremind-example-module1-api初始化
moremind-example-module1-api的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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>cn.moremind</groupId>
<artifactId>moremind-example-module1</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<packaging>jar</packaging>
<artifactId>moremind-example-module1-api</artifactId>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<mybatis-plus.version>3.5.3.1</mybatis-plus.version>
<mysql-driver.version>8.0.32</mysql-driver.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-undertow</artifactId>
</dependency>
<!-- nacos discovery -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<!-- nacos config -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-loadbalancer</artifactId>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>${mybatis-plus.version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql-driver.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
配置多环境以及nacos
配置applicatioin-dev.yml
server:
port: 8001
## Spring Information
spring:
application:
name: module1-api
main:
allow-bean-definition-overriding: true
# config:
# import:
# # - optional:nacos:application-dev.yml # 监听 PROVIDER_GROUP :module1-api-dev.yml
# - optional:nacos:${spring.application.name}-${spring.profiles.active}.${spring.cloud.nacos.config.file-extension} # 监听 DEFAULT_GROUP:module1-api-dev.yaml
# # - optional:nacos:module1-api-dev.yaml?group=group_01 # 覆盖默认 group,监听 group_01:module1-api-dev.yaml
# # - optional:nacos:module1-api-dev.yaml?group=group_02&refreshEnabled=false # 不开启动态刷新
# - nacos:${spring.application.name}-${spring.profiles.active}.${spring.cloud.nacos.config.file-extension} # 在拉取nacos配置异常时会快速失败,会导致 spring 容器启动失败
# 可在nacos配置的文件
datasource:
url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai&zeroDateTimeBehavior=convertToNull&allowPublicKeyRetrieval=true
username: root
password: admin@123456
driver-class-name: com.mysql.cj.jdbc.Driver
cloud:
nacos:
server-addr: 127.0.0.1:8848
username: nacos
password: nacos
config:
enabled: false
namespace: 3c42f17a-23f2-4f4f-8cf4-bfe086289312
group: user-center
context-path: /nacos
file-extension: yaml
discovery:
enabled: true
namespace: public
service: ${spring.application.name}
# actuator
management:
endpoints:
web:
exposure:
include:
- 'health'
- 'prometheus'
enabled-by-default: true
# mybatis plus
mybatis-plus:
config-location: classpath:/mybatis/mybatis-config.xml
mapper-locations: classpath:/mappers/*.xml
# feign config
feign:
client:
config:
default:
connectTimeout: 3000
readTimeout: 3000
配置application-test.yml
server:
port: 8001
# Spring Information
spring:
application:
name: module1-api
main:
allow-bean-definition-overriding: true
config:
import:
# - optional:nacos:application-dev.yml # 监听 PROVIDER_GROUP :module1-api-dev.yml
- optional:nacos:${spring.application.name}-${spring.profiles.active}.${spring.cloud.nacos.config.file-extension} # 监听 DEFAULT_GROUP:module1-api-dev.yaml
# - optional:nacos:module1-api-dev.yaml?group=group_01 # 覆盖默认 group,监听 group_01:module1-api-dev.yaml
# - optional:nacos:module1-api-dev.yaml?group=group_02&refreshEnabled=false # 不开启动态刷新
# - nacos:${spring.application.name}-${spring.profiles.active}.${spring.cloud.nacos.config.file-extension} # 在拉取nacos配置异常时会快速失败,会导致 spring 容器启动失败
cloud:
nacos:
config:
enabled: true
server-addr: 127.0.0.1:8848
username: nacos
password: nacos
# namespace: 3c42f17a-23f2-4f4f-8cf4-bfe086289312
group: DEFAULT_GROUP
context-path: /nacos
file-extension: yaml
refresh-enabled: true
配置application-prod.yml
server:
port: 8001
# Spring Information
spring:
application:
name: module1-api
main:
allow-bean-definition-overriding: true
config:
import:
# - optional:nacos:application-dev.yml # 监听 PROVIDER_GROUP :module1-api-dev.yml
- optional:nacos:${spring.application.name}-${spring.profiles.active}.${spring.cloud.nacos.config.file-extension} # 监听 DEFAULT_GROUP:module1-api-dev.yaml
# - optional:nacos:module1-api-dev.yaml?group=group_01 # 覆盖默认 group,监听 group_01:user-center-service-dev.yaml
# - optional:nacos:module1-api-dev.yaml?group=group_02&refreshEnabled=false # 不开启动态刷新
# - nacos:${spring.application.name}-${spring.profiles.active}.${spring.cloud.nacos.config.file-extension} # 在拉取nacos配置异常时会快速失败,会导致 spring 容器启动失败
cloud:
nacos:
config:
enabled: true
server-addr: 127.0.0.1:8848
username: nacos
password: nacos
# namespace: 3c42f17a-23f2-4f4f-8cf4-bfe086289312
group: DEFAULT_GROUP
context-path: /nacos
file-extension: yaml
refresh-enabled: true
module1-api-test.yaml文件配置
spring:
datasource:
url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai&zeroDateTimeBehavior=convertToNull&allowPublicKeyRetrieval=true
username: root
password: admin@123456
driver-class-name: com.mysql.cj.jdbc.Driver
cloud:
nacos:
discovery:
enabled: true
server-addr: 127.0.0.1:8848
username: nacos
password: nacos
namespace: public
service: ${spring.application.name}
# actuator
management:
endpoints:
web:
exposure:
include:
- 'health'
- 'prometheus'
enabled-by-default: true
# mybatis plus
mybatis-plus:
config-location: classpath:/mybatis/mybatis-config.xml
mapper-locations: classpath:/mappers/*.xml
# feign config
feign:
client:
config:
default:
connectTimeout: 3000
readTimeout: 3000
module1-api-prod.yaml文件配置
spring:
datasource:
url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai&zeroDateTimeBehavior=convertToNull&allowPublicKeyRetrieval=true
username: root
password: admin@123456
driver-class-name: com.mysql.cj.jdbc.Driver
cloud:
nacos:
discovery:
enabled: true
server-addr: 127.0.0.1:8848
username: nacos
password: nacos
namespace: public
service: ${spring.application.name}
# actuator
management:
endpoints:
web:
exposure:
include:
- 'health'
- 'prometheus'
enabled-by-default: true
# mybatis plus
mybatis-plus:
config-location: classpath:/mybatis/mybatis-config.xml
mapper-locations: classpath:/mappers/*.xml
# feign config
feign:
client:
config:
default:
connectTimeout: 3000
readTimeout: 3000
配置logback文件
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<shutdownHook class="ch.qos.logback.core.hook.DelayingShutdownHook"/>
<property name="LOG_HOME" value="${log.home:-./logs}"/>
<property name="LOG_APP_NAME" value="${log.app-name:-module1-api}"/>
<property name="MAX_SINGLE_LOG_FILE_SIZE" value="${log.max-single-log-file-size:-100MB}"/>
<property name="MAX_LOG_FILE_HISTORY" value="${log.max-log-file-history:-7}"/>
<property name="LOG_FILE_TOTAL_CAPACITY" value="${log.log-file-total-capacity:-10GB}"/>
<property name="ASYNC_DISCARDING_THRESHOLD" value="${log.async.discarding-threshold:-0}"/>
<property name="ASYNC_LOG_QUEUE_SIZE" value="${log.async.queue-size:-256}"/>
<property name="LOG_PATTERN"
value="%red(%d{yyyy-MM-dd HH:mm:ss}) %green([%thread]) %highlight(%-5level) %boldMagenta(%logger) - %cyan(%msg%n)"/>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>${LOG_PATTERN}</pattern>
</encoder>
</appender>
<appender name="ASYNC_STDOUT" class="ch.qos.logback.classic.AsyncAppender">
<discardingThreshold>${ASYNC_DISCARDING_THRESHOLD}</discardingThreshold>
<queueSize>${ASYNC_LOG_QUEUE_SIZE}</queueSize>
<includeCallerData>true</includeCallerData>
<appender-ref ref="STDOUT"/>
</appender>
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${LOG_HOME}/${LOG_APP_NAME}.log</file>
<append>true</append>
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>${LOG_HOME}/${LOG_APP_NAME}.%d{yyyy-MM-dd}.%i.log.zip</fileNamePattern>
<maxFileSize>${MAX_SINGLE_LOG_FILE_SIZE}</maxFileSize>
<maxHistory>${MAX_LOG_FILE_HISTORY}</maxHistory>
<totalSizeCap>${LOG_FILE_TOTAL_CAPACITY}</totalSizeCap>
</rollingPolicy>
<encoder>
<pattern>${LOG_PATTERN}</pattern>
</encoder>
</appender>
<appender name="ASYNC_FILE" class="ch.qos.logback.classic.AsyncAppender">
<discardingThreshold>${ASYNC_DISCARDING_THRESHOLD}</discardingThreshold>
<queueSize>${ASYNC_LOG_QUEUE_SIZE}</queueSize>
<includeCallerData>true</includeCallerData>
<appender-ref ref="FILE"/>
</appender>
<appender name="ERROR_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>ERROR</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
<file>${LOG_HOME}/${LOG_APP_NAME}-error.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>${LOG_HOME}/${LOG_APP_NAME}.%d{yyyy-MM-dd}-error.%i.log.zip</fileNamePattern>
<maxFileSize>${MAX_SINGLE_LOG_FILE_SIZE}</maxFileSize>
<maxHistory>${MAX_LOG_FILE_HISTORY}</maxHistory>
<totalSizeCap>${LOG_FILE_TOTAL_CAPACITY}</totalSizeCap>
</rollingPolicy>
<encoder>
<pattern>${LOG_PATTERN}</pattern>
</encoder>
</appender>
<appender name="ASYNC_ERROR_FILE" class="ch.qos.logback.classic.AsyncAppender">
<discardingThreshold>${ASYNC_DISCARDING_THRESHOLD}</discardingThreshold>
<queueSize>${ASYNC_LOG_QUEUE_SIZE}</queueSize>
<includeCallerData>false</includeCallerData>
<appender-ref ref="ERROR_FILE"/>
</appender>
<root level="INFO">
<appender-ref ref="ASYNC_STDOUT"/>
<appender-ref ref="ASYNC_FILE"/>
<appender-ref ref="ASYNC_ERROR_FILE"/>
</root>
</configuration>
启动测试
启动nacos
为了测试,本地都使用nacos单机模式启动,启动命令./startup.sh -m "standalone"
设置spring.profiles.active=dev参数
- dev模式为本地开发模式,应用配置无需配置在配置中心,直接启动module1,无错误并如下日志表示启动成功。
[main] INFO cn.moremind.moremind.example.module1.api.MoremindExampleModule1ApiApplication - The following 1 profile is active: "dev"
[main] INFO org.springframework.cloud.commons.util.InetUtils - Cannot determine local hostname
[main] WARN org.springframework.cloud.loadbalancer.config.LoadBalancerCacheAutoConfiguration$LoadBalancerCaffeineWarnLogger - Spring Cloud LoadBalancer is currently working with the default cache. While this cache implementation is useful for development and tests, it's recommended to use Caffeine cache in production.You can switch to using Caffeine cache, by adding it and org.springframework.cache.caffeine.CaffeineCacheManager to the classpath.
[main] INFO org.springframework.boot.actuate.endpoint.web.EndpointLinksResolver - Exposing 1 endpoint(s) beneath base path '/actuator'
[main] INFO io.undertow - starting server: Undertow - 2.2.23.Final
[main] INFO org.xnio - XNIO version 3.8.7.Final
[main] INFO org.xnio.nio - XNIO NIO Implementation Version 3.8.7.Final
[main] INFO org.jboss.threads - JBoss Threads version 3.1.0.Final
[main] INFO org.springframework.boot.web.embedded.undertow.UndertowWebServer - Undertow started on port(s) 8001 (http)
[main] INFO com.alibaba.nacos.plugin.auth.spi.client.ClientAuthPluginManager - [ClientAuthPluginManager] Load ClientAuthService com.alibaba.nacos.client.auth.impl.NacosClientAuthServiceImpl success.
[main] INFO com.alibaba.nacos.plugin.auth.spi.client.ClientAuthPluginManager - [ClientAuthPluginManager] Load ClientAuthService com.alibaba.nacos.client.auth.ram.RamClientAuthServiceImpl success.
[main] INFO com.alibaba.cloud.nacos.registry.NacosServiceRegistry - nacos registry, DEFAULT_GROUP module1-api 192.168.81.152:8001 register finished
[main] INFO org.springframework.cloud.commons.util.InetUtils - Cannot determine local hostname
[main] INFO cn.moremind.moremind.example.module1.api.MoremindExampleModule1ApiApplication - Started MoremindExampleModule1ApiApplication in 11.372 seconds (JVM running for 12.328)
[RMI TCP Connection(1)-192.168.81.152] INFO com.zaxxer.hikari.HikariDataSource - HikariPool-1 - Starting...
[RMI TCP Connection(1)-192.168.81.152] INFO com.zaxxer.hikari.HikariDataSource - HikariPool-1 - Start completed.
[RMI TCP Connection(3)-192.168.81.152] INFO io.undertow.servlet - Initializing Spring DispatcherServlet 'dispatcherServlet'
[RMI TCP Connection(3)-192.168.81.152] INFO org.springframework.web.servlet.DispatcherServlet - Initializing Servlet 'dispatcherServlet'
[RMI TCP Connection(3)-192.168.81.152] INFO org.springframework.web.servlet.DispatcherServlet - Completed initialization in 1 ms
- nacos注册中心已注册module1-api服务。
设置spring.profiles.active=test参数
将module1-api-test.yaml文件添加到nacos中
以test环境进行启动,见如下日志则启动成功
[main] INFO cn.moremind.moremind.example.module1.api.MoremindExampleModule1ApiApplication - The following 1 profile is active: "test"
[main] INFO com.alibaba.cloud.nacos.configdata.NacosConfigDataLoader - [Nacos Config] Load config[dataId=module1-api-test.yaml, group=DEFAULT_GROUP] success
[main] INFO org.springframework.cloud.commons.util.InetUtils - Cannot determine local hostname
[main] WARN org.springframework.cloud.loadbalancer.config.LoadBalancerCacheAutoConfiguration$LoadBalancerCaffeineWarnLogger - Spring Cloud LoadBalancer is currently working with the default cache. While this cache implementation is useful for development and tests, it's recommended to use Caffeine cache in production.You can switch to using Caffeine cache, by adding it and org.springframework.cache.caffeine.CaffeineCacheManager to the classpath.
[main] INFO org.springframework.boot.actuate.endpoint.web.EndpointLinksResolver - Exposing 1 endpoint(s) beneath base path '/actuator'
[main] INFO io.undertow - starting server: Undertow - 2.2.23.Final
[main] INFO org.xnio - XNIO version 3.8.7.Final
[main] INFO org.xnio.nio - XNIO NIO Implementation Version 3.8.7.Final
[main] INFO org.jboss.threads - JBoss Threads version 3.1.0.Final
[main] INFO org.springframework.boot.web.embedded.undertow.UndertowWebServer - Undertow started on port(s) 8001 (http)
[main] INFO com.alibaba.nacos.plugin.auth.spi.client.ClientAuthPluginManager - [ClientAuthPluginManager] Load ClientAuthService com.alibaba.nacos.client.auth.impl.NacosClientAuthServiceImpl success.
[main] INFO com.alibaba.nacos.plugin.auth.spi.client.ClientAuthPluginManager - [ClientAuthPluginManager] Load ClientAuthService com.alibaba.nacos.client.auth.ram.RamClientAuthServiceImpl success.
[main] INFO com.alibaba.cloud.nacos.registry.NacosServiceRegistry - nacos registry, DEFAULT_GROUP module1-api 192.168.81.152:8001 register finished
[main] INFO org.springframework.cloud.commons.util.InetUtils - Cannot determine local hostname
[main] INFO cn.moremind.moremind.example.module1.api.MoremindExampleModule1ApiApplication - Started MoremindExampleModule1ApiApplication in 12.291 seconds (JVM running for 13.54)
[main] INFO com.alibaba.cloud.nacos.refresh.NacosContextRefresher - [Nacos Config] Listening config: dataId=module1-api-test.yaml, group=DEFAULT_GROUP
[RMI TCP Connection(2)-192.168.81.152] INFO io.undertow.servlet - Initializing Spring DispatcherServlet 'dispatcherServlet'
[RMI TCP Connection(2)-192.168.81.152] INFO org.springframework.web.servlet.DispatcherServlet - Initializing Servlet 'dispatcherServlet'
[RMI TCP Connection(2)-192.168.81.152] INFO org.springframework.web.servlet.DispatcherServlet - Completed initialization in 1 ms
[RMI TCP Connection(1)-192.168.81.152] INFO com.zaxxer.hikari.HikariDataSource - HikariPool-1 - Starting...
[RMI TCP Connection(1)-192.168.81.152] INFO com.zaxxer.hikari.HikariDataSource - HikariPool-1 - Start completed.
设置spring.profiles.active=prod参数
将module1-api-prod.yaml文件添加到nacos中
以prod环境进行启动,见如下日志则启动成功
[main] INFO cn.moremind.moremind.example.module1.api.MoremindExampleModule1ApiApplication - The following 1 profile is active: "prod"
[main] INFO com.alibaba.cloud.nacos.configdata.NacosConfigDataLoader - [Nacos Config] Load config[dataId=module1-api-prod.yaml, group=DEFAULT_GROUP] success
[main] INFO org.springframework.cloud.commons.util.InetUtils - Cannot determine local hostname
[main] WARN org.springframework.cloud.loadbalancer.config.LoadBalancerCacheAutoConfiguration$LoadBalancerCaffeineWarnLogger - Spring Cloud LoadBalancer is currently working with the default cache. While this cache implementation is useful for development and tests, it's recommended to use Caffeine cache in production.You can switch to using Caffeine cache, by adding it and org.springframework.cache.caffeine.CaffeineCacheManager to the classpath.
[main] INFO org.springframework.boot.actuate.endpoint.web.EndpointLinksResolver - Exposing 1 endpoint(s) beneath base path '/actuator'
[main] INFO io.undertow - starting server: Undertow - 2.2.23.Final
[main] INFO org.xnio - XNIO version 3.8.7.Final
[main] INFO org.xnio.nio - XNIO NIO Implementation Version 3.8.7.Final
[main] INFO org.jboss.threads - JBoss Threads version 3.1.0.Final
[main] INFO org.springframework.boot.web.embedded.undertow.UndertowWebServer - Undertow started on port(s) 8001 (http)
[main] INFO com.alibaba.nacos.plugin.auth.spi.client.ClientAuthPluginManager - [ClientAuthPluginManager] Load ClientAuthService com.alibaba.nacos.client.auth.impl.NacosClientAuthServiceImpl success.
[main] INFO com.alibaba.nacos.plugin.auth.spi.client.ClientAuthPluginManager - [ClientAuthPluginManager] Load ClientAuthService com.alibaba.nacos.client.auth.ram.RamClientAuthServiceImpl success.
[main] INFO com.alibaba.cloud.nacos.registry.NacosServiceRegistry - nacos registry, DEFAULT_GROUP module1-api 192.168.81.152:8001 register finished
[main] INFO org.springframework.cloud.commons.util.InetUtils - Cannot determine local hostname
[main] INFO cn.moremind.moremind.example.module1.api.MoremindExampleModule1ApiApplication - Started MoremindExampleModule1ApiApplication in 12.291 seconds (JVM running for 13.54)
[main] INFO com.alibaba.cloud.nacos.refresh.NacosContextRefresher - [Nacos Config] Listening config: dataId=module1-api-test.yaml, group=DEFAULT_GROUP
[RMI TCP Connection(2)-192.168.81.152] INFO io.undertow.servlet - Initializing Spring DispatcherServlet 'dispatcherServlet'
[RMI TCP Connection(2)-192.168.81.152] INFO org.springframework.web.servlet.DispatcherServlet - Initializing Servlet 'dispatcherServlet'
[RMI TCP Connection(2)-192.168.81.152] INFO org.springframework.web.servlet.DispatcherServlet - Completed initialization in 1 ms
[RMI TCP Connection(1)-192.168.81.152] INFO com.zaxxer.hikari.HikariDataSource - HikariPool-1 - Starting...
[RMI TCP Connection(1)-192.168.81.152] INFO com.zaxxer.hikari.HikariDataSource - HikariPool-1 - Start completed.
添加测试的Controller
package cn.moremind.moremind.example.module1.api.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/test")
public class TestController {
@GetMapping("/hello")
public String hello() {
return "moremind, hello world!";
}
}
新建moremind-example-module1-openfeign子模块
moremind-example-module1-openfeign子模块的init
moremind-example-module1-api-openfeign的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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>cn.moremind</groupId>
<artifactId>moremind-example-module1</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<artifactId>moremind-example-module1-api-openfeign</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>moremind-example-module1-api-openfeign</name>
<description>module1-api-openfeign</description>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
</dependencies>
</project>
在api-feign目录下编写添加FeignClient
package cn.moremind.example.module1.api.openfeign.feign;
import cn.moremind.example.module1.api.openfeign.constants.FeignClientNames;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
@FeignClient(value = FeignClientNames.USER_CENTER_SERVICE, path = FeignClientNames.MODULE1_API_TEST)
public interface HelloFeignService {
@GetMapping("/hello")
String hello();
}
package cn.moremind.example.module1.api.openfeign.constants;
public interface FeignClientNames {
/**
* module1 service name
*/
String MODULE1_API_SERVICE = "module1-api";
String MODULE1_API_TEST = "test";
}
将moremind-example-module1-api-openfeign打包到本地
进入moremind-example-module1-api-openfeign目录执行命令mvn clean install
测试调用feign服务
moremind-example-module1-consumer项目初始化
为了方便测试,在moremind-example-module1下建立测试项目moremind-example-module1-consumer
moremind-example-module1-consumer的pom.xml文件
<?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>cn.moremind</groupId>
<artifactId>moremind-example-module1</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<artifactId>moremind-example-module1-consumer</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>moremind-example-module1-consumer</name>
<description>moremind-example-module1-consumer</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>cn.moremind</groupId>
<artifactId>moremind-example-module1-api-openfeign</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-undertow</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-loadbalancer</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
配置nacos注册中心
moremind-example-module1-consumer的application.yml配置文件如下:
server:
port: 8002
## Spring Information
spring:
application:
name: module1-consumer
cloud:
nacos:
discovery:
enabled: true
username: nacos
password: nacos
server-addr: 127.0.0.1:8848
namespace: public
service: ${spring.application.name}
消费者启动类配置
package cn.moremind.moremind.example.module1.consumer;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;
@SpringBootApplication
@EnableFeignClients(basePackages = "cn.moremind.*")
public class MoremindExampleModule1ConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(MoremindExampleModule1ConsumerApplication.class, args);
}
}
调用openfeign接口
package cn.moremind.moremind.example.module1.consumer.controller;
import cn.moremind.example.module1.api.openfeign.feign.HelloFeignService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/consumer")
public class TestHelloController {
private final HelloFeignService helloFeignService;
public TestHelloController(HelloFeignService helloFeignService) {
this.helloFeignService = helloFeignService;
}
@GetMapping("/hello")
public String testHello() {
return helloFeignService.hello();
}
}
检查nacos是否已经注册consumer服务
调用服务
GET http://localhost:8001/test/hello
HTTP/1.1 200 OK
Connection: keep-alive
Content-Type: text/plain;charset=UTF-8
Content-Length: 22
Date: Fri, 31 Mar 2023 05:10:50 GMT
moremind, hello world!
Response code: 200 (OK); Time: 5ms (5 ms); Content length: 22 bytes (22 B)
项目git管理问题
通常使用git进行项目的版本管理,通常分为以下集中管理方式
- 按照模块进行git管理
- 每个项目都是一个git仓库
项目地址
Powered by Waline v2.15.8