com.alibaba.cloud
spring-cloud-starter-alibaba-nacos-config
spring:
application:
name: user-service # 服务名称
profiles:
active: dev #开发环境,这里是dev
cloud:
nacos:
server-addr: localhost:8848 # Nacos地址
config:
file-extension: yaml # 文件后缀名
检测是否成功读取nacos配置文件
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@Value("${pattern.dateformat}")
private String dateformat;
@GetMapping("/now")
public String now(){
return LocalDateTime.now().format(DateTimeFormatter.ofPattern(dateformat));
}
}
修改nacos中的配置后,微服务中无需重启即可让配置生效
实现配置热更新,可以使用两种方式
@Value注入的变量所在类上添加注解@RefreshScope
使用@ConfigurationProperties注解代替@Value注解
@Data
@Component
@ConfigurationProperties(prefix = "pattern")
public class PatternProperties{
private String dateformat;
}
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@Autowired
private PatternProperties patternProperties;
@GetMapping("/now")
public String now(){
return LocalDateTime.now().format(DateTimeFormatter.ofPattern(patternProperties.getDateformat()));
}
}
环境不同,都能读取到共享配置的属性值。
配置共享的优先级
@Data
@Component
@ConfigurationProperties(prefix = "pattern")
public class PatternProperties{
private String dateformat;
private String enShareValue;
}
@GetMapping("/porp")
public PatternProperties patternProperties(){
return patternProperties;
}
启动UserApplication和UserApplication2,