SpringCloud10-Alibaba_Nacos(服务注册、配置中心、负载均衡、消息总线)

Spring Cloud Alibaba官网:

  • Git:
    https://github.com/alibaba/spring-cloud-alibaba/blob/2.2.x/README-zh.md

  • Spring Cloud:
    https://spring.io/projects/spring-cloud-alibaba/

1、Nacos介绍(NamingConfigurationService)

1.1 基本概念

  • 更易于构建云原生应用的动态服务发现,配置管理和服务管理平台;
  • Nacos =Eureka(注册)+Config(配置)+Bus(总线);
  • 官网:https://nacos.io/zh-cn/index.html

SpringCloud10-Alibaba_Nacos(服务注册、配置中心、负载均衡、消息总线)_第1张图片

  • 安装请查看:https://blog.csdn.net/weixin_45176509/article/details/123583281

1.2 使用

父工程pom.xml添加依赖;

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>com.alibaba.cloudgroupId>
            <artifactId>spring-cloud-alibaba-dependenciesartifactId>
            <version>2.2.7.RELEASEversion>
            <type>pomtype>
            <scope>importscope>
        dependency>
    dependencies>
dependencyManagement>

2、服务注册

2.1 注册服务提供者(支付模块)

  • pom.xml
       <dependency>
            <groupId>org.springframework.cloudgroupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discoveryartifactId>
            <version>0.9.0.RELEASEversion>
        dependency>

<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>cloud2022artifactId>
        <groupId>org.examplegroupId>
        <version>1.0-SNAPSHOTversion>
    parent>
    <modelVersion>4.0.0modelVersion>

    <groupId>org.payment9001groupId>
    <artifactId>cloud-alibaba-payment9001artifactId>

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloudgroupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discoveryartifactId>
            <version>0.9.0.RELEASEversion>
        dependency>
        <dependency>
            <groupId>com.commonsgroupId>
            <artifactId>commonsartifactId>
            <version>1.0-SNAPSHOTversion>
            <scope>compilescope>
        dependency>

        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-actuatorartifactId>
        dependency>
        <dependency>
            <groupId>com.baomidougroupId>
            <artifactId>mybatis-plus-boot-starterartifactId>
        dependency>
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>druid-spring-boot-starterartifactId>
            <version>1.1.10version>
        dependency>
        
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
        dependency>
        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-jdbcartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-devtoolsartifactId>
            <scope>runtimescope>
            <optional>trueoptional>
        dependency>
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <optional>trueoptional>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
        dependency>

        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-devtoolsartifactId>
            <scope>runtimescope>
            <optional>trueoptional>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-autoconfigureartifactId>
        dependency>

    dependencies>

project>


  • application.yml
server:
  port: 9001

spring:
  application:
    name: payment-nacos
  cloud:
    nacos:
      discovery:
        server-addr: 127.0.0.1:8848

management:
  endpoints:
    web:
      exposure.include: '*'

server:
  port: 9001

spring:
  application:
    name: payment-nacos
  cloud:
    nacos:
      discovery:
        server-addr: 127.0.0.1:8848
  datasource:
    url: jdbc:mysql://localhost:3306/springboot-mybatisplus?serverTimezone=Asia/Shanghai&useSSL=false&useUnicode=true&characterEncoding=utf8&characterSetResults=utf8
    username: root
    password: 123456
    driver-class-name=com: mysql.cj.jdbc.Driver

management:
  endpoints:
    web:
      exposure.include: '*'


