AlibabaNacos服务注册和配置中心

  Springcloud Netflix提供的服务进入维护模式,也就是一段时间内SpringcloudNetflix提供的服务和功能就这么多了,不在开发新的组件和功能。

  SpringcloudAlibaba致力于提供微服务开发的一站式解决方案。方便开发者通过springcloud编程模型轻松使用这些组件开发分布式应用服务。依托于coud alibaba,只需要添加一些注解和少量配置,就可以将Spring cloud应用接入阿里微服务解决方案。其主要组件包括Sentinel、Nacos、RocketMQ、Dubbo、Seata、Alibaba Cloud OSS、Alibaba Cloud Scheduler、Alibaba Cloud SMS等。

  阿里cloud项目官网:https://github.com/alibaba/spring-cloud-alibaba

1.Nacos简介和安装

1.简介

一个更易于构建云原生应用的动态服务发现、配置管理和服务管理平台。

Dynamic Naming And Configuration Service,实际上相当于注册中心+配置中心的组合。相当Springcloud中Eureka + Config + Bus的组合。

nacos官网:https://nacos.io/zh-cn/

git官网:https://github.com/alibaba/nacos

2.安装(我下载的版本是1.3.1)

(1)到https://github.com/alibaba/nacos/releases下载安装包。如下:

nacos-server-1.3.1.zip

(2)解压后启动

 直接运行bin/startup.cmd

(3)访问测试,默认的端口是8848,可以在application.properties中进行修改

默认的账号密码都是:nacos

登录之后如下:

 2.支付订单模块使用nacos做注册中心

0.父pom文件确定pom有下面坐标

            <!--spring cloud alibaba 2.1.0.RELEASE-->
            <dependency>
                <groupId>com.alibaba.cloud</groupId>
                <artifactId>spring-cloud-alibaba-dependencies</artifactId>
                <version>2.1.0.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>

1.支付模块

1.新建moudle

 2.修改pom

<?xml version="1.0" encoding="UTF-8"?>
<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>cloud</artifactId>
        <groupId>cn.qz.cloud</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>cloudalibaba-provider-nacos-payment9001</artifactId>

    <dependencies>
        <!--引入自己抽取的工具包-->
        <dependency>
            <groupId>cn.qz.cloud</groupId>
            <artifactId>cloud-api-commons</artifactId>
            <version>${project.version}</version>
        </dependency>
        <!--SpringCloud ailibaba nacos -->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>
        <!-- SpringBoot整合Web组件 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <!--日常通用jar包配置-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>

3.修改yml

server:
  port: 9001

spring:
  application:
    name: nacos-payment-provider
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848 #配置Nacos地址

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

4.主启动类

package cn.qz.cloud.alibaba;

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

/**
 * @Author: qlq
 * @Description
 * @Date: 21:51 2020/10/26
 */
@EnableDiscoveryClient
@SpringBootApplication
public class PaymentMain9001 {
    public static void main(String[] args) {
        SpringApplication.run(PaymentMain9001.class, args);
    }
}

5.业务类:

package cn.qz.cloud.alibaba.controller;

import cn.qz.cloud.utils.JSONResultUtil;
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;

/**
 * @Author: qlq
 * @Description
 * @Date: 21:52 2020/10/26
 */
@RestController
@RequestMapping("/nacos/payment")
public class PaymentController {

    @Value("${server.port}")
    private String serverPort;

    @GetMapping(value = "/getServerPort")
    public JSONResultUtil<String> getServerPort() {
        return JSONResultUtil.successWithData(serverPort);
    }
}

6.启动后查看nacos服务列表

 2.创建模块cloudalibaba-provider-nacos-payment9002和上面构成集群

启动后查看nacos服务列表:

 3.创建订单服务调用上面支付服务

1.新建订单模块cloudalibaba-consumer-nacos-order83

 2.修改pom

<?xml version="1.0" encoding="UTF-8"?>
<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>cloud</artifactId>
        <groupId>cn.qz.cloud</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>cloudalibaba-consumer-nacos-order83</artifactId>

    <dependencies>
        <!--SpringCloud ailibaba nacos -->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>
        <!--引入自己抽取的工具包-->
        <dependency>
            <groupId>cn.qz.cloud</groupId>
            <artifactId>cloud-api-commons</artifactId>
            <version>${project.version}</version>
        </dependency>
        <!-- SpringBoot整合Web组件 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <!--日常通用jar包配置-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>

