通过Spring Cloud Alibaba相关组件nacos+sentinel+dubbo实行服务注册、配置中心、熔断限流等功能


1.本机安装nacos和sentinel-dashboard服务端

具体操作可以百度

下载后存放到本机目录:

配置启动sentinel-dashboard服务的快捷方式start-sentinel-dashboard-8066.bat,脚本内容:

cd D:\DevSoft\Eclipse201812\workspace_springcloud_alibaba_20190910\sca-sentinel-dashboardjava -Dserver.port=8066 -Dcsp.sentinel.dashboard.server=localhost:8066 -Dproject.name=sca-sentinel-dashboard -jar sentinel-dashboard-1.6.3.jarpause

以后可以直接点击脚本启动。

测试前先启动:

nacos:sca-nacos-server\bin\startup.cmd

sentinel-dashboard: start-sentinel-dashboard-8066.bat


2.新建服务提供者微服务autoee-busi-dubbo-sentinel-nacos-provider

2.1pom配置

<dependencies><!-- Busi API --><dependency><groupId>com.autoee</groupId><artifactId>autoee-busi-api</artifactId><version>1.0.0-SNAPSHOT</version></dependency><!-- Spring Boot Begin --><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><!-- Spring Boot End --><!-- Spring Cloud Begin --><dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId></dependency><dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-dubbo</artifactId></dependency><dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-sentinel</artifactId></dependency><dependency><!-- 客户端引入 Transport 模块来与 Sentinel 控制台进行通信 --><groupId>com.alibaba.csp</groupId><artifactId>sentinel-transport-simple-http</artifactId></dependency><dependency><groupId>com.alibaba.csp</groupId><artifactId>sentinel-apache-dubbo-adapter</artifactId></dependency><dependency><!-- Sentinel 针对 Nacos 作了适配,底层可以采用 Nacos 作为规则配置数据源 --><groupId>com.alibaba.csp</groupId><artifactId>sentinel-datasource-nacos</artifactId></dependency><!-- Spring Cloud End --></dependencies>

2.2启动类配置:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;@SpringBootApplication
@EnableDiscoveryClient // 表明是一个Nacos客户端,该注解是 SpringCloud 提供的原生注解。
@EnableAutoConfiguration
public class AutoeeBusiDubboSentinelNacosProviderApplication {public static void main(String[] args) {SpringApplication.run(AutoeeBusiDubboSentinelNacosProviderApplication.class, args);}}

2.3配置文件application-dev.yml配置

spring:application:name: autoee-busi-dubbo-sentinel-nacos-providermain:# Spring Boot 2.1 需要设定allow-bean-definition-overriding: truecloud:nacos:discovery:server-addr: 127.0.0.1:8848# 使用 Sentinel 作为熔断器sentinel:transport:port: 8721dashboard: localhost:8066    # 设置Sentinel Nacos数据源配置datasource:#其中flow是数据源名,可以自行随意修改flow:nacos:server-addr: 127.0.0.1:8848data-id: ${spring.application.name}-flow-rulesgroupId: DEFAULT_GROUP# 规则类型,取值见:# org.springframework.cloud.alibaba.sentinel.datasource.RuleType# 配置后报错提示:Type 'com.alibaba.cloud.sentinel.datasource.config.NacosDataSourceProperties' has no property 'rule-type' , 以为哪里配置错了或版本不对, 最后发现忽略即可, 项目可正常启动rule-type: flow#在nacos配置列表中添加配置autoee-busi-dubbo-sentinel-nacos-provider-flow-rules#nacos中的规则会自动同步到sentinel控制台的流控规则中#            [#                {#                    "app":"autoee-busi-dubbo-sentinel-nacos-provider",#                    "resource":"com.autoee.busi.service.EchoService:echo(java.lang.String)",#                    "limitApp":"default",#                    "grade":1,#                    "count":1,#                    "strategy":0,#                    "controlBehavior":0,#                    "clusterMode":false#                }#            ]       #        degrade:
#          nacos:
#            server-addr: localhost:8848
#            dataId: ${spring.application.name}-degrade-rules
#            groupId: SENTINEL_GROUP
#            rule-type: degrade
#        system:
#          nacos:
#            server-addr: localhost:8848
#            dataId: ${spring.application.name}-system-rules
#            groupId: SENTINEL_GROUP
#            rule-type: system
#        authority:
#          nacos:
#            server-addr: localhost:8848
#            dataId: ${spring.application.name}-authority-rules
#            groupId: SENTINEL_GROUP
#            rule-type: authority
#        param-flow:
#          nacos:
#            server-addr: localhost:8848
#            dataId: ${spring.application.name}-param-flow-rules
#            groupId: SENTINEL_GROUP
#            rule-type: param-flowserver:port: 8090dubbo:scan:# dubbo 服务扫描基准包base-packages: com.autoeeprotocol:# dubbo 协议name: dubbo# dubbo 协议端口( -1 表示自增端口,从 20880 开始)port: -1registry:# 挂载到 Spring Cloud 注册中心address: spring-cloud://localhost

