Spring Boot通过Nacos动态获取yaml配置的List数组对象并映射

方案一

需求简介

  1. 在yml文件动态配置项目名称与项目ID(动态配置通过nacos实现)
  2. 因为列表数量很少,又会改动,又不想存数据库单独建个表维护,故通过配置文件的项目列表信息

application.yml 配置

新增/删除/更改 list 即可

1
2
3
4
5
6
projects:
list:
- name: project_one
projectId: project_01
- name: project_two
projectId: project_02

配置类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@RefreshScope
@Configuration
@ConfigurationProperties(prefix = "projects")
public class Projects {

public static List<Map<String, String>> list; //static 才能拿配置值

public static List<Map<String, String>> getList() {
return list;
}

public void setList(List<Map<String, String>> list) {
Projects.list = list;
}
}

REST接口

1
2
3
4
5
6
@GetMapping("/projects")
public Result<Object> projectList() {
List<Map<String, String>> list = Projects.getMap();

return Result.ok(list);
}

缺陷:不能动态刷新

方案二(终极方案)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
alipay:
custom:
productList:
- productId: alipay_test1
productType: offline
merchantIds: 10000001,10000002
partnerId: '2088******'
commissionFlag: test1
signType: MD5
signKey: ******
callbackKey: ******
- productId: alipay_test2
productType: offline
merchantIds: 10000005,10000006
partnerId: '2088******'
commissionFlag: test2
signType: RSA
signKey: ******
callbackKey: ******
- productId: alipay_test3
productType: online
merchantIds: 10000007,10000008
partnerId: '2088******'
commissionFlag: test3
signType: RSA
signKey: ******
callbackKey: ******
1
2
3
4
5
6
7
8
9
10
11
@Configuration
@RefreshScope
public class AlipayCustomConfig {

@Bean
@ConfigurationProperties(prefix = "alipay.custom.products")
public List<Map<String, String>> products() {
// old key still exist when delete this key on nacos
return new ArrayList<>();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
@Slf4j
@RestController
public class TestController {

@Autowired
private AlipayCustomConfig alipayCustomConfig;

@GetMapping("/test")
@ResponseBody
public String getKey() {
return JsonUtil.obj2Str(alipayCustomConfig.products());
}
}

Powered by AppBlog.CN     浙ICP备14037229号

Copyright © 2012 - 2021 APP开发技术博客 All Rights Reserved.

访客数 : | 访问量 :