一、安装并启动polaris
二、新建spring cloud项目并加入相应依赖
<?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>
<groupId>com.tencent</groupId>
<artifactId>polaris2022</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.10</version>
</parent>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.tencent.cloud</groupId>
<artifactId>spring-cloud-tencent-dependencies</artifactId>
<version>1.7.0-2021.0.3</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>2021.0.3</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.tencent.cloud</groupId>
<artifactId>spring-cloud-starter-tencent-polaris-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bootstrap</artifactId>
</dependency>
</dependencies>
</project>
三、在bootstrap.yml中配置polaris相关属性:
server:
port: 48084
spring:
application:
name: ConfigExample
cloud:
polaris:
address: grpc://127.0.0.1:8091
namespace: default # 设置配置中心命名空间
config:
auto-refresh: true # auto refresh when config file changed
groups:
- name: ${spring.application.name} # group name
files: [ "config/user.properties" ]
四,编写启动类:
package cn.edu.tju;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Start {
public static void main(String[] args) {
SpringApplication.run(Start.class, args);
}
}
五、编写controller,要加上@RefreshScop注解,让配置能自动刷新
package cn.edu.tju.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RefreshScope
public class TestController {
@Value("${name}")
private String name;
@GetMapping(value = "/name")
public String name() {
return name;
}
}
六、去polaris控制台进行属性的配置:
创建配置分组 ConfigExample
创建配置文件 config/user.properties
修改user.properties的内容为:
name=amadeus2022
然后发布
七、启动spring cloud程序并访问:http://127.0.0.1:48084/name,
返回:amadeusliu2022
去polaris控制台修改name的值为amadeusliu2023
再次访问:http://127.0.0.1:48084/name
返回: amadeusliu2023