2.4添加NacosDataSourceConfig

package com.autoee.boot.config;import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.alibaba.cloud.sentinel.SentinelProperties;
import com.alibaba.cloud.sentinel.datasource.config.NacosDataSourceProperties;
import com.alibaba.csp.sentinel.datasource.ReadableDataSource;
import com.alibaba.csp.sentinel.datasource.nacos.NacosDataSource;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;/** 规则持久化 - 推模式* Sentinel控制台不再是调用客户端的API推送规则数据,而是将规则推送到Nacos或其他远程配置中心* Sentinel客户端通过连接Nacos,来获取规则配置;并监听Nacos配置变化,如发生变化,就更新本地缓存(从而让本地缓存总是和Nacos一致)* Sentinel控制台也监听Nacos配置变化,如发生变化就更新本地缓存(从而让Sentinel控制台的本地缓存总是和Nacos一致)* */
@Configuration
public class NacosDataSourceConfig {@Autowiredprivate SentinelProperties sentinelProperties;@Beanpublic NacosDataSourceConfig init() throws Exception {// NacosSource初始化,从Nacos中获取熔断规则sentinelProperties.getDatasource().entrySet().stream().filter(map -> {return map.getValue().getNacos() != null;}).forEach(map -> {NacosDataSourceProperties nacos = map.getValue().getNacos();ReadableDataSource<String, List<FlowRule>> flowRuleDataSource = new NacosDataSource<>(nacos.getServerAddr(),nacos.getGroupId(), nacos.getDataId(), source -> JSON.parseObject(source,new TypeReference<List<FlowRule>>() {}));FlowRuleManager.register2Property(flowRuleDataSource.getProperty());});return new NacosDataSourceConfig();}}

2.5添加服务类,配置dubbo注解

package com.autoee.boot.serviceImpl;import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Value;
import com.autoee.busi.service.EchoService;@Service
public class EchoServiceImpl implements EchoService{@Value("${server.port}")private String serverPort;@Overridepublic String echo(String message) {return "Dubbo Sentinel Nacos Provider:"+ serverPort +" - 输出消息:" + message;}}

3.新建服务消费者微服务autoee-busi-dubbo-sentinel-nacos-consumer

3.1pom配置

<dependencies><!-- Busi API --><dependency><groupId>com.autoee</groupId><artifactId>autoee-busi-api</artifactId><version>1.0.0-SNAPSHOT</version></dependency><!-- Spring Boot Begin --><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><!-- Spring Boot End --><!-- Spring Cloud Begin --><dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId></dependency><dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-dubbo</artifactId></dependency><dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-sentinel</artifactId></dependency><dependency><!-- 客户端引入 Transport 模块来与 Sentinel 控制台进行通信 --><groupId>com.alibaba.csp</groupId><artifactId>sentinel-transport-simple-http</artifactId></dependency><dependency><!-- Sentinel 针对 Nacos 作了适配,底层可以采用 Nacos 作为规则配置数据源 --><groupId>com.alibaba.csp</groupId><artifactId>sentinel-datasource-nacos</artifactId></dependency><!-- Spring Cloud End --></dependencies>

3.2启动类配置

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;@SpringBootApplication
@EnableDiscoveryClient // 表明是一个Nacos客户端,该注解是 SpringCloud 提供的原生注解。
@EnableAutoConfiguration
public class AutoeeBusiDubboSentinelNacosConsumerApplication {public static void main(String[] args) {SpringApplication.run(AutoeeBusiDubboSentinelNacosConsumerApplication.class, args);}}

3.3配置文件application-dev.yml配置

spring:application:name: autoee-busi-dubbo-sentinel-nacos-consumermain:# Spring Boot 2.1 需要设定allow-bean-definition-overriding: truecloud:nacos:discovery:server-addr: 127.0.0.1:8848# 使用 Sentinel 作为熔断器sentinel:transport:port: 8721dashboard: localhost:8066    # 设置Sentinel Nacos数据源配置datasource:#其中flow是数据源名,可以自行随意修改flow:nacos:server-addr: 127.0.0.1:8848data-id: ${spring.application.name}-flow-rulesgroupId: DEFAULT_GROUP# 规则类型,取值见:# org.springframework.cloud.alibaba.sentinel.datasource.RuleType# 配置后报错提示:Type 'com.alibaba.cloud.sentinel.datasource.config.NacosDataSourceProperties' has no property 'rule-type' , 以为哪里配置错了或版本不对, 最后发现忽略即可, 项目可正常启动rule-type: flowserver:port: 8091dubbo:registry:# 挂载到 Spring Cloud 注册中心address: spring-cloud://localhostcloud:# 用于服务消费方订阅服务提供方的应用名称的列表,若需订阅多应用,使用 "," 分割。 不推荐使用默认值为 "*",它将订阅所有应用subscribed-services: autoee-busi-dubbo-sentinel-nacos-provider

3.4添加消费端RestController,配置sentinel限流资源名称,fallback函数或处理类

package com.autoee.boot.controller;import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.dubbo.config.annotation.Reference;
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.RestController;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.autoee.busi.service.EchoService;@RestController
public class ConsumerController {@Referenceprivate EchoService echoService;@Value("${server.port}")private String serverPort;@GetMapping(value = "/dubbo/sentinel/nacos/consumer/echo/{message}")// 特别地,若 blockHandler 和 fallback 都进行了配置,则被限流降级而抛出 BlockException 时只会进入 blockHandler 处理逻辑。若未配置 blockHandler、fallback// 和 defaultFallback,则被限流降级时会将 BlockException 直接抛出。// @SentinelResource(value = "consumer-echo", blockHandler = "exceptionHandler", fallback = "echoFallBack")@SentinelResource(value = "consumer-echo", fallback = "echoFallBack")public String echo(@PathVariable("message")String message) {SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");return echoService.echo("Dubbo Sentinel Nacos Consumer: " + serverPort + " - 调用该方法:参数[" + message + "] " + df.format(new Date()));}// Fallback 函数,函数签名与原函数一致或加一个 Throwable 类型的参数public String echoFallBack(String message) {SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");return "[echoFallBack] Dubbo Sentinel Nacos Consumer:  - fallback " + df.format(new Date());}// Block 异常处理函数,参数最后多一个 BlockException,其余与原函数一致.public String exceptionHandler(String message, BlockException ex) {ex.printStackTrace();SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");return "[exceptionHandler] Dubbo Sentinel Nacos Consumer:  - exception exMessage[" + ex.getMessage() + "]" + df.format(new Date());}// 对应的 `handleException` 函数需要位于 `ExceptionUtil` 类中,并且必须为 static 函数.// @SentinelResource(value = "test", blockHandler = "handleException", blockHandlerClass = {ExceptionUtil.class})// public void test() {// System.out.println("Test");// }
}

4.启动服务提供者和消费者,测试是否正常

调用成功


5.进入nacos控制台,配置动态规则,并实时推送到sentinel,实现sentinel限流等

5.1登陆nacos

5.2新建sentinel限流规则

autoee-busi-dubbo-sentinel-nacos-consumer-flow-rules 对应程序配置文件中的

spring.cloud.sentinel.datasource.flow.nacos.data-id: ${spring.application.name}-flow-rules

 

配置内容:

[{"resource":"consumer-echo","limitApp":"default","grade":1,"count":1,"strategy":0,"controlBehavior":0,"clusterMode":false}
]

6.登陆sentinel,查看规则是否已同步到sentinel-dashboard

已同步


7.测试限流规则是否生效

多次频繁访问http://localhost:8091/dubbo/sentinel/nacos/consumer/echo/fxs

测试结果显示


8.查看sentinel实时监控信息

已实现每秒QPS为1的限流控制


9.修改nacos中的限流规则,实时查看sentinel的限流效果,实行动态规则配置



Spring Cloud Alibaba实例群

群文件中提供了Spring Cloud Alibaba各种组件配置使用的具体实例,一个个组件分别组装的实例,包括以下组件nacos、sentinel、dubbo、gateway等,如果想获取具体代码,需要通过下面的二维码付费 9.80元,付费后申请进群,在群文件中获取代码压缩包。

微信二维码:                                         Spring Cloud Alibaba实例群:

            

Spring Cloud Alibaba实例内容包括以下项目:

测试地址:

Spring Cloud Alibaba配置实例nacos+sentinel+dubbo实行服务注册、配置中心、熔断限流相关推荐

