Maven使用

微服务

非单体项目,可以用下面的脚本启动微服务。

#!/bin/bash

# 获取服务名称和额外参数
SERVICE_NAME=$1
shift # 移除第一个参数(服务名),将剩余参数保存到 $@
EXTRA_ARGS="$@"

# 检查是否输入服务名称
if [ -z "$SERVICE_NAME" ]; then
echo "Usage: ./run.sh <servicename|all> [additional_maven_args]"
exit 1
fi

# 定义运行单个服务的函数
run_service() {
local service=$1
local args=$2
echo "Building and running $service with args: $args..."
mvn clean install -pl $service -am
if [ "$service" == "gateway/" ]; then
echo "Gateway starting..."
mvn spring-boot:run -pl $service -Dreactor.netty.http.server.accessLogEnabled=true $args
else
mvn spring-boot:run -pl $service $args
fi
}

# 如果输入 "all",运行所有服务(默认不传参)
if [ "$SERVICE_NAME" == "all" ]; then
echo "Building and running all services..."
mvn clean install -pl "!generator"
for module in $(mvn help:evaluate -Dexpression=project.modules -q -DforceStdout | sed -e 's/<[^>]*>//g' -e 's/\s*//g' | tr ',' '\n'); do
if [ "$module" != "generator" ]; then
echo "Running $module..."
mvn spring-boot:run -pl $module
fi
done
else
# 运行指定的单个服务,并传递额外参数
run_service $SERVICE_NAME "$EXTRA_ARGS"
fi

核心命令是这一条:

mvn spring-boot:run -pl $your_service

想要增加JVM参数,指定端口可以加上

-Dspring-boot.run.arguments=--server.port=$your_port

全局换源

找到 settings.xml 文件:

  • 全局配置:位于 Maven 安装目录的 conf 文件夹下(例如/usr/local/maven/conf/settings.xml)。
  • 用户配置:位于用户主目录下的 .m2 文件夹中(例如~/.m2/settings.xml)。
<settings>
<!-- 其他配置 -->
<mirrors>
<!-- 阿里云 Maven 镜像 -->
<mirror>
<id>aliyun-maven</id>
<name>阿里云公共仓库</name>
<url>https://maven.aliyun.com/repository/public</url>
<mirrorOf>central</mirrorOf> <!-- 指定替换中央仓库 -->
</mirror>
<!-- 华为云 Maven 镜像 -->
<mirror>
<id>huaweicloud</id>
<name>华为云 Maven</name>
<url>https://mirrors.huaweicloud.com/repository/maven/</url>
<mirrorOf>central</mirrorOf>
</mirror>
</mirrors>
<!-- 其他配置 -->
</settings>