Spring Cloud Alibaba基础教程之Nacos实现服务注册与发现

文章目录

    • Spring Cloud Alibaba 是什么
      • 主要功能:
      • 组件:
    • Nacos实现服务注册与发现
      • 下载源码或者安装包
      • 修改数据库
      • 创建服务注册到Nacos
    • Nacos负载均衡
    • Nacos服务注册与发现整合Feign和WebFlux
      • Feign
      • WebFlux
    • Nacos实现服务注册与发现整合Spring Cloud GateWay

Spring Cloud Alibaba 是什么

Spring Cloud Alibaba 致力于提供分布式应用服务开发的一站式解决方案。此项目包含开发分布式应用服务的必需组件,方便开发者通过 Spring Cloud 编程模型轻松使用这些组件来开发分布式应用服务。

主要功能:

服务限流降级:默认支持WebServlet、WebFlux, OpenFeign、RestTemplate、Spring Cloud Gateway, Zuul, Dubbo 和 RocketMQ 限流降级功能的接入,也支持添加注解实现方法的自定义限流降级,且支持动态修改限流降级规则。

服务注册与发现:适配 Spring Cloud 服务注册与发现标准,默认集成了 Ribbon 的支持。

分布式配置管理:支持分布式系统中的外部化配置,配置更改时自动刷新。

消息驱动能力:基于Spring Cloud Stream 为服务应用构建消息驱动能力。

分布式事务:使用 @GlobalTransaction 注解,高效并且对业务零侵入的解决分布式事务问题。

阿里云对象存储:阿里云提供的海量、安全、低成本、高可靠的云存储服务。支持在任何应用、任何时间、任何地点存储和访问任意类型的数据。

分布式任务调度:提供秒级、精准、高可靠、高可用的定时(基于 Cron 表达式)任务调度服务。同时提供分布式的任务执行模型,如网格任务。网格任务支持海量子任务均匀分配到所有 Worker(schedulerx-client)上执行。

阿里云短信服务:覆盖全球的短信服务,友好、高效、智能的互联化通讯能力,帮助企业迅速搭建客户触达通道。

组件:

Sentinel:把流量作为切入点,从流量控制、熔断降级、系统负载保护等多个维度保护服务的稳定性。

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

RocketMQ:一款开源的分布式消息系统,基于高可用分布式集群技术,提供低延时的、高可靠的消息发布与订阅服务。

Dubbo:Apache Dubbo™ 是一款高性能 Java RPC 框架。

Seata:阿里巴巴开源产品,一个易于使用的高性能微服务分布式事务解决方案。

Alibaba Cloud ACM:一款在分布式架构环境中对应用配置进行集中管理和推送的应用配置中心产品。

Alibaba Cloud OSS: 阿里云对象存储服务(Object Storage Service,简称 OSS),是阿里云提供的海量、安全、低成本、高可靠的云存储服务。您可以在任何应用、任何时间、任何地点存储和访问任意类型的数据。

Alibaba Cloud SchedulerX: 阿里中间件团队开发的一款分布式任务调度产品,提供秒级、精准、高可靠、高可用的定时(基于 Cron 表达式)任务调度服务。

Alibaba Cloud SMS: 覆盖全球的短信服务,友好、高效、智能的互联化通讯能力,帮助企业迅速搭建客户触达通道。

详情请参考

Nacos实现服务注册与发现

Nacos 支持几乎所有主流类型的“服务”的发现、配置和管理,可以相当于Spring Cloud 组件的Eureka + Spring Cloud Config。
详情参考Nacos官网

下载源码或者安装包

本文版本:1.2
下载编译后压缩包方式地址:https://github.com/alibaba/nacos/releases

下载完成后,cd 到nacos的bin目录下,根据不同系统,执行不同命令,启动Nacos服务:
启动命令(standalone代表着单机模式运行,非集群模式):
Linux/Unix/Mac:sh startup.sh-m standalone

Windows:cmd startup.cmd 或者双击 startup.cmd 运行文件

启动完成之后,访问:http://localhost:8848/nacos/,即可进入Nacos 管理页面(默认用户名/密码: nacos/nacos)
Spring Cloud Alibaba基础教程之Nacos实现服务注册与发现_第1张图片

修改数据库

Nacos配置的数据默认存储到内嵌数据库derby,可支持修改为支持mysql
如果mysql版本过高,需要修改nacos源码的mysql驱动版本 参考这篇博客
1.安装数据库,版本要求:5.6.5+

2.初始化mysql数据库,数据库初始化文件:nacos-mysql.sql

3.修改conf/application.properties文件,增加支持mysql数据源配置(目前只支持mysql),添加mysql数据源的url、用户名和密码