  1. Spring Cloud Alibaba基础教程:Sentinel Dashboard中修改规则同步到Nacos

    上一篇我们介绍了如何通过改造Sentinel Dashboard来实现修改规则之后自动同步到Apollo.下面通过这篇,详细介绍当使用Nacos作为配置中心之后,如何实现Sentinel Dashbo ...

  2. Spring Cloud Alibaba基础教程:Sentinel Dashboard中修改规则同步到Apollo

    在之前的两篇教程中我们分别介绍了如何将Sentinel的限流规则存储到Nacos和Apollo中.同时,在文末的思考中,我都指出了这两套整合方案都存在一个不足之处:不论采用什么配置中心,限流规则都只能 ...

  3. Spring Cloud Alibaba基础教程:与Dubbo的完美融合

    很早以前,在刚开始搞Spring Cloud基础教程的时候,写过这样一篇文章:<微服务架构的基础框架选择:Spring Cloud还是Dubbo?>,可能不少读者也都看过.之后也就一直有关 ...

  4. 【Spring Cloud Alibaba】(五)Dubbo启动报错?一直重连报错?你值得学习的是排查问题的方法

    系列目录 [Spring Cloud Alibaba](一)微服务介绍 及 Nacos注册中心实战 [Spring Cloud Alibaba](二)微服务调用组件Feign原理+实战 [Spring ...

  5. Spring Cloud Alibaba基础教程:Sentinel使用Nacos存储规则

    点击蓝色"程序猿DD"关注我哟 加个"星标",不忘签到哦 通过上一篇<使用Sentinel实现接口限流>的介绍,相信大家对Sentinel已经有了初 ...

  6. Spring Cloud Alibaba 之 RPC 消息:Dubbo 与 Nacos 体系如何协同作业

    上一节我介绍了什么是 OpenFeign 通信组件,讲解了如何基于 OpenFeign 实现微服务间的高可用通信.本文我们将继续探讨微服务通信话题,了解阿里巴巴自家的 RPC 框架 Dubbo 是如何 ...

  7. Spring Cloud Alibaba (一) 之Nacos

    关于Nacos 在微服务概念兴起之后,越来越多的项目使用微服务的架构理念,随着服务节点的逐渐增多,我们需要一个独立的服务或者说组件,对我们的所有微服务节点进行管理.最早还没有SpringCloud的时 ...

  8. Spring Cloud Alibaba基础教程:Sentinel使用Apollo存储规则

    点击蓝色"程序猿DD"关注我哟 加个"星标",不忘签到哦 上一篇我们介绍了如何通过Nacos的配置功能来存储限流规则.Apollo是国内用户非常多的配置中心,所 ...

  9. Spring Cloud Alibaba基础教程:Sentinel Dashboard同步Apollo存储规则

    点击蓝色"程序猿DD"关注我哟 加个"星标",不忘签到哦 在之前的两篇教程中我们分别介绍了如何将Sentinel的限流规则存储到Nacos和Apollo中.同时 ...

最新文章

  1. python文件句柄_Python文件操作
  2. 《Cisco IPv6网络实现技术(修订版)》一2.6 配置练习:使用Cisco路由器配置一个IPv6网络...
  3. 服务器看端口信息命令行,查看服务器进入端口命令行
  4. 未来十年,Java 仍会是最受欢迎的编程语言吗?
  5. mysql数据库高级查询笔记_MySQL数据库基础——高级查询
  6. 前端学习(3345):设计模式之工厂模式2
  7. jQuery实现表格行上移下移和置顶
  8. 利用IDisposable接口构建包含非托管资源对象
  9. matlibplot 一张图画多个曲线_从一张风景照中就学会的SinGAN模型,究竟是什么神操作?| ICCV 2019最佳论文...
  10. LPTHW 笨办法学python 37章 python关键字/关键词介绍
  11. SpringMVC自学日志04(Controller 及 RestFul风格 )
  12. php rpoplpush,Redis Rpoplpush 命令
  13. 通过SessionID和用户名来保证同一个用户不能同时登录
  14. 一次跳槽经历(阿里/美团/头条/网易/有赞...)
  15. Linux卸载JDK(虚拟机自带JDK)
  16. 推荐几个浏览器插件帮助你查论文显示期刊等级(分区及影响因子),sci文章便捷下载
  17. 跳舞毯行业调研报告 - 市场现状分析与发展前景预测
  18. UVA-12304 测试圆相关模板
  19. java定义两个动物抽象类 程序_java抽象类和接口详解
  20. Eclipse设置护眼背景调整字体

热门文章

  1. LEARN TO DESIGN THE HEURISTICS FOR VEHICLE ROUTING PROBLEM翻译
  2. 01-【istio】-【服务网格概述】服务网格的优势
  3. 学软件测试最好的几本书,这8本书能帮你很多
  4. java报错--java.io.IOException: Server returned HTTP response code: 502
  5. [开源名人录] Fabrice Bellard
  6. EDK2之debug
  7. 飞飞php影视系统漏洞,飞飞影视系统PHP版 v1.9 injection exploit漏洞预警 -电脑资料...
  8. 关于网站在不同的网络访问不了的原因
  9. 【高并发】多线程之无锁队列|性能优化
  10. C++程序设计 重载函数