服务发现
  # Nacos
单机版启动命令startup.sh -m standalone,默认用户名密码 nacos,高版本在没有内置用户的情况下首次登录就是创建用户
# 服务发现
Maven依赖
<!-- 服务注册发现 -->
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
配置文件
spring:
  cloud:
    nacos:
      server-addr: 127.0.0.1:8848    # Nacos注册中心地址
			username: nacos
			password: nacos
      discovery:  # 服务注册发现
        server-addr: 127.0.0.1:8848  # Nacos注册中心地址
        username: nacos
        password: nacos
        namespace: xxxx       # 命名空间ID
				group: DEFAULT_GROUP  # 分组名称
        cluster-name: HK      # 集群名称
        ephemeral: true       # 是否为临时实例,默认为true
- Nacos 存储服务级别:
- Namespace 命名空间:命名空间属于最外层,一般用作环境隔离,例如 dev 和 prod 两个命名空间,两个命名空间中的微服务互相不可访问
 - Group 分组:微服务较多时可以将每个微服务单独放到一个分组中,例如订单模块的都放在 order 分组中
- discovery:站在注册中心的角度来看微服务之间互相远程调用并不区分分组,只要服务注册上来无论在哪个分组下都能调用到
 - config:站在配置中心的角度来看配置文件是区分分组的,如果配置中心写了
DEFAULT_GROUP分组那么其他分组下的配置文件就无法读取 
 - Service/Data 服务:服务指拆出来的独立的模块,例如用户模块,订单模块,支付模块
 - Cluster 集群:服务下可以搭建集群,例如在阿里云部署了三个用户服务,这三个可以放在同一个集群中,在远程调用场景下会优先选择同集群内的微服务以减少网络延迟
 
 
# 配置中心
Maven依赖
<!-- 动态配置更新 -->
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<!-- 高版本需要单独引入读取bootstrap文件的依赖 -->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-bootstrap</artifactId>
</dependency>
配置文件
spring:
  cloud:
    nacos:
      server-addr: 127.0.0.1:8848    # Nacos注册中心地址
			username: nacos
			password: nacos
      config:     # 动态配置更新
        server-addr: 127.0.0.1:8848  # Nacos注册中心地址
        username: nacos
        password: nacos
        file-extension: yml       # 配置中心 配置文件扩展名
        shared-configs:            # 读取某个共享的配置文件
          - data-id: shared-swagger.${spring.cloud.nacos.config.file-extension}
- 动态更新:DataId 推荐以【服务名-环境.yaml】格式命名,项目中通过
@ConfigurationProperties注入的配置都会动态更新,使用@Value注入的需要类上加@RefreshScope注解- 动态配置更新可能空指针异常,需要改成
@RefreshScope(proxyMode = ScopedProxyMode.DEFAULT)这种写法,或者在类中为该属性提供一个 get 方法,也可取到值 
 - 动态配置更新可能空指针异常,需要改成
 - 共享配置:当 DataId 默认以【服务名-环境.yaml】命名时属于 profiles 环境配置,直接使用【服务名.yaml】为共享配置,无论当前是什么环境都会生效
 - 配置优先级:云端环境 > 云端共享 > 本地配置
 
# Eureka
Eureka 不同与 Naocs 需要单独启动,它属于微服务中的一个项目,服务端用server依赖搭建客户端用client依赖进行注册
Maven依赖
<!-- 服务端依赖,需要使用@EnableEurekaServer注解 -->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
<!-- 客户端依赖 -->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
配置文件
eureka:
  client:
    service-url:
      defaultZone: http://127.0.0.1:8000/eureka # 注册中心地址,服务端客户端通用
上次更新: 2024-12-06, 17:32:54