spring.datasource.platform=mysql

db.num=1
db.url.0=jdbc:mysql://127.0.0.1:3306/nacos_config?characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true
db.user=root
db.password=root

创建服务注册到Nacos

新建maven工程
Spring Cloud Alibaba基础教程之Nacos实现服务注册与发现_第2张图片
再新建两个maven模块充当服务消费和提供者
nacos-discovery-consumer 、nacos-discovery-provider

Spring Cloud Alibaba基础教程之Nacos实现服务注册与发现_第3张图片
Spring Cloud Alibaba基础教程之Nacos实现服务注册与发现_第4张图片
nacos-discovery-provider
编辑 pom.xml文件

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.learn.alibaba</groupId>
    <artifactId>nacos-discovery-provider</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>nacos-discovery-provider</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
        <spring-cloud.version>Hoxton.RELEASE</spring-cloud.version>
        <spring-cloud-alibaba.version>2.1.1.RELEASE</spring-cloud-alibaba.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <!--spring cloud alibaba-->
            <dependency>
                <groupId>com.alibaba.cloud</groupId>
                <artifactId>spring-cloud-alibaba-dependencies</artifactId>
                <version>${spring-cloud-alibaba.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

编辑application.yml 配置服务名称和nacos注册地址

server:
  port: 8051
spring:
  application:
    name: nacos-discovery-provider
  cloud:
    nacos:
      discovery:
        server-addr: 127.0.0.1:8848

创建请求类,并实现一个接口

package com.learn.alibaba.nacosdiscoveryprovider.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author lian
 */
@RestController
public class HelloController {
    @GetMapping("/hello")
    private String hello(String name) {
        return "hello" + name;
    }
}

启动类添加@EnableDiscoveryClient 开启服务注册发现功能

package com.learn.alibaba.nacosdiscoveryprovider;

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


/**
 * @author lian
 */
@EnableDiscoveryClient
@SpringBootApplication
public class NacosDiscoveryProviderApplication {

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

nacos-discovery-consumer
编辑 pom.xml文件

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.learn-alibaba</groupId>
    <artifactId>nacos-discovery-consumer</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>nacos-discovery-consumer</name>
    <description>nacos-discovery-consumer</description>

    <properties>
        <java.version>1.8</java.version>
        <spring-cloud.version>Hoxton.RELEASE</spring-cloud.version>
        <spring-cloud-alibaba.version>2.1.1.RELEASE</spring-cloud-alibaba.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <!--spring cloud alibaba-->
            <dependency>
                <groupId>com.alibaba.cloud</groupId>
                <artifactId>spring-cloud-alibaba-dependencies</artifactId>
                <version>${spring-cloud-alibaba.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

编辑application.yml 配置服务名称和nacos注册地址

spring:
  application:
    name: nacos-discovery-consumer
  # 服务注册中心地址  
  cloud:
    nacos:
      discovery:
        server-addr: 127.0.0.1:8848
server:
  port: 8050

创建请求类,并实现一个接口

package com.learnalibaba.nacosdiscoveryconsumer.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.net.URI;

/**
 * @author lian
 */
@RestController
public class HelloController {
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private LoadBalancerClient loadBalancerClient;
    @GetMapping
    public String test(String name) {
        // 通过spring cloud common中的负载均衡接口选取服务提供节点实现接口调用
        // serviceId为spring.application.name
        ServiceInstance serviceInstance = loadBalancerClient.choose("nacos-discovery-consumer");
        URI uri = serviceInstance.getUri();
        return restTemplate.getForObject(uri + "/hello?name=" + name, String.class);
    }
}

package com.learnalibaba.nacosdiscoveryconsumer;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

/**
 * @author lian
 */
@EnableDiscoveryClient
@SpringBootApplication
public class NacosDiscoveryConsumerApplication {

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

    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
}

访问http://localhost:8050/hello?name=dang
Spring Cloud Alibaba基础教程之Nacos实现服务注册与发现_第5张图片
可以看到,发送请求时,已经成功调用并返回信息,以上通过nacos做服务发现并利用RestTemplate进行微服务中服务与服务之间相互调用的过程

Nacos负载均衡

spring-cloud-starter-alibaba-nacos-discovery 默认依赖netiflix-ribbon作为客户端的负载均衡组件
Spring Cloud Alibaba基础教程之Nacos实现服务注册与发现_第6张图片
因此nacos-discovery-consumer代码可以改写成直接调用服务名称

package com.learnalibaba.nacosdiscoveryconsumer.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.net.URI;

/**
 * @author lian
 */
@RestController
public class HelloController {
    @Autowired
    private RestTemplate restTemplate;
    @GetMapping
    public String test(String name) {
        return restTemplate.getForObject("http://nacos-discovery-provider/hello?name=" + name, String.class);
    }
}

package com.learnalibaba.nacosdiscoveryconsumer;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

/**
 * @author lian
 */
@EnableDiscoveryClient
@SpringBootApplication
public class NacosDiscoveryConsumerApplication {

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

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

点击services视图的provider服务,通过快捷键ctrl+D 复制一个provider服务,设置端口8052
Spring Cloud Alibaba基础教程之Nacos实现服务注册与发现_第7张图片
Spring Cloud Alibaba基础教程之Nacos实现服务注册与发现_第8张图片
为了方便观看效果修改代码

package com.learn.alibaba.nacosdiscoveryprovider.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author lian
 */
@RestController
public class HelloController {
    @Value("${server.port}")
    private Integer port;
    @GetMapping("/hello")
    private String hello(String name) {
        return "hello" + name + port;
    }
}

访问http://localhost:8050/hello?name=dang
第一次
Spring Cloud Alibaba基础教程之Nacos实现服务注册与发现_第9张图片
第二次
Spring Cloud Alibaba基础教程之Nacos实现服务注册与发现_第10张图片
实现了交叉轮询负载均衡

Nacos服务注册与发现整合Feign和WebFlux

Feign

Feign 是从Netflix中分离出来的轻量级项目,能够在类接口上添加注释,成为一个REST API客户端。
OpenFeign是SpringCloud在netiflix feign 的基础上扩展了支持Spring MVC注释,并通过自动配置为Spring Boot应用程序提供集成。
创建nacos-discovery-consumer-feign模块
编辑 pom.xml文件

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.learn-alibaba</groupId>
    <artifactId>nacos-discovery-consumer-feign</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>nacos-discovery-consumer-feign</name>
    <description>nacos-discovery-consumer-feign</description>

    <properties>
        <java.version>1.8</java.version>
        <spring-cloud.version>Hoxton.RELEASE</spring-cloud.version>
        <spring-cloud-alibaba.version>2.1.1.RELEASE</spring-cloud-alibaba.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>

        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <!--spring cloud alibaba-->
            <dependency>
                <groupId>com.alibaba.cloud</groupId>
                <artifactId>spring-cloud-alibaba-dependencies</artifactId>
                <version>${spring-cloud-alibaba.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

编辑application.yml 配置服务名称和nacos注册地址

spring:
  application:
    name: nacos-discovery-consumer-feign
  # 服务注册中心地址
  cloud:
    nacos:
      discovery:
        server-addr: 127.0.0.1:8848
server:
  port: 8053

@EnableFeignClients注解开启扫描Spring Cloud Feign客户端

package com.learnalibaba.nacosdiscoveryconsumer;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

/**
 * @author lian
 */
@EnableFeignClients
@EnableDiscoveryClient
@SpringBootApplication
public class NacosDiscoveryConsumerFeignApplication {

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

创建远程服务接口

package com.learnalibaba.nacosdiscoveryconsumer.service;

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * @author lian
 */
@FeignClient("nacos-discovery-provider")
public interface HelloFeignService {
    @GetMapping("/hello")
    String hello(@RequestParam("name") String name);
}

创建请求类,并实现一个接口

package com.learnalibaba.nacosdiscoveryconsumer.controller;

import com.learnalibaba.nacosdiscoveryconsumer.service.HelloFeignService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;


/**
 * @author lian
 */
@RestController
public class HelloController {
    @Autowired
    private HelloFeignService helloFeignService;
    @GetMapping("/hello")
    public String test(String name) {
        return helloFeignService.hello(name);
    }
}

通过@EnableFeignClients注解开启扫描Spring Cloud Feign客户端的功能;然后又创建一个Feign的客户端接口定义。使用@FeignClient注解来指定这个接口所要调用的服务名称,在Controller中,注入了Client接口的实现,并调用test方法来触发对服务提供方的调用。

启动 nacos-discovery-consumer-feign服务和nacos-discovery-provider服务
访问http://127.0.0.1:8053/hello?name=dang
Spring Cloud Alibaba基础教程之Nacos实现服务注册与发现_第11张图片
成功调用nacos-discovery-provider服务的接口

WebFlux

Spring WebFlux 是一套全新的 Reactive Web 栈技术,实现完全非阻塞,支持 Reactive Streams 背压等特性
创建nacos-discovery-consumer-webflux模块
编辑 pom.xml文件

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.learn-alibaba</groupId>
    <artifactId>nacos-discovery-consumer-webflux</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>nacos-discovery-consumer-webflux</name>
    <description>nacos-discovery-consumer-webflux</description>

    <properties>
        <java.version>1.8</java.version>
        <spring-cloud.version>Hoxton.RELEASE</spring-cloud.version>
        <spring-cloud-alibaba.version>2.1.1.RELEASE</spring-cloud-alibaba.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-webflux</artifactId>
        </dependency>

        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>

    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <!--spring cloud alibaba-->
            <dependency>
                <groupId>com.alibaba.cloud</groupId>
                <artifactId>spring-cloud-alibaba-dependencies</artifactId>
                <version>${spring-cloud-alibaba.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

编辑application.yml 配置服务名称和nacos注册地址

spring:
  application:
    name: nacos-discovery-consumer-webflux
  # 服务注册中心地址
  cloud:
    nacos:
      discovery:
        server-addr: 127.0.0.1:8848
server:
  port: 8054

启动类注入WebClient.Builder Bean

package com.learnalibaba.nacosdiscoveryconsumer;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.reactive.function.client.WebClient;

/**
 * @author lian
 */
@EnableDiscoveryClient
@SpringBootApplication
public class NacosDiscoveryConsumerWebFluxApplication {

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

    @Bean
    @LoadBalanced
    public WebClient.Builder webClientBuilder() {
        return WebClient.builder();
    }
}

创建请求类,并实现一个接口

package com.learnalibaba.nacosdiscoveryconsumer.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

/**
 * @author lian
 */
@RestController
public class HelloController {
    @Autowired
    private WebClient.Builder webClientBuilder;

    @GetMapping("/hello")
    public Mono<String> test(String name) {
        return webClientBuilder.build()
                .get()
                .uri("http://nacos-discovery-provider/hello?name="+name)
                .retrieve()
                .bodyToMono(String.class);
    }
}

启动nacos-discovery-consumer-webflux和nacos-discovery-provider服务
访问http://127.0.0.1:8054/hello?name=dang
Spring Cloud Alibaba基础教程之Nacos实现服务注册与发现_第12张图片

Nacos实现服务注册与发现整合Spring Cloud GateWay

Spring Cloud Gateway 是 Spring Cloud 的一个全新项目,该项目是基于 Spring 5.0,Spring Boot 2.0 和 Project Reactor 等技术开发的网关,它旨在为微服务架构提供一种简单有效的统一的 API 路由管理方式。

Spring Cloud Gateway 作为 Spring Cloud 生态系统中的网关,目标是替代 Netflix Zuul,其不仅提供统一的路由方式,并且基于 Filter 链的方式提供了网关基本的功能,例如:安全,监控/指标,和限流。
创建nacos-discovery-gateway-server模块
编辑 pom.xml文件

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.learn-alibaba</groupId>
    <artifactId>nacos-discovery-gateway-server</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>nacos-discovery-gateway-server</name>
    <description>nacos-discovery-gateway-server</description>

    <properties>
        <java.version>1.8</java.version>
        <spring-cloud.version>Hoxton.RELEASE</spring-cloud.version>
        <spring-cloud-alibaba.version>2.1.1.RELEASE</spring-cloud-alibaba.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
        </dependency>

        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <!--spring cloud alibaba-->
            <dependency>
                <groupId>com.alibaba.cloud</groupId>
                <artifactId>spring-cloud-alibaba-dependencies</artifactId>
                <version>${spring-cloud-alibaba.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

编辑application.yml 配置服务名称和nacos注册地址

spring:
  application:
    name: nacos-discovery-gateway-server
  # 服务注册中心地址
  cloud:
    nacos:
      discovery:
        server-addr: 127.0.0.1:8848
    gateway:
      routes:
        - id: nacos-discovery-provider
          uri: lb://nacos-discovery-provider #注册中心的服务名称,实现负载均衡
          predicates:
            - Path=/provider/** #所有业务的请求前缀
          filters:
            - StripPrefix=1 #去除掉provider前缀,不用nacos-discovery-provider服务设置context-path: /provider
#当通过网关提出/provider/foo请求时,发出的请求provider将看起来像nacos-discovery-provider/foo。
server:
  port: 8055



启动类

package com.learnalibaba.nacosdiscoverygateway;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

/**
 * @author lian
 */
@EnableDiscoveryClient
@SpringBootApplication
public class NacosDiscoveryGateWayApplication {

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

访问http://127.0.0.1:8055/provider/hello?name=dang
Spring Cloud Alibaba基础教程之Nacos实现服务注册与发现_第13张图片
通过nacos作为注册中心,Spring Cloud GateWay来进行路由转发,浏览器请求通过Spring Cloud GateWay转发到provider服务的接口。

你可能感兴趣的:(Spring,Cloud,Alibaba,nacos,feign,webflux,Spring,cloud,GateWay)