3.修改yml

server:
  port: 83

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

#消费者将要去访问的微服务名称(注册成功进nacos的微服务提供者)
service-url:
  nacos-payment-provider: http://nacos-payment-provider

4.主启动类:

package cn.qz.cloud.alibaba;

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

/**
 * @Author: qlq
 * @Description
 * @Date: 22:27 2020/10/26
 */
@EnableDiscoveryClient
@SpringBootApplication
public class OrderNacosMain83 {
    public static void main(String[] args) {
        SpringApplication.run(OrderNacosMain83.class, args);
    }
}

5.业务类:

(1)配置类

package cn.qz.cloud.alibaba.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 ApplicationContextConfig {
    @Bean
    @LoadBalanced
    public RestTemplate getRestTemplate() {
        return new RestTemplate();
    }
}

(2)Controller

package cn.qz.cloud.alibaba.controller;

import cn.qz.cloud.utils.JSONResultUtil;
import lombok.extern.slf4j.Slf4j;
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 org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

@RestController
@Slf4j
@RequestMapping("/nacos/consumer/")
public class OrderNacosController {
    @Resource
    private RestTemplate restTemplate;

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

    @GetMapping(value = "/getServerPort")
    public JSONResultUtil<String> getServerPort() {
        return restTemplate.getForObject(serverURL + "/nacos/payment/getServerPort", JSONResultUtil.class);
    }
}

6.启动后测试

liqiang@root MINGW64 ~/Desktop
$ curl http://localhost:83/nacos/consumer/getServerPort
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:  0     0    0     0    0     0      0      0 --:--:--  0:00:01 --:100    52    0    52    0     0     35      0 --:--:--  0:00:01 --:--:--    35{"success":true,"code":"200","msg":"","data":"9002"}

liqiang@root MINGW64 ~/Desktop
$ curl http://localhost:83/nacos/consumer/getServerPort
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:100    52    0    52    0     0    666      0 --:--:-- --:--:-- --:--:--  1106{"success":true,"code":"200","msg":"","data":"9001"}

   当然订单模块也可以用feign来进行服务调用。

补充:各注册中心的异同点 

   另外Nacos可以支持AP与CP模式。C是所有节点在同一时间看到的数据是一致的;而A的定义是所有的请求都会得到响应。nacos默认是AP,如果需要切换CP如下:

$ curl -X PUT "http://localhost:8848/nacos/v1/ns/operator/switches?entry=serverMode&value=CP"
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100     2  100     2    0     0     14      0 --:--:-- --:--:-- --:--:--    16ok

3.nacos做配置中心 

1.基本的使用

 1.新建项目cloudalibaba-config-nacos-client3377

 2.修改pom

