1、在linux中启动nacos
进入nacos的bin目录下(要有jdk环境)
启动:sh startup.sh -m standalone
2、登录nacos并写配置文件
代码
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/testdemo?serverTimezone=UTC&characterEncoding=utf8
username: root
password: 123456
data:
list:
- {goodsId: 12,goodsName: lcc,goodsTotal: 100}
- {goodsId: 13,goodsName: lca,goodsTotal: 30}
logging:
level:
com.cfay: debug
pattern:
dateformat: yyyy-MM-dd HH:mm:ss:SSS
3、添加nacos配置中心依赖
<!--配置中心-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
4、编写bootstrap.application配置文件
spring:
application:
name: orderservice # 服务名称
profiles:
active: dev #开发环境,这里是dev
cloud:
nacos:
server-addr: linux上nacos的IP地址:8848 # Nacos地址
config:
file-extension: yaml # 文件后缀名
5、编写配置类(可实现配置信息的热更新,即在nacos更改后,数据直接同步,无需重启服务)
package com.cfay.config;
import com.cfay.pojo.Order;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
@Component
@ConfigurationProperties(prefix = "data" )
@Data
public class NacosConfig {
private ArrayList<Order> list;
}
6、利用配置类获取nacos配置中心的配置信息
package com.cfay.controller;
import com.cfay.config.NacosConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
@RestController
@RequestMapping("/order")
public class OrderController {
@Value("${logging.pattern.dateformat}")
private String dateformat;
@Autowired
private NacosConfig nacosConfig;
@GetMapping("/hello")
public String hello() {
//使用配置中心的时间格式,格式化时间
System.out.println(LocalDateTime.now().format(DateTimeFormatter.ofPattern(dateformat)));
System.out.println(nacosConfig.getList().get(0));
return nacosConfig.getList().toString();
}
}