• SpringCloud - Spring Cloud Alibaba 之 Gateway 集成Sentinel (十一)


    阅读本文前可先参考

    SpringCloud - Spring Cloud 之 Gateway网关(十三)_MinggeQingchun的博客-CSDN博客_spring.cloud.gateway.routes[0]

    SpringCloud - Spring Cloud Alibaba 之 Sentinel 规则持久化(十)_MinggeQingchun的博客-CSDN博客

    一、Gateway 集成Sentinel

    Gateway网关集成Sentinel是为了流控、熔断、降级

    1、添加 sentinel-spring-cloud-gateway-adapter 依赖

    1. <dependency>
    2. <groupId>com.alibaba.cspgroupId>
    3. <artifactId>sentinel-spring-cloud-gateway-adapterartifactId>
    4. <version>1.8.0version>
    5. dependency>

    2、添加sentinel控制台配置

    1. #sentinel dashboard管理后台
    2. spring:
    3. cloud:
    4. sentinel:
    5. eager: true
    6. transport:
    7. dashboard: 192.168.172.128:8080

    3、在配置类spring容器中配置一个Sentinel的全局过滤器

    1. @Configuration
    2. public class GatewayConfiguration {
    3. //省略号代表其它配置
    4. ......
    5. @Bean
    6. @Order(-1)
    7. public GlobalFilter sentinelGatewayFilter() {
    8. return new SentinelGatewayFilter();
    9. }
    10. ......
    11. }

    4、启动测试

    (1)启动Nacos(如果使用MySQL数据持久化,则要先启动mysql服务)

    1. cd /opt/software/nacos/bin/
    2. sh startup.sh -m standalone

    启动MySQL服务(如果docker启动,先启动docker并挂载mysql,防止数据丢失)

    http://192.168.133.129:8848/nacos

    (2)启动Sentinel DashBoard控制台

    1. cd /opt/software/sentinel-dashboard-1.8.4/
    2. java -jar sentinel-dashboard-1.8.4.jar

    http://192.168.133.129:8080/

    (3)分别启动服务提供者、服务消费者

    (4)启动Spring Cloud Gateway

    (5)浏览器输入访问

    http://localhost:8081/test

    二、Spring Cloud Gateway集成Sentinel规则持久化

    一、使用SPI配置 

    1、在application.properties中配置依赖

    1. <dependency>
    2. <groupId>com.alibaba.cspgroupId>
    3. <artifactId>sentinel-datasource-extensionartifactId>
    4. dependency>

    由于之前添加过了  spring-cloud-starter-alibaba-sentinel 依赖,包含了 sentinel-datasource 依赖,此处可以不加

    2、自定义 FileDataSourceInit 类 实现 InitFunc(配置文件暂时不动)

    1. import com.alibaba.csp.sentinel.command.handler.ModifyParamFlowRulesCommandHandler;
    2. import com.alibaba.csp.sentinel.datasource.*;
    3. import com.alibaba.csp.sentinel.init.InitFunc;
    4. import com.alibaba.csp.sentinel.slots.block.authority.AuthorityRule;
    5. import com.alibaba.csp.sentinel.slots.block.authority.AuthorityRuleManager;
    6. import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule;
    7. import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager;
    8. import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
    9. import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
    10. import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowRule;
    11. import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowRuleManager;
    12. import com.alibaba.csp.sentinel.slots.system.SystemRule;
    13. import com.alibaba.csp.sentinel.slots.system.SystemRuleManager;
    14. import com.alibaba.csp.sentinel.transport.util.WritableDataSourceRegistry;
    15. import com.alibaba.fastjson.JSON;
    16. import com.alibaba.fastjson.TypeReference;
    17. import java.io.File;
    18. import java.io.IOException;
    19. import java.util.List;
    20. /**
    21. * 规则持久化
    22. */
    23. public class FileDataSourceInit implements InitFunc {
    24. @Override
    25. public void init() throws Exception {
    26. //可以根据需要指定规则文件的位置
    27. //"user.home" 即C盘 C:\Users\用户名 下
    28. String ruleDir = System.getProperty("user.home") + "/sentinel/rules";
    29. String flowRulePath = ruleDir + "/flow-rule.json";
    30. String degradeRulePath = ruleDir + "/degrade-rule.json";
    31. String paramFlowRulePath = ruleDir + "/param-flow-rule.json";
    32. String systemRulePath = ruleDir + "/system-rule.json";
    33. String authorityRulePath = ruleDir + "/authority-rule.json";
    34. this.mkdirIfNotExits(ruleDir);
    35. this.createFileIfNotExits(flowRulePath);
    36. this.createFileIfNotExits(degradeRulePath);
    37. this.createFileIfNotExits(paramFlowRulePath);
    38. this.createFileIfNotExits(systemRulePath);
    39. this.createFileIfNotExits(authorityRulePath);
    40. //以下代码从官网拷贝过来
    41. // 流控规则:可读数据源
    42. ReadableDataSource> flowRuleRDS = new FileRefreshableDataSource<>(
    43. flowRulePath,
    44. flowRuleListParser
    45. );
    46. // 将可读数据源注册至FlowRuleManager
    47. // 这样当规则文件发生变化时,就会更新规则到内存
    48. FlowRuleManager.register2Property(flowRuleRDS.getProperty());
    49. // 流控规则:可写数据源
    50. WritableDataSource> flowRuleWDS = new FileWritableDataSource<>(
    51. flowRulePath,
    52. this::encodeJson
    53. );
    54. // 将可写数据源注册至transport模块的WritableDataSourceRegistry中
    55. // 这样收到控制台推送的规则时,Sentinel会先更新到内存,然后将规则写入到文件中
    56. WritableDataSourceRegistry.registerFlowDataSource(flowRuleWDS);
    57. // 降级规则:可读数据源
    58. ReadableDataSource> degradeRuleRDS = new FileRefreshableDataSource<>(
    59. degradeRulePath,
    60. degradeRuleListParser
    61. );
    62. DegradeRuleManager.register2Property(degradeRuleRDS.getProperty());
    63. // 降级规则:可写数据源
    64. WritableDataSource> degradeRuleWDS = new FileWritableDataSource<>(
    65. degradeRulePath,
    66. this::encodeJson
    67. );
    68. WritableDataSourceRegistry.registerDegradeDataSource(degradeRuleWDS);
    69. // 热点参数规则:可读数据源
    70. ReadableDataSource> paramFlowRuleRDS = new FileRefreshableDataSource<>(
    71. paramFlowRulePath,
    72. paramFlowRuleListParser
    73. );
    74. ParamFlowRuleManager.register2Property(paramFlowRuleRDS.getProperty());
    75. // 热点参数规则:可写数据源
    76. WritableDataSource> paramFlowRuleWDS = new FileWritableDataSource<>(
    77. paramFlowRulePath,
    78. this::encodeJson
    79. );
    80. ModifyParamFlowRulesCommandHandler.setWritableDataSource(paramFlowRuleWDS);
    81. // 系统规则:可读数据源
    82. ReadableDataSource> systemRuleRDS = new FileRefreshableDataSource<>(
    83. systemRulePath,
    84. systemRuleListParser
    85. );
    86. SystemRuleManager.register2Property(systemRuleRDS.getProperty());
    87. // 系统规则:可写数据源
    88. WritableDataSource> systemRuleWDS = new FileWritableDataSource<>(
    89. systemRulePath,
    90. this::encodeJson
    91. );
    92. WritableDataSourceRegistry.registerSystemDataSource(systemRuleWDS);
    93. // 授权规则:可读数据源
    94. ReadableDataSource> authorityRuleRDS = new FileRefreshableDataSource<>(
    95. authorityRulePath,
    96. authorityRuleListParser
    97. );
    98. AuthorityRuleManager.register2Property(authorityRuleRDS.getProperty());
    99. // 授权规则:可写数据源
    100. WritableDataSource> authorityRuleWDS = new FileWritableDataSource<>(
    101. authorityRulePath,
    102. this::encodeJson
    103. );
    104. WritableDataSourceRegistry.registerAuthorityDataSource(authorityRuleWDS);
    105. }
    106. private Converter> flowRuleListParser = source -> JSON.parseObject(
    107. source,
    108. new TypeReference>() {
    109. }
    110. );
    111. private Converter> degradeRuleListParser = source -> JSON.parseObject(
    112. source,
    113. new TypeReference>() {
    114. }
    115. );
    116. private Converter> systemRuleListParser = source -> JSON.parseObject(
    117. source,
    118. new TypeReference>() {
    119. }
    120. );
    121. private Converter> authorityRuleListParser = source -> JSON.parseObject(
    122. source,
    123. new TypeReference>() {
    124. }
    125. );
    126. private Converter> paramFlowRuleListParser = source -> JSON.parseObject(
    127. source,
    128. new TypeReference>() {
    129. }
    130. );
    131. private void mkdirIfNotExits(String filePath) throws IOException {
    132. File file = new File(filePath);
    133. if (!file.exists()) {
    134. file.mkdirs();
    135. }
    136. }
    137. private void createFileIfNotExits(String filePath) throws IOException {
    138. File file = new File(filePath);
    139. if (!file.exists()) {
    140. file.createNewFile();
    141. }
    142. }
    143. private String encodeJson(T t) {
    144. return JSON.toJSONString(t);
    145. }
    146. }

    3、配置SPI(Service Provider Interface,JDK内置的一种服务提供发现机制,可以用来启用框架扩展和替换组件) 

    Java SPI是一种以接口为基础,使用配置文件来加载(或称之为服务发现)的动态加载机制,主要使用JDK中ServiceLoader来实现

    (1)在classPath下 resources 创建路径META-INF/services/目录下 创建一个 文件 com.alibaba.csp.sentinel.init.InitFunc(以接口的全路径做为名称,不要带文件格式后缀)

    (2)将自定义的类 包路径名拷贝至此(实现类的全路径)

     

    4、启动消费者服务,此时去 Sentinel DashBoard中创建一条流控规则

    根据自定义类 FileDataSourceInit  中 存放sentinel 规则的文件夹,

    即 C:\Users\用户名\sentinel\rules 可找到相应Sentinel 规则持久化的JSON文件

    1.         //可以根据需要指定规则文件的位置
    2.         //"user.home" 即C盘 C:\Users\用户名 下
    3.         String ruleDir = System.getProperty("user.home") + "/sentinel/rules";

     二、使用Nacos配置

    1、添加sentinel-datasource-nacos依赖;

    1. <dependency>
    2. <groupId>com.alibaba.cspgroupId>
    3. <artifactId>sentinel-datasource-nacosartifactId>
    4. dependency>

    2、application.properties配置持久化数据源

    1. #配置sentinel规则持久化到nacos
    2. datasource:
    3. ncs1:
    4. nacos:
    5. server-addr: 192.168.133.128:80
    6. data-id: ${spring.application.name}.json
    7. group-id: DEFAULT_GROUP
    8. rule-type: flow
    9. data-type: json
    10. degrade:
    11. nacos:
    12. server-addr: 192.168.133.128:80
    13. data-id: ${spring.application.name}-degrade.json
    14. group-id: DEFAULT_GROUP
    15. rule-type: degrade
    16. data-type: json

    3、在nacos配置中心配置流控规则

    1. [
    2. {
    3. "resource": "abc",
    4. "controlBehavior": 0,
    5. "count": 1.0,
    6. "grade": 1,
    7. "limitApp": "default",
    8. "strategy": 0
    9. }
    10. ]

    三、Sprng Cloud Gateway跨域CORS

    可参考 https://blog.csdn.net/MinggeQingchun/article/details/125538531

    传统的Ajax请求只能获取在同一个域名下的资源,但是HTML5规范中打破了这限制,允许Ajax发起跨域的请求(需要设置一下)

    其实浏览器本身是可以发起跨域请求的,比如你可以链接一个另一个域名下的图片或者js,比如但是javascript脚本是不能获取这些另一个域名下的资源内容的

    CORS是一个W3C标准,全称是”跨域资源共享”(Cross-origin resource sharing),允许浏览器向跨源服务器,发出XMLHttpRequest请求,从而克服了AJAX只能同源使用的限制

    这种CORS使用了一个额外的HTTP响应头来赋予当前user-agent(浏览器)获得跨域资源的权限,这里的跨域也就是Cross-Origin的概念,这里的权限就是访问另一个域名下的资源权限

    CORS现在HTML5标准的一部分,在大部分现代浏览器中有所支持,可能在某些老版本的浏览器不支持CORS,如果要兼容一些老的浏览器版本,则需要采用JSONP进行跨域请求

    同源与非同源(跨域和不跨域)

    如果 访问协议、端口(如果指定了端口)、host 都相同,则称之为同源(不跨域),否则为非同源(跨域)

    如源链接: http://shop.company.com/good/page.html

    解决跨域:

    1. /**
    2. * 配置网关跨域cors请求支持
    3. */
    4. @Configuration
    5. public class CorsConfig {
    6. @Bean
    7. public CorsWebFilter corsFilter() {
    8. CorsConfiguration config = new CorsConfiguration();
    9. config.addAllowedMethod("*"); //是什么请求方法,比如 GET POST PUT DELATE .....
    10. config.addAllowedOrigin("*"); //来自哪个域名的请求,*号表示所有
    11. config.addAllowedHeader("*"); //是什么请求头
    12. UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser());
    13. source.registerCorsConfiguration("/**", config);
    14. return new CorsWebFilter(source);
    15. }
    16. }

  • 相关阅读:
    配置hadoop模板虚拟机
    Go语言并发控制
    EXCEL常用快捷键
    「教师资格证定期注册」相关答疑
    代理IP和Socks5代理在跨界电商中的关键作用
    问题随记 —— Cannot create directory /tmp/hive. Name node is in safe mode.
    Parallel 与 ConcurrentBag<T> 这对儿黄金搭档(C#)【并发编程系列_2】
    【SSD1306 OLED屏幕测试程序 (开源)orangepi zero2 全志H616 】.md updata: 23/11/07
    Java基础面经1
    rac进行image copy备份,以及异机单机switch to copy方式恢复
  • 原文地址:https://blog.csdn.net/MinggeQingchun/article/details/125975493