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

通过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-dashboard

java -Dserver.port=8066 -Dcsp.sentinel.dashboard.server=localhost:8066 -Dproject.name=sca-sentinel-dashboard -jar sentinel-dashboard-1.6.3.jar

pause

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

测试前先启动:

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

Spring Cloud Alibaba配置实例nacos+sentinel+dubbo实行服务注册、配置中心、熔断限流_第1张图片

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

Spring Cloud Alibaba配置实例nacos+sentinel+dubbo实行服务注册、配置中心、熔断限流_第2张图片


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

2.1pom配置


		
		
			com.autoee
			autoee-busi-api
			1.0.0-SNAPSHOT
		

		
		
			org.springframework.boot
			spring-boot-starter-web
		
		
			org.springframework.boot
			spring-boot-starter-actuator
		
		

		
		
			com.alibaba.cloud
			spring-cloud-starter-alibaba-nacos-discovery
		
		
			com.alibaba.cloud
			spring-cloud-starter-dubbo
		
		
			com.alibaba.cloud
			spring-cloud-starter-alibaba-sentinel
		
		
			com.alibaba.csp
			sentinel-transport-simple-http
		
		
			com.alibaba.csp
			sentinel-apache-dubbo-adapter
		
		
			com.alibaba.csp
			sentinel-datasource-nacos
		
		
	

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-provider
  main:
    # Spring Boot 2.1 需要设定
    allow-bean-definition-overriding: true
  cloud:
    nacos:
      discovery:
        server-addr: 127.0.0.1:8848
    # 使用 Sentinel 作为熔断器
    sentinel:
      transport:
        port: 8721
        dashboard: localhost:8066    
      # 设置Sentinel Nacos数据源配置
      datasource:
        #其中flow是数据源名,可以自行随意修改
        flow:
          nacos:
            server-addr: 127.0.0.1:8848
            data-id: ${spring.application.name}-flow-rules
            groupId: 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-flow
            
server:
  port: 8090
          
dubbo:
  scan:
    # dubbo 服务扫描基准包
    base-packages: com.autoee
  protocol:
    # dubbo 协议
    name: dubbo
    # dubbo 协议端口( -1 表示自增端口,从 20880 开始)
    port: -1
  registry:
    # 挂载到 Spring Cloud 注册中心
    address: spring-cloud://localhost
              

2.4添加NacosDataSourceConfig

Spring Cloud Alibaba配置实例nacos+sentinel+dubbo实行服务注册、配置中心、熔断限流_第3张图片

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 {

	@Autowired
	private SentinelProperties sentinelProperties;

	@Bean
	public 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> flowRuleDataSource = new NacosDataSource<>(nacos.getServerAddr(),
					nacos.getGroupId(), nacos.getDataId(), source -> JSON.parseObject(source,
							new TypeReference>() {}));
			FlowRuleManager.register2Property(flowRuleDataSource.getProperty());
		});
		return new NacosDataSourceConfig();
	}

}

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

Spring Cloud Alibaba配置实例nacos+sentinel+dubbo实行服务注册、配置中心、熔断限流_第4张图片

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;
	
	@Override
	public String echo(String message) {
		return "Dubbo Sentinel Nacos Provider:"+ serverPort +" - 输出消息:" + message;
	}
	
}

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

3.1pom配置


		
		
			com.autoee
			autoee-busi-api
			1.0.0-SNAPSHOT
		

		
		
			org.springframework.boot
			spring-boot-starter-web
		
		
			org.springframework.boot
			spring-boot-starter-actuator
		
		

		
		
			com.alibaba.cloud
			spring-cloud-starter-alibaba-nacos-discovery
		
		
			com.alibaba.cloud
			spring-cloud-starter-dubbo
		
		
			com.alibaba.cloud
			spring-cloud-starter-alibaba-sentinel
		
		
			com.alibaba.csp
			sentinel-transport-simple-http
		
		
			com.alibaba.csp
			sentinel-datasource-nacos
		
		
	

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-consumer
  main:
    # Spring Boot 2.1 需要设定
    allow-bean-definition-overriding: true
  cloud:
    nacos:
      discovery:
        server-addr: 127.0.0.1:8848
    # 使用 Sentinel 作为熔断器
    sentinel:
      transport:
        port: 8721
        dashboard: localhost:8066    
      # 设置Sentinel Nacos数据源配置
      datasource:
        #其中flow是数据源名,可以自行随意修改
        flow:
          nacos:
            server-addr: 127.0.0.1:8848
            data-id: ${spring.application.name}-flow-rules
            groupId: 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
        
server:
  port: 8091
          
dubbo:
  registry:
    # 挂载到 Spring Cloud 注册中心
    address: spring-cloud://localhost
  cloud:
    # 用于服务消费方订阅服务提供方的应用名称的列表,若需订阅多应用,使用 "," 分割。 不推荐使用默认值为 "*",它将订阅所有应用
    subscribed-services: autoee-busi-dubbo-sentinel-nacos-provider
    

   

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

Spring Cloud Alibaba配置实例nacos+sentinel+dubbo实行服务注册、配置中心、熔断限流_第5张图片

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 {

	@Reference
	private 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

Spring Cloud Alibaba配置实例nacos+sentinel+dubbo实行服务注册、配置中心、熔断限流_第6张图片

5.2新建sentinel限流规则

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

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

 

Spring Cloud Alibaba配置实例nacos+sentinel+dubbo实行服务注册、配置中心、熔断限流_第7张图片

配置内容:

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

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

已同步

Spring Cloud Alibaba配置实例nacos+sentinel+dubbo实行服务注册、配置中心、熔断限流_第8张图片


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

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

测试结果显示


8.查看sentinel实时监控信息

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

Spring Cloud Alibaba配置实例nacos+sentinel+dubbo实行服务注册、配置中心、熔断限流_第9张图片


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

 



Spring Cloud Alibaba实例群

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

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

Spring Cloud Alibaba配置实例nacos+sentinel+dubbo实行服务注册、配置中心、熔断限流_第10张图片                         Spring Cloud Alibaba配置实例nacos+sentinel+dubbo实行服务注册、配置中心、熔断限流_第11张图片

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

Spring Cloud Alibaba配置实例nacos+sentinel+dubbo实行服务注册、配置中心、熔断限流_第12张图片

测试地址:

Spring Cloud Alibaba配置实例nacos+sentinel+dubbo实行服务注册、配置中心、熔断限流_第13张图片

你可能感兴趣的:(Spring,Cloud,Alibaba,nacos,sentinel,dubbo,Spring,Cloud,Alibaba)