nacos部署
下载nacos:https://gitee.com/mirrors/Nacos?utm_source=alading&utm_campaign=repo#download 解压后首先新建数据库并执行sql
/opt/nacos/conf/nacos-mysql.sql
进行数据库配置
vim /opt/nacos/conf/application.properties
spring.datasource.platform=mysql
db.num=1
db.url.0=jdbc:mysql://127.0.0.1:3306/nacos_config?characterEncoding=utf8&config?characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true&useUnicode=true&useSSL=false&serverTimezone=UTC
db.user=user
db.password=password
启动nacos
./bin/startup.sh -m standalone
启动后,可以在 * . * . * . * :8848/nacos 访问控制台,用户名密码皆为nacos:
springboot配置
添加依赖
新建工程,在pom.xml中添加依赖
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<dependencyManagement>
<dependencies>
<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>
需注意springboot版本与alibaba版本兼容性,参考spring cloud alibaba springboot nacos 版本对应
新增配置文件
由于使用nacos配置中心,需要新建bootstrap.yaml作为配置文件
spring:
application:
name: nacos-client
profiles:
active: test
cloud:
nacos:
discovery:
server-addr: *.*.*.*:8848
namespace: 3fe465e8-3247-43f8-9d29-qqqqqqqqqqq
config:
server-addr: *.*.*.*:8848
file-extension: yaml
namespace: 3fe465e8-3247-43f8-9d29-qqqqqqqqqqq
refresh-enabled: true
如果不使用配置中心,则可以使用application.properties
server.port=5055
server.tomcat.uri-encoding=utf-8
spring.application.name=nacos-client
spring.cloud.nacos.server-addr=*.*.*.*:8848
spring.cloud.nacos.discovery.namespace=3fe465e8-3247-43f8-9d29-qqqqqqqqqqqqq
使用配置中心
使用控制台新增配置
首先在nacos控制台新建配置文件,其中dataID需严格按照规则起名,起名规则为:
${spring.application.name}-${spring.profiles.active}.${spring.cloud.nacos.config.file-extension}
例如:nacos-client-test.yaml
配置文件类型一定要与服务端bootstrap文件一致,即bootstrap.yaml对应yaml配置文件类型
完成配置后发布
springboot动态使用配置
@RestController
@RefreshScope
public class testController {
@Value("${name}")
private String name;
public void setName(String name) {
this.name = name;
}
@RequestMapping(value = "/get", method = GET)
@ResponseBody
public String get() {
return name;
}
}
@RefreshScope为动态配置注解
服务启动
|