<?xml version="1.0" encoding="UTF-8"?>
<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>cloud</artifactId>
        <groupId>cn.qz.cloud</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>cloudalibaba-config-nacos-client3377</artifactId>

    <dependencies>
        <!-- nacos config-->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
        </dependency>
        <!-- SpringCloud ailibaba nacos-->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>
        <!--引入自己抽取的工具包-->
        <dependency>
            <groupId>cn.qz.cloud</groupId>
            <artifactId>cloud-api-commons</artifactId>
            <version>${project.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--监控-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <!--热部署-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>

3.建立bootstrap.yml

server:
  port: 3377

spring:
  application:
    name: nacos-config-client
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848 #Nacos服务注册中心地址
      config:
        server-addr: localhost:8848 #Nacos作为配置中心地址
        file-extension: yaml #指定yaml格式配置

#${prefix}-${spring.profile.active}.${file-extension}
# ${spring.application.name}-${spring.profile.active}.${file-extension}
# nacos-config-client-dev.yml

4.建立application.yml

spring:
  profiles:
#    active: prod
    active: dev #表示开发环境

5.建立主启动类:

package cn.qz.cloud.alibaba;

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

@EnableDiscoveryClient
@SpringBootApplication
public class NacosConfigClientMain3377 {

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

6.建立controller测试

package cn.qz.cloud.alibaba.controller;

import cn.qz.cloud.utils.JSONResultUtil;
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.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RefreshScope // 支持Nacos的动态刷新功能
@RequestMapping("/nacos/config/")
public class ConfigClientController {

    @Value("${config.info}")
    private String configInfo;

    @GetMapping("/configInfo")
    public JSONResultUtil<String> configInfo() {
        return JSONResultUtil.successWithData(configInfo);
    }
}

7.nacos建立配置文件:

(1)点击如下按钮:

 

 (2)新建dataId为nacos-config-client-dev.ymal。  实际dataId的值为: ${prefix}-${spring.profile.active}.${file-extension},默认prefix是${spring.application.name},例如上面的对应nacos-config-client-dev.yaml

 

启动后访问测试:

$ curl http://localhost:3377/nacos/config/configInfo
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   101    0   101    0     0    404      0 --:--:-- --:--:-- --:--:--   404{"success":true,"code":"200","msg":"","data":"nacos-config-client-dev文件,ymal类型。version=2!"}

(3)nacos新建dataId为nacos-config-client-prod.yaml的配置,内容如下:

 修改applicaiton.yml中激活的版本,如下:

spring:
  profiles:
    active: prod
#    active: dev #表示开发环境

测试:

$ curl http://localhost:3377/nacos/config/configInfo
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   102    0   102    0     0    502      0 --:--:-- --:--:-- --:--:--   502{"success":true,"code":"200","msg":"","data":"nacos-config-client-prod文件,ymal类型。version=1!"}

2.nacos按组group分组方案

   nacos允许通过group区分不同的配置文件。默认是组DEFAULT_GROUP。

1.新建配置文件并且指定组

2.bootstrap.yml指定组和application.yml指定激活的开发环境

server:
  port: 3377

spring:
  application:
    name: nacos-config-client
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848 #Nacos服务注册中心地址
      config:
        server-addr: localhost:8848 #Nacos作为配置中心地址
        file-extension: yaml #指定yaml格式配置
        group: group1

 

spring:
  profiles:
#    active: prod
    active: dev #表示开发环境

3.启动测试:

$ curl http://localhost:3377/nacos/config/configInfo
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   108    0   108    0     0    532      0 --:--:-- --:--:-- --:--:--   532{"success":true,"code":"200","msg":"","data":"nacos-config-client-dev文件,ymal类型。version=1!group1!"}

3.按namespace分组

  nacos还支持按namespace分组,namespace包含group,group包含dataId。 类似于java的package。

1.新建一个namespace

 2.该namespace下面新建配置文件,dataId为 nacos-config-client-dev.yaml

 新建的配置如下:

 3.修改bootstrap.yaml,指定group和namespace

server:
  port: 3377

spring:
  application:
    name: nacos-config-client
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848 #Nacos服务注册中心地址
      config:
        server-addr: localhost:8848 #Nacos作为配置中心地址
        file-extension: yaml #指定yaml格式配置
        group: group1
        namespace: namespace-dev

4.重启后测试

$ curl http://localhost:3377/nacos/config/configInfo
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   139    0   139    0     0    684      0 --:--:-- --:--:-- --:--:--   684{"success":true,"code":"200","msg":"","data":"nacos-config-client-dev文件,ymal类型。version=1!group1!namespace为【namespace-dev】"}

 5.修改配置内容的版本为2:

config: 
    info:  nacos-config-client-dev文件,ymal类型。version=2!group1!namespace为【namespace-dev】

6.保存后测试:(说明自动更新为nacos配置文件中的内容)

$ curl http://localhost:3377/nacos/config/configInfo
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   139    0   139    0     0    139      0 --:--:-- --:--:-- --:--:--  135k{"success":true,"code":"200","msg":"","data":"nacos-config-client-dev文件,ymal类型。version=2!group1!namespace为【namespace-dev】"}

 

posted @ 2020-10-28 21:31  QiaoZhi  阅读(2342)  评论(0编辑  收藏  举报