#2、mybatis-plus配置
mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  global-config :
    db-config:
      logic-delete-value: 1
      logic-not-delete-value: 0
  mapper-locations: classpath:mapper/*.xml


  • 主启动
package com.payment;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

@SpringBootApplication
@EnableDiscoveryClient
public class NacosProviderDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(NacosProviderDemoApplication.class, args);
    }
}
  • Controller
package com.payment.Controller;

import com.commons.Entity.Result;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("nacos1/")
public class PaymentController {

    @GetMapping("/{id}")
    public Result saveEntity(@PathVariable("id") Integer id) {
        System.out.println(id);
        return new Result(200,"成功9001",id);
    }
}

  • 启动访问

SpringCloud10-Alibaba_Nacos(服务注册、配置中心、负载均衡、消息总线)_第2张图片

  • 使用以上方法再建一个服务生产者,端口为9002,其余内容相同;

2.2 注册服务消费者(消费模块)

  • pom.xml:与生产者相同

<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>cloud2022artifactId>
        <groupId>org.examplegroupId>
        <version>1.0-SNAPSHOTversion>
    parent>
    <modelVersion>4.0.0modelVersion>

    <groupId>org.consumer8083groupId>
    <artifactId>cloud-alibaba-consumer8083artifactId>

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloudgroupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discoveryartifactId>
            <version>0.9.0.RELEASEversion>
        dependency>
        <dependency>
            <groupId>com.commonsgroupId>
            <artifactId>commonsartifactId>
            <version>1.0-SNAPSHOTversion>
            <scope>compilescope>
        dependency>

        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-actuatorartifactId>
        dependency>
        <dependency>
            <groupId>com.baomidougroupId>
            <artifactId>mybatis-plus-boot-starterartifactId>
        dependency>
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>druid-spring-boot-starterartifactId>
            <version>1.1.10version>
        dependency>
        
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
        dependency>
        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-jdbcartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-devtoolsartifactId>
            <scope>runtimescope>
            <optional>trueoptional>
        dependency>
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <optional>trueoptional>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
        dependency>

        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-devtoolsartifactId>
            <scope>runtimescope>
            <optional>trueoptional>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-autoconfigureartifactId>
        dependency>

    dependencies>

project>
  • application.yml
server:
  port: 8083

spring:
  application:
    name: consumer-nacos
  cloud:
    nacos:
      discovery:
        server-addr: 127.0.0.1:8848

service-url: #注册成功的服务生产者
  nacos-user-service: http://payment-nacos



server:
  port: 8083

spring:
  application:
    name: consumer-nacos
  cloud:
    nacos:
      discovery:
        server-addr: 127.0.0.1:8848
  datasource:
    url: jdbc:mysql://localhost:3306/springboot-mybatisplus?serverTimezone=Asia/Shanghai&useSSL=false&useUnicode=true&characterEncoding=utf8&characterSetResults=utf8
    username: root
    password: 123456
    driver-class-name=com: mysql.cj.jdbc.Driver

service-url: #注册成功的服务生产者
  nacos-user-service: http://payment-nacos


#2、mybatis-plus配置
mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  global-config :
    db-config:
      logic-delete-value: 1
      logic-not-delete-value: 0
  mapper-locations: classpath:mapper/*.xml


  • 主启动
package com.consumer;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

@SpringBootApplication
@EnableDiscoveryClient
public class NacosConsumerDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(NacosConsumerDemoApplication.class, args);
    }


}

  • RestTemplatef负载均衡配置config
    Nacos引入Robbion负载均衡配置,无需单独引入依赖

SpringCloud10-Alibaba_Nacos(服务注册、配置中心、负载均衡、消息总线)_第3张图片

package com.consumer.Config;

import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

@Configuration
public class RestTemplateConfig {

    @Bean
    @LoadBalanced
    public RestTemplate getRestTemplate(){
        return new RestTemplate();
    }

}

  • 业务Controller,调用服务提供者接口
package com.consumer.Controller;

import com.commons.Entity.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

@RestController
@RequestMapping("nacos/")
public class ConsumerController {

    @Resource
    private RestTemplate restTemplate;

    @Value("${service-url.nacos-user-service}")
    private String url;

    @GetMapping("/{id}")
    public Result saveEntity(@PathVariable("id") Integer id) {

        return restTemplate.getForObject(url+"/nacos/"+id,Result.class);
    }
}

  • 访问:http://localhost:8083/nacos/1

SpringCloud10-Alibaba_Nacos(服务注册、配置中心、负载均衡、消息总线)_第4张图片
SpringCloud10-Alibaba_Nacos(服务注册、配置中心、负载均衡、消息总线)_第5张图片
2.3 各服务中心对比

  • AP:注册临时实例;
  • CP:注册持久化实例
Eureka AP、支持控制台、低社区活跃
Zookeeper CP、不支持控制台、中社区活跃
Consul CP、支持控制台、高社区活跃
Nacos AP+CP切换、支持控制台、高社区活跃

SpringCloud10-Alibaba_Nacos(服务注册、配置中心、负载均衡、消息总线)_第6张图片

3、配置中心

3.1 配置中心使用(以消费模块为例)
(1)引入依赖

   <dependency>
            <groupId>com.alibaba.cloudgroupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-configartifactId>
            <version>2.2.7.RELEASEversion>
        dependency>

<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>cloud2022artifactId>
        <groupId>org.examplegroupId>
        <version>1.0-SNAPSHOTversion>
    parent>
    <modelVersion>4.0.0modelVersion>

    <groupId>org.consumer8083groupId>
    <artifactId>cloud-alibaba-consumer8083artifactId>

    <dependencies>
        <dependency>
            <groupId>com.alibaba.cloudgroupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-configartifactId>
            <version>2.2.7.RELEASEversion>
        dependency>
        <dependency>
            <groupId>org.springframework.cloudgroupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discoveryartifactId>
            <version>0.9.0.RELEASEversion>
        dependency>
        <dependency>
            <groupId>com.commonsgroupId>
            <artifactId>commonsartifactId>
            <version>1.0-SNAPSHOTversion>
            <scope>compilescope>
        dependency>

        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-actuatorartifactId>
        dependency>
        <dependency>
            <groupId>com.baomidougroupId>
            <artifactId>mybatis-plus-boot-starterartifactId>
        dependency>
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>druid-spring-boot-starterartifactId>
            <version>1.1.10version>
        dependency>
        
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
        dependency>
        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-jdbcartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-devtoolsartifactId>
            <scope>runtimescope>
            <optional>trueoptional>
        dependency>
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <optional>trueoptional>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
        dependency>

        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-devtoolsartifactId>
            <scope>runtimescope>
            <optional>trueoptional>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-autoconfigureartifactId>
        dependency>

    dependencies>

project>


(2)更改配置

  • application.yml
spring:
  profiles:
    active: dev
  • bootstrap.yml:将配置注册进注册中心
server:
  port: 8083

spring:
  application:
    name: consumer-nacos
  cloud:
    nacos:
      discovery:
        server-addr: 127.0.0.1:8848
      config:
        server-addr: localhost:8848 #将配置注册进注册中心
        file-extension: yaml

(3)Nacos配置列表添加配置

在 Nacos Config Starter 中,dataId 的拼接格式如下

${prefix} - ${spring.profiles.active} . ${file-extension}
  • prefix 默认为 spring.application.name 的值,也可以通过配置项 spring.cloud.nacos.config.prefix来配置。

  • spring.profiles.active 即为当前环境对应的 profile,详情可以参考 Spring Boot文档。
    注意,当 active profile 为空时,对应的连接符 - 也将不存在,dataId 的拼接格式变成 p r e f i x . {prefix}. prefix.{file-extension}

  • file-extension 为配置内容的数据格式,可以通过配置项 spring.cloud.nacos.config.file-extension来配置。 目前只支持 properties 类型。

SpringCloud10-Alibaba_Nacos(服务注册、配置中心、负载均衡、消息总线)_第7张图片
SpringCloud10-Alibaba_Nacos(服务注册、配置中心、负载均衡、消息总线)_第8张图片
配置内容:
SpringCloud10-Alibaba_Nacos(服务注册、配置中心、负载均衡、消息总线)_第9张图片

(4)主启动

package com.consumer;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

@SpringBootApplication
@EnableDiscoveryClient
public class NacosConsumerDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(NacosConsumerDemoApplication.class, args);
    }
}

(5)配置访问接口
SpringCloud10-Alibaba_Nacos(服务注册、配置中心、负载均衡、消息总线)_第10张图片
SpringCloud10-Alibaba_Nacos(服务注册、配置中心、负载均衡、消息总线)_第11张图片
(6)支持动态刷新:@RefreshScope //动态刷新

package com.consumer.Controller;

import com.commons.Entity.Result;
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.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

@RestController
@RequestMapping("nacos/")
@RefreshScope //动态刷新
public class ConsumerController {

    @Resource
    private RestTemplate restTemplate;

    @Value("${spring.datasource.username}")
    private String configInfo;

    @Value("${service-url.nacos-user-service}")
    private String url;

    @GetMapping("/{id}")
    public Result saveEntity(@PathVariable("id") Integer id) {

        return restTemplate.getForObject(url+"/nacos/"+id,Result.class);
    }

    @GetMapping("/getInfo")
    public String getInfo() {
        return configInfo;
    }

}

编辑root为root2SpringCloud10-Alibaba_Nacos(服务注册、配置中心、负载均衡、消息总线)_第12张图片
SpringCloud10-Alibaba_Nacos(服务注册、配置中心、负载均衡、消息总线)_第13张图片

3.2 命名空间、分组和、DataId三者关系

(1)关系

  • 配置文件寻找时按照先找命名空间,再从命名空间寻找对应的组,再从组里面寻找匹配DataId的配置;

(2)使用

  • 新建两个命名空间

SpringCloud10-Alibaba_Nacos(服务注册、配置中心、负载均衡、消息总线)_第14张图片
SpringCloud10-Alibaba_Nacos(服务注册、配置中心、负载均衡、消息总线)_第15张图片

  • 命名空间新建组

SpringCloud10-Alibaba_Nacos(服务注册、配置中心、负载均衡、消息总线)_第16张图片
新建成功后可以看到dev命名空间下游存在刚才新建的分组配置。SpringCloud10-Alibaba_Nacos(服务注册、配置中心、负载均衡、消息总线)_第17张图片

  • 更改配置文件,选择命名空间和分组

SpringCloud10-Alibaba_Nacos(服务注册、配置中心、负载均衡、消息总线)_第18张图片
group:组名;
namespace:命名空间名,为命名空间的编号;

4、Nacos集群和持久化配置

4.1 基本概念

  • Nacos支持单机、集群、多集群3种部署模式;
  • 在实际生产中,需要注册多集群来保证服务安全,相关集群配置也需要持久化到数据库保证服务重启之后配置信息不丢失。
  • 其默认使用嵌入式数据库实现数据存储,但是每个nacos都自带一个数据库,多集群会导致数据不同步问题,所以需要手动配置数据库,目前仅支持MySQL数据库;

4.2 使用

  • 打开Nacos的conf目录,会看到一个Mysql文件和一个application.properties配置文件;SpringCloud10-Alibaba_Nacos(服务注册、配置中心、负载均衡、消息总线)_第19张图片
  • 创建数据库nacos_config,执行数据库脚本创建表结构;
    SpringCloud10-Alibaba_Nacos(服务注册、配置中心、负载均衡、消息总线)_第20张图片
  • 更改application配置

SpringCloud10-Alibaba_Nacos(服务注册、配置中心、负载均衡、消息总线)_第21张图片

spring.datasource.platform=mysql
db.num=1
db.url.0=jdbc:mysql://localhost:3306/nacos_config?serverTimezone=Asia/Shanghai&useSSL=false&useUnicode=true&characterEncoding=utf8&characterSetResults=utf8
db.user=root
db.password=123456![在这里插入图片描述](https://img-blog.csdnimg.cn/6735ae5221604980a3df98aa1b13e280.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBA5b6u5YeJ5b2S5pyf,size_20,color_FFFFFF,t_70,g_se,x_16)

  • 关掉Nacos重新启动
    之前的配置都不见了,说明配置成功了;

SpringCloud10-Alibaba_Nacos(服务注册、配置中心、负载均衡、消息总线)_第22张图片

  • 使用过程
    SpringCloud10-Alibaba_Nacos(服务注册、配置中心、负载均衡、消息总线)_第23张图片

你可能感兴趣的:(#,5-6,SpringCloud,5-Java开发框架,spring,cloud,开发语言,erlang)