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

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-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

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<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;
	
	@Override
	public 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-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函数或处理类

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
    //可参考 https://blog.csdn.net/z69183787/article/details/109010369
	// 和 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实例内容包括以下项目:

测试地址:

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值