diff --git a/event/2.6.1-release.md b/event/2.6.1-release.md new file mode 100644 index 00000000000..fb87ef51200 --- /dev/null +++ b/event/2.6.1-release.md @@ -0,0 +1,177 @@ +--- +title: 2.6.1 +sidebar_position: 2 +keywords: ["release-notes"] +description: release-notes +--- + +## 2.6.1 + +### New Features + +1. Add dubbo annotation analysis for shenyu ingress controller +2. Support plugin lifecycle +3. Support shenyu-sdk-client by openFeign +4. Adding a Motan plugin and Spring Cloud to shenyu ingress-controller +5. Support alert notice +6. Shenyu client add discovery register center +7. Add shenyu context-path plugin ingress controller +8. Add shenyu grpc plugin ingress controller +9. Add shenyu sofa ingress controller +10. Add nacos, etcd, eureka as discovery service +11. Add new plugin: basic-auth +12. Add shenyu logging-rabbitmq plugin +13. Binding selector by shenyu-discovery + +### API Changes + +1. Refactor shenyu sync data data structure + + ``` + plugin.list ["plugin.sign", "plugin.dubbo", "plugin.pluginName"] + -> plugin.sign + -> plugin.dubbo + -> plugin.pluginName + + examples data: + selector.key1.list ["selector.key1.value1", "selector.key1.value2", "selector.key1.value3"] + -> selector.key1.value1 + -> selector.key1.value2 + -> selector.key1.value3 + + selector.key2.list ["selector.key2.value1", "selector.key2.value2", "selector.key2.value3"] + -> selector.key2.value4 + -> selector.key2.value5 + -> selector.key2.value6 + ``` + +2. Support NettyClient as default httpclient + +3. Refactor admin-listener to support admin data sync + +4. Remove brpc supports including brpc plugin, brpc example, brpc integrated test + +5. Remove Apollo dependency to support Java 17(add jar by yourself) + +6. Remove shenyu middleware register client + +### Enhancement + +1. Add test cases for shenyu model event +2. Add selector event test cases +3. Add motan e2e test cases +4. Support the motan protocol +5. Add Grpc e2e test cases +6. Bump apache-rat-plugin to 0.15 +7. Support String isBlank in match condition +8. Clickhouse support ttl field +9. Support HttpUtils log level +10. Add unit test for Ingress Reconciler +11. Support checksum when packing distribution +12. Implement zero-copy in TCP plugin +13. shenyu-client-springmvc supports default appName and contextPath +14. Add sdk-feign example and integrated test case +15. ElasticSearch logging support for custom index +16. Enhance grpc plugin to support shenyu loadbalancer +17. Support http2 upstream server +18. Enhance Dubbo plugin support shenyu loadbalancer +19. Add ingress-controller integration springCloud test case +20. Add WebSocket plugin proxy ping configuration +21. Add ingress-controller integration websocket test +22. RewritePlugin supports percentage +23. Admin use discovery config init discovery-service +24. Divide plugin adapt shenyu discovery +25. Alert report support config admin cluster multi servers +26. WebSocket plugin adapt shenyu discovery +27. Register service instance into discovery +28. Admin adapter discovery local mode +29. Add test case for ShenYu sdk core +30. Add unit test for shenyu-discovery +31. Add opengauss e2e test case +32. Add upload plugin jar size limit +33. Add unit test for shenyu-client-spring-websocket +34. Upgrade Shiro version to a secure version(1.18.0) +35. Update license and upgrade springboot(2.7.17) +36. Send alarm message when gateway global error happen +37. Add EurekaDiscoveryService unit test + +### Refactor + +1. Refactor 2.6.1 version(pom.xml) +2. Simplify Map operations by computeIfAbsent +3. Refactor polaris test cases +4. Migrate Maven Wrapper from io.takari to official release +5. Use compiled Pattern in WebClientMessageWriter +6. Refactor HttpUtils request method +7. Update github action version +8. Refactor Sync data center abstract template method +9. Update MenuProject, MenuModule, MenuDocItem to VO +10. Unified dubbo version +11. Refactor Httpclient's package +12. Refactor github ci action cache +13. Refactor motan pojo as rpc method parameter +14. Upgrade Kafka client version to 3.4.0 +15. Migrate Admin swagger from springfox to springdoc +16. Upgrade Dubbo version to 3.2.5 and refactor some methods +17. Refactor AbstractShenyuSdkClient getOrDefault method +18. Refactor http client properties +19. Refactor webcliet plugin implement +20. Upgrade com.google.guava:guava to 32.0.0-jre +21. support k8s as e2e test case enviroment +22. Refactor @Restapi as rest api request mapping +23. String concatenation recommended using StringBuilder +24. Set the netty allocator to unpooled +25. Refactor startup banner +26. Removing duplicate code and extracting the same code for common use +27. Standardized null detection coding +28. Refactor log plugin selector handler +29. Refactor plugin classloader +30. Refactor Logging plugin to support sampleRate at plugin level +31. Refactor context-path register to avoid repeat context-path(use select for update) + +### Bug Fix + +1. Avoid the permanent overhead of creating TimeoutException +2. Fix example module main class path +3. Fix plugin page sorting bug +4. Update Makefile SNAPSHOT version +5. Fix typo in RELEASE-NOTES.md +6. Fix the error package name of shenyu-example +7. Fix password rules, add special characters '#' and '.' +8. Fix health check for zookeeper:3.8.0 in e2e +9. Fix unstable ci check +10. Add e2e WaitForHelper exception log +11. Fix springcloud plugin can't get scheme +12. Fix javadoc build errors +13. Fix the wrong request type in HttpUtils +14. Fix userId can not update success when update auth +15. Fix thread leak in TCP plugin +16. Format "Quick start" part in shenyu-integrated-test/README +17. Fix SQL script error +18. Fix uri plugin path error and change path to rawpath +19. Fix WebSocket plugin to support rewrite plugin +20. Fix indexName not working for es-logging +21. Fix the error of context-path plugin +22. Fix shenyu-admin cpu surge +23. Fix alert localDateTime format problem +24. shenyu-client persist ApiDoc error retry +25. Fix applicationContextAware initialization too late +26. Fix duplicate response header +27. Set the maximum time to wait for the k8s cluster to start up +28. Fix type for status field for clickhouse log plugin +29. Fix response plugin memory leak +30. Fix dataType contrast error +31. Fix http data sync error +32. Fix spelling error +33. Fix shenyu-dubbo register status +34. Fix buildDiscoveryUpstreamPath causing multiple `/` +35. Fix bug when registering with Eureka through EurekaInstanceRegisterRepository#persistInstance +36. Fix AbstractLogPluginDataHandler hashcode error +37. Fix Ratelimit plugin key error in redis cluster mode +38. Fix multi shenyu client register repeat context path +39. Fix shenyu can't load ext plugin after close the plugin +40. Fix upload plugin jar bug in shenyu admin +41. Fix plugin can not load resource path file +42. Fix Admin script to show dictionary code +43. Fix authorization conflict in sign plugin +44. Fix sign plugin context path match error diff --git a/i18n/zh/docusaurus-plugin-content-docs-event/current/2.6.0-release.md b/i18n/zh/docusaurus-plugin-content-docs-event/current/2.6.0-release.md index 5c6fa42b455..b0f7e822baf 100644 --- a/i18n/zh/docusaurus-plugin-content-docs-event/current/2.6.0-release.md +++ b/i18n/zh/docusaurus-plugin-content-docs-event/current/2.6.0-release.md @@ -1,3 +1,10 @@ +--- +title: 2.6.0 +sidebar_position: 3 +keywords: ["release-notes"] +description: release-notes +--- + ## 2.6.0 ### 新功能 diff --git a/i18n/zh/docusaurus-plugin-content-docs-event/current/2.6.1-release.md b/i18n/zh/docusaurus-plugin-content-docs-event/current/2.6.1-release.md new file mode 100644 index 00000000000..2a17c255929 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs-event/current/2.6.1-release.md @@ -0,0 +1,189 @@ +--- +title: 2.6.1 +sidebar_position: 3 +keywords: ["release-notes"] +description: release-notes +--- + +## 2.6.1 + +### New Features + +1. 添加Dubbo添加Ingress controller支持 + +2. 支持插件生命周期 + +3. 添加shenyu-sdk-openfeign模块 + +4. 添加Motan和Spring Cloud添加Ingress controller支持 + +5. shenyu支持告警功能 + +6. shenyu client添加discovery的注册中心 + +7. 添加shenyu context-path Ingress controller + +8. 添加shenyu grpc Ingress controller + +9. 添加shenyu sofa Ingress controller + +10. 添加nacos, etcd, eureka作为shenyu discovery服务注册中心 + +11. 添加新的插件:basic-plugin + +12. 添加新插件:shenyu-rabbitmq-logging plugin + +13. 通过shenyu-discovery绑定selector + +### API Changes + +1. 重构shenyu数据同步的数据结构 + + ``` + plugin.list ["plugin.sign", "plugin.dubbo", "plugin.pluginName"] + -> plugin.sign + -> plugin.dubbo + -> plugin.pluginName + + examples data: + selector.key1.list ["selector.key1.value1", "selector.key1.value2", "selector.key1.value3"] + -> selector.key1.value1 + -> selector.key1.value2 + -> selector.key1.value3 + + selector.key2.list ["selector.key2.value1", "selector.key2.value2", "selector.key2.value3"] + -> selector.key2.value4 + -> selector.key2.value5 + -> selector.key2.value6 + ``` + +2. 使用netty作为默认的httpclient + +3. 重构shenyu-admin-listener来支持shenyu admin数据同步 + +4. 删除shenyu对brpc的支持,包括brpc插件,brpc示例,brpc集成测试 + +5. 移除Apollo的依赖以便支持Java 17(自行添加依赖) + +6. 删除shenyu的中间件register center + +### Enhancement + +1. 为shenyu model event添加测试用例 +2. 添加shenyu selector测试用例 +3. 添加motan的端到端测试用例 +4. 支持motan插件选择协议 +5. 添加Grpc的端到端测试用例 +6. 升级apache-rat-plugin版本到0.15 +7. 在匹配时地址isBlank条件匹配 +8. Clickhouse支持ttl字段 +9. 支持HttpUtils的日志级别判断 +10. 为Ingress Reconciler添加单元测试 +11. 当软件包分发时自动checksum +12. 在tcp插件中实现零拷贝 +13. shenyu-client-springmvc支持默认的appname和context-path +14. 添加sdk-feign的示例和集成测试 +15. es log插件支持用户自定义的索引 +16. 增强grpc插件支持shenyu-loadbalancer负载均衡算法 +17. 支持http2协议的下游服务 +18. 重构增强dubbo插件支持shenyu-loadbalancer负载均衡算法 +19. 添加ingress controller的springcloud集成测试 +20. 添加WebSocket插件代理ping的功能 +21. 添加ingress controller的websocket集成测试 +22. Rewrite插件支持百分比重写 +23. Admin使用discovery config初始化discovery server +24. Divide插件适配shenyu discovery +25. Alert支持多个admin的集群 +26. WebSocket插件适配shenyu discovery +27. 注册服务实例到shenyu discovery +28. ShenYu Admin适配shenyu-discovery的local模式 +29. 添加shenyu sdk core的测试用例 +30. 添加shenyu-discovery的测试用例 +31. 添加opengauss的e2e测试 +32. 添加上传插件包大小的限制 +33. 添加shenyu-client-websocket的测试用例 +34. 34 升级shiro到安全版本(1.18.0) +35. 升级SpringBoot版本到2.7.17,更新license +36. 添加网关异常时发送通知到shenyu-alert +37. 添加EurekaDiscoveryService单元测试 + +### Refactor + +1. 重构整理2.6.1版本(pom.xml) +2. 使用computeIfAbsent重构Map的操作 +3. 重构polaris测试用例 +4. 迁移Maven Wrapper到官方镜像 +5. 在WebClientMessageWriter中编译过的Pattern +6. 重构HttpUtils的请求方法 +7. 升级github action版本 +8. 重构数据同步的抽象模板方法 +9. 重构MenuProject, MenuModule, MenuDocItem为VO对象 +10. 统一dubbo版本 +11. 重构HttpClient的目录 +12. 重构github action ci缓存 +13. 重构motan插件支持pojo对象作为方法参数 +14. 升级kafka-client版本到3.4.0 +15. 迁移admin swagger springfox到springdoc +16. 升级dubbo版本到3.2.5并重构过期方法 +17. 重构AbstractShenyuSdkClient getOrDefault方法 +18. 重构HttpClient的参数 +19. 重构webclient插件的实现 +20. 升级guava版本到32.0.0-jre +21. 支持k8s作为e2e的测试环境 +22. 使用@Restapi作为rest api的请求路径映射 +23. 使用StringBuilder作为字符串连接器 +24. 设置netty allocator参数为unpooled +25. 重构启动的banner +26. 删除重复的代码并且将部分代码作为公用 +27. 重构null的判断方法 +28. 重构日志插件的选择器处理器 +29. 重构自定义插件类加载器 +30. 重构日志插件支持插件级别的采样比率 +31. 重构Context-path避免重复注册(使用selector for update) + +### Bug Fix + +1. 避免创建TimeoutException的永久开销 +2. 修复示例模块的主类路径 +3. 修复插件排序问题 +4. 修复Makefile Snapshot版本问题 +5. 修复RELEASE-NOTES.md的拼写错误 +6. 修复示例中的错误包名 +7. 修复密码验证规则,并且添加#和.的支持 +8. 修复e2e中zookeeper:3.8.0的健康检查 +9. 修复不稳定的ci检验 +10. 添加e2e WaitForHelper异常日志 +11. 修复springcloud在某些注册中心中间件不能获取scheme +12. 修复javadoc编译错误 +13. 修复HttpUtils中错误的请求类型 +14. 修复更新auth时未更新用户id +15. 修复TCP插件的eventloop线程泄漏 +16. 格式化shenyu-integrated-test中的quickstart +17. 修复SQL脚本错误 +18. 修复uri插件path错误,并且使用rawpath替代path +19. 修复websocket插件对rewrite插件的支持 +20. 修复ElasticSearchLog Plugin索引名称无效 +21. 修复context-path插件的错误 +22. 修复shenyu-admin的cpu占用过高问题 +23. 修复alert中LocalDateTime的格式化问题 +24. 修复shenyu-client的apiDoc的错误重试问题 +25. 修复applicationContextAware初始化顺序过晚 +26. 修复重复的response header +27. 设置k8s的最大等待时间 +28. 修改clickhouse日志插件的status字段类型 +29. 修复response write plugin可能造成的内存泄漏 +30. 修复dataType字段选择错误 +31. 修复http数据同步错误 +32. 修复单词拼写错误 +33. 修复shenyu dubbo代理插件的注册状态 +34. 修复buildDiscoveryUpstreamPath造成多个`/` +35. 修复shenyu-registry的eureka注册错误逻辑 +36. 修复AbstractLogPluginDataHandler hashcode错误 +37. 修复ratelimit插件在集群模式下的key错误 +38. 修复同一个应用多个shenyu-client重复注册context-path的错误 +39. 修复在插件关闭后不会重新加载插件 +40. 修复shenyu admin上传插件的错误 +41. 修复shenyu不能加载resource目录下的资源 +42. 修复Admin来展示字典值 +43. 修复Authorization在sign插件中的冲突 +44. 修复签名插件的context-path路径匹配错误 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1.json b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1.json new file mode 100644 index 00000000000..d1e95b65e5f --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1.json @@ -0,0 +1,81 @@ +{ + "version.label": { + "message": "2.6.1", + "description": "The label for version 2.6.1" + }, + "sidebar.tutorialSidebar.category.Design": { + "message": "设计文档", + "description": "The label for category Design in sidebar tutorialSidebar" + }, + "sidebar.tutorialSidebar.category.Deployment": { + "message": "运维部署", + "description": "The label for category Deployment in sidebar tutorialSidebar" + }, + "sidebar.tutorialSidebar.category.Quick Start": { + "message": "快速开始", + "description": "The label for category Quick Start in sidebar tutorialSidebar" + }, + "sidebar.tutorialSidebar.category.User Guide": { + "message": "用户指南", + "description": "The label for category User Guide in sidebar tutorialSidebar" + }, + "sidebar.tutorialSidebar.category.Admin Usage": { + "message": "Admin使用", + "description": "The label for category Admin Usage in sidebar tutorialSidebar" + }, + "sidebar.tutorialSidebar.category.Property Config": { + "message": "属性配置", + "description": "The label for category Property-Config in sidebar tutorialSidebar" + }, + "sidebar.tutorialSidebar.category.Quick Connect to Your Service": { + "message": "快速接入", + "description": "The label for category User-Guide/Proxy in sidebar tutorialSidebar" + }, + "sidebar.tutorialSidebar.category.Plugin Center": { + "message": "插件集合", + "description": "The label for category Plugin-Center in sidebar tutorialSidebar" + }, + "sidebar.tutorialSidebar.category.Http Handle": { + "message": "Http处理", + "description": "The label for category Http-Handle in sidebar tutorialSidebar" + }, + "sidebar.tutorialSidebar.category.RPC Proxy": { + "message": "RPC代理", + "description": "The label for category RPC-Proxy in sidebar tutorialSidebar" + }, + "sidebar.tutorialSidebar.category.Fault Tolerance": { + "message": "熔断限流", + "description": "The label for category Fault-Tolerance in sidebar tutorialSidebar" + }, + "sidebar.tutorialSidebar.category.Security": { + "message": "安全性", + "description": "The label for category Security in sidebar tutorialSidebar" + }, + "sidebar.tutorialSidebar.category.Mock": { + "message": "Mock", + "description": "The label for mock" + }, + "sidebar.tutorialSidebar.category.Common": { + "message": "通用组件", + "description": "The label for category Common" + }, + "sidebar.tutorialSidebar.category.Observability": { + "message": "可观测性", + "description": "The label for category Observability in sidebar tutorialSidebar" + }, + "sidebar.tutorialSidebar.category.Developer": { + "message": "开发者文档", + "description": "The label for category Developer-Documentation in sidebar tutorialSidebar" + }, + "sidebar.tutorialSidebar.category.SPI": { + "message": "SPI", + "description": "The label for category SPI in sidebar tutorialSidebar" + }, + "sidebar.tutorialSidebar.category.Benchmark Test": { + + "message": "基准测试", + + "description": "ShenYu Benchmark Test" + + } +} diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/benchmark-test/_category_.json b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/benchmark-test/_category_.json new file mode 100644 index 00000000000..eee4d46dad4 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/benchmark-test/_category_.json @@ -0,0 +1,4 @@ +{ + "label": "基准测试", + "position": 8 +} diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/benchmark-test/benchmark-test.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/benchmark-test/benchmark-test.md new file mode 100644 index 00000000000..1e5f663da32 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/benchmark-test/benchmark-test.md @@ -0,0 +1,301 @@ +--- +sidebar_position: 8 +title: 基准测试报告 +keywords: ["test", "benchmark-test"] +description: ShenYu 基准测试报告 +--- + +## 硬件环境 + +### 后端Mock服务所在服务器: + +- CPU: 4核8线程 Intel Cascade Lake @ 3.0GHz +- RAM: 16G + +### 网关节点所在服务器: + +- CPU: 4核8线程 Intel Cascade Lake @ 3.0GHz +- RAM: 16G + +测试工具占用资源很少,安装在网关节点服务器。 + +## ShenYu 版本 + +- ShenYu Admin: 2.6.0 +- ShenYu Bootstrap: 2.6.0 + +## 测试工具 + +wrk-4.2.0 + +## 测试用例说明 + +### 说明 + +- 使用 Mock 服务模拟一个平均响应时长 20ms ,响应报文约 2k 的接口 +- 每次测试时长 3 分钟 +- JDK版本: OpenJdk-1.8.0 +- HTTP 请求端分别使用 `NettyClient` 和 `WebClient` 进行测试 +- 日志级别为WARN +- Apache ShenYu Bootstrap部署模式:单机部署 +- Apache ShenYu Admin部署在mock服务器上。 + +### JVM 配置 + +``` +-Xmx 4g +-Xms 4g +-Xmn 1g +-Xss 512k +-XX: +DisableExplicitGC +-XX: LargePageSizeInBytes=128m +``` + +### 公共配置 + +* application.yml + +```yml +matchCache: + selector: + selectorEnabled: true + initialCapacity: 10000 # initial capacity in cache + maximumSize: 10000 # max size in cache + rule: + initialCapacity: 10000 # initial capacity in cache + maximumSize: 65536 # max size in cache +trie: + enabled: true + childrenSize: 10000 + pathVariableSize: 1000 + pathRuleCacheSize: 1000 + matchMode: antPathMatch +``` + +```yml +netty: + http: + # set to false, user can custom the netty tcp server config. + webServerFactoryEnabled: true + selectCount: 1 + workerCount: 8 + accessLog: false + serverSocketChannel: + soRcvBuf: 87380 + soBackLog: 128 + soReuseAddr: false + connectTimeoutMillis: 10000 + writeBufferHighWaterMark: 65536 + writeBufferLowWaterMark: 32768 + writeSpinCount: 16 + autoRead: false + allocType: "pooled" + messageSizeEstimator: 8 + singleEventExecutorPerGroup: true + socketChannel: + soKeepAlive: false + soReuseAddr: false + soLinger: -1 + tcpNoDelay: true + soRcvBuf: 87380 + soSndBuf: 16384 + ipTos: 0 + allowHalfClosure: false + connectTimeoutMillis: 10000 + writeBufferHighWaterMark: 65536 + writeBufferLowWaterMark: 32768 + writeSpinCount: 16 + autoRead: false + allocType: "pooled" + messageSizeEstimator: 8 + singleEventExecutorPerGroup: true +``` + +```yaml + file: + enabled: false + maxSize : 10 +``` + +```yaml + cross: + enabled: false +``` + +```yaml +logging: + level: + root: warn + org.springframework.boot: warn + org.apache.ibatis: warn + org.apache.shenyu.bonuspoint: warn + org.apache.shenyu.lottery: warn + org.apache.shenyu: warn +``` + +* logback.xml + +```xml + + + + + +``` + +### WebClient配置 + +```yml +httpclient: + strategy: webClient # netty + connectTimeout: 45000 # 45000 + responseTimeout: 3000 # 3000 + readerIdleTime: 3000 # 3000 + writerIdleTime: 3000 # 3000 + allIdleTime: 3000 # 3000 + readTimeout: 3000 # 3000 + writeTimeout: 3000 # 3000 + wiretap: false # false + keepAlive: false # false + maxInMemorySize: 1 # 1 + pool: + type: ELASTIC # ELASTIC + name: proxy # proxy + maxConnections: 16 # 16 + acquireTimeout: 45000 # 45000 + maxIdleTime: 3000 # 3000 +``` + +### NettyClient配置 + +```yml +httpclient: + strategy: netty # netty + connectTimeout: 45000 # 45000 + responseTimeout: 3000 # 3000 + readerIdleTime: 3000 # 3000 + writerIdleTime: 3000 # 3000 + allIdleTime: 3000 # 3000 + readTimeout: 3000 # 3000 + writeTimeout: 3000 # 3000 + wiretap: false # false + keepAlive: false # false + maxInMemorySize: 1 # 1 + pool: + type: ELASTIC # ELASTIC + name: proxy # proxy + maxConnections: 16 # 16 + acquireTimeout: 45000 # 45000 + maxIdleTime: 3000 # 3000 +``` + +## 基准测试结果 + +* 直接访问后端 + +| **QPS** | **50% latency (ms)** | **75% latency (ms)** | **90% latency (ms)** | **99% latency (ms)** | **平均响应时间(ms)** | **最大响应时间(ms)** | +|:---------------:|:----------------------:|:----------------------:|:----------------------:|:----------------------:|:----------------:|:----------------:| +| 28998.20 | 19.81 | 23.78 | 28.26 | 41.24 | 20.92 | 402.90 | + +* netty + +| currency | QPS | 50% latency (ms) | 75% latency (ms) | 90% latency (ms) | 99% latency (ms) | 平均响应时间(ms) | 最大响应时间(ms) | +|:---------:|:----------:|:------------------:|:------------------:|:------------------:|:------------------:|:------------:|:------------:| +| 600 并发 | 20472.95 | 19.37 | 25.36 | 32.89 | 69.92 | 22.09 | 1043.33 | +| 800 并发 | 20703.55 | 23.57 | 31.32 | 40.11 | 77.28 | 26.11 | 576.47 | +| 1000 并发 | 20979.91 | 29.21 | 37.86 | 47.23 | 80.91 | 31.20 | 860.55 | +| 1200 并发 | 21129.88 | 32.45 | 42.40 | 52.68 | 96.10 | 35.06 | 1070 | + +* webClient + +| currency | QPS | 50% latency (ms) | 75% latency (ms) | 90% latency (ms) | 99% latency (ms) | 平均响应时间(ms) | 最大响应时间(ms) | +|:--------:|:----------:|:------------------:|:------------------:|:------------------:|:------------------:|:------------:|:------------:| +| 600 并发 | 18640.47 | 15.77 | 24.77 | 38.26 | 80.31 | 20.32 | 852.06 | +| 800 并发 | 18723.44 | 18.12 | 28.69 | 44.96 | 95.3 | 23.52 | 765.26 | +| 1000 并发 | 18928.99 | 19.99 | 31.42 | 49.09 | 108.84 | 25.93 | 1040 | +| 1200 并发 | 18965.37 | 22.10 | 34.62 | 54.48 | 122.31 | 28.66 | 1075 | + + +### 直接访问后端测试结果 + +#### 测试结果 + +| **QPS** | **50% latency (ms)** | **75% latency (ms)** | **90% latency (ms)** | **99% latency (ms)** | **平均响应时间(ms)** | **最大响应时间(ms)** | +|:---------------:|:----------------------:|:----------------------:|:----------------------:|:----------------------:|:----------------:|:----------------:| +| 28998.20 | 19.81 | 23.78 | 28.26 | 41.24 | 20.92 | 402.90 | + +#### 测试截图 + + + +### netty 测试结果 + +#### 测试结果 + +| currency | QPS | 50% latency (ms) | 75% latency (ms) | 90% latency (ms) | 99% latency (ms) | 平均响应时间(ms) | 最大响应时间(ms) | +|:---------:|:----------:|:------------------:|:------------------:|:------------------:|:------------------:|:------------:|:------------:| +| 600 并发 | 20472.95 | 19.37 | 25.36 | 32.89 | 69.92 | 22.09 | 1043.33 | +| 800 并发 | 20703.55 | 23.57 | 31.32 | 40.11 | 77.28 | 26.11 | 576.47 | +| 1000 并发 | 20979.91 | 29.21 | 37.86 | 47.23 | 80.91 | 31.20 | 860.55 | +| 1200 并发 | 21129.88 | 32.45 | 42.40 | 52.68 | 96.10 | 35.06 | 1070 | + +#### 测试截图 + +##### 600 并发 + + + + + +##### 800 并发 + + + + + +##### 1000 并发 + + + + + +##### 1200 并发 + + + + + +### webClient 测试结果 + +#### 测试结果 + +| currency | QPS | 50% latency (ms) | 75% latency (ms) | 90% latency (ms) | 99% latency (ms) | 平均响应时间(ms) | 最大响应时间(ms) | +|:--------:|:----------:|:------------------:|:------------------:|:------------------:|:------------------:|:------------:|:------------:| +| 600 并发 | 18640.47 | 15.77 | 24.77 | 38.26 | 80.31 | 20.32 | 852.06 | +| 800 并发 | 18723.44 | 18.12 | 28.69 | 44.96 | 95.3 | 23.52 | 765.26 | +| 1000 并发 | 18928.99 | 19.99 | 31.42 | 49.09 | 108.84 | 25.93 | 1040 | +| 1200 并发 | 18965.37 | 22.10 | 34.62 | 54.48 | 122.31 | 28.66 | 1075 | + +#### 测试截图 + +##### 600 并发 + + + + + +##### 800 并发 + + + + +##### 1000 并发 + + + + +##### 1200 并发 + + + + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/deployment/_category_.json b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/deployment/_category_.json new file mode 100644 index 00000000000..d5c06da5450 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/deployment/_category_.json @@ -0,0 +1,4 @@ +{ + "label": "运维部署", + "position": 3 +} diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/deployment/deployment-before.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/deployment/deployment-before.md new file mode 100644 index 00000000000..c69d013ded5 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/deployment/deployment-before.md @@ -0,0 +1,56 @@ +--- +sidebar_position: 0 +title: 部署先决条件 +keywords: ["Prerequisites"] +description: 部署先决条件 +--- + +本文介绍在部署 `Apache ShenYu` 网关前, 所需要准备的一些先决条件。 + +## 数据库环境准备 + +在部署`shenyu-admin`项目前, 需初始化其所使用的数据库(数据库目前支持: Mysql、PostgreSql、Oracle), 其中所用到的脚本文件都存放在 [项目根目录下的db目录](https://github.com/apache/shenyu/tree/master/db) 中, 以下介绍了各数据库的初始步骤. + +### Mysql + +在[项目mysql初始化脚本目录](https://github.com/apache/shenyu/tree/master/db/init/mysql) 中找到初始化脚本`schema.sql`, 使用客户端连接工具连接您的Mysql服务并执行, 由此您会得到一个名为`shenyu`的数据库, 它之后可作为`shenyu-admin`项目的数据库使用. + +* sql脚本: https://github.com/apache/shenyu/tree/master/db/init/mysql + +* 驱动: + + * maven repository: https://repo1.maven.org/maven2/mysql/mysql-connector-java/8.0.30/ + * homepage: https://www.mysql.com/products/connector/ + +### PostgreSql + +在[项目pg初始化脚本目录](https://github.com/apache/shenyu/tree/master/db/init/pg) 中找到初始化脚本`create-database.sql`、`create-table.sql`, 并使用客户端连接工具连接您的PostgreSql服务依次执行,由此您会得到一个名为shenyu的数据库, 它之后可作为`shenyu-admin`项目的数据库使用. + +* sql脚本: https://github.com/apache/shenyu/tree/master/db/init/pg + +* 驱动: + + * maven repository: https://mvnrepository.com/artifact/org.postgresql/postgresql/42.5.0 + * homepage: https://jdbc.postgresql.org/download/ + +### Oracle + +在[项目oracle初始化脚本目录](https://github.com/apache/shenyu/blob/master/db/init/oracle) 中找到初始化脚本`schema.sql`, 使用客户端连接工具连接您的Oracle服务创建一个数据库, 在此数据库上执行`schema.sql`脚本, 由此您便初始化了`shenyu-admin`的数据库, 之后可在[项目配置文件](https://github.com/apache/shenyu/blob/master/shenyu-admin/src/main/resources/application-oracle.yml) 中调整您的oracle环境配置. + +* sql脚本: https://github.com/apache/shenyu/blob/master/db/init/oracle + +* 驱动: + + * maven repository: https://mvnrepository.com/artifact/com.oracle.database.jdbc/ojdbc8/19.3.0.0 + * homepage: https://www.oracle.com/database/technologies/appdev/jdbc-downloads.html + +### OpenGauss + +在[项目openGauss初始化脚本目录](https://github.com/apache/shenyu/blob/master/db/init/og) 中找到初始化脚本`create-table.sql`, 使用客户端连接工具连接您的openGauss服务创建一个数据库, 在此数据库上执行`create-table.sql`脚本, 由此您便初始化了`shenyu-admin`的数据库, 之后可在[项目配置文件](https://github.com/apache/shenyu/blob/master/shenyu-admin/src/main/resources/application-og.yml) 中调整您的openGauss环境配置. + +* sql脚本: https://github.com/apache/shenyu/blob/master/db/init/og + +* 驱动: + + * maven repository: https://mvnrepository.com/artifact/org.opengauss/opengauss-jdbc/5.0.0-og + * homepage: https://gitee.com/opengauss/openGauss-connector-jdbc diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/deployment/deployment-cluster.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/deployment/deployment-cluster.md new file mode 100644 index 00000000000..497ff4e469e --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/deployment/deployment-cluster.md @@ -0,0 +1,230 @@ +--- +sidebar_position: 7 +title: 集群部署 +keywords: ["网关集群", "集群部署"] +description: 集群部署 +--- + +> 在阅读本文档前,你需要先阅读[部署先决条件](./deployment-before.md)文档来完成部署 `shenyu` 前的环境准备工作。 + +本文是介绍在集群环境中快速部署`ShenYu`网关。 + +> 在阅读本文档时,你可以先阅读[二进制包部署](./deployment-package.md)。 + +### 环境准备 + +* 至少准备两台已经安装了JDK1.8+的服务器用于部署网关启动器。 +* 准备一台已经安装了mysql、pgsql、h2和JDK1.8+的服务器用于部署网关管理端。 +* 准备一台服务器用于部署Nginx。 + +### 启动 Apache ShenYu Admin + +* 在你的网关管理端服务器下载并解压[apache-shenyu-${current.version}-admin-bin.tar.gz](https://archive.apache.org/dist/shenyu/2.6.0/apache-shenyu-incubating-2.6.0-admin-bin.tar.gz) 。 + +* 配置你的数据库,进入`/conf`目录,在`application.yaml`文件中修改`spring.profiles.active`节点为`mysql`, `pg` or `h2`。 + +* 配置你的数据同步方式,进入`/conf`目录,在`application.yaml`文件中修改`shenyu.sync`节点为`websocket`, `http`, `zookeeper`, `etcd`, `consul` 或者 `nacos`。 + +* 进入`bin`目录,启动ShenYu Admin。 + +``` +> windows: start.bat + +> linux: ./start.sh +``` + +### 启动 Apache ShenYu Boostrap + +* 在你的网关启动器服务器下载并解压[apache-shenyu-${current.version}-bootstrap-bin.tar.gz](https://archive.apache.org/dist/shenyu/2.6.0/apache-shenyu-incubating-2.6.0-bootstrap-bin.tar.gz) 。 + +* 配置你的数据同步方式,进入`/conf`目录,在`application.yaml`文件中修改`shenyu.sync`节点为`websocket`, `http`, `zookeeper`, `etcd`, `consul` 或者 `nacos`,这个配置必须与`ShenyYu Admin`的配置保持相同。 + +* 进入`bin`目录,启动ShenYu Bootstrap。 + +``` +> windwos : start.bat + +> linux : ./start.sh +``` + +> 在完成这些操作后,你将成功部署`ShenYu Boostrap`集群。 +> +> 假如你`10.1.1.1`和`10.1.1.2`两台服务器在将部署`ShenYu Bootstrap`,并且在`10.1.1.3`部署nginx。 + +### 启动 Nginx + +* 下载并安装nginx。 + +* 在`nginx.conf`文件中修改`upstream`和`server`节点的配置。 + +```nginx +upstream shenyu_gateway_cluster { + ip_hash; + server 10.1.1.1:9195 max_fails=3 fail_timeout=10s weight=50; + server 10.1.1.2:9195 max_fails=3 fail_timeout=10s weight=50; +} + +server { + listen 9195; + location / { + proxy_pass http://shenyu_gateway_cluster; + proxy_set_header HOST $host; + proxy_read_timeout 10s; + proxy_connect_timeout 10s; + } +} +``` + +* 启动 nginx. + +``` +> windows: ./nginx.exe + +> linux: /usr/local/nginx/sbin/nginx +``` + +* 验证nginx配置是否生效,在`ShenYu Bootstrap`或者`Nginx`的日志文件中查看请求被分发到那台服务器上。 + + +### Apache Shenyu-nginx模块实现集群 + +> 该模块提供SDK,用于通过注册中心为OpenResty自动监听Apache Shenyu可用的实例节点。 +>在集群模式下,Apache Shenyu支持部署多个Shenyu实例,随时可能有新的实例上线或下线。因此,Apache Shenyu引入了服务发现 +> OpenResty 模块来帮助客户端检测可用Shenyu实例。目前Apache Shenyu已经支持Zookeeper、Nacos、Etcd和Consul。Client或LoadBalancer +> 可以通过这些Service注册中心获取可用的Shenyu实例。 +1. [Etcd](./deployment-cluster.md#Etcd开始)(支持) +2. [Nacos](./deployment-cluster.md#Nacos开始)(支持) +3. [Zookeeper](./deployment-cluster.md#Zookeeper开始)(支持) +4. Consul(进行中) + +#### 入门 + +* 先决条件 +1. Luarocks +2. OpenResty + +#### 从源码构建 + +首先,从GitHub clone源码。 + +``` +git clone https://github.com/apache/shenyu-nginx +``` + +然后,从源代码构建并安装。 + +``` +cd shenyu-nginx +luarocks make rockspec/shenyu-nginx-main-0.rockspec +``` + +#### Etcd开始 + +修改Nginx配置,创建并初始化Shenyu register模块,连接至目标注册中心。该模块将获取在同一个集群中注册到Etcd的 +所有Shenyu实例。它与Etcd客户端一样监视(基于长轮询)Shenyu实例列表。 +*Etcd示例:* + +``` +init_worker_by_lua_block { + local register = require("shenyu.register.etcd") + register.init({ + balancer_type = "chash", + etcd_base_url = "http://127.0.0.1:2379", + }) +} +``` + +1. `balancer_type`指定负载均衡模式。它支持`chash`和`round` `robin`。 +2. `etcd_base_url`指定 `Etcd` 服务器。(目前不支持身份验证)。 + +最后,重启OpenResty。 + +``` +openresty -s reload +``` + +这就是一个完整的Etcd的使用[示例](https://github.com/apache/shenyu-nginx/blob/main/example/etcd/nginx.conf) 。 + +#### Nacos开始 + +修改Nginx配置,创建并初始化Shenyu register模块,连接至目标注册中心。以下是Nacos的示例: + +**Nacos示例:** + +``` +init_worker_by_lua_block { + local register = require("shenyu.register.nacos") + register.init({ + shenyu_storage = ngx.shared.shenyu_storage, + balancer_type = "chash", + nacos_base_url = "http://127.0.0.1:8848", + username = "nacos", + password = "naocs", + }) +} +``` + +1. `balancer_type`指定负载均衡模式。它支持`chash`和`round` `robin`。 +2. `nacos_base_url`指定 `Nacos` 服务器地址。 +3. `username`指定登录 `Nacos` 的用户名。(仅在启用 Nacos auth 时才需要) +4. `password`指定登录 `Nacos` 的密码。 + +修改`upstream`启用动态更新shenyu实例列表。本案例将Shenyu实例列表与注册中心同步。 + +``` +upstream shenyu { + server 0.0.0.1; -- bad + + balancer_by_lua_block { + require("shenyu.register.nacos").pick_and_set_peer() + } +} +``` + +最后,重启OpenResty。 + +``` +openresty -s reload +``` + +这就是一个完整的Nacos的使用[example](https://github.com/apache/shenyu-nginx/blob/main/example/nacos/nginx.conf) 。 + +#### Zookeeper开始 + +修改Nginx配置,创建并初始化Shenyu register模块,连接目标注册中心。 +通过 zookeeper watch 事件监听Shenyu实例列表的变化。下面是 zookeeper 配置的示例。 + +**Zookeeper示例:** + +``` +init_worker_by_lua_block { + local register = require("shenyu.register.zookeeper") + register.init({ + servers = {"127.0.0.1:2181","127.0.0.1:2182"}, + shenyu_storage = ngx.shared.shenyu_storage, + balancer_type = "roundrobin" + }); + } +``` + +1. `servers` zookeeper 集群地址。 +2. `balancer_type`指定负载均衡模式。它支持chash和round robin。 + +修改`upstream`启用动态更新Shenyu实例列表。本案例将Shenyu实例列表与注册中心同步。 + +``` +upstream shenyu { + server 0.0.0.1; + balancer_by_lua_block { + require("shenyu.register.zookeeper").pick_and_set_peer() + } + } +``` + +最后,重启 OpenResty。 + +``` +openresty -s reload +``` + +这是一个使用 Zookeeper的完整[示例](https://github.com/apache/shenyu-nginx/blob/main/example/zookeeper/nginx.conf) 。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/deployment/deployment-custom.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/deployment/deployment-custom.md new file mode 100644 index 00000000000..d9a3983215e --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/deployment/deployment-custom.md @@ -0,0 +1,75 @@ +--- +sidebar_position: 6 +title: 自定义部署 +description: 自定义部署 +--- + +本文介绍如何基于 `Apache ShenYu` 搭建属于你自己的网关。 + +> 在阅读本文档前,你需要先阅读[部署先决条件](./deployment-before.md)文档来完成部署 `shenyu` 前的环境准备工作。 + +### 启动Apache ShenYu Admin + +* docker 用户参考 docker部署 Apache ShenYu Admin + +* liunx/windows 用户参考二进制包部署 Apache ShenYu Admin + +### 搭建自己的网关(推荐) + +* 首先新建一个空的 `springboot` 项目,可以参考 `shenyu-bootstrap`, 也可以在 [spring 官网](https://spring.io/quickstart) 创建。 + +* 引入如下`jar`包: + +```xml + + + org.springframework.boot + spring-boot-starter-webflux + 2.2.2.RELEASE + + + org.springframework.boot + spring-boot-starter-actuator + 2.2.2.RELEASE + + + org.apache.shenyu + shenyu-spring-boot-starter-gateway + ${current.version} + + + org.apache.shenyu + shenyu-spring-boot-starter-sync-data-websocket + ${current.version} + + +``` + +其中, `${project.version}` 请使用当前最新版本。 + +* 在你的 `application.yaml` 文件中加上如下配置: + +```yaml +spring: + main: + allow-bean-definition-overriding: true +management: + health: + defaults: + enabled: false +shenyu: + sync: + websocket: + urls: ws://localhost:9095/websocket //设置成你的 shenyu-admin 地址 + allowOrigin: ws://localhost:9195 +``` + + + + + + + + + + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/deployment/deployment-docker-compose.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/deployment/deployment-docker-compose.md new file mode 100644 index 00000000000..c42a71faade --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/deployment/deployment-docker-compose.md @@ -0,0 +1,38 @@ +--- +sidebar_position: 3 +title: Docker-compose 部署 +keywords: ["docker-compose", "Deployment"] +description: Docker-compose Deployment +--- + +本文介绍使用 `docker-compose` 来部署 `Apache ShenYu` 网关。 + +> 在阅读本文档前,你需要先阅读[部署先决条件](./deployment-before.md)文档来完成部署 `shenyu` 前的环境准备工作。 + +### 下载 shell 脚本 + +```shell +curl -O https://raw.githubusercontent.com/apache/shenyu/master/shenyu-dist/shenyu-docker-compose-dist/src/main/resources/install.sh +``` + +### 执行脚本 + +这个脚本会下载需要的配置文件、mysql-connector,如果发现下载失败可以重复执行。 + +```shell +sh ./install.sh #默认拉取最新配置,如果需要部署已发布版本,可增加一个参数表示版本号,比如:v2.4.2 或 latest +``` + +### 初始化`shenyu-admin`存储数据源 + +参考[数据库初始文档](./deployment-before.md#数据库环境准备) 初始化数据库环境 。 + +### 修改配置文件 + +修改脚本下载的配置文件来设置`JDBC`等配置。 + +### 执行 docker-compose + +```shell +docker-compose -f ./shenyu-${VERSION}/docker-compose.yaml up -d +``` diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/deployment/deployment-docker.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/deployment/deployment-docker.md new file mode 100644 index 00000000000..b83300ad8de --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/deployment/deployment-docker.md @@ -0,0 +1,113 @@ +--- +sidebar_position: 3 +title: Docker部署 +keywords: ["Docker", "部署"] +description: docker部署 +--- + +本文介绍使用 `docker` 来部署 `Apache ShenYu` 网关。 + +> 在阅读本文档前,你需要先阅读[部署先决条件](./deployment-before.md)文档来完成部署 `shenyu` 前的环境准备工作。 + +### 创建 Docker Network + +``` +docker network create shenyu +``` + +### 启动 Apache ShenYu Admin + +``` +docker pull apache/shenyu-admin:${current.version} +``` + +> 在 2.5.1 版本之后,在 `docker run` 时,可以通过添加 `-e ADMIN_JVM="xxxx"` 来自定义 JVM 启动参数 + +* 使用 `h2` 来存储后台数据: + +``` +docker run -d -p 9095:9095 --name shenyu-admin --net shenyu apache/shenyu-admin:${current.version} +``` + +* 使用 `MySQL` 来存储后台数据, 按照 [指引文档](./deployment-before.md#mysql) 初始化数据库, 将 [mysql-connector.jar](https://repo1.maven.org/maven2/mysql/mysql-connector-java/8.0.29/mysql-connector-java-8.0.29.jar) 拷贝到 `/${your_work_dir}/ext-lib`: + +``` +docker run --name shenyu-admin -v /${your_work_dir}/ext-lib:/opt/shenyu-admin/ext-lib -e "SPRING_PROFILES_ACTIVE=mysql" -e "spring.datasource.url=jdbc:mysql://${your_ip_port}/shenyu?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai&zeroDateTimeBehavior=convertToNull" -e "spring.datasource.username=${your_username}" -e "spring.datasource.password=${your_password}" -d -p 9095:9095 --net shenyu apache/shenyu-admin:${current.version} +``` + +另外一种方式, 从 [配置文件地址](https://github.com/apache/shenyu/blob/master/shenyu-admin/src/main/resources/) 中把 `application.yml`、`application-mysql.yml`配置放到`${your_work_dir}/conf` , 调整`application.yml`中的配置`spring.profiles.active = mysql`,然后执行以下语句: + +``` +docker run --name shenyu-admin -v ${your_work_dir}/conf:/opt/shenyu-admin/conf -v /${your_work_dir}/ext-lib:/opt/shenyu-admin/ext-lib -d -p 9095:9095 --net shenyu apache/shenyu-admin:${current.version} +``` + +* 使用 `PostgreSql` 来存储后台数据, 按照 [指引文档](./deployment-before.md#postgresql) 初始化数据库, 执行以下语句: + +``` +docker run --name shenyu-admin -e "SPRING_PROFILES_ACTIVE=pg" -e "spring.datasource.url=jdbc:postgresql://${your_ip_port}/shenyu?useUnicode=true&characterEncoding=utf-8&useSSL=false" -e "spring.datasource.username=${your_username}" -e "spring.datasource.password=${your_password}" -d -p 9095:9095 --net shenyu apache/shenyu-admin:${current.version} +``` + +另外一种方式, 从 [配置文件地址](https://github.com/apache/shenyu/blob/master/shenyu-admin/src/main/resources/) 中把 `application.yml`、`application-pg.yml`配置放到`${your_work_dir}/conf`, 调整`application.yml`中的配置`spring.profiles.active = pg`,然后执行以下语句: + +``` +docker run --name shenyu-admin -v ${your_work_dir}/conf:/opt/shenyu-admin/conf -d -p 9095:9095 --net shenyu apache/shenyu-admin:${current.version} +``` + +* 使用 `Oracle` 来存储后台数据, 按照 [指引文档](./deployment-before.md#oracle) 初始化数据库, 执行以下语句: + +``` +docker run --name shenyu-admin -e "SPRING_PROFILES_ACTIVE=oracle" -e "spring.datasource.url=jdbc:oracle:thin:@localhost:1521/shenyu" -e "spring.datasource.username=${your_username}" -e "spring.datasource.password=${your_password}" -d -p 9095:9095 --net shenyu apache/shenyu-admin:${current.version} +``` + +另外一种方式, 从 [配置文件地址](https://github.com/apache/shenyu/blob/master/shenyu-admin/src/main/resources/) 中把 `application.yml`、`application-oracle.yml` 配置放到`${your_work_dir}/conf`, 调整`application.yml`中的配置`spring.profiles.active = oracle`,然后执行以下语句: + +``` +docker run --name shenyu-admin -v ${your_work_dir}/conf:/opt/shenyu-admin/conf -d -p 9095:9095 --net shenyu apache/shenyu-admin:${current.version} +``` + +* 使用 `OpenGauss` 来存储后台数据, 按照 [指引文档](./deployment-before.md#opengauss) 初始化数据库, 执行以下语句: + +``` +docker run --name shenyu-admin -e "SPRING_PROFILES_ACTIVE=opengauss" -e "spring.datasource.url=jdbc:opengauss://localhost:5432/shenyu" -e "spring.datasource.username=${your_username}" -e "spring.datasource.password=${your_password}" -d -p 9095:9095 --net shenyu apache/shenyu-admin:${current.version} +``` + +另外一种方式, 从 [配置文件地址](https://github.com/apache/shenyu/blob/master/shenyu-admin/src/main/resources/) 中把 `application.yml`、`application-og.yml` 配置放到`${your_work_dir}/conf`, 调整`application.yml`中的配置`spring.profiles.active = og`,然后执行以下语句: + +``` +docker run --name shenyu-admin -v ${your_work_dir}/conf:/opt/shenyu-admin/conf -d -p 9095:9095 --net shenyu apache/shenyu-admin:${current.version} +``` + +### 启动Apache ShenYu Bootstrap + +> 在 2.5.1 版本之后,在 `docker run` 时,可以通过添加 `-e BOOT_JVM="xxxx"` 来自定义 JVM 启动参数 + +首先拉取 Docker 镜像 + +```shell +docker pull apache/shenyu-bootstrap:${current.version} +``` + +如果不需要修改配置,可以直接使用以下命令启动 + +```shell +docker run -d \ + -p 9195:9195 \ + --name shenyu-bootstrap \ + --net shenyu \ + --env SHENYU_SYNC_WEBSOCKET_URLS=ws://shenyu-admin:9095/websocket \ + apache/shenyu-bootstrap:${current.version} +``` + +> 使用 SHENYU_SYNC_WEBSOCKET_URLS 环境变量可以为 bootstrap 指定与 admin 通信的 Websocket 地址 + +如果需要修改配置,可以从 Github 中拉取 bootstrap 的[配置文件](https://github.com/apache/shenyu/tree/master/shenyu-bootstrap/src/main/resources),将其所在目录记为 `$BOOTSTRAP_CONF`,并进行配置修改。修改完毕后,使用以下命令启动 + +```shell +docker run -d \ + -p 9195:9195 \ + -v $BOOTSTRAP_CONF:/opt/shenyu-bootstrap/conf \ + --name shenyu-bootstrap \ + --net shenyu \ + --env SHENYU_SYNC_WEBSOCKET_URLS=ws://shenyu-admin:9095/websocket \ + apache/shenyu-bootstrap:${current.version} +``` diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/deployment/deployment-helm.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/deployment/deployment-helm.md new file mode 100644 index 00000000000..233e74c81e6 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/deployment/deployment-helm.md @@ -0,0 +1,10 @@ +--- +sidebar_position: 5 +title: Helm部署 +keywords: ["Helm"] +description: Helm部署 +--- + +本文介绍使用 `helm` 来部署 `Apache ShenYu` 网关。 + +详见 [Helm 部署](https://shenyu.apache.org/zh/helm/index/) diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/deployment/deployment-k8s.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/deployment/deployment-k8s.md new file mode 100644 index 00000000000..c367c1e6449 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/deployment/deployment-k8s.md @@ -0,0 +1,865 @@ +--- +sidebar_position: 4 +title: K8s部署 +keywords: ["k8s"] +description: K8s部署 +--- + +本文介绍使用 `K8s` 来部署 `Apache ShenYu` 网关。 + + +> 目录 +> +> 示例一. 使用 h2 作为数据库 +> +> 1. 创建 Namespace 和 ConfigMap +> 2. 部署 shenyu-admin +> 3. 部署 shenyu-bootstrap +> 示例二. 使用 MySQL 作为数据库 +> +> 和 h2 过程类似,需要额外注意的两个地方: +> +> 1. 需要下载 mysql-connector.jar,容器启动时会执行下载命令 +> 2. 需要指定外部 MySQL 数据库配置 +> +> 具体流程如下: +> +> 1. 创建 Namespace和 ConfigMap +> 2. 部署 shenyu-admin +> 3. 部署 shenyu-bootstrap + +## 示例一:使用 h2 作为数据库 + +### 1. 创建 Namespace 和 ConfigMap + +> 创建 Namespace 和网关用到的配置文件 + +- 创建文件 shenyu-ns.yaml + +```yaml +apiVersion: v1 +kind: Namespace +metadata: + name: shenyu + labels: + name: shenyu +--- +apiVersion: v1 +kind: ConfigMap +metadata: + name: shenyu-cm + namespace: shenyu +data: + shenyu-admin-application.yml: | + server: + port: 9095 + address: 0.0.0.0 + spring: + profiles: + active: h2 + thymeleaf: + cache: true + encoding: utf-8 + enabled: true + prefix: classpath:/static/ + suffix: .html + mvc: + pathmatch: + matching-strategy: ant_path_matcher + mybatis: + config-location: classpath:/mybatis/mybatis-config.xml + mapper-locations: classpath:/mappers/*.xml + shenyu: + register: + registerType: http #http #zookeeper #etcd #nacos #consul + serverLists: #localhost:2181 #http://localhost:2379 #localhost:8848 + props: + sessionTimeout: 5000 + connectionTimeout: 2000 + checked: true + zombieCheckTimes: 5 + scheduledTime: 10 + nacosNameSpace: ShenyuRegisterCenter + sync: + websocket: + enabled: true + messageMaxSize: 10240 + allowOrigins: ws://shenyu-admin-svc.shenyu.svc.cluster.local:9095;ws://shenyu-bootstrap-svc.shenyu.svc.cluster.local:9195; + ldap: + enabled: false + url: ldap://xxxx:xxx + bind-dn: cn=xxx,dc=xxx,dc=xxx + password: xxxx + base-dn: ou=xxx,dc=xxx,dc=xxx + object-class: person + login-field: cn + jwt: + expired-seconds: 86400000 + shiro: + white-list: + - / + - /favicon.* + - /static/** + - /index** + - /platform/login + - /websocket + - /error + - /actuator/health + - /swagger-ui.html + - /webjars/** + - /swagger-resources/** + - /v2/api-docs + - /csrf + swagger: + enable: true + apidoc: + gatewayUrl: http://127.0.0.1:9195 + envProps: + - envLabel: Test environment + addressLabel: Request Address + addressUrl: http://127.0.0.1:9195 + - envLabel: Prod environment + addressLabel: Request Address + addressUrl: http://127.0.0.1:9195 + logging: + level: + root: info + org.springframework.boot: info + org.apache.ibatis: info + org.apache.shenyu.bonuspoint: info + org.apache.shenyu.lottery: info + org.apache.shenyu: info + shenyu-admin-application-h2.yml: | + shenyu: + database: + dialect: h2 + init_script: "sql-script/h2/schema.sql" + init_enable: true + spring: + datasource: + url: jdbc:h2:mem:~/shenyu;DB_CLOSE_DELAY=-1;MODE=MySQL; + username: sa + password: sa + driver-class-name: org.h2.Driver + shenyu-bootstrap-application.yml: | + server: + port: 9195 + address: 0.0.0.0 + spring: + main: + allow-bean-definition-overriding: true + allow-circular-references: true + application: + name: shenyu-bootstrap + codec: + max-in-memory-size: 2MB + cloud: + discovery: + enabled: false + nacos: + discovery: + server-addr: 127.0.0.1:8848 # Spring Cloud Alibaba Dubbo use this. + enabled: false + namespace: ShenyuRegisterCenter + eureka: + client: + enabled: false + serviceUrl: + defaultZone: http://localhost:8761/eureka/ + instance: + prefer-ip-address: true + management: + health: + defaults: + enabled: false + shenyu: + matchCache: + selector: + selectorEnabled: false + initialCapacity: 10000 # initial capacity in cache + maximumSize: 10000 # max size in cache + rule: + initialCapacity: 10000 # initial capacity in cache + maximumSize: 10000 # max size in cache + trie: + childrenSize: 10000 + pathVariableSize: 1000 + pathRuleCacheSize: 1000 + matchMode: antPathMatch + netty: + http: + # set to false, user can custom the netty tcp server config. + webServerFactoryEnabled: true + selectCount: 1 + workerCount: 4 + accessLog: false + serverSocketChannel: + soRcvBuf: 87380 + soBackLog: 128 + soReuseAddr: false + connectTimeoutMillis: 10000 + writeBufferHighWaterMark: 65536 + writeBufferLowWaterMark: 32768 + writeSpinCount: 16 + autoRead: false + allocType: "pooled" + messageSizeEstimator: 8 + singleEventExecutorPerGroup: true + socketChannel: + soKeepAlive: false + soReuseAddr: false + soLinger: -1 + tcpNoDelay: true + soRcvBuf: 87380 + soSndBuf: 16384 + ipTos: 0 + allowHalfClosure: false + connectTimeoutMillis: 10000 + writeBufferHighWaterMark: 65536 + writeBufferLowWaterMark: 32768 + writeSpinCount: 16 + autoRead: false + allocType: "pooled" + messageSizeEstimator: 8 + singleEventExecutorPerGroup: true + instance: + enabled: false + registerType: zookeeper #etcd #consul + serverLists: localhost:2181 #http://localhost:2379 #localhost:8848 + props: + cross: + enabled: true + allowedHeaders: + allowedMethods: "*" + allowedAnyOrigin: true # the same of Access-Control-Allow-Origin: "*" + allowedExpose: "" + maxAge: "18000" + allowCredentials: true + switchConfig: + local: true + file: + enabled: true + maxSize : 10 + sync: + websocket: + urls: ws://shenyu-admin-svc.shenyu.svc.cluster.local:9095/websocket + allowOrigin: ws://shenyu-bootstrap-svc.shenyu.svc.cluster.local:9195 + exclude: + enabled: false + paths: + - /favicon.ico + fallback: + enabled: false + paths: + - /fallback/hystrix + - /fallback/resilience4j + health: + enabled: false + paths: + - /actuator/health + - /health_check + extPlugin: + path: + enabled: true + threads: 1 + scheduleTime: 300 + scheduleDelay: 30 + scheduler: + enabled: false + type: fixed + threads: 16 + upstreamCheck: + enabled: false + timeout: 3000 + healthyThreshold: 1 + unhealthyThreshold: 1 + interval: 5000 + printEnabled: true + printInterval: 60000 + ribbon: + serverListRefreshInterval: 10000 + metrics: + enabled: false + name : prometheus + host: 127.0.0.1 + port: 8090 + jmxConfig: + props: + jvm_enabled: true + local: + enabled: false + sha512Key: "BA3253876AED6BC22D4A6FF53D8406C6AD864195ED144AB5C87621B6C233B548BAEAE6956DF346EC8C17F5EA10F35EE3CBC514797ED7DDD3145464E2A0BAB413" + logging: + level: + root: info + org.springframework.boot: info + org.apache.ibatis: info + org.apache.shenyu.bonuspoint: info + org.apache.shenyu.lottery: info + org.apache.shenyu: info + +``` + +- 执行 `kubectl apply -f shenyu-ns.yaml` + +### 2. 部署 shenyu-admin + +> 创建网关管理服务 + +- 创建文件 shenyu-admin.yaml + +```yaml +# 示例使用 nodeport 方式暴露端口 +apiVersion: v1 +kind: Service +metadata: + namespace: shenyu + name: shenyu-admin-svc +spec: + selector: + app: shenyu-admin + type: NodePort + ports: + - protocol: TCP + port: 9095 + targetPort: 9095 + nodePort: 31095 +--- +# shenyu-admin +apiVersion: apps/v1 +kind: Deployment +metadata: + namespace: shenyu + name: shenyu-admin +spec: + selector: + matchLabels: + app: shenyu-admin + replicas: 1 + template: + metadata: + labels: + app: shenyu-admin + spec: + volumes: + - name: shenyu-admin-application + configMap: + name: shenyu-cm + items: + - key: shenyu-admin-application.yml + path: shenyu-admin-application.yml + - name: shenyu-admin-application-h2 + configMap: + name: shenyu-cm + items: + - key: shenyu-admin-application-h2.yml + path: shenyu-admin-application-h2.yml + containers: + - name: shenyu-admin + image: apache/shenyu-admin:latest + imagePullPolicy: Always + ports: + - containerPort: 9095 + env: + - name: 'TZ' + value: 'Asia/Beijing' + volumeMounts: + - name: shenyu-admin-application + mountPath: /opt/shenyu-admin/conf/application.yml + subPath: shenyu-admin-application.yml + - name: shenyu-admin-application-h2 + mountPath: /opt/shenyu-admin/conf/application-h2.yml + subPath: shenyu-admin-application-h2.yml +``` + +- 执行`kubectl apply -f shenyu-admin.yaml` + +### 3. 部署 shenyu-bootstrap + +> 创建网关服务 + +- 创建文件 shenyu-bootstrap.yaml + +```yaml +# 示例使用 nodeport 方式暴露端口 +apiVersion: v1 +kind: Service +metadata: + namespace: shenyu + name: shenyu-bootstrap-svc +spec: + selector: + app: shenyu-bootstrap + type: NodePort + ports: + - protocol: TCP + port: 9195 + targetPort: 9195 + nodePort: 31195 +--- +# shenyu-bootstrap +apiVersion: apps/v1 +kind: Deployment +metadata: + namespace: shenyu + name: shenyu-bootstrap +spec: + selector: + matchLabels: + app: shenyu-bootstrap + replicas: 1 + template: + metadata: + labels: + app: shenyu-bootstrap + spec: + volumes: + - name: shenyu-bootstrap-application + configMap: + name: shenyu-cm + items: + - key: shenyu-bootstrap-application.yml + path: shenyu-bootstrap-application.yml + containers: + - name: shenyu-bootstrap + image: apache/shenyu-bootstrap:latest + ports: + - containerPort: 9195 + env: + - name: TZ + value: Asia/Beijing + volumeMounts: + - name: shenyu-bootstrap-application + mountPath: /opt/shenyu-bootstrap/conf/application.yml + subPath: shenyu-bootstrap-application.yml +``` + +- 执行 `kubectl apply -f shenyu-bootstrap.yaml` + +## 示例二:使用 MySQL 作为数据库 + +### 1. 创建 Namespace和 ConfigMap + +- 创建文件 shenyu-ns.yaml + +```yaml +apiVersion: v1 +kind: Namespace +metadata: + name: shenyu + labels: + name: shenyu +--- +apiVersion: v1 +kind: ConfigMap +metadata: + name: shenyu-cm + namespace: shenyu +data: + shenyu-admin-application.yml: | + server: + port: 9095 + address: 0.0.0.0 + spring: + profiles: + active: mysql + thymeleaf: + cache: true + encoding: utf-8 + enabled: true + prefix: classpath:/static/ + suffix: .html + mvc: + pathmatch: + matching-strategy: ant_path_matcher + mybatis: + config-location: classpath:/mybatis/mybatis-config.xml + mapper-locations: classpath:/mappers/*.xml + shenyu: + register: + registerType: http #http #zookeeper #etcd #nacos #consul + serverLists: #localhost:2181 #http://localhost:2379 #localhost:8848 + props: + sessionTimeout: 5000 + connectionTimeout: 2000 + checked: true + zombieCheckTimes: 5 + scheduledTime: 10 + nacosNameSpace: ShenyuRegisterCenter + sync: + websocket: + enabled: true + messageMaxSize: 10240 + allowOrigins: ws://shenyu-admin-svc.shenyu.svc.cluster.local:9095;ws://shenyu-bootstrap-svc.shenyu.svc.cluster.local:9195; + ldap: + enabled: false + url: ldap://xxxx:xxx + bind-dn: cn=xxx,dc=xxx,dc=xxx + password: xxxx + base-dn: ou=xxx,dc=xxx,dc=xxx + object-class: person + login-field: cn + jwt: + expired-seconds: 86400000 + shiro: + white-list: + - / + - /favicon.* + - /static/** + - /index** + - /platform/login + - /websocket + - /error + - /actuator/health + - /swagger-ui.html + - /webjars/** + - /swagger-resources/** + - /v2/api-docs + - /csrf + swagger: + enable: true + apidoc: + gatewayUrl: http://127.0.0.1:9195 + envProps: + - envLabel: Test environment + addressLabel: Request Address + addressUrl: http://127.0.0.1:9195 + - envLabel: Prod environment + addressLabel: Request Address + addressUrl: http://127.0.0.1:9195 + logging: + level: + root: info + org.springframework.boot: info + org.apache.ibatis: info + org.apache.shenyu.bonuspoint: info + org.apache.shenyu.lottery: info + org.apache.shenyu: info + shenyu-admin-application-mysql.yml: | + shenyu: + database: + dialect: mysql + init_script: "sql-script/mysql/schema.sql" + init_enable: true + spring: + datasource: + url: jdbc:mysql://{your_mysql_ip}:{your_mysql_port}/shenyu?useUnicode=true&characterEncoding=utf-8&useSSL=false + username: {your_mysql_user} + password: {your_mysql_password} + driver-class-name: com.mysql.jdbc.Driver + shenyu-bootstrap-application.yml: | + server: + port: 9195 + address: 0.0.0.0 + spring: + main: + allow-bean-definition-overriding: true + allow-circular-references: true + application: + name: shenyu-bootstrap + codec: + max-in-memory-size: 2MB + cloud: + discovery: + enabled: false + nacos: + discovery: + server-addr: 127.0.0.1:8848 # Spring Cloud Alibaba Dubbo use this. + enabled: false + namespace: ShenyuRegisterCenter + eureka: + client: + enabled: false + serviceUrl: + defaultZone: http://localhost:8761/eureka/ + instance: + prefer-ip-address: true + management: + health: + defaults: + enabled: false + shenyu: + matchCache: + selector: + selectorEnabled: false + initialCapacity: 10000 # initial capacity in cache + maximumSize: 10000 # max size in cache + rule: + initialCapacity: 10000 # initial capacity in cache + maximumSize: 10000 # max size in cache + trie: + childrenSize: 10000 + pathVariableSize: 1000 + pathRuleCacheSize: 1000 + matchMode: antPathMatch + netty: + http: + # set to false, user can custom the netty tcp server config. + webServerFactoryEnabled: true + selectCount: 1 + workerCount: 4 + accessLog: false + serverSocketChannel: + soRcvBuf: 87380 + soBackLog: 128 + soReuseAddr: false + connectTimeoutMillis: 10000 + writeBufferHighWaterMark: 65536 + writeBufferLowWaterMark: 32768 + writeSpinCount: 16 + autoRead: false + allocType: "pooled" + messageSizeEstimator: 8 + singleEventExecutorPerGroup: true + socketChannel: + soKeepAlive: false + soReuseAddr: false + soLinger: -1 + tcpNoDelay: true + soRcvBuf: 87380 + soSndBuf: 16384 + ipTos: 0 + allowHalfClosure: false + connectTimeoutMillis: 10000 + writeBufferHighWaterMark: 65536 + writeBufferLowWaterMark: 32768 + writeSpinCount: 16 + autoRead: false + allocType: "pooled" + messageSizeEstimator: 8 + singleEventExecutorPerGroup: true + instance: + enabled: false + registerType: zookeeper #etcd #consul + serverLists: localhost:2181 #http://localhost:2379 #localhost:8848 + props: + cross: + enabled: true + allowedHeaders: + allowedMethods: "*" + allowedAnyOrigin: true # the same of Access-Control-Allow-Origin: "*" + allowedExpose: "" + maxAge: "18000" + allowCredentials: true + switchConfig: + local: true + file: + enabled: true + maxSize : 10 + sync: + websocket: + urls: ws://shenyu-admin-svc.shenyu.svc.cluster.local:9095/websocket + allowOrigin: ws://shenyu-bootstrap-svc.shenyu.svc.cluster.local:9195 + exclude: + enabled: false + paths: + - /favicon.ico + fallback: + enabled: false + paths: + - /fallback/hystrix + - /fallback/resilience4j + health: + enabled: false + paths: + - /actuator/health + - /health_check + extPlugin: + path: + enabled: true + threads: 1 + scheduleTime: 300 + scheduleDelay: 30 + scheduler: + enabled: false + type: fixed + threads: 16 + upstreamCheck: + enabled: false + timeout: 3000 + healthyThreshold: 1 + unhealthyThreshold: 1 + interval: 5000 + printEnabled: true + printInterval: 60000 + ribbon: + serverListRefreshInterval: 10000 + metrics: + enabled: false + name : prometheus + host: 127.0.0.1 + port: 8090 + jmxConfig: + props: + jvm_enabled: true + local: + enabled: false + sha512Key: "BA3253876AED6BC22D4A6FF53D8406C6AD864195ED144AB5C87621B6C233B548BAEAE6956DF346EC8C17F5EA10F35EE3CBC514797ED7DDD3145464E2A0BAB413" + logging: + level: + root: info + org.springframework.boot: info + org.apache.ibatis: info + org.apache.shenyu.bonuspoint: info + org.apache.shenyu.lottery: info + org.apache.shenyu: info +``` + +- 执行 `kubectl apply -f shenyu-ns.yaml` + +### 2. 部署 shenyu-admin + +- 创建文件 shenyu-admin.yaml + +```yaml +# 示例使用 nodeport 方式暴露端口 +apiVersion: v1 +kind: Service +metadata: + namespace: shenyu + name: shenyu-admin-svc +spec: + selector: + app: shenyu-admin + type: NodePort + ports: + - protocol: TCP + port: 9095 + targetPort: 9095 + nodePort: 31095 +--- +# shenyu-admin +apiVersion: apps/v1 +kind: Deployment +metadata: + namespace: shenyu + name: shenyu-admin +spec: + selector: + matchLabels: + app: shenyu-admin + replicas: 1 + template: + metadata: + labels: + app: shenyu-admin + spec: + volumes: + - name: shenyu-admin-application + configMap: + name: shenyu-cm + items: + - key: shenyu-admin-application.yml + path: shenyu-admin-application.yml + - name: shenyu-admin-application-mysql + configMap: + name: shenyu-cm + items: + - key: shenyu-admin-application-mysql.yml + path: shenyu-admin-application-mysql.yml + - name: mysql-connector-volume + emptyDir: {} + initContainers: + - name: download-mysql-jar + image: busybox:1.35.0 + command: [ "sh","-c"] + args: ["wget https://repo1.maven.org/maven2/mysql/mysql-connector-java/8.0.23/mysql-connector-java-8.0.23.jar; + wget https://repo1.maven.org/maven2/mysql/mysql-connector-java/8.0.23/mysql-connector-java-8.0.23.jar.md5; + if [ $(md5sum mysql-connector-java-8.0.23.jar | cut -d ' ' -f1) = $(cat mysql-connector-java-8.0.23.jar.md5) ]; + then echo success; + else echo failed; + exit 1; + fi; + mv /mysql-connector-java-8.0.23.jar /opt/shenyu-admin/ext-lib/mysql-connector-java.jar" ] + volumeMounts: + - name: mysql-connector-volume + mountPath: /opt/shenyu-admin/ext-lib + containers: + - name: shenyu-admin + image: apache/shenyu-admin:latest + imagePullPolicy: Always + ports: + - containerPort: 9095 + env: + - name: 'TZ' + value: 'Asia/Beijing' + - name: SPRING_PROFILES_ACTIVE + value: mysql + volumeMounts: + - name: shenyu-admin-application + mountPath: /opt/shenyu-admin/conf/application.yml + subPath: shenyu-admin-application.yml + - name: shenyu-admin-application-mysql + mountPath: /opt/shenyu-admin/conf/application-mysql.yml + subPath: shenyu-admin-application-mysql.yml + - name: mysql-connector-volume + mountPath: /opt/shenyu-admin/ext-lib +``` + +- 执行`kubectl apply -f shenyu-admin.yaml` + +### 3. 部署 shenyu-bootstrap + +- 创建文件 shenyu-bootstrap.yaml + +```yaml +# 示例使用 nodeport 方式暴露端口 +apiVersion: v1 +kind: Service +metadata: + namespace: shenyu + name: shenyu-bootstrap-svc +spec: + selector: + app: shenyu-bootstrap + type: NodePort + ports: + - protocol: TCP + port: 9195 + targetPort: 9195 + nodePort: 31195 +--- +# shenyu-bootstrap +apiVersion: apps/v1 +kind: Deployment +metadata: + namespace: shenyu + name: shenyu-bootstrap +spec: + selector: + matchLabels: + app: shenyu-bootstrap + replicas: 1 + template: + metadata: + labels: + app: shenyu-bootstrap + spec: + volumes: + - name: shenyu-bootstrap-application + configMap: + name: shenyu-cm + items: + - key: shenyu-bootstrap-application.yml + path: shenyu-bootstrap-application.yml + containers: + - name: shenyu-bootstrap + image: apache/shenyu-bootstrap:latest + ports: + - containerPort: 9195 + env: + - name: TZ + value: Asia/Beijing + volumeMounts: + - name: shenyu-bootstrap-application + mountPath: /opt/shenyu-bootstrap/conf/application.yml + subPath: shenyu-bootstrap-application.yml +``` + +- 执行 `kubectl apply -f shenyu-bootstrap.yaml` + +## 测试访问 + +**访问地址**:http://{K8S_CLUSTER_IP}:31095/ + +**账号密码**:admin/123456 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/deployment/deployment-local.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/deployment/deployment-local.md new file mode 100644 index 00000000000..892f7a72953 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/deployment/deployment-local.md @@ -0,0 +1,52 @@ +--- +sidebar_position: 1 +title: 本地部署 +keywords: ["Deployment"] +description: 本地部署 +--- + +本文介绍本地环境启动 `Apache ShenYu` 网关。 + +> 在阅读本文档前,你需要先阅读[部署先决条件](./deployment-before.md)文档来完成部署 `shenyu` 前的环境准备工作。 + +### 环境准备 + +* 本地正确安装JDK1.8+ +* 本地正确安装Git +* 本地正确安装Maven +* 选择一款开发工具,比如IDEA + +### 下载编译代码 + +* 下载代码 + +``` +git clone https://github.com/apache/shenyu.git +cd shenyu +mvn clean install '-Dmaven.javadoc.skip=true' '-B' '-Drat.skip=true' '-Djacoco.skip=true' '-DskipITs' '-DskipTests' +``` + +* 使用开发工具启动 `org.apache.shenyu.admin.ShenyuAdminBootstrap`,访问 http://localhost:9095 , 默认用户名和密码分别为: `admin` 和 `123456`。 + + * 如果使用`h2`来存储,设置变量 `--spring.profiles.active = h2` 启动服务。 + + * 如果使用`MySQL`来存储,需按照 [指引文档](./deployment-before.md#mysql) 初始化数据库和修改 `application-mysql.yml` 中的 `jdbc` 相关配置,再设置变量 `--spring.profiles.active = mysql` 启动服务。 + + * 如果使用`PostgreSql`来存储,需按照 [指引文档](./deployment-before.md#postgresql) 初始化数据库和修改 `application-pg.yml` 中的 `jdbc` 相关配置,再设置变量 `--spring.profiles.active = pg` 启动服务。 + + * 如果使用`Oracle`来存储,需按照 [指引文档](./deployment-before.md#oracle) 初始化数据库和修改 `application-oracle.yml` 中的 `jdbc` 相关配置,再设置变量 `--spring.profiles.active = oracle` 启动服务。 + + * 如果使用`OpenGuass`来存储,需按照 [指引文档](./deployment-before.md#opengauss) 初始化数据库和修改 `application-og.yml` 中的 `jdbc` 相关配置,再设置变量 `--spring.profiles.active = og` 启动服务。 + +* 使用开发工具启动 `org.apache.shenyu.bootstrap.ShenyuBootstrapApplication`。 + + + + + + + + + + + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/deployment/deployment-package.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/deployment/deployment-package.md new file mode 100644 index 00000000000..960037442a2 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/deployment/deployment-package.md @@ -0,0 +1,81 @@ +--- +sidebar_position: 2 +title: 二进制包部署 +keywords: ["二进制", "部署"] +description: 二进制包部署 +--- + +本文介绍使用二进制包部署 `Apache ShenYu` 网关。 + +> 在阅读本文档前,你需要先阅读[部署先决条件](./deployment-before.md)文档来完成部署 `shenyu` 前的环境准备工作。 + + +### 启动 Apache ShenYu Admin + +* 下载 [apache-shenyu-${current.version}-admin-bin.tar.gz](https://archive.apache.org/dist/shenyu/2.6.0/apache-shenyu-2.6.0-admin-bin.tar.gz) + +* 解压缩 `apache-shenyu-${current.version}-admin-bin.tar.gz`。 进入 `bin` 目录。 + +> 2.5.1版本后,`start.sh` 开始支持通过环境变量 `ADMIN_JVM` 自定义 JVM 启动参数。 + +* 使用 `h2` 来存储后台数据: + +``` +> windows: start.bat + +> linux: ./start.sh +``` + +* 使用 `MySQL` 来存储后台数据,需按照 [指引文档](./deployment-before.md#mysql) 初始化数据库,将 [mysql-connector.jar](https://repo1.maven.org/maven2/mysql/mysql-connector-java/8.0.18/mysql-connector-java-8.0.18.jar) 拷贝到 `/${your_work_dir}/ext-lib`, 进入 `/conf` 目录修改 `application-mysql.yaml` 中 `jdbc` 的配置。 + +* 将 `conf/application.yml` 中的 `spring.profiles.active` 修改成 `mysql` + +``` +> windows: start.bat + +> linux: ./start.sh +``` + +* 使用 `PostgreSql` 来存储后台数据,需按照 [指引文档](./deployment-before.md#postgresql) 初始化数据库, 进入 `/conf` 目录修改 `application-pg.yaml` 中 `jdbc` 的配置。 + +* 将 `conf/application.yml` 中的 `spring.profiles.active` 修改成 `pg` + +``` +> windows: start.bat + +> linux: ./start.sh +``` + +* 使用 `Oracle` 来存储后台数据,需按照 [指引文档](./deployment-before.md#oracle) 初始化数据库, 进入 `/conf` 目录修改 `application-oracle.yaml` 中 `jdbc` 的配置。 + +* 将 `conf/application.yml` 中的 `spring.profiles.active` 修改成 `oracle` + +``` +> windows: start.bat + +> linux: ./start.sh +``` + +* 使用 `OpenGauss` 来存储后台数据,需按照 [指引文档](./deployment-before.md#opengauss) 初始化数据库, 进入 `/conf` 目录修改 `application-og.yaml` 中 `jdbc` 的配置。 + +* 将 `conf/application.yml` 中的 `spring.profiles.active` 修改成 `og` + +``` +> windows: start.bat + +> linux: ./start.sh +``` + +### 启动 Apache ShenYu Bootstrap + +* 下载 [`apache-shenyu-${current.version}-bootstrap-bin.tar.gz`](https://archive.apache.org/dist/shenyu/2.6.0/apache-shenyu-2.6.0-bootstrap-bin.tar.gz) + +* 解压缩 `apache-shenyu-${current.version}-bootstrap-bin.tar.gz`。 进入 bin 目录。 + +> 2.5.1版本后,`start.sh` 开始支持通过环境变量 `BOOT_JVM` 自定义 JVM 启动参数。 + +``` +> windwos : start.bat + +> linux : ./start.sh +``` diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/deployment/deployment-quick.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/deployment/deployment-quick.md new file mode 100644 index 00000000000..29f40c42d63 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/deployment/deployment-quick.md @@ -0,0 +1,109 @@ +--- +sidebar_position: 1 +title: 单机快速部署 +keywords: ["Deployment"] +description: 单机快速部署 +--- + +本文介绍单机环境快速启动 `Apache ShenYu` 网关。 + +> 在阅读本文档前,你需要先阅读[部署先决条件](./deployment-before.md)文档来完成部署 `shenyu` 前的环境准备工作。 + +### 环境准备 + +* 本地正确安装JDK1.8+ + +### 启动 Apache ShenYu Bootstrap + +* 下载 [apache-shenyu-${current.version}-bootstrap-bin.tar.gz](https://archive.apache.org/dist/shenyu/2.6.0/apache-shenyu-2.6.0-bootstrap-bin.tar.gz) + +* 解压缩 `apache-shenyu-${current.version}-bootstrap-bin.tar.gz`。 进入 bin 目录。 + +``` +> windwos : start.bat + +> linux : ./start.sh +``` + +### 选择器及规则配置 + +参考[本地模式](../developer/local-model#新增选择器与规则)进行选择器及规则的配置。 + +示例: + +* 如服务地址是`http://127.0.0.1:8080/helloworld`,直接访问将返回如下 + +```json +{ + "name" : "Shenyu", + "data" : "hello world" +} +``` + +* 按照如下进行选择器和规则配置 + +### 使用postman + +> Headers 中添加 `localKey: 123456`。如果需要自定义 localKey,可以使用 sha512 工具根据明文生成 key,并更新 `shenyu.local.sha512Key` 属性。 +> +> 请求方式POST,地址`http://localhost:9195/shenyu/plugin/selectorAndRules`,body 选择raw json,内容如下: + +``` +Headers + +localKey: 123456 +``` + +```json +{ + "pluginName": "divide", + "selectorHandler": "[{\"upstreamUrl\":\"127.0.0.1:8080\"}]", + "conditionDataList": [{ + "paramType": "uri", + "operator": "match", + "paramValue": "/**" + }], + "ruleDataList": [{ + "ruleHandler": "{\"loadBalance\":\"random\"}", + "conditionDataList": [{ + "paramType": "uri", + "operator": "match", + "paramValue": "/**" + }] + }] +} +``` + +### 使用curl + +```bash +curl --location --request POST 'http://localhost:9195/shenyu/plugin/selectorAndRules' \ +--header 'Content-Type: application/json' \ +--header 'localKey: 123456' \ +--data-raw '{ + "pluginName": "divide", + "selectorHandler": "[{\"upstreamUrl\":\"127.0.0.1:8080\"}]", + "conditionDataList": [{ + "paramType": "uri", + "operator": "match", + "paramValue": "/**" + }], + "ruleDataList": [{ + "ruleHandler": "{\"loadBalance\":\"random\"}", + "conditionDataList": [{ + "paramType": "uri", + "operator": "match", + "paramValue": "/**" + }] + }] +}' +``` + +* 通过`http://localhost:9195/helloworld`请求服务,返回如下: + +```json +{ + "name" : "Shenyu", + "data" : "hello world" +} +``` diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/design/_category_.json b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/design/_category_.json new file mode 100644 index 00000000000..681e473796f --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/design/_category_.json @@ -0,0 +1,4 @@ +{ + "label": "设计文档", + "position": 2 +} diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/design/data-sync.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/design/data-sync.md new file mode 100644 index 00000000000..816e3c21296 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/design/data-sync.md @@ -0,0 +1,110 @@ +--- +sidebar_position: 2 +title: 数据同步设计 +keywords: ["Apache ShenYu"] +description: 数据同步 +--- + +本篇主要讲解数据同步原理,数据同步是指在 `shenyu-admin` 后台操作数据以后,使用何种策略将数据同步到 `Apache ShenYu` 网关。`Apache ShenYu` 网关当前支持`ZooKeeper`、`WebSocket`、`Http长轮询`、`Nacos` 、`Etcd` 和 `Consul` 进行数据同步。 + + + +数据同步的相关配置请参考用户文档中的 [数据同步配置](../user-guide/property-config/use-data-sync.md) 。 + +### 背景 + +网关是流量请求的入口,在微服务架构中承担了非常重要的角色,网关高可用的重要性不言而喻。在使用网关的过程中,为了满足业务诉求,经常需要变更配置,比如流控规则、路由规则等等。因此,网关动态配置是保障网关高可用的重要因素。 + + +在实际使用 `Apache ShenYu` 网关过程中,用户也反馈了一些问题: + +* 依赖 `Zookeeper`,怎么使用 `Etcd`、`Consul`、`Nacos`等其他注册中心? +* 依赖 `Redis`、`influxdb`,没有使用限流插件、监控插件,为什么需要这些? +* 配置同步为什么不使用配置中心? +* 为什么不能动态配置更新? +* 每次都要查询数据库,使用`Redis`不就行了吗? + +根据用户的反馈信息,我们对 `Apache ShenYu` 也进行了部分的重构,当前数据同步特性如下: + +- 所有的配置都缓存在 `Apache ShenYu` 网关内存中,每次请求都使用本地缓存,速度非常快。 +- 用户可以在 `shenyu-admin` 后台任意修改数据,并马上同步到网关内存。 +- 支持 `Apache ShenYu` 的插件、选择器、规则数据、元数据、签名数据等数据同步。 +- 所有插件的选择器,规则都是动态配置,立即生效,不需要重启服务。 +- 数据同步方式支持 `Zookeeper`、`Http 长轮询`、`Websocket`、`Nacos`、`Etcd` 和 `Consul`。 + +### 原理分析 + +下图展示了 `Apache ShenYu` 数据同步的流程,`Apache ShenYu` 网关在启动时,会从配置服务同步配置数据,并且支持推拉模式获取配置变更信息,然后更新本地缓存。管理员可以在管理后台(`shenyu-admin`),变更用户权限、规则、插件、流量配置,通过推拉模式将变更信息同步给 `Apache ShenYu` 网关,具体是 `push` 模式,还是 `pull` 模式取决于使用哪种同步方式。 + + ![](/img/shenyu/dataSync/plugin-data.png) + +在最初的版本中,配置服务依赖 `Zookeeper` 实现,管理后台将变更信息 `push` 给网关。而现在可以支持 `WebSocket`、`Http长轮询`、`Zookeeper`、`Nacos`、`Etcd` 和 `Consul`,通过在配置文件中设置 `shenyu.sync.${strategy}` 指定对应的同步策略,默认使用 `WebSocket` 同步策略,可以做到秒级数据同步。但是,有一点需要注意的是,`Apache ShenYu`网关 和 `shenyu-admin` 必须使用相同的同步策略。 + +如下图所示,`shenyu-admin` 在用户发生配置变更之后,会通过 `EventPublisher` 发出配置变更通知,由 `EventDispatcher` 处理该变更通知,然后根据配置的同步策略(`Http、WebSocket、Zookeeper、Nacos、Etcd、Consul`),将配置发送给对应的事件处理器。 + +- 如果是 `WebSocket` 同步策略,则将变更后的数据主动推送给 `shenyu-web`,并且在网关层,会有对应的 `WebsocketDataHandler` 处理器来处理 `shenyu-admin` 的数据推送。 +- 如果是 `Zookeeper` 同步策略,将变更数据更新到 `Zookeeper`,而 `ZookeeperSyncCache` 会监听到 `Zookeeper` 的数据变更,并予以处理。 +- 如果是 `Http` 同步策略,由网关主动发起长轮询请求,默认有 `90s` 超时时间,如果 `shenyu-admin` 没有数据变更,则会阻塞 `Http` 请求,如果有数据发生变更则响应变更的数据信息,如果超过 `60s` 仍然没有数据变更则响应空数据,网关层接到响应后,继续发起 `Http` 请求,反复同样的请求。 + + + +### Zookeeper同步原理 + +基于 `Zookeeper` 的同步原理很简单,主要是依赖 `Zookeeper` 的 `watch` 机制。`Apache ShenYu`网关会监听配置的节点,`shenyu-admin` 在启动的时候,会将数据全量写入 `Zookeeper`,后续数据发生变更时,会增量更新 `Zookeeper` 的节点,与此同时,`Apache ShenYu`网关会监听配置信息的节点,一旦有信息变更时,会更新本地缓存。 + +![zookeeper节点设计](https://yu199195.github.io/images/soul/soul-zookeeper.png) + +`Apache ShenYu` 将配置信息写到`zookeeper`节点,是通过精心设计的,如果您想深入了解代码实现,请参考源码 `ZookeeperSyncDataService`。 + +### WebSocket同步原理 + +`WebSocket` 和 `Zookeeper` 机制有点类似,将网关与 `shenyu-admin` 建立好 `WebSocket` 连接时,`shenyu-admin` 会推送一次全量数据,后续如果配置数据发生变更,则以增量形式将变更数据通过 `WebSocket` 主动推送给 `Apache ShenYu`网关。 + +使用 `WebSocket` 同步的时候,特别要注意断线重连,也就是要保持心跳。`Apache ShenYu`使用`java-websocket` 这个第三方库来进行`websocket`连接。 +如果您想深入了解代码实现,请参考源码 `WebsocketSyncDataService`。 + + +### Http长轮询同步原理 + +`Zookeeper`和`WebSocket` 数据同步的机制比较简单,而 `Http长轮询`则比较复杂。 `Apache ShenYu` 借鉴了 `Apollo`、`Nacos` 的设计思想,取其精华,自己实现了 `Http长轮询`数据同步功能。注意,这里并非传统的 `ajax` 长轮询! + + + +`Http长轮询` 机制如上所示,`Apache ShenYu`网关主动请求 `shenyu-admin` 的配置服务,读取超时时间为 `90s`,意味着网关层请求配置服务最多会等待 `90s`,这样便于 `shenyu-admin` 配置服务及时响应变更数据,从而实现准实时推送。 + +`http` 请求到达 `shenyu-admin` 之后,并非立马响应数据,而是利用 `Servlet3.0` 的异步机制,异步响应数据。首先,将长轮询请求任务 `LongPollingClient` 扔到 `BlockingQueue` 中,并且开启调度任务,`60s` 后执行,这样做的目的是 `60s` 后将该长轮询请求移除队列。因为即便是没有配置变更,也需要让网关知道,不能一直等待。而且网关请求配置服务时,也有 `90s` 的超时时间。 + + +如果这段时间内,管理员在 `shenyu-admin` 变更了配置数据,此时,会挨个移除队列中的长轮询请求,并响应数据,告知是哪个 `Group` 的数据发生了变更(我们将插件、规则、流量配置、用户配置数据分成不同的组)。网关收到响应信息之后,只知道是哪个 `Group` 发生了配置变更,还需要再次请求该 `Group` 的配置数据。这里可能会存在一个疑问:为什么不是直接将变更的数据写出?我们在开发的时候,也深入讨论过该问题,因为 `http 长轮询` 机制只能保证准实时,如果在网关层处理不及时,或者管理员频繁更新配置,很有可能便错过了某个配置变更的推送,安全起见,我们只告知某个 `Group` 信息发生了变更。 + +当 `shenyu-web` 网关层接收到 `http` 响应信息之后,拉取变更信息(如果有变更的话),然后再次请求 `shenyu-admin` 的配置服务,如此反复循环。 +如果您想深入了解代码实现,请参考源码 `HttpSyncDataService`。 + + +### Nacos同步原理 + +`Nacos`的同步原理与Zookeeper基本类似,主要依赖于`Nacos`的`配置管理`,各个配置节点的路径与Zookeeper类似。 + +`Apache ShenYu`网关会监听配置的节点,启动时,如果`Nacos`中不存在配置节点,将同步全量的数据写入`Nacos`中,后续数据发生变更时,全量更新`Nacos`中的配置节点,与此同时,`Apache ShenYu`网关会监听配置信息的节点,一旦有信息变更时,会更新本地缓存。 + +如果您想深入了解代码实现,请参考源码 `NacosSyncDataService`和`Nacos`的[官方文档](https://nacos.io/zh-cn/docs/sdk.html)。 + + +### Etcd同步原理 + +`Etcd` 数据同步原理与Zookeeper类似,主要依赖于`Etcd`的`watch`机制,各个配置节点路径与`Zookeeper`相同。 + +`Etcd`的原生API使用稍有点复杂,所有对其进行了一定的封装。 + +`Apache ShenYu`网关会监听配置的节点,启动时,如果`Etcd`中不存在配置节点,将同步全量的数据写入`Etcd`中,后续数据发生变更时,增量更新`Etcd`中的配置节点,与此同时,`Apache ShenYu`网关会监听配置信息的节点,一旦有信息变更时,会更新本地缓存。 + +如果您想深入了解代码实现,请参考源码 `EtcdSyncDataService`。 + +### Consul同步原理 + +`Consul` 数据同步原理是网关定时轮询 `Consul` 的配置中心,获取配置版本号与本地进行比对。 + +`Apache ShenYu`网关会定时轮询配置的节点,默认间隔时间为1s。启动时,如果 `Consul` 中不存在配置节点,将同步全量的数据写入`Consul`中,后续数据发生变更时,增量更新 `Consul` 中的配置节点,与此同时,`Apache ShenYu`网关会定时轮询配置信息的节点,拉取配置版本号与本地进行比对,若发现版本号变更时,会更新本地缓存。 + +如果您想深入了解代码实现,请参考源码 `ConsulSyncDataService`。 + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/design/database-design.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/design/database-design.md new file mode 100644 index 00000000000..ec6ee2ac241 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/design/database-design.md @@ -0,0 +1,95 @@ +--- +sidebar_position: 1 +title: 管理后台数据结构设计 +keywords: ["db"] +description: ShenYu Admin数据结构 +--- + +`Apache ShenYu Admin` 是网关的后台管理系统,能够可视化管理所有插件、选择器和规则,设置用户、角色,控制资源。 + +## 插件、选择器和规则 + +* 插件:`Apache ShenYu` 使用插件化设计思想,实现插件的热插拔,极易扩展。内置丰富的插件,包括 `RPC` 代理、熔断和限流、权限认证、监控等等。 +* 选择器:每个插件可设置多个选择器,对流量进行初步筛选。 +* 规则:每个选择器可设置多个规则,对流量进行更细粒度的控制。 +* 数据库 `UML` 类图: + + + +* 设计详解: + + * 一个插件对应多个选择器,一个选择器对应多个规则。 + + * 一个选择器对应多个匹配条件,一个规则对应多个匹配条件。 + + * 每个规则在对应插件下,有不同的处理能力。 + +## 资源权限 + +* 资源代表的是 `shenyu-admin` 用户后台中的菜单或者按钮。 + +* 资源权限数据表用来存储用户名称、角色、资源数据以及对应关系。 + +* 数据库 `UML` 类图: + + + +* 设计详解: + * 一个用户对应多个角色,一个角色对应多个资源。 + + +## 数据权限 + +* 数据权限表用来存储用户,选择器、规则对应关系。 +* 数据库 `UML` 类图: + + + +* 设计详解: + * 数据权限的表为: `data_permission`,一个用户对应多条数据权限。 + * 数据权限表中字段 `data_type` 区分不同的类型数据, 具体对应关系如下:`0 -> 选择器, 1 -> 规则`。 + * 数据权限表中字段 `data_id` 存放相应类型的主键`id`。 + +## 元数据 + +* 元数据主要是用于网关的泛化调用。 +* 每个接口方法,对应一条元数据。 +* 数据库 `UML` 类图: + + + + +* 设计详解: + * `path`:在请求网关的时候,会根据 `path` 来匹配到一条数据,然后进行后续的流程。 + + * `rpc_ext`:用于保存`RPC`代理中的扩展信息。 + +## 字典管理 + +* 字典管理主要用来维护和管理公用数据字典。 +* 数据库 `UML` 类图: + + + +## API文档 + +* API文档表用来维护和管理API文档。 +* 常见规范(如OpenApi3.0规范、yapi规范)的api doc(如json、md、html等)可以导入`shenyu-admin`,并最终存储到API文档表。 +* 通过API文档表可以生成其他常见规范的api doc。 +* 数据库 `UML` 类图: + + + +* 设计详解: + * 一个tag可以有多个子tag,tag的层级无限,最下面的叶子节点是API。 + * 相同path、支持多种http_method的接口,算多个API。 + * 一个API有多个请求参数、多个响应字段。 + * 一个参数/字段有它自己的类型(也就是model),每个类型由多个字段构成。 + * 一个字段有它自己的类型,对应多个值。 + * 一个值既可以作为请求示例值,也可以描述响应示例值(比如200表示OK、400表示非法参数)。 + * `mock_request_record`表的`query`、`header`、`body`都存储json,但是`body`不支持存储特殊类型(比如文件)。 + * `tag`表的`ext`存储它父tag(包括父tag的父tag,以此类推)的全量json数据。 + * `api`表的`ext`可能存储ip列表、SpringCloud的service name。 + * `parameter`表的`type`主要包括`requestUrlParam`、`requestHeader`、`requestBody`、`requestPathVariable`、`responseHeader`和`responseBody`;如果返回的类型是特殊类型(如文件),则不用关联`model_id`。 + * `field`表的`ext`以json格式(方便后续扩展)存储泛型,如`{"genericTypes":[model_id1,model_id2]}`;`model_id`表示该字段属于哪个类型,`self_model_id`表示该字段自身是什么类型。 + * `detail`表的`is_example`表示一个值是否是请求示例值,true是请求示例值,false是响应值。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/design/flow-control.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/design/flow-control.md new file mode 100644 index 00000000000..f4499de3ee5 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/design/flow-control.md @@ -0,0 +1,77 @@ +--- +title: 流量控制设计 +keywords: ["flow-control"] +description: Apache ShenYu 流量控制设计 +--- + +`Apache ShenYu`网关通过插件、选择器和规则完成流量控制。相关数据结构可以参考之前的 [ShenYu Admin数据结构](./database-design) 。 + +## 插件 + +* 在`shenyu-admin`后台,每个插件都用`handle`(`json`格式)字段来表示不同的处理,而插件处理就是用来管理编辑`json`里面的自定义处理字段。 +* 该功能主要是用来支持插件处理模板化配置的。 + + +## 选择器和规则 + +选择器和规则是 `Apache ShenYu` 网关中最灵魂的设计。掌握好它,你可以对任何流量进行管理。 + + 一个插件有多个选择器,一个选择器对应多种规则。选择器相当于是对流量的一级筛选,规则就是最终的筛选。 +对一个插件而言,我们希望根据我们的配置,达到满足条件的流量,插件才会被执行。 + 选择器和规则就是为了让流量在满足特定的条件下,才去执行我们想要的,这种规则首先要明白。 + +插件、选择器和规则执行逻辑如下,当流量进入到`Apache ShenYu`网关之后,会先判断是否有对应的插件,该插件是否开启;然后判断流量是否匹配该插件的选择器;然后再判断流量是否匹配该选择器的规则。如果请求流量能满足匹配条件才会执行该插件,否则插件不会被执行,处理下一个。`Apache ShenYu`网关就是这样通过层层筛选完成流量控制。 + + + +## 流量筛选 + + + +流量筛选,是选择器和规则的灵魂,对应为选择器与规则里面的匹配条件(conditions),根据不同的流量筛选规则,我们可以处理各种复杂的场景。流量筛选可以从`Header`, `URI`, `Query`, `Cookie` 等等Http请求获取数据, + +然后可以采用 `Match`,`=`,`SpEL`,`Regex`,`Groovy`,`Exclude`等匹配方式,匹配出你所预想的数据。多组匹配添加可以使用And/Or的匹配策略。 + + +具体的介绍与使用请看: [选择器与规则管理](../user-guide/admin-usage/selector-and-rule) 。 + + +```mermaid +stateDiagram-v2 + state "插件1..n" as p1 + state pc1 <> + state "选择器1..n" as s1 + state sc1 <> + state "规则1..n" as r1 + state rc1 <> + state "执行规则" as rr1 + state rrc1 <> + + [*] --> p1 + + state p1 { + [*] --> pc1 + pc1 --> [*] : 插件未开启
继续执行下一个插件 + + state s1 { + [*] --> sc1 + sc1 --> [*] : 选择器未匹配
继续匹配下一个选择器 + + state r1 { + [*] --> rc1 + rc1 --> [*] : 规则未匹配
继续匹配下一个规则 + + state rr1 { + [*] --> rrc1 + rrc1 --> [*] : 继续执行下一个插件 + } + rc1 --> rr1 : 规则已匹配
开始执行规则 + } + sc1 --> r1 : 选择器已匹配
开始匹配规则 + note left of r1 : 当选择器类型为《全流量》时
该选择器和其下规则
的条件均无效
取末尾规则执行 + } + pc1 --> s1 : 插件已开启
开始匹配选择器 + note left of s1 : 在一个选择器里,至多只会匹配&执行一条规则 + } + note left of p1 : 在一个插件里,至多只会匹配到一个选择器 +``` diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/design/register-center-design.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/design/register-center-design.md new file mode 100644 index 00000000000..834068aeb27 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/design/register-center-design.md @@ -0,0 +1,67 @@ +--- +title: 客户端注册设计 +keywords: ["客户端接入"] +description: 客户端接入原理 +--- + +> *注意* +> 在Apache ShenYu version 2.6.1, ShenYu注册中心只支持http类型,中间件注册类型已经被移除。 +> 所以,请使用http注册类型来注册你的服务。 +> ShenYu注册中心不是微服务注册中心,它只是将元数据、选择器数据、规则数据注册到shenyu-admin,然后shenyu-admin将数据同步到shenyu-gateway。 + +应用客户端接入是指将你的微服务接入到`Apache ShenYu`网关,当前支持`Http`、 `Dubbo`、 `Spring Cloud`、 `gRPC`、 `Motan`、 `Sofa`、 `Tars`等协议的接入。 + + +将应用客户端接入到`Apache ShenYu`网关是通过注册中心来实现的,涉及到客户端注册和服务端同步数据。注册中心支持`Http`。 + + + + +客户端接入的相关配置请参考用户文档中的 [客户端接入配置](../user-guide/property-config/register-center-access.md) 。 + + +## 设计原理 + +### 注册中心客户端 + +![](/img/shenyu/register/client.png) + +在你的微服务配置中声明注册中心客户端类型,如`Http`。 +应用程序启动时使用`SPI`方式加载并初始化对应注册中心客户端,通过实现`Spring Bean`相关的后置处理器接口,在其中获取需要进行注册的服务接口信息,将获取的信息放入`Disruptor`中。 + +注册中心客户端从`Disruptor`中读取数据,并将接口信息注册到`shenyu-admin`,`Disruptor`在其中起数据与操作解耦的作用,利于扩展。 + +### 注册中心服务端 + +![](/img/shenyu/register/server.png) + +在`shenyu-admin`配置中声明注册中心服务端类型,如`Http`。当`shenyu-admin`启动时,读取配置类型,加载并初始化对应的注册中心服务端,注册中心服务端收到`shenyu-client`注册的接口信息后,将其放入`Disruptor`中,然后会触发注册处理逻辑,将服务接口信息更新并发布同步事件。 + +`Disruptor`在其中起到数据与操作解耦,利于扩展。如果注册请求过多,导致注册异常,也有数据缓冲作用。 + +### Http注册原理 + +`Http`服务注册原理较为简单,在`shenyu-client`启动后,会调用`shenyu-admin`的相关服务注册接口,上传数据进行注册。 + +`shenyu-admin` 收到请求后进行数据更新和数据同步事件发布,将接口信息同步到`Apache ShenYu`网关。 + + +### SPI扩展 + +| *SPI 名称* | *详细说明* | +| -------------------------------- | --------------------------- | +| ShenyuClientRegisterRepository | ShenYu网关客户端接入注册服务资源 | + +| *已知实现类* | *详细说明* | +| -------------------------------- | --------------------------- | +| HttpClientRegisterRepository | 基于Http请求的实现 | + + +| *SPI 名称* | *详细说明* | +| -------------------------------- | ----------------------------- | +| ShenyuServerRegisterRepository | ShenYu网关客户端注册的后台服务资源 | + +| *已知实现类* | *详细说明* | +| -------------------------------- | ----------------------------- | +| ShenyuHttpRegistryController | 使用Http服务接口来处理客户端注册请求 | + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/design/spi-design.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/design/spi-design.md new file mode 100644 index 00000000000..e07e4951046 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/design/spi-design.md @@ -0,0 +1,42 @@ +--- +title: SPI扩展设计 +keywords: ["spi design"] +description: 对ShenYu网关中SPI的使用进行介绍 +--- + +`SPI` 全称为 `Service Provider Interface`, 是 `JDK` 内置的一种服务提供发现功能, 一种动态替换发现的机制。 + +[shenyu-spi](https://github.com/apache/shenyu/tree/master/shenyu-spi) 是`Apache ShenYu`网关自定义的`SPI`扩展实现,设计和实现原理参考了`Dubbo`的 [SPI扩展实现](https://dubbo.apache.org/zh/docs/v2.7/dev/impls/) 。 + + +### 注册中心扩展 + +通过哪种方式实现服务的注册,当前支持`Consul`、`Etcd`、`Http`、`Nacos`和`Zookeeper`。注册中心的扩展包括客户端和服务端,接口分别为 `ShenyuServerRegisterRepository` 和 `ShenyuClientRegisterRepository` 。 + +### 监控中心扩展 + +负责服务的监控,通过`SPI`加载具体实现,当前支持`Prometheus` ,服务接口是 `MetricsService` 。 + +### 负载均衡扩展 + +从多个服务提供方中选择一个进行调用,当前支持的算法有`Hash`、`Random` 和 `RoundRobin`,扩展接口是 `LoadBalance` 。 + + +### RateLimiter扩展 + +在`RateLimiter`插件中,使用何种限流算法,当前支持`Concurrent`、`LeakyBucket`、`SlidingWindow` 和 `TokenBucket`,扩展接口是 `RateLimiterAlgorithm` 。 + + +### 匹配方式扩展 + +在添加选择器和规则时,使用哪种匹配方式,当前支持`And`、`Or`,扩展接口是 `MatchStrategy` 。 + + +### 条件参数扩展 + +在添加选择器和规则时,使用哪种条件参数,当前支持`URI`、`RequestMethod`、`Query`、`Post`、`IP`、`Host`、`Cookie` 和 `Header`,扩展接口是 `ParameterData` 。 + + +### 条件策略扩展 + +在添加选择器和规则时,使用哪种条件策略,当前支持`Match`、`Contains`、`Equals`、`Regex`、`TimerAfter`、`TimerBefore`和`Exclude`,扩展接口是 `PredicateJudge` 。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/design/wasm-plugin-design.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/design/wasm-plugin-design.md new file mode 100644 index 00000000000..d7da73ed680 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/design/wasm-plugin-design.md @@ -0,0 +1,25 @@ +--- +title: WASM插件设计 +keywords: ["WASM"] +description: Apache ShenYu WASM插件设计 +--- + +`Apache ShenYu`是一个Java原生,用于服务代理、协议转换和API管理的API网关。目前shenyu在Java语言中具有良好的可扩展性,然而shenyu对多种语言的支持仍然相对较弱。 + +`WASM`(即WebAssembly)字节码被设计为以大小和加载时间高效的二进制格式进行编码。WebAssembly旨在利用各种平台上可用的通用硬件功能,以机器码的速度在浏览器中执行。 + +`WASI`(即WebAssembly System Interface)则是让WASM可以运行在非浏览器环境中(比如linux)。 + +`WASMPlugin`的目标是能够运行WASM字节码。其他语言,只要这种语言的代码能被编译成WASM字节码(如Rust/golang/C++),那么这种语言就可以用来编写ShenYu插件。 + +## 开发阶段 + + + +## 准备阶段 + + + +## 运行阶段 + + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/developer/_category_.json b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/developer/_category_.json new file mode 100644 index 00000000000..35803c66300 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/developer/_category_.json @@ -0,0 +1,4 @@ +{ + "label": "开发者文档", + "position": 7 +} diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/developer/custom-filter.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/developer/custom-filter.md new file mode 100644 index 00000000000..8bb85010302 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/developer/custom-filter.md @@ -0,0 +1,113 @@ +--- +title: 自定义Filter +description: filter扩展 +--- + + +## 说明 + +* 本文介绍如何对 `org.springframework.web.server.WebFliter` 进行扩展。 + +## 跨域支持 + +* 新增 `org.apache.shenyu.web.filter.CrossFilter` 实现 `WebFilter`。 + +```java + public class CrossFilter implements WebFilter { + + private static final String ALLOWED_HEADERS = "x-requested-with, authorization, Content-Type, Authorization, credential, X-XSRF-TOKEN,token,username,client"; + + private static final String ALLOWED_METHODS = "*"; + + private static final String ALLOWED_ORIGIN = "*"; + + private static final String ALLOWED_EXPOSE = "*"; + + private static final String MAX_AGE = "18000"; + + @Override + @SuppressWarnings("all") + public Mono filter(final ServerWebExchange exchange, final WebFilterChain chain) { + ServerHttpRequest request = exchange.getRequest(); + if (CorsUtils.isCorsRequest(request)) { + ServerHttpResponse response = exchange.getResponse(); + HttpHeaders headers = response.getHeaders(); + headers.add("Access-Control-Allow-Origin", ALLOWED_ORIGIN); + headers.add("Access-Control-Allow-Methods", ALLOWED_METHODS); + headers.add("Access-Control-Max-Age", MAX_AGE); + headers.add("Access-Control-Allow-Headers", ALLOWED_HEADERS); + headers.add("Access-Control-Expose-Headers", ALLOWED_EXPOSE); + headers.add("Access-Control-Allow-Credentials", "true"); + if (request.getMethod() == HttpMethod.OPTIONS) { + response.setStatusCode(HttpStatus.OK); + return Mono.empty(); + } + } + return chain.filter(exchange); + } + } +``` + + + + +- 将 `CrossFilter` 注册成为 `Spring`的`bean`。 + + +## 网关过滤 springboot健康检查 + +* 注意顺序,使用 `@Order` 注解 + +```java +@Component +@Order(-99) +public final class HealthFilter implements WebFilter { + + private static final String[] FILTER_TAG = {"/actuator/health", "/health_check"}; + + @Override + public Mono filter(@Nullable final ServerWebExchange exchange, @Nullable final WebFilterChain chain) { + ServerHttpRequest request = Objects.requireNonNull(exchange).getRequest(); + String urlPath = request.getURI().getPath(); + for (String check : FILTER_TAG) { + if (check.equals(urlPath)) { + String result = JsonUtils.toJson(new Health.Builder().up().build()); + DataBuffer dataBuffer = exchange.getResponse().bufferFactory().wrap(result.getBytes()); + return exchange.getResponse().writeWith(Mono.just(dataBuffer)); + } + } + return Objects.requireNonNull(chain).filter(exchange); + } +} +``` + + + +## 继承 `org.apache.shenyu.web.filter.AbstractWebFilter` + +* 新增一个类继承`AbstractWebFilter`,并实现它的两个方法。 + +```java + /** + * this is Template Method ,children Implement your own filtering logic. + * + * @param exchange the current server exchange + * @param chain provides a way to delegate to the next filter + * @return {@code Mono} result:TRUE (is pass),and flow next filter;FALSE (is not pass) execute doDenyResponse(ServerWebExchange exchange) + */ + protected abstract Mono doFilter(ServerWebExchange exchange, WebFilterChain chain); + + /** + * this is Template Method ,children Implement your own And response client. + * + * @param exchange the current server exchange. + * @return {@code Mono} response msg. + */ + protected abstract Mono doDenyResponse(ServerWebExchange exchange); +``` + +* `doFilter` 方法返回 `Mono` 表示通过,反之则不通过,不通过的时候,会调用 `doDenyResponse`输出相关信息到前端。 + + + + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/developer/custom-jwt-covert-algorithm.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/developer/custom-jwt-covert-algorithm.md new file mode 100644 index 00000000000..b4a7cdfd73a --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/developer/custom-jwt-covert-algorithm.md @@ -0,0 +1,93 @@ +--- +title: 自定义JWT插件转化算法 +description: 自定义JWT插件转化算法 +--- + + + +## 说明 + ++ 用户可以自定义JWT插件中转化算法 + + + +## 扩展 + + 转化算法的默认实现为 `org.apache.shenyu.plugin.jwt.strategy.DefaultJwtConvertStrategy`,采用的是SPI机制进行扩展,步骤如下: + +1. 实现接口`org.apache.shenyu.plugin.jwt.strategy.JwtConvertStrategy` + + ```java + /** + * Represents a conversion strategy that convert jwt to some attributes of + * serverWebExchange, especially attributes of the request header. + */ + @SPI + public interface JwtConvertStrategy { + + /** + * HandleJson needs to be parsed into jwtRuleHandle in order to + * specify how to convert jwt. + * + * @param handleJson handleJson from rule + * @return jwtRuleHandle + */ + JwtRuleHandle parseHandleJson(String handleJson); + + /** + * Converts jwt to some attributes of serverWebExchange based on jwtRuleHandle. + * + * @param jwtRuleHandle jwtRuleHandle + * @param exchange exchange + * @param jwtBody jwtBody + * @return serverWebExchange + */ + ServerWebExchange convert(JwtRuleHandle jwtRuleHandle, ServerWebExchange exchange, Map jwtBody); + + } + ``` + + ```java + @Join + public class CustomJwtConvertStrategy implements JwtConvertStrategy { + + @Override + public CustomJwtRuleHandle parseHandleJson(final String handleJson) { + + return GsonUtils.getInstance().fromJson(handleJson, CustomJwtRuleHandle.class); + } + + @Override + public ServerWebExchange convert(final JwtRuleHandle jwtRuleHandle, final ServerWebExchange exchange, final Map jwtBody) { + final CustomJwtRuleHandle customJwtRuleHandle = (CustomJwtRuleHandle) jwtRuleHandle; + String customConvert = customJwtRuleHandle.getCustomConvert(); + ServerHttpRequest modifiedRequest = + exchange.getRequest().mutate().header("custom", customConvert).build(); + + return exchange.mutate().request(modifiedRequest).build(); + } + } + + ``` + + + +2. 配置SPI + + ```tex + custom=org.apache.shenyu.plugin.jwt.strategy.CustomJwtConvertStrategy + ``` + + + +说明:系统会根据`JwtRuleHandle`的`handleType`参数来使用不同转化策略,比如下面的`JwtRuleHandle`系统会使用我们上面自定义的`CustomJwtConvertStrategy`。(注意:`handleType`为`default`或者不存在`handleType`属性,系统默认使用`DefaultJwtConvertStrategy`) + +```json +{ + "handleType":"custom", + "customConvert":"customConvert" +} +``` + +案例代码可查看`org.apache.shenyu.plugin.jwt.strategy.CustomJwtConvertStrategy` + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/developer/custom-parsing-ip-and-host.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/developer/custom-parsing-ip-and-host.md new file mode 100644 index 00000000000..4a900190b2e --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/developer/custom-parsing-ip-and-host.md @@ -0,0 +1,50 @@ +--- +title: 正确获取IP与Host +description: 正确获取Ip与host +--- + +## 说明 + +* 本文是说明,如果网关前面有一层`nginx` 的时候,如何获取正确的`ip`与端口。 +* 获取正确的之后,在插件以及选择器中,可以根据 `ip`,与`host`来进行匹配。 + +## 默认实现 + +* 在 `Apache ShenYu` 网关自带实现为:`org.apache.shenyu.web.forward.ForwardedRemoteAddressResolver`。 + +* 它需要你在 `nginx` 设置 `X-Forwarded-For`,以便来获取正确的 `ip` 与 `host`。 + + +## 扩展实现 + +* 新增一个类 `CustomRemoteAddressResolver`,实现`org.apache.shenyu.plugin.api.RemoteAddressResolver` + +```java +public interface RemoteAddressResolver { + + /** + * Resolve inet socket address. + * + * @param exchange the exchange + * @return the inet socket address + */ + default InetSocketAddress resolve(ServerWebExchange exchange) { + return exchange.getRequest().getRemoteAddress(); + } + +} +``` + +* 把你新增的实现类注册成为spring的bean,如下 + +```java + @Bean +public RemoteAddressResolver customRemoteAddressResolver() { + return new CustomRemoteAddressResolver(); + } +``` + + + + + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/developer/custom-plugin.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/developer/custom-plugin.md new file mode 100644 index 00000000000..969720dc59e --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/developer/custom-plugin.md @@ -0,0 +1,324 @@ +--- +title: 插件扩展 +keywords: ["扩展"] +description: 插件扩展 +--- + +## 说明 + +* 插件是 `Apache ShenYu` 网关的核心执行者,每个插件在开启的情况下,都会对匹配的流量,进行自己的处理。 +* 在 `Apache ShenYu` 网关里面,插件分为两类。 + * 一类是单一职责的调用链,不能对流量进行自定义的筛选。 + * 一类是能对匹配的流量,执行自己的职责调用链。 +* 用户可以参考 [shenyu-plugin](https://github.com/apache/shenyu/tree/master/shenyu-plugin) 模块,新增自己的插件处理,如果有好的公用插件,可以向官网提交`pr`。 + +## 单一职责插件 + +* 引入如下依赖: + +```xml + + org.apache.shenyu + shenyu-plugin-api + ${project.version} + +``` + +* 用户新增一个类 `MyShenyuPlugin`,直接实现 `org.apache.shenyu.plugin.api.ShenyuPlugin` + +```java +public interface ShenyuPlugin { + + /** + * Process the Web request and (optionally) delegate to the next + * {@code WebFilter} through the given {@link ShenyuPluginChain}. + * + * @param exchange the current server exchange + * @param chain provides a way to delegate to the next filter + * @return {@code Mono} to indicate when request processing is complete + */ + Mono execute(ServerWebExchange exchange, ShenyuPluginChain chain); + + /** + * return plugin order . + * This attribute To determine the plugin execution order in the same type plugin. + * + * @return int order + */ + int getOrder(); + + /** + * acquire plugin name. + * this is plugin name define you must Provide the right name. + * if you impl AbstractShenyuPlugin this attribute not use. + * + * @return plugin name. + */ + default String named() { + return ""; + } + + /** + * plugin is execute. + * if return true this plugin can not execute. + * + * @param exchange the current server exchange + * @return default false. + */ + default Boolean skip(ServerWebExchange exchange) { + return false; + } +} + +``` + +* 接口方法详细说明 + + * `execute()` 方法为核心的执行方法,用户可以在里面自由的实现自己想要的功能。 + + * `getOrder()` 指定插件的排序。 + + * `named()` 指定插件的名称,命名采用`Camel Case`,如:`dubbo`、`springCloud`。 + + * `skip()` 在特定的条件下,该插件是否被跳过。 + + +* 注册成`Spring`的`bean`,参考如下,或者直接在实现类上加 `@Component` 注解。 + +```java + @Bean + public ShenyuPlugin myShenyuPlugin() { + return new MyShenyuPlugin(); + } +``` + + +## 匹配流量处理插件 + +* 引入如下依赖: + +```xml + + org.apache.shenyu + shenyu-plugin-base + ${project.version} + +``` + +* 新增一个类 `CustomPlugin`,继承 `org.apache.shenyu.plugin.base.AbstractShenyuPlugin` + +* 以下是参考: + +```java +/** + * This is your custom plugin. + * He is running in after before plugin, implement your own functionality. + * extends AbstractShenyuPlugin so you must user shenyu-admin And add related plug-in development. + * + * @author xiaoyu(Myth) + */ +public class CustomPlugin extends AbstractShenyuPlugin { + + /** + * return plugin order . + * The same plugin he executes in the same order. + * + * @return int + */ + @Override + public int getOrder() { + return 0; + } + + /** + * acquire plugin name. + * return you custom plugin name. + * It must be the same name as the plug-in you added in the admin background. + * + * @return plugin name. + */ + @Override + public String named() { + return "shenYu"; + } + + /** + * plugin is execute. + * Do I need to skip. + * if you need skip return true. + * + * @param exchange the current server exchange + * @return default false. + */ + @Override + public Boolean skip(final ServerWebExchange exchange) { + return false; + } + + /** + * this is Template Method child has Implement your own logic. + * + * @param exchange exchange the current server exchange + * @param chain chain the current chain + * @param selector selector + * @param rule rule + * @return {@code Mono} to indicate when request handling is complete + */ + @Override + protected abstract Mono doExecute(ServerWebExchange exchange, ShenyuPluginChain chain, SelectorData selector, RuleData rule) { + LOGGER.debug(".......... function plugin start.............."); + /* + * Processing after your selector matches the rule. + * rule.getHandle() is you Customize the json string to be processed. + * for this example. + * Convert your custom json string pass to an entity class. + */ + final String ruleHandle = rule.getHandle(); + + final Test test = GsonUtils.getInstance().fromJson(ruleHandle, Test.class); + + /* + * Then do your own business processing. + * The last execution chain.execute(exchange). + * Let it continue on the chain until the end. + */ + System.out.println(test.toString()); + return chain.execute(exchange); + } +} + +``` + +* 详细讲解: + + * 继承该类的插件,插件会进行选择器规则匹配。 + + * 首先在 `shenyu-admin` 后台管理系统 --> 基础配置 --> 插件管理 中,新增一个插件,注意 名称与 你自定义插件的 `named()` 方法要一致。 + + * 重新登陆 `shenyu-admin` 后台,可以看见刚新增的插件,然后就可以进行选择器规则匹配。 + + * 在规则中,有个 `handler` 字段,是自定义处理数据,在 `doExecute()` 方法中,通过 `final String ruleHandle = rule.getHandle();` 获取,然后进行你的操作。 + +* 注册成`Spring`的`bean`,参考如下或者直接在实现类上加 `@Component` 注解。 + +```java + @Bean + public ShenyuPlugin customPlugin() { + return new CustomPlugin(); + } +``` + +## 订阅你的插件数据,进行自定义的处理 + +* 新增一个类 `PluginDataHandler`,实现 `org.apache.shenyu.plugin.base.handler.PluginDataHandler` + +```java +public interface PluginDataHandler { + + /** + * Handler plugin. + * + * @param pluginData the plugin data + */ + default void handlerPlugin(PluginData pluginData) { + } + + /** + * Remove plugin. + * + * @param pluginData the plugin data + */ + default void removePlugin(PluginData pluginData) { + } + + /** + * Handler selector. + * + * @param selectorData the selector data + */ + default void handlerSelector(SelectorData selectorData) { + } + + /** + * Remove selector. + * + * @param selectorData the selector data + */ + default void removeSelector(SelectorData selectorData) { + } + + /** + * Handler rule. + * + * @param ruleData the rule data + */ + default void handlerRule(RuleData ruleData) { + } + + /** + * Remove rule. + * + * @param ruleData the rule data + */ + default void removeRule(RuleData ruleData) { + } + + /** + * Plugin named string. + * + * @return the string + */ + String pluginNamed(); + +} +``` + +* 注意 `pluginNamed()` 要和你自定义的插件名称相同。 + +* 注册成`Spring`的`bean`,参考如下或者直接在实现类上加 `@Component` 注解。 + +```java +@Bean +public PluginDataHandler pluginDataHandler() { + return new PluginDataHandler(); +} +``` + +## 动态加载自定义插件 + +* 当使用此功能时候,上述扩展 `ShenyuPlugin`, `PluginDataHandler`, 不用成为 `spring bean`。只需要构建出扩展项目的jar包即可。 + +* 使用以下配置: + +```yaml +shenyu: + extPlugin: + path: //加载扩展插件jar包路径 + enabled: true //是否开启 + threads: 1 //加载插件线程数量 + scheduleTime: 300 //间隔时间(单位:秒) + scheduleDelay: 30 //网关启动后延迟多久加载(单位:秒) +``` + +#### 插件加载路径详解 + +* 此路径是为存放扩展插件jar包的目录。 + +* 可以使用 `-Dplugin-ext=xxxx` 指定,也可以使用 `shenyu.extPlugin.path`配置文件指定,如果都没配置,默认会加载网关启动路径下的 `ext-lib`目录。 + +* 优先级 :`-Dplugin-ext=xxxx` > `shenyu.extPlugin.path` > `ext-lib(default)` + + + +## 插件jar包上传 + +* 当使用这个功能时候, 需要把上述扩展的`ShenyuPlugin` 打包成自定义的 ShenyuPlugin Jar 包 +* 并且在 ShenyuAdmin 进行配置 + * 进入 ShenyuAdmin - BasicConfig - Plugin 进行添加 plugin 在 pluginJar 中可以添加自定义的 plugin Jar 包 +* 自定义的 ShenyuPlugin 如果依赖了其他的第三方包可以 ShenyuBootstrap 启动时加载到 -cp 的第三方jar包目录 + +注意: + +上传jar包插件支持热加载 +如果你需要在线修改jar包. 你可以重新打一个jar包. 并且提升版本号, 例如 `1.0.1` 升高至 `1.0.2` + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/developer/custom-result.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/developer/custom-result.md new file mode 100644 index 00000000000..8b43611425d --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/developer/custom-result.md @@ -0,0 +1,116 @@ +--- +title: 自定义返回结果 +description: 自定义网关返回数据格式 +--- + +## 说明 + +* 本文介绍基于 `Apache ShenYu` 网关返回自定义的数据格式。 +* 网关需要统一的返回格式,如果需要自己定义格式,可以进行扩展。 + + +## 默认实现 + +* 默认的实现为 `org.apache.shenyu.plugin.api.result.DefaultShenyuResult` + +* 返回的数据格式如下: + +```java +public class DefaultShenyuEntity implements Serializable { + + private static final long serialVersionUID = -2792556188993845048L; + + private Integer code; + + private String message; + + private Object data; + +} +``` + +* 返回的 `json` 格式如下: + +```json +{ + "code": -100, //返回码, + "message": "您的参数错误,请检查相关文档!", //提示字段 + "data": null // 具体的数据 +} +``` + +## 扩展 + +* 新增一个类 `CustomShenyuResult` 实现 `org.apache.shenyu.plugin.api.result.ShenyuResult` + +```java +/** + * The interface shenyu result. + */ +public interface ShenyuResult { + + /** + * The response result. + * + * @param exchange the exchange + * @param formatted the formatted object + * @return the result object + */ + default Object result(ServerWebExchange exchange, Object formatted) { + return formatted; + } + + /** + * format the origin, default is json format. + * + * @param exchange the exchange + * @param origin the origin + * @return format origin + */ + default Object format(ServerWebExchange exchange, Object origin) { + // basic data + if (ObjectTypeUtils.isBasicType(origin)) { + return origin; + } + // error result or rpc origin result. + return JsonUtils.toJson(origin); + } + + /** + * the response context type, default is application/json. + * + * @param exchange the exchange + * @param formatted the formatted data that is origin data or byte[] convert string + * @return the context type + */ + default MediaType contentType(ServerWebExchange exchange, Object formatted) { + return MediaType.APPLICATION_JSON; + } + + /** + * Error t. + * + * @param code the code + * @param message the message + * @param object the object + * @return the t + */ + T error(int code, String message, Object object); +} +``` + +> 处理顺序:`format`->`contextType`->`result`。`format`方法进行数据的格式化,若数据为基本类型返回自身,其他类型转换为`JSON`,参数`origin`为原始数据,可根据情况执行格式化处理。`contextType`,若是基本类型,使用`text/plain`,默认为`application/json`,参数`formatted`为`format`方法处理之后的数据,可结合`format`的返回结果进行数据类型的自定义处理。`result`的参数`formatted`为`format`方法处理之后的数据,默认返回自身,可结合`format`的返回结果进行数据类型的自定义处理。 + +* 其中泛型 `T` 为自定义的数据格式,返回它就好。 + +* 把你新增的实现类注册成为`Spring`的`bean`,如下: + +```java +@Bean +public ShenyuResult customShenyuResult() { + return new CustomShenyuResult(); +} +``` + + + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/developer/custom-sign-algorithm.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/developer/custom-sign-algorithm.md new file mode 100644 index 00000000000..6ca0966a633 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/developer/custom-sign-algorithm.md @@ -0,0 +1,57 @@ +--- +title: 自定义sign插件检验算法 +description: 自定义sign插件检验 +--- + + +## 说明 + +* 用户可以自定义签名认证算法来实现验证。 + +## 扩展 + +* 默认的实现为 `org.apache.shenyu.plugin.sign.service.ComposableSignService`。 + + ```java + @Bean + @ConditionalOnMissingBean(value = SignService.class, search = SearchStrategy.ALL) + public SignService signService() { + return new ComposableSignService(new DefaultExtractor(), new DefaultSignProvider()); + } + ``` + + + +* 新增一个类 `CustomSignService` 实现 `org.apache.shenyu.plugin.sign.api.SignService`。 + +```java +public interface SignService { + + /** + * Gets verifyResult. + * @param exchange exchange + * @param requestBody requestBody + * @return result + */ + VerifyResult signatureVerify(ServerWebExchange exchange, String requestBody); + + /** + * Gets verifyResult. + * @param exchange exchange + * @return result + */ + VerifyResult signatureVerify(ServerWebExchange exchange); +} + +``` + +* `VerifyResult`中`isSuccess()`返回`true`,表示验证通过,为`false`的时候,会把`getReason()`中的信息输出到前端。 + +* 把新增的实现类注册成为`Spring`的`bean`,如下 + +```java +@Bean +public SignService customSignService() { + return new CustomSignService(); +} +``` diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/developer/developer-shenyu-client.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/developer/developer-shenyu-client.md new file mode 100644 index 00000000000..4da3bce1d1f --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/developer/developer-shenyu-client.md @@ -0,0 +1,184 @@ +--- +title: 多语言Http客户端 +keywords: ["客户端"] +description: 多语言http客户端 +--- + +## 说明 + +* 本文主要讲解其他语言的`http`服务如何接入网关。 +* 接入网关需要先获取 token, 然后可以根据需求调用注册服务或元数据接口 + + + +## 获取 token + +- **请求方式** + + `GET` + +- **请求路径** + - `http://{shenyu-admin}/platform/login` + - 其中 `shenyu-admin` 表示为 `admin` 后台管理系统的 `ip + port` + + +- **请求参数** + + - `query`参数,账号密码为 admin 服务的用户名和密码 + + | 字段 | 类型 | 是否必填 | 描述 | + | -------- | ------ | -------- | ------ | + | userName | String | 是 | 用户名 | + | password | String | 是 | 密码 | + +- **返回数据** + + | 字段 | | 类型 | 描述 | + | ------- | ----------- | ------- | -------------------- | + | code | | Integer | 返回码 | + | message | | String | 返回信息 | + | data | | Object | 返回对象 | + | | id | Integer | 用户id | + | | userName | String | 账号 | + | | role | Integer | 角色 | + | | enabled | Boolean | 是否启用 | + | | dateCreated | String | 创建时间 | + | | dateUpdated | String | 更新时间 | + | | token | String | token | + | | expiredTime | Long | 超时时间,单位:毫秒 | + + **示例** + + ```json + { + "code": 200, + "message": "login dashboard user success", + "data": { + "id": "1", + "userName": "admin", + "role": 1, + "enabled": true, + "dateCreated": "2022-09-07 22:08:23", + "dateUpdated": "2022-09-07 22:08:23", + "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyTmFtZSI6ImFkbWluIiwiZXhwIjoxNjYyNjQ2MzU5fQ.WBXBgCcGsnnC00pRbDOtqCVoAaZr8MKH6WE6kY-NGaI", + "expiredTime": 86400000 + } + } + ``` + +## 注册服务 + +- **请求方式** + + `POST` + +- **请求路径** + - `http://{shenyu-admin}/shenyu-client/register-uri` + - 其中 `shenyu-admin` 表示为 `admin` 后台管理系统的 `ip + port` + + +- **请求参数** + + - `Header`参数 + + - `contentType: application/json` + + - `X-Access-Token: {token}`,token 为调用登陆接口获取的 token + + - `Body`参数,`json`类型 + + | 字段 | 类型 | 是否必填 | 描述 | + | ----------- | ------- | -------- | ------------------------------------------------------------ | + | protocol | String | 是 | 协议类型 | + | appName | String | 是 | 应用名称 | + | contextPath | String | 是 | 项目路径 | + | rpcType | String | 是 | rpc类型,支持的类型参考 [RpcTypeEnum](https://github.com/apache/shenyu/blob/master/shenyu-common/src/main/java/org/apache/shenyu/common/enums/RpcTypeEnum.java) | + | host | String | 是 | 客户端IP | + | port | Integer | 是 | 客户端端口 | + | eventType | String | 是 | 事件类型,支持的类型参考 [EventType](https://github.com/apache/shenyu/blob/master/shenyu-register-center/shenyu-register-common/src/main/java/org/apache/shenyu/register/common/enums/EventType.java) | + + **示例** + + ```json + { + "protocol": "http", + "appName": "app", + "contextPath": "/test", + "rpcType": "http", + "host": "127.0.0.1", + "port": "8080", + "eventType": "REGISTER" + } + ``` + +- **返回数据** + + 注册成功会返回 `success` + + + + +## 注册元数据 + +- **请求方式** + + `POST` + +- **请求路径** + - `http://{shenyu-admin}/shenyu-client/register-metadata` + - 其中 `shenyu-admin` 表示为 `admin` 后台管理系统的 `ip + port` + +- **请求参数** + - `Header`参数 + + - `contentType: application/json` + + - `X-Access-Token: {token}`,token 为调用登陆接口获取的 token + + - `Body`参数,`json`类型 + + | 字段 | 类型 | 是否必填 | 描述 | + | ---------------- | ------------ | -------- | ------------------------------------------------------------ | + | appName | String | 是 | 应用名称 | + | contextPath | String | 是 | 项目路径 | + | path | String | 是 | 路径 | + | pathDesc | String | 是 | 路径描述 | + | rpcType | String | 是 | rpc类型,支持的类型参考 [RpcTypeEnum](https://github.com/apache/shenyu/blob/master/shenyu-common/src/main/java/org/apache/shenyu/common/enums/RpcTypeEnum.java) | + | serviceName | String | 是 | 服务名称 | + | methodName | String | 是 | 方法名称 | + | ruleName | String | 是 | 规则名称 | + | parameterTypes | String | 是 | 参数类型 | + | rpcExt | String | 是 | Rpc拓展参数 | + | enabled | Boolean | 否 | 状态 | + | host | String | 是 | 服务 IP | + | port | Integer | 是 | 服务端口 | + | pluginNames | List | 是 | 插件名称列表 | + | registerMetaData | Boolean | 否 | 是否注册元数据 | + + **示例** + + ```json + { + "appName": "app", + "contextPath": "/", + "path": "/test", + "rpcType": "http", + "serviceName": "测试服务", + "parameterTypes": "java.lang.String", + "pathDesc": "测试路径", + "methodName": "测试方法", + "ruleName": "测试规则", + "rpcExt": "{\"loadbalance\":\"hash\",\"retries\":3,\"timeout\":-1}", + "enabled": true, + "host": "127.0.0.1", + "port": 8080, + "pluginNames": [], + "registerMetaData": true + } + ``` + +- **返回数据** + + 注册成功会返回 `success` + + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/developer/file-and-image.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/developer/file-and-image.md new file mode 100644 index 00000000000..fe412e9d3d8 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/developer/file-and-image.md @@ -0,0 +1,18 @@ +--- +title: 文件上传下载 +description: 文件上传下载 +--- + +## 说明 + +* 本文主要介绍 `Apache ShenYu` 的文件上传下载的支持。 + +## 文件上传 + +* 默认限制文件大小为`10M`。 +* 如果想修改,在启动服务的时候,使用`--file.size = 30`,为`int`类型。 +* 你之前怎么上传文件,还是怎么上传。 + +## 文件下载 + +* `Apache ShenYu` 支持流的方式进行下载,之前的接口怎么写的,现在还是怎么写,根本不需要变。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/developer/integration-test.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/developer/integration-test.md new file mode 100644 index 00000000000..ebe38f36c3a --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/developer/integration-test.md @@ -0,0 +1,38 @@ +--- +title: 本地运行集成测试 +description: Run Integration Test Locally +tags: ["integration test"] +--- + +### 准备 + +1. 克隆 [Apache ShenYu](https://github.com/apache/shenyu) 的代码. +2. 安装并启动 `docker` . + +### 在本地开启集成测试 + +1. 用 Maven 构建 + +```shell +./mvnw -B clean install -Prelease,docker -Dmaven.javadoc.skip=true -Dmaven.test.skip=true +``` + +2. 构建 `shenyu-integrated-test` + +```shell +./mvnw -B clean install -Pit -DskipTests -f ./shenyu-integrated-test/pom.xml +``` + +3. docker-compose 运行 + +```shell +docker-compose -f ./shenyu-integrated-test/${{ matrix.case }}/docker-compose.yml up -d +``` + +> 你需要把 `${{ matrix.case }}` 替换成具体的目录, 比如 `shenyu-integrated-test-http`. + +4. 运行测试 + +```shell +./mvnw test -Pit -f ./shenyu-integrated-test/${{ matrix.case }}/pom.xml +``` diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/developer/local-model.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/developer/local-model.md new file mode 100644 index 00000000000..82abd902295 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/developer/local-model.md @@ -0,0 +1,551 @@ +--- +title: 本地模式 +keywords: ["本地模式"] +description: 本地模式 +--- + +## 说明 + +* 主要介绍在单机环境下,然后使用本地 `API` 更新网关数据。 配置属性: + +```yaml +shenyu: + local: + enabled: true + sha512Key: 123456 +``` + +* 统一返回结果: + +``` +success +``` + +* 统一请求前缀:`localhost:9095/shenyu` + +* 统一请求头:`localKey: 123456` + +## 插件数据 + +### 新增或者更新插件 + +新增或者更新插件 + +##### 请求方式 + +POST + +##### 请求路径 + +/plugin/saveOrUpdate + +##### 请求参数 + +|名称|类型|是否必需|默认值|描述| +|---|---|---|---|---| +|**PluginData**|[PluginData](#PluginData)|True| |插件对象(Body里面传Json对象)| + +#####
PluginData
+ +|名称|类型|是否必需|默认值|描述| +|---|---|---|---|---| +|**id**|String|False| |插件ID| +|**name**|String|True| |插件名称| +|**config**|String|False| |插件配置(Json格式)| +|**role**|String|False| |插件角色| +|**enabled**|Boolean|False| |是否开启| + +##### 请求示例 + +POST body + +``` +{"id":3,"name":"divide","enabled":"true"} + +``` + +### 清空所有数据 + +清空所有插件,选择器,规则数据 + +##### 请求方式 + +GET + +##### 请求路径 + +/cleanAll + +### 清空插件数据 + +清空单个插件,选择器,规则数据 + +##### 请求方式 + +GET + +##### 请求路径 + +/cleanPlugin?name = xxxx + +##### Request参数 + +|名称|类型|是否必需|默认值|描述| +|---|---|---|---|---| +|**name**|String|true| |插件名称 | + +### 删除插件 + +删除单个插件(不包含,插件里面的选择器与规则) + +##### 请求方式 + +GET + +##### 请求路径 + +/plugin/delete?name = xxxx + +##### Request参数 + +|名称|类型|是否必需|默认值|描述| +|---|---|---|---|---| +|**name**|String|true| |插件名称 | + +### 删除所有插件 + +删除所有插件(不包含,插件里面的选择器与规则) + +##### 请求方式 + +GET + +##### 请求路径 + +/plugin/deleteAll + +### 获取插件 + +根据名称获取插件数据 + +##### 请求方式 + +GET + +##### 请求路径 + +/plugin/findByName?name=xxxx + +##### Request参数 + +|名称|类型|是否必需|默认值|描述| +|---|---|---|---|---| +|**name**|String|true| |插件名称 | + +### 新增或更新选择器 + +新增或者更新插件 + +##### 请求方式 + +POST + +##### 请求路径 + +/plugin/selector/saveOrUpdate + +##### 请求参数 + +|名称|类型|是否必需|默认值|描述| +|---|---|---|---|---| +|**SelectorData**|[SelectorData](#SelectorData)|True| |选择器对象(Body里面传Json对象)| + +#####
SelectorData
+ +|名称|类型|是否必需|默认值|描述| +|---|---|---|---|---| +|**id**|String|False| |选择器ID| +|**pluginName**|String|True| |插件名称| +|**name**|String|False| |选择器名称(不填则默认生成 plugin:selector+随机数字)| +|**matchMode**|Integer|False| |匹配模式(0:and;1:or),不填默认生成 And模式| +|**type**|Integer|False| |流量类型0:全流量;1:自定义流量)不填默认生成全流量| +|**sort**|Integer|False| |排序 ,不填默认生成 10| +|**enabled**|Boolean|False| |是否开启,不填默认生成 true| +|**logged**|Boolean|False| |是否打印日志,不填默认生成为false| +|**handle**|String|False| |选择器处理(Json对象,根据每个插件不同,传的对象不同)| +|**conditionList**|[Condition](#Condition)|False| |条件集合,自定义流量需要传,全流量不用传(Json List对象)| + +#####
Condition
+ +|名称|类型|是否必需|默认值|描述| +|---|---|---|---|---| +|**paramType**|String|True| |参数类型(post,uri,query,host,header,cookie,req_method,domain)| +|**operator**|String|True| |匹配方式(match,=,regex,>,<,contains,SpEL,Groovy,TimeBefore,TimeAfter)| +|**paramName**|String|False| |参数名称(uri 参数类型时候,可以不传)| +|**paramValue**|Integer|False| |匹配值| + +##### 请求示例 + +POST body + +``` +{ + "pluginName": "divide", + "type": 1, + "handle": "[{\"upstreamUrl\":\"127.0.0.1:8089\"}]", + "conditionDataList": [{ + "paramType": "uri", + "operator": "match", + "paramName": null, + "paramValue": "/**" + }] +} + +``` + +##### 返回数据 + +选择器ID + +``` +xxxxx +``` + +### 新增选择器与规则 + +新增一条选择器与多条规则 + +##### 请求方式 + +POST + +##### 请求路径 + +/plugin/selectorAndRules + +##### 请求参数 + +|名称|类型|是否必需|默认值|描述| +|---|---|---|---|---| +|**SelectorRulesData**|[SelectorRulesData](#SelectorRulesData)|True| |选择器规则对象(Body里面传Json对象)| + +#####
SelectorRulesData
+ +|名称|类型|是否必需|默认值|描述| +|---|---|---|---|---| +|**pluginName**|String|True| |插件名称| +|**selectorName**|String|False| |选择器名称(不填则默认生成 plugin:selector+随机数字)| +|**matchMode**|Integer|False| |匹配模式(0:and;1:or),不填默认生成 And模式| +|**selectorHandler**|String|False| |选择器处理(Json对象,根据每个插件不同,传的对象不同)| +|**conditionList**|[ConditionData](#ConditionData)|True| |选择器条件集合(Json List对象)| +|**ruleDataList**|[RuleLocalData](#RuleLocalData)|True| |规则对象集合(Json List对象)| + +#####
RuleLocalData
+ +|名称|类型|是否必需|默认值|描述| +|---|---|---|---|---| +|**ruleName**|String|False| |规则名称| +|**ruleHandler**|String|True| |规则处理(不同的插件传不同的值)| +|**matchMode**|Integer|False| |匹配模式(0:and;1:or)| +|**conditionList**|[ConditionData](#ConditionData)|True| |规则条件集合(Json List对象)| + +#####
ConditionData
+ +|名称|类型|是否必需|默认值|描述| +|---|---|---|---|---| +|**paramType**|String|True| |参数类型(post,uri,query,host,header,cookie,req_method,domain)| +|**operator**|String|True| |匹配方式(match,=,regex,>,<,contains,SpEL,Groovy,TimeBefore,TimeAfter)| +|**paramName**|String|False| |参数名称(uri 参数类型时候,可以不传)| +|**paramValue**|Integer|False| |匹配值| + +##### 请求示例 + +POST body + +``` +{ + "pluginName": "divide", + "selectorHandler": "[{\"upstreamUrl\":\"127.0.0.1:8089\"}]", + "conditionDataList": [{ + "paramType": "uri", + "operator": "match", + "paramValue": "/http/**" + }], + "ruleDataList": [{ + "ruleHandler": "{\"loadBalance\":\"random\"}", + "conditionDataList": [{ + "paramType": "uri", + "operator": "=", + "paramValue": "/http/test/payment" + }] + }, { + "ruleHandler": "{\"loadBalance\":\"random\"}", + "conditionDataList": [{ + "paramType": "uri", + "operator": "=", + "paramValue": "/http/order/save" + }] + }] +} + +``` + +### 删除选择器 + +根据选择器id与插件名称删除选择器 + +##### 请求方式 + +GET + +##### 请求路径 + +/plugin/selector/delete?pluginName=xxxx&&id=xxxx + +##### Request参数 + +|名称|类型|是否必需|默认值|描述| +|---|---|---|---|---| +|**pluginName**|String|true| |插件名称 | +|**id**|String|true| |选择器id | + +### 获取插件下的所有选择器 + +根据插件名称获取所有选择器 + +##### 请求方式 + +GET + +##### 请求路径 + +/plugin/selector/findList?pluginName=xxxx + +##### Request参数 + +|名称|类型|是否必需|默认值|描述| +|---|---|---|---|---| +|**pluginName**|String|true| |插件名称 | + +### 新增或更新规则 + +新增或者更新规则数据 + +##### 请求方式 + +POST + +##### 请求路径 + +/plugin/rule/saveOrUpdate + +##### 请求参数 + +|名称|类型|是否必需|默认值|描述| +|---|---|---|---|---| +|**RuleData**|[RuleData](#RuleData)|True| |规则对象(Body里面传Json对象)| + +#####
RuleData
+ +|名称|类型|是否必需|默认值|描述| +|---|---|---|---|---| +|**id**|String|False| |规则ID| +|**pluginName**|String|True| |插件名称| +|**name**|String|False| |规则名称(不填则默认生成 plugin:rule+随机数字)| +|**selectorId**|String|True| |选择器ID(不填则默认生成 plugin:rule+随机数字)| +|**matchMode**|Integer|False| |匹配模式(0:and;1:or),不填默认生成 And模式| +|**sort**|Integer|False| |排序 ,不填默认生成 10| +|**enabled**|Boolean|False| |是否开启,不填默认生成 true| +|**logged**|Boolean|False| |是否打印日志,不填默认生成为false| +|**handle**|String|False| |规则处理(Json对象,根据每个插件不同,传的对象不同)| +|**conditionList**|[ConditionData](#ConditionData)|False| |条件集合(Json List对象)| + +#####
conditionList
+ +|名称|类型|是否必需|默认值|描述| +|---|---|---|---|---| +|**paramType**|String|True| |参数类型(post,uri,query,host,header,cookie,req_method,domain)| +|**operator**|String|True| |匹配方式(match,=,regex,>,<,contains,SpEL,Groovy,TimeBefore,TimeAfter)| +|**paramName**|String|False| |参数名称(uri 参数类型时候,可以不传)| +|**paramValue**|Integer|False| |匹配值| + +##### 请求示例 + +POST body + +``` +{ + "pluginName": "divide", + "selectorId": 123456, + "handle": "{\"loadBalance\":\"random\"}", + "conditionDataList": [{ + "paramType": "uri", + "operator": "=", + "paramValue": "/test" + }] +} + +``` + +##### 返回数据 + +规则ID + +``` +xxxxx +``` + +### 删除规则 + +根据选择器id与规则id删除规则 + +##### 请求方式 + +GET + +##### 请求路径 + +/plugin/rule/delete?selectorId=xxxx&&id=xxxx + +##### Request参数 + +|名称|类型|是否必需|默认值|描述| +|---|---|---|---|---| +|**selectorId**|String|true| |选择器ID | +|**id**|String|true| |规则ID | + +### 获取规则集合 + +根据选择器ID获取所有规则 + +##### 请求方式 + +GET + +##### 请求路径 + +/plugin/rule/findList?selectorId=xxxx + +##### Request参数 + +|名称|类型|是否必需|默认值|描述| +|---|---|---|---|---| +|**selectorId**|String|true| |选择器ID | + +## 元数据 + +### 新增或者更新元数据 + +新增或者更新元数据 + +##### 请求方式 + +POST + +##### 请求路径 + +/meta/saveOrUpdate + +##### 请求参数 + +|名称|类型|是否必需|默认值|描述| +|---|---|---|---|---| +|**MetaData**|[MetaData](#MetaData)|True| |元数据对象(Body里面传Json对象)| + +#####
MetaData
+ +|名称|类型|是否必需|默认值|描述| +|---|---|---|---|---| +|**id**|String|False| |元数据ID| +|**appName**|String|True| |应用名称| +|**contextPath**|String|True| |contextPath| +|**path**|String|True| |请求路径| +|**rpcType**|String|True| |rpc类型(dubbo,sofa,tars,springCloud,motan,grpc)| +|**serviceName**|String|True| |接口名称| +|**methodName**|String|True| |方法名称| +|**parameterTypes**|String|True| |参数类型| +|**rpcExt**|String|False| |rpc扩展参数(json对象)| +|**enabled**|Boolean|False| |是否开启| + +### 删除元数据 + +删除元数据 + +##### 请求方式 + +GET + +##### 请求路径 + +/meta/delete?rpcType=xxxx&&path=xxx + +##### Request参数 + +|名称|类型|是否必需|默认值|描述| +|---|---|---|---|---| +|**rpcType**|String|true| |rpc类型(dubbo,sofa,tars,springCloud,motan,grpc) | +|**path**|String|true| |路径 | + +## 签名数据 + +### 新增或者更新 + +新增或者更新签名数据 + +##### 请求方式 + +POST + +##### 请求路径 + +/auth/saveOrUpdate + +##### 请求参数 + +|名称|类型|是否必需|默认值|描述| +|---|---|---|---|---| +|**AppAuthData**|[AppAuthData](#AppAuthData)|True| |签名对象(Body里面传Json对象)| + +#####
AppAuthData
+ +|名称|类型|是否必需|默认值|描述| +|---|---|---|---|---| +|**appKey**|String|True| |app key| +|**appSecret**|String|True| |app secret| +|**enabled**|Boolean|False| |是否开启| +|**open**|Boolean|False| |是否是开放平台| +|**paramDataList**|[AuthParamData](#AuthParamData)|false| |参数集合,open为true时候需要传(Json list对象)| +|**AuthPathData**|[AuthPathData](#AuthPathData)|false| |路径集合,open为true时候需要传(Json list对象)| + +#####
AuthParamData
+ +|名称|类型|是否必需|默认值|描述| +|---|---|---|---|---| +|**appName**|String|True| |应用名称| +|**appParam**|String|True| |应用参数| + +#####
AuthPathData
+ +|名称|类型|是否必需|默认值|描述| +|---|---|---|---|---| +|**appName**|String|True| |应用名称| +|**path**|String|True| |路径| +|**enabled**|Boolean|False| |是否开启| + +### 删除 + +删除签名数据 + +##### 请求方式 + +GET + +##### 请求路径 + +/auth/delete?appKey=xxxx + +##### Request参数 + +|名称|类型|是否必需|默认值|描述| +|---|---|---|---|---| +|**appKey**|String|true| |app key | diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/developer/notice-alert.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/developer/notice-alert.md new file mode 100644 index 00000000000..5ec7aea0968 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/developer/notice-alert.md @@ -0,0 +1,83 @@ +--- +title: 告警通知 +keywords: ["alarm"] +description: Alarm message dispatch and notice +--- + +## 说明 + +* 本文主要介绍 Apache ShenYu 的网关插件发送告警通知消息的支持。 + +## ShenYu网关开启告警通知 + +* 配置 ShenYu网关的配置文件 `application.yml`,开启告警,配置 ShenYu Admin服务地址。 + +```yaml +shenyu: + alert: + enabled: true + # the shenyu admin servers, if admin cluster, config like 127.0.0.1:9095,192.3.4.2:9095 + admins: localhost:9095 +``` + +## 发送告警消息 + +* 在网关插件中使用 `AlarmSender.alarm()` 发送自定义告警消息。 + +参考如下: + +```java +public class ParamMappingPlugin extends AbstractShenyuPlugin { + + @Override + public Mono doExecute(final ServerWebExchange exchange, final ShenyuPluginChain chain, final SelectorData selector, final RuleData rule) { + ParamMappingRuleHandle paramMappingRuleHandle = ParamMappingPluginDataHandler.CACHED_HANDLE.get().obtainHandle(CacheKeyUtils.INST.getKey(rule)); + + if(some condition) { + Map labels = new HashMap<>(8); + labels.put("plugin", "http-redirect"); + labels.put("component", "http"); + AlarmSender.alarmHighEmergency("alarm-title", "alarm-content", labels); + AlarmSender.alarmMediumCritical("alarm-title", "alarm-content", labels); + AlarmSender.alarmLowWarning("alarm-title", "alarm-content", labels); + AlarmSender.alarm((byte) 0, "alarm-title", "alarm-content"); + } + + HttpHeaders headers = exchange.getRequest().getHeaders(); + MediaType contentType = headers.getContentType(); + return match(contentType).apply(exchange, chain, paramMappingRuleHandle); + } +} +``` + +## 告警消息转发 + +* 在上一步中,我们在插件中发送的告警消息。 +* 现在我们需要配置这些消息发给谁,通过什么渠道发(邮件,钉钉。。。) +* 在 ShenYu Admin 页面操作配置。 + +![alarm-config](/img/shenyu/alert/alarm-config.png) + +Have fun! + +## 注意 + +1. 若您使用了邮件通知渠道,您需要提前在 ShenYu Admin 的配置文件配置自己的邮件服务器参数 `application.yml` + +```yaml +spring: + mail: + # Attention: this is mail server address. + host: smtp.qq.com + username: shenyu@apache.com + # Attention: this is not email account password, this requires an email authorization code + password: your-password + port: 465 + default-encoding: UTF-8 + properties: + mail: + smtp: + socketFactoryClass: javax.net.ssl.SSLSocketFactory + ssl: + enable: true +``` diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/developer/shenyu-optimize.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/developer/shenyu-optimize.md new file mode 100644 index 00000000000..24af347f1f2 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/developer/shenyu-optimize.md @@ -0,0 +1,55 @@ +--- +title: ShenYu 性能优化 +keywords: ["优化"] +description: ShenYu 性能优化 +--- + +## 说明 + +* 本文主要介绍如何对 `Apache ShenYu` 进行优化。 + + +## 本身消耗 + +* `Apache ShenYu`本身所有的操作,都是基于 `JVM` 内存来匹配,本身消耗时间大概在 `1-3ms` 左右。 + +## 底层Netty调优 + +* `Apache ShenYu`内置依赖 `spring-webflux` 而其底层是使用的 `netty` 。 + +* 我们可以自定义 `netty` 的相关参数来对 `Apache ShenYu` 进行优化,以下是示例: + +```java + @Bean + public NettyReactiveWebServerFactory nettyReactiveWebServerFactory() { + NettyReactiveWebServerFactory webServerFactory = new NettyReactiveWebServerFactory(); + webServerFactory.addServerCustomizers(new EventLoopNettyCustomizer()); + return webServerFactory; + } + + private static class EventLoopNettyCustomizer implements NettyServerCustomizer { + + @Override + public HttpServer apply(final HttpServer httpServer) { + return httpServer + .tcpConfiguration(tcpServer -> tcpServer + .runOn(LoopResources.create("shenyu-netty", 1, DEFAULT_IO_WORKER_COUNT, true), false) + .selectorOption(ChannelOption.SO_REUSEADDR, true) + .selectorOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) + .option(ChannelOption.TCP_NODELAY, true) + .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)); + } + } +``` + +* 这个类在 `shenyu-bootstrap` 中已经内置,在压测的时候,可以根据自己的需求来进行优化设置。 + +* 业务线程模型,请参考:[线程模型](./thread-model) 。 + + + + + + + + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/developer/spi/_category_.json b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/developer/spi/_category_.json new file mode 100644 index 00000000000..9976e06d561 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/developer/spi/_category_.json @@ -0,0 +1,4 @@ +{ + "label": "自定义SPI", + "position": 1 +} diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/developer/spi/custom-load-balance.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/developer/spi/custom-load-balance.md new file mode 100644 index 00000000000..1cd1c9376a3 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/developer/spi/custom-load-balance.md @@ -0,0 +1,64 @@ +--- +title: 自定义负载均衡策略 +description: 自定义负载均衡策略 +--- + +本文介绍如何对 `org.apache.shenyu.loadbalancer.spi.LoadBalancer` 进行自定义扩展。 + +* 新建一个工程,引入如下依赖: + +```xml + + + org.apache.shenyu + shenyu-plugin-base + ${project.version} + + +``` + +* 新增一个类 `CustomLoadBalancer`,继承`org.apache.shenyu.loadbalancer.spi.AbstractLoadBalancer`。 + +```java +public class CustomLoadBalancer extends AbstractLoadBalancer { + + @Override + public Upstream doSelect(final List upstreamList, final String ip) { + // 自定义负载均衡实现逻辑 + } +} +``` + +* 在工程的META-INF/services目录创建 `org.apache.shenyu.loadbalancer.spi.LoadBalancer`文件中添加如下内容: + +```shell title="script" +${spi name}=${custom class path} +``` + +`${spi name}`表示`spi`的名称,`${custom class path}`表示该类的全限定名。比如: + +```shell title="script" +custom=xxx.xxx.xxx.CustomLoadBalancer +``` + +* 将工程打包,拷贝到网关 (bootstrap-bin) 的 `lib` 或 `ext-lib` 目录。 + +* 在`Apache ShenYu`网关管理系统 --> 基础配置 --> 字典管理, 找到字典编码为 `LOAD_BALANCE`,新增一条数据,注意字典名称要为: `${spi name}`,图中的示例是`custom`。 + + + +> 字典类型:`loadBalance`; +> +> 字典编码:`LOAD_BALANCE`; +> +> 字典名称:`${spi name}`,填写自定义`spi`的名称; +> +> 字典值:使用时,下拉框的值,不要和现有的重复; +> +> 字典描述或备注信息:描述信息; +> +> 排序: 排序; + +* 在添加选择器或规则时,就可以使用自定义的匹配方式: + + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/developer/spi/custom-match-mode.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/developer/spi/custom-match-mode.md new file mode 100644 index 00000000000..a024d89162f --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/developer/spi/custom-match-mode.md @@ -0,0 +1,71 @@ +--- +title: 自定义匹配方式 +keywords: ["MatchStrategy"] +description: 自定义匹配方式 +--- + +本文介绍如何对 `org.apache.shenyu.plugin.base.condition.strategy.MatchStrategy` 进行自定义扩展。 + +* 新建一个工程,引入如下依赖: + +```xml + + + org.apache.shenyu + shenyu-plugin-base + ${project.version} + + +``` + +* 新增一个类 `CustomMatchStrategy`,继承`org.apache.shenyu.plugin.base.condition.strategy.AbstractMatchStrategy`,实现 `org.apache.shenyu.plugin.base.condition.strategy.MatchStrategy` ,添加注解`org.apache.shenyu.spi.Join`。 + +```java +/** + * This is custom match strategy. + */ +@Join +public class CustomMatchStrategy extends AbstractMatchStrategy implements MatchStrategy { + + @Override + public Boolean match(final List conditionDataList, final ServerWebExchange exchange) { + // 匹配逻辑实现 + } +} +``` + +* 在工程的META-INF/services目录创建 `org.apache.shenyu.plugin.base.condition.strategy.MatchStrategy`文件中添加如下内容: + +```shell title="script" +${spi name}=${custom class path} +``` + +`${spi name}`表示`spi`的名称,`${custom class path}`表示该类的全限定名。比如: + +```shell title="script" +custom=xxx.xxx.xxx.CustomMatchStrategy +``` + +* 将工程打包,拷贝到网关 (bootstrap-bin) 的 `lib` 或 `ext-lib` 目录。 + +* 在`Apache ShenYu`网关管理系统 --> 基础配置 --> 字典管理, 找到字典编码为 `MATCH_MODE`,新增一条数据,注意字典名称要为: `${spi name}`,图中的示例是`custom`。 + + + +> 字典类型:`matchMode`; +> +> 字典编码:`MATCH_MODE`; +> +> 字典名称:`${spi name}`,填写自定义`spi`的名称; +> +> 字典值:使用时,下拉框的值,不要和现有的重复; +> +> 字典描述或备注信息:描述信息; +> +> 排序: 排序; +> +> 状态:打开或关闭。 + +* 在添加选择器或规则时,就可以使用自定义的匹配方式: + + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/developer/spi/custom-metrics-monitor.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/developer/spi/custom-metrics-monitor.md new file mode 100644 index 00000000000..ef573e8258f --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/developer/spi/custom-metrics-monitor.md @@ -0,0 +1,60 @@ +--- +title: 自定义指标监控 +description: 自定义指标监控 +--- + +## 说明 + +* 在自定义开发前,请先自定义搭建好网关环境,请参考: [自定义部署](../../deployment/deployment-custom) + +* 本文介绍如何对 `org.apache.shenyu.plugin.metrics.spi.MetricsService` 进行自定义扩展。 + +## 扩展实现 + +* 新建一个工程,引入如下依赖: + +```xml + + + org.apache.shenyu + shenyu-plugin-base + ${project.version} + + +``` + +* 新增一个类 `${you class}`,实现 `org.apache.shenyu.plugin.metrics.spi.MetricsService` + +```java +public class ${you class} implements MetricsService { + + /** + * Start metrics tracker. + * + * @param metricsConfig metrics config + * @param metricsRegister the metrics register + */ + public void start(MetricsConfig metricsConfig, MetricsRegister metricsRegister){ + //自定义监控逻辑 + } + + /** + * Stop metrics tracker. + */ + public void stop() { + //自定义关闭逻辑 + } +} +``` + +* 在项目 `resources` 目录下,新建 `META-INF/shenyu` 目录, 并且新增文件名为 : `org.apache.shenyu.plugin.metrics.spi.MetricsService`. +内容新增 `${you spi name}` = `${you class path}`: + +``` +${you spi name} = ${you class path} +``` + +* 将工程打包,拷贝到网关 (bootstrap-bin) 的 `lib` 或 `ext-lib` 目录。 + +* 在 `Admin` 后台 ---> 基础管理 ---> 插件管理 , 找到 `Monitor` 插件,编辑插件信息,注意``metricsName要为: `${you spi name}`。 + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/developer/spi/custom-mock-generator.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/developer/spi/custom-mock-generator.md new file mode 100644 index 00000000000..6335433f2f1 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/developer/spi/custom-mock-generator.md @@ -0,0 +1,75 @@ +--- +title: 自定义mock数据生成器 +description: 自定义mock数据生成器 +--- +## 说明 + +1. 本文介绍如何对 `org.apache.shenyu.plugin.mock.generator.Generator` 进行自定义扩展。 +2. mock 数据生成表达式需要满足 `${name|param1|param2|...}` 的格式。 + +## 扩展实现 + +* 新建一个工程,引入如下依赖: + +```xml + + + org.apache.shenyu + shenyu-plugin-mock + ${project.version} + + +``` + +* 新增一个类 `CustomerGenerator`,实现 `org.apache.shenyu.plugin.mock.generator.Generator`。 + +```java +@Join +public class CustomGenerator implements Generator { + @Override + public String getName() { + // 生成器的名称,即 表达式第一个 | 之前的内容 + } + + @Override + public String generate() { + // 实现数据生成的逻辑 + } + + @Override + public int getParamSize() { + // 表达式必填参数的个数 + } + + @Override + public void initParam(List params, String rule) { + // params 会返回 表达式按照 | 切分后,除名称之外的内容 + // rule 原表达式的内容,如果有自定的参数处理逻辑 可以使用这个参数 + } + + @Override + public boolean match(String rule) { + // 校验当前表达式是否可以合法 + } + + @Override + public String[] getPrefixAndSuffix() { + // 返回 生成内容之后添加的前缀和后缀 ,请返回 包含两个元素的字符串数组 + // 第 0 个元素是前缀,第 1 个元素是后缀 + } +} +``` + +* 在工程的 META-INF/shenyu 目录创建 `org.apache.shenyu.plugin.mock.generator.Generator`文件中添加如下内容: + +```shell title="script" +${spi name}=${custom class path} +``` + +`${spi name}`表示`spi`的名称,`${spi name }` 需要与 Generator 实现类中 getName() 方法定义的一致 `${custom class path}`表示该类的全限定名。比如: + +```shell title="script" +custom=xxx.xxx.xxx.CustomGenerator +``` + +* 将工程打包,拷贝到网关 (bootstrap-bin) 的 `lib` 或 `ext-lib` 目录。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/developer/spi/custom-parameter-data.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/developer/spi/custom-parameter-data.md new file mode 100644 index 00000000000..fe44fa372ad --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/developer/spi/custom-parameter-data.md @@ -0,0 +1,71 @@ +--- +title: 自定义条件参数 +keywords: ["ParameterData"] +description: 自定义条件参数 +--- + +本文介绍如何对 `org.apache.shenyu.plugin.base.condition.data.ParameterData` 进行自定义扩展。 + +* 新建一个工程,引入如下依赖: + +```xml + + + org.apache.shenyu + shenyu-plugin-base + ${project.version} + + +``` + +* 新增一个类 `CustomParameterData`,实现 `org.apache.shenyu.plugin.base.condition.data.ParameterData` 接口 ,添加注解`org.apache.shenyu.spi.Join`。 + +```java +/** + * This is custom parameter data. + */ +@Join +public class CustomParameterData implements ParameterData { + + @Override + public String builder(final String paramName, final ServerWebExchange exchange) { + // 自定义条件参数 + } +} +``` + +* 在工程的META-INF/services目录创建 `org.apache.shenyu.plugin.base.condition.data.ParameterData` 文件中添加如下内容: + +```shell title="script" +${spi name}=${custom class path} +``` + +`${spi name}`表示`spi`的名称,`${custom class path}`表示该类的全限定名。比如: + +```shell title="script" +custom=xxx.xxx.xxx.CustomParameterData +``` + +* 将工程打包,拷贝到网关 (bootstrap-bin) 的 `lib` 或 `ext-lib` 目录。 + +* 在`Apache ShenYu`网关管理系统 --> 基础配置 --> 字典管理, 找到字典编码为 `PARAM_TYPE`,新增一条数据,注意字典名称要为: `${spi name}`,图中的示例是`custom`。 + + + +> 字典类型:`paramType`; +> +> 字典编码:`PARAM_TYPE`; +> +> 字典名称:`${spi name}`,填写自定义`spi`的名称; +> +> 字典值:使用时,下拉框的值,不要和现有的重复; +> +> 字典描述或备注信息:描述信息; +> +> 排序: 排序; +> +> 状态:打开或关闭。 + +* 在添加选择器或规则时,就可以使用自定义的条件参数: + + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/developer/spi/custom-predicate-judge.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/developer/spi/custom-predicate-judge.md new file mode 100644 index 00000000000..9415fd95ef9 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/developer/spi/custom-predicate-judge.md @@ -0,0 +1,120 @@ +--- +title: 自定义条件策略 +keywords: ["PredicateJudge"] +description: 自定义条件策略 +--- + +## 说明 + +* 本文介绍如何对 `org.apache.shenyu.plugin.base.condition.judge.PredicateJudge` 进行自定义扩展。 +* 条件谓语是选择器中连接数据和规则的桥梁,作用是筛选出符合条件的请求。 +* 目前已经存在包括 match, =, regex, contains, TimeBefore, TimeAfter, exclude 共七个条件谓语。 +* 用户可以参考 [judge](https://github.com/apache/shenyu/tree/master/shenyu-plugin/shenyu-plugin-base/src/main/java/org/apache/shenyu/plugin/base/condition/judge) 模块,新增自己的条件谓语,如果有好的公用插件,可以向官网提交 `pr`。 + +## 扩展 + +* 新建一个工程,引入如下依赖: + +```xml + + + org.apache.shenyu + shenyu-plugin-base + ${project.version} + + +``` + +* 新增类 `CustomPredicateJudge`,实现 `org.apache.shenyu.plugin.base.condition.judge.PredicateJudge` 接口,添加注解 `org.apache.shenyu.spi.Join`。 + +```java +/** + * custom predicate judge. + */ +@Join +public class CustomPredicateJudge implements PredicateJudge { + + @Override + public Boolean judge(final ConditionData conditionData, final String realData) { + // 自定义条件策略 + } +} +``` + +* 在工程的META-INF/services目录创建 `org.apache.shenyu.plugin.base.condition.judge.PredicateJudge` 文件,并添加如下内容: + +```shell title="script" +${spi name}=${custom class path} +``` + +`${spi name}` 表示 `spi` 的名称, `${custom class path}` 表示该类的全限定名。比如: + +```shell title="script" +custom=xxx.xxx.xxx.CustomPredicateJudge +``` + +* 将工程打包,拷贝到网关 (bootstrap-bin) 的 `lib` 或 `ext-lib` 目录。 + +* 在 `Apache ShenYu` 网关管理系统 --> 基础配置 --> 字典管理, 找到字典编码为 `OPERATOR`,新增一条数据,注意字典名称要为: `${spi name}`,图中的示例是 `custom`。 + + + +> 字典类型:`operator`; +> +> 字典编码:`OPERATOR`; +> +> 字典名称:`${spi name}`,填写自定义`spi`的名称; +> +> 字典值:使用时,下拉框的值,不要和现有的重复; +> +> 字典描述或备注信息:描述信息; +> +> 排序: 排序; +> +> 状态:打开或关闭。 + +* 在添加选择器或规则时,就可以使用自定义的条件策略: + + + +## 示例 + +* 添加 `GroovyPredicateJudge` 和 `SpELPredicateJudge` 扩展。 + +```java +/** + * Groovy predicate judge. + */ +@Join +public class GroovyPredicateJudge implements PredicateJudge { + + @Override + public Boolean judge(final ConditionData conditionData, final String realData) { + return (Boolean) Eval.me(conditionData.getParamName(), realData, conditionData.getParamValue()); + } +} +``` + +```java +/** + * SpEL predicate judge. + */ +@Join +public class SpELPredicateJudge implements PredicateJudge { + + private static final ExpressionParser EXPRESSION_PARSER = new SpelExpressionParser(); + + @Override + public Boolean judge(final ConditionData conditionData, final String realData) { + Expression expression = EXPRESSION_PARSER.parseExpression(conditionData.getParamValue().replace('#' + conditionData.getParamName(), realData)); + return expression.getValue(Boolean.class); + } +} +``` + +* 更新 `org.apache.shenyu.plugin.base.condition.judge.PredicateJudge`, 添加: + +```shell title="script" +Groovy=xxx.xxx.xxx.GroovyPredicateJudge +SpEL=xxx.xxx.xxx.SpELPredicateJudge +``` diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/developer/spi/custom-rate-limiter.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/developer/spi/custom-rate-limiter.md new file mode 100644 index 00000000000..b3573d15fba --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/developer/spi/custom-rate-limiter.md @@ -0,0 +1,103 @@ +--- +title: 自定义限流策略 +description: 自定义限流策略 +--- + + +## 说明 + +* 在自定义开发前,请先自定义搭建好网关环境,请参考: [自定义部署](../../deployment/deployment-custom) + +* 本文介绍如何对 `org.apache.shenyu.plugin.ratelimiter.algorithm.RateLimiterAlgorithm` 进行自定义扩展。 + +## 扩展实现 + +* 新建一个工程,引入如下依赖: + +```xml + + + org.apache.shenyu + shenyu-plugin-base + ${project.version} + + +``` + +* 新增一个类 `${you class}`,实现 `org.apache.shenyu.plugin.ratelimiter.algorithm.RateLimiterAlgorithm` + +```java +public class ${you class} implements RateLimiterAlgorithm { + + /** + * Gets script. + * + * @return the script + */ + public RedisScript getScript() { + //你的开发逻辑 + } + + /** + * Gets keys. + * + * @param id the id + * @return the keys + */ + public List getKeys(String id) { + //你的开发逻辑 + } + /** + * Callback string. + * + * @param script the script + * @param keys the keys + * @param scriptArgs the script args + */ + default void callback(final RedisScript script, final List keys, final List scriptArgs) { + //你的开发逻辑 + } +} +``` + +* 在项目 `resources` 目录下,新建 `META-INF/shenyu` 目录, 并且新增文件名为 : `org.apache.shenyu.plugin.ratelimiter.algorithm.RateLimiterAlgorithm`. +内容新增 `${you spi name}` = `${you class path}`: + +``` +${you spi name} = ${you class path} +``` + +* 将工程打包,拷贝到网关 (bootstrap-bin) 的 `lib` 或 `ext-lib` 目录。 + +* 在 `Admin` 后台 ---> 基础管理 ---> 字典管理 , 找到字典编码为 `ALGORITHM_*`,新增一条数据,注意字典名称要为: `${you spi name}`。 + + + +* 或者执行以下自定义`SQL`语句: + +```sql +INSERT IGNORE INTO `shenyu_dict` ( + `id`, + `type`, + `dict_code`, + `dict_name`, + `dict_value`, + `desc`, + `sort`, + `enabled`, + `date_created`, + `date_updated` + ) +VALUES ( + 'you id', + 'matchMode', + 'MATCH_MODE', + 'you spi name', + 'you value', + 'you spi name', + 0, + 1, + '2021-08-30 19:29:10', + '2021-08-30 20:15:23' + ); +``` diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/developer/thread-model.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/developer/thread-model.md new file mode 100644 index 00000000000..f284df3406f --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/developer/thread-model.md @@ -0,0 +1,29 @@ +--- +title: 线程模型 +keywords: ["线程模型"] +description: 线程模型 +--- + +## 说明 + +* 本文主要介绍 `Apache ShenYu` 的线程模型,以及各种场景的使用。 + +## IO与Work线程 + +* `Apache ShenYu` 内置依赖 `spring-webflux`, 而其底层是使用的是 `netty`,这一块主要是使用的 `netty` 线程模型。 + +## 业务线程 + +* 默认使用调度线程来执行。 +* 默认使用固定的线程池来执行,其线程数为 `cpu * 2 + 1`。 + +## 切换类型 + +* `reactor.core.scheduler.Schedulers`。 +* 可以使用 `-Dshenyu.scheduler.type=fixed` 这个是默认。 设置其他的值 就会使用弹性线程池来执行`Schedulers.elastic()`。 +* 可以使用 `-Dshenyu.work.threads = xx` 来指定线程数量,默认为 `cpu * 2 + 1`,最小为`16`个线程。 + + + + + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/index.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/index.md new file mode 100644 index 00000000000..7d01a934b3a --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/index.md @@ -0,0 +1,174 @@ +--- +sidebar_position: 1 +title: Apache ShenYu 介绍 +keywords: ["Apache shenyu"] +description: Apache ShenYu 是一个异步的,高性能的,跨语言的,响应式的`API`网关。 +--- + +# 架构图 + + ![](/img/architecture/shenyu-architecture-3d.png) + +# 什么是 Apache ShenYu + +这是一个异步的,高性能的,跨语言的,响应式的 `API` 网关。 + +# 为什么叫ShenYu + + ShenYu(神禹)是中国古代君主夏禹(后世亦称大禹)的尊称,他留下了三渡黄河造福人民并成功治理黄河洪水的感人故事。他和尧、舜一起被认为是中国古代三大帝王之一。 + +* 首先,ShenYu这个名字是为了弘扬我们中华文明的传统美德。 +* 其次,对于网关来说最重要的是流量管理。 +* 最后,社区将以公平、公正、公开、择优的方式做事,在向神禹致敬的同时,也符合 Apache Way。 + +# 特点 + +* 代理:支持Apache Dubbo,Spring Cloud,gRPC,Motan,SOFA,TARS,WebSocket,MQTT +* 安全性:签名,OAuth 2.0,JSON Web令牌,WAF插件 +* API治理:请求、响应、参数映射、Hystrix、RateLimiter插件 +* 可观测性:跟踪、指标、日志记录插件 +* 仪表板:动态流量控制,用户菜单权限的可视化后端 +* 扩展:插件热插拔,动态加载 +* 集群:NGINX、Docker、Kubernetes +* 语言:提供.NET,Python,Go,Java客户端用于API注册 + +--- + +# 脑图 + +![](https://shenyu.apache.org/img/shenyu/activite/shenyu-xmind.png) + +# 快速开始 (docker) + +### 运行 Apache ShenYu Admin + +``` +docker pull apache/shenyu-admin +docker network create shenyu +docker run -d -p 9095:9095 --net shenyu apache/shenyu-admin +``` + +默认账号: **admin** + +默认密码: **123456** + +### 运行 Apache ShenYu Bootstrap + +``` +docker pull apache/shenyu-bootstrap +docker run -d -p 9195:9195 -e "shenyu.local.enabled=true" --net shenyu apache/shenyu-bootstrap +``` + +### 路由设置 + +* Real requests :, + +```json +{ + "name" : "Shenyu", + "data" : "hello world" +} +``` + +* 设置路由规则 (Standalone) + +将`localKey: 123456`添加到Headers中。如果需要自定义localKey,可以使用sha512工具基于明文生成密钥,并更新`shenyu.local.sha512Key`属性。 + +``` +curl --location --request POST 'http://localhost:9195/shenyu/plugin/selectorAndRules' \ +--header 'Content-Type: application/json' \ +--header 'localKey: 123456' \ +--data-raw '{ + "pluginName": "divide", + "selectorHandler": "[{\"upstreamUrl\":\"127.0.0.1:8080\"}]", + "conditionDataList": [{ + "paramType": "uri", + "operator": "match", + "paramValue": "/**" + }], + "ruleDataList": [{ + "ruleHandler": "{\"loadBalance\":\"random\"}", + "conditionDataList": [{ + "paramType": "uri", + "operator": "match", + "paramValue": "/**" + }] + }] +}' +``` + +* 代理请求 : + +```json +{ + "name" : "Shenyu", + "data" : "hello world" +} +``` + +--- + +# 插件 + + 每当有请求进来,Apache ShenYu将基于责任链模式由所有启用的插件来执行它。 + + 作为Apache ShenYu的核心,插件是可扩展和可热插拔的。 + + 不同的插件做不同的事情。 + + 当然,用户也可以自定义插件来满足自己的需求。 + + 如果要自定义,见[自定义插件](https://shenyu.apache.org/docs/developer/custom-plugin/) + +--- + +# Selector & Rule + + 根据您的HTTP请求头,Selector和Rule将用于路由您的请求。 + + Selector是您的第一层路由,它是粗粒度的,例如模块级。 + + Rule是你的第二层路由,你认为你的请求应该做什么。例如模块中的方法级别。 + + Selector和Rule只匹配一次,然后返回匹配结果。因此最粗的粒度应该最后排序。 + +--- + +# Data Caching & Data Sync + + 因为所有数据都是使用JVM中的ConcurrentHashMap缓存的,所以速度非常快。 + + Apache ShenYu通过监听ZooKeeper节点(或WebSocket push,HTTP long polling),在后台管理中用户更改配置信息时动态更新缓存。 + + ![](/img/shenyu/dataSync/shenyu-config-processor-en.png) + + ![](/img/shenyu/dataSync/config-strategy-processor-en.png) + +--- + +# Prerequisite + +* JDK 1.8+ + +--- + +# Stargazers over time + + + +--- + +# 贡献与支持 + +* [贡献方式](https://shenyu.apache.org/community/contributor-guide) +* [邮件我们](mailto:dev@shenyu.apache.org) + +--- + +# 已知用户 + +按注册顺序,欢迎更多接入公司在 https://github.com/apache/shenyu/issues/68 注册(仅限开源用户)。 + +用户 : [已知用户](https://shenyu.apache.org/community/user-registration) + +--- diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/_category_.json b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/_category_.json new file mode 100644 index 00000000000..4b82d108723 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/_category_.json @@ -0,0 +1,4 @@ +{ + "label": "插件集合", + "position": 6 +} diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/cache/_category_.json b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/cache/_category_.json new file mode 100644 index 00000000000..1452462222c --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/cache/_category_.json @@ -0,0 +1,4 @@ +{ + "label": "缓存123", + "position": 7 +} diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/cache/cache-plugin.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/cache/cache-plugin.md new file mode 100644 index 00000000000..8c7d33419aa --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/cache/cache-plugin.md @@ -0,0 +1,149 @@ +--- +title: 缓存插件 +keywords: ["缓存"] +description: 缓存插件 +--- + + +# 1. 概述 + +## 1.1 插件名称 + +* 缓存插件 + +## 1.2 适用场景 + +* 数据不会频繁更新,而且需要大量调用的场景。 + +* 对于数据一致性要求不高的场景。 + +## 1.3 插件功能 + +* `Cache`插件能够缓存目标服务的结果,允许用户配置缓存结果的失效时间。 + +## 1.4 插件代码 + +* 核心模块 `shenyu-plugin-cache-handler`. +* 核心模块 `shenyu-plugin-cache-redis`. +* 核心模块 `shenyu-plugin-cache-memory`. + +* 核心类 `org.apache.shenyu.plugin.cache.CachePlugin` +* 核心类 `org.apache.shenyu.plugin.cache.redis.RedisCache` +* 核心类 `org.apache.shenyu.plugin.cache.memory.MemoryCache` + +## 1.5 添加自哪个shenyu版本 + +* 2.4.3 + +# 2. 如何使用插件 + +## 2.1 插件使用流程图 + +![](/img/shenyu/plugin/plugin_use_zh.jpg) + +## 2.2 导入pom + +* 在`ShenYu Bootstrap`导入cache插件的依赖。 + +```xml + + + org.apache.shenyu + shenyu-spring-boot-starter-plugin-cache + ${project.version} + + +``` + +## 2.3 启用插件 + +在 `shenyu-admin` --> 基础配置 --> 插件管理 --> `Cache` 设置为开启。 + +## 2.4 配置插件 + +### 2.4.1 插件配置 + +![](/img/shenyu/plugin/cache/cache-plugin-config-zh.png) + +* `cacheType`: Cache目前支持两种模式缓存数据 + +* memory:本地内存模式 + +* redis:redis模式 + +目前默认的是`本地内存模式`,目标服务的结果都存储在本地内存中,如果网关是通过集群的方式部署的,不建议使用`本地内存模式`,推荐使用`redis模式`,目标服务的数据都缓存到redis中。 + +如果使用的是`本地内存模式`,只需要在cacheType中选择memory即可,其他配置都不需要配置。 + +如果使用的是`redis模式`,在cacheType中选择redis,参数介绍: + +* `database`:缓存结果存储到哪个数据库中,默认是索引库0。 + +* `master`:默认为master。 + +* `mode`:redis的工作模式,默认为单点模式:`standalone`,此外还有集群模式:`cluster`,哨兵模式:`sentinel`。 + +* `url` :配置 redis 数据库的IP和端口,通过冒号连接配置,示例:`192.168.1.1:6379`。 + +* `password`: redis 数据库的密码,如果没有的话,可以不配置。 + +* `maxldle`:连接池中最大空闲连接 + +* `minldle`:连接池中最小空闲连接 + +* `maxActive`:连接池最大连接数 + +* `maxWait`:连接池最大阻塞等待时间(使用负值表示没有限制)默认 -1 + +### 2.4.2 选择器配置 + +* 选择器和规则设置,请参考:[选择器和规则管理](../../user-guide/admin-usage/selector-and-rule) + +### 2.4.3 规则配置 + +![](/img/shenyu/plugin/cache/cache-plugin-rule-zh.png) + +* 只有匹配的请求,`Cache`插件才会对目标服务的结果进行缓存。 + +`timeoutSecods`,该值为目标服务结果数据缓存时间,默认是60,单位`秒`。 + +注意:当前版本的Cache插件是把url作为唯一key,标识同一个请求的。 + +## 2.5 示例 + +### 2.5.1 使用redis缓存请求结果 + +#### 2.5.1.1 插件配置 + +![](/img/shenyu/plugin/cache/cache-plugin-config-example-zh.png) + +选择redis缓存模式,并且配置redis的数据库,url,模式和密码。 + +#### 2.5.1.2 选择器配置 + +![](/img/shenyu/plugin/cache/cache-plugin-selector-zh.png) + +#### 2.5.1.3 规则配置 + +![](/img/shenyu/plugin/cache/cache-plugin-rule-zh.png) + +#### 2.5.1.4 发送请求 + +* 发送请求并且缓存结果 + +```http title="request" +### shengyu getway proxy orderSave +GET http://localhost:9195/http/order/findById?id=123 +Accept: application/json +Content-Type: application/json +``` + +#### 2.5.1.5 核验缓存结果 + +![](/img/shenyu/plugin/cache/cache-result.jpg) + +![](/img/shenyu/plugin/cache/cache-result-check.png) + +# 3. 如何禁用插件 + +在 `shenyu-admin` --> 基础配置 --> 插件管理 --> `Cache` 设置为关闭。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/common/_category_.json b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/common/_category_.json new file mode 100644 index 00000000000..55d9bb979c2 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/common/_category_.json @@ -0,0 +1,4 @@ +{ + "label": "通用组件", + "position": 6 +} diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/common/general-context-plugin.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/common/general-context-plugin.md new file mode 100644 index 00000000000..b18bc4f0180 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/common/general-context-plugin.md @@ -0,0 +1,40 @@ +--- +title: GeneralContext插件 +keywords: ["generalContext"] +description: generalContext插件 +--- + +## 说明 + +* `Apache ShenYu` 网关在对目标服务调用的时候,还容许用户使用 `generalContext` 插件在本次请求中通过读取header,进行服务上下文参数传递。 + +## 插件设置 + +* 在 `shenyu-admin`--> 基础配置 --> 插件管理-> `generalContext` ,设置为开启。 + +* 如果用户不需要,可以把插件禁用。 + + + + + +* 在网关的 `pom.xml` 文件中添加 `generalContext` 的支持。 + + +```xml + + + org.apache.shenyu + shenyu-spring-boot-starter-plugin-general-context + ${project.version} + + +``` + +* 选择器和规则配置,请参考: [选择器和规则管理](../../user-guide/admin-usage/selector-and-rule)。 +* 只有匹配的请求,并且配置规则才会传递上下文信息。 + +## 场景 + +* 需要对请求header中的参数传递至代理服务端。 +* 需要对请求header中的某个key进行替换后传递至代理服务端。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/fault-tolerance/_category_.json b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/fault-tolerance/_category_.json new file mode 100644 index 00000000000..cb67e969999 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/fault-tolerance/_category_.json @@ -0,0 +1,4 @@ +{ + "label": "熔断限流", + "position": 3 +} diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/fault-tolerance/hystrix-plugin.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/fault-tolerance/hystrix-plugin.md new file mode 100644 index 00000000000..58d9cf34391 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/fault-tolerance/hystrix-plugin.md @@ -0,0 +1,145 @@ +--- +title: Hystrix插件 +keywords: ["Hystrix"] +description: hystrix插件 +--- + +# 1. 概述 + +## 1.1 插件名称 + +* Hystrix插件 + +## 1.2 适用场景 + +* 服务不稳定,使用hystrix熔断保护服务 + +## 1.3 插件功能 + +* 熔断流量 +* 保护网关代理的服务 +* 隔离模式支持 `thread` 和 `semaphore` + +## 1.4 插件代码 + +* 核心模块: `shenyu-plugin-hystrix` + +* 核心类: `org.apache.shenyu.plugin.hystrix.HystrixPlugin` + +## 1.5 添加自哪个shenyu版本 + +ShenYu 2.4.0 + +# 2. 如何使用插件 + +## 2.1 插件使用流程图 + +![](/img/shenyu/plugin/plugin_use_zh.jpg) + +## 2.2 导入pom + +* 在网关的 `pom.xml` 文件中添加 `hystrix`的依赖。 + +```xml + + + org.apache.shenyu + shenyu-spring-boot-starter-plugin-hystrix + ${project.version} + + +``` + +## 2.3 启用插件 + +在 `shenyu-admin` --> 基础配置 --> 插件管理 --> `hystrix` 设置为开启。 + +## 2.4 配置插件 + +### 2.4.1 插件配置 + +* 无配置,但你应该打开hystrix插件。 + +### 2.4.2 选择器配置 + +用于对流量第一次筛选,不需要特殊处理字段。 + +关于选择器和规则配置的更多说明,请参考:[选择器和规则管理](../../user-guide/admin-usage/selector-and-rule), 这里只对部分字段进行了介绍。 + +![](/img/shenyu/plugin/hystrix/selector.png) + +### 2.4.3 规则配置 + +用于对流量最终筛选,有规则处理逻辑,隔离模式支持 `thread` 和 `semaphore` 。 + +![](/img/shenyu/plugin/hystrix/rule.png) + +* `hystrix`处理详解: + + * 跳闸最小请求数量:最小的请求量,至少要达到这个量才会触发熔断。 + + * 错误百分比阀值: 这段时间内,发生异常的百分比。 + + * 超时时间`(ms)`:执行超时时间。 + + * 最大并发量: 最大的并发量。 + + * 跳闸休眠时间`(ms)`:熔断以后恢复的时间。 + + * 分组`Key`: 一般设置为:`contextPath` 。 + + * 失败降级`URL`: 默认为 `/fallback/hystrix`。 + + * 命令`Key`: 一般设置为具体的路径接口。 + + +## 2.5 示例 + +### 2.5.1 使用hystrix熔断保护服务 + +#### 2.5.1.1 准备工作 + +- 启动 ShenYu Admin +- 启动 ShenYu Bootstrap +- 启动一个后端服务 + +#### 2.5.1.2 选择器配置 + +![](/img/shenyu/plugin/hystrix/selector.png) + +#### 2.5.1.3 规则配置 + +* 以下图片的规则仅为测试使用,实际情况取决于特定的场景而定。 + +![](/img/shenyu/plugin/hystrix/hystrix-example-rule-zh.png) + +* 测试案例 + +```java +@RestController +@RequestMapping("/test") +@ShenyuSpringMvcClient("/test/**") +public class HttpTestController { + @PostMapping("/testHystrix") + public ResultBean ok() { + Random random = new Random(); + int num = random.nextInt(100); + if (num > 20) { + throw new RuntimeException(); + } + return new ResultBean(200, "ok", null); + } +} +``` + +#### 2.5.1.4 使用`Apache Jmeter`发送请求 + +![](/img/shenyu/plugin/hystrix/hystrix-send-request.png) + +#### 2.5.1.5 验证结果 + +![](/img/shenyu/plugin/hystrix/hystrix-result.png) + +# 3. 如何禁用插件 + +在 `shenyu-admin` --> 基础配置 --> 插件管理 --> `hystrix` 设置为关闭。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/fault-tolerance/rate-limiter-plugin.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/fault-tolerance/rate-limiter-plugin.md new file mode 100644 index 00000000000..ac5e2d78804 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/fault-tolerance/rate-limiter-plugin.md @@ -0,0 +1,195 @@ +--- +title: RateLimiter插件 +keywords: ["rateLimiter"] +description: rateLimiter插件 +--- + +# 1. 概述 + +## 1.1 插件名称 + +* RateLimiter 插件 + +## 1.2 适用场景 + +* 在网关集群环境下进行流量控制 +* 根据特定规则进行流量控制 +* 可以到接口级别,也可以到参数级别。 + +## 1.3 插件功能 + +* 基于redis进行流量控制 + +## 1.4 插件代码 + +* 核心模块 `shenyu-plugin-ratelimiter`. + +* 核心类 `org.apache.shenyu.plugin.ratelimiter.RateLimiterPlugin` +* 核心类 `org.apache.shenyu.plugin.ratelimiter.executor.RedisRateLimiter` + +## 1.5 添加自哪个shenyu版本 + +* ShenYu 2.4.0 + +## 1.6 技术方案 + +### 1.6.1 采用redis令牌桶算法进行限流 + +- 系统以恒定的速率产⽣令牌,然后将令牌放⼊令牌桶中。 +- 令牌桶有⼀个容量,当令牌桶满了的时候,再向其中放⼊的令牌就会被丢弃。 +- 每次⼀个请求过来,需要从令牌桶中获取⼀个令牌,如果有令牌,则提供服务;如果没有令牌,则拒绝服务。 + +* 流程图: + ![](/img/shenyu/plugin/ratelimiter/tokenbucket.png) + +### 1.6.2 采用redis漏桶算法进行限流。 + +- ⽔(请求)先进⼊到漏桶⾥,漏桶以⼀定的速度出⽔,当⽔流⼊速度过⼤会直接溢出(拒绝服务) + +* 流程图: + ![](/img/shenyu/plugin/ratelimiter/leakybucket.png) + + +### 1.6.3 基于redis实现的滑动窗口算法 + +- 滑动时间窗口通过维护⼀个单位时间内的计数值,每当⼀个请求通过时,就将计数值加1,当计数值超过预先设定的阈值时,就拒绝单位时间内的其他请求。如果单位时间已经结束,则将计数器清零,开启下⼀轮的计数。 + +* 算法图: + ![](/img/shenyu/plugin/ratelimiter/huadongwindow.jpg) + +* 流程图: + ![](/img/shenyu/plugin/ratelimiter/sldingwindow.png) + +# 2. 如何使用插件 + +## 2.1 插件使用流程图 + +![](/img/shenyu/plugin/plugin_use_zh.jpg) + +## 2.2 导入pom + +* 在网关的 `pom.xml` 文件中添加 `rateLimiter` 的依赖。 + +```xml + + + org.apache.shenyu + shenyu-spring-boot-starter-plugin-ratelimiter + ${project.version} + + +``` + +## 2.3 启用插件 + +在 `shenyu-admin` --> 基础配置 --> 插件管理 --> `rateLimiter` 设置为开启。 + +## 2.4 配置插件 + +### 2.4.1 插件配置 + +![](/img/shenyu/plugin/ratelimiter/ratelimiter-plugin-zh.png) + +* `mode`:redis的工作模式,默认为单点模式:`standalone`,此外还有集群模式:`cluster`,哨兵模式:`sentinel`。 + +* `master`:默认为master。 + +* `url` :配置 redis 数据库的IP和端口,通过冒号连接配置,示例:`192.168.1.1:6379`。 + +* `password`: redis 数据库的密码,如果没有的话,可以不配置。 + +### 2.4.2 选择器配置 + +* 选择器和规则设置,请参考:[选择器和规则管理](../../user-guide/admin-usage/selector-and-rule)。 + +### 2.4.3 规则配置 + +![](/img/shenyu/plugin/ratelimiter/ratelimiter-plugin-rule-zh.png) + +* 令牌桶算法/并发令牌桶算法 + + * `algorithmName`(算法名):`tokenBucket/concurrent`。 + + * `replenishRate`(速率):允许用户每秒执行多少请求,而丢弃任何请求。这是令牌桶的填充速率。 + + * `burstCapacity`(容量):允许用户在一秒钟内执行的最大请求数。这是令牌桶可以保存的令牌数。 + + * `keyResolverName`(限流依据):`whole`表示按网关每秒限流,`remoteAddress`表示按IP每秒限流。 + +* 漏桶算法 + + * `algorithmName`(算法名):`leakyBucket`。 + + * `replenishRate`(速率):单位时间内执行请求的速率,漏桶中水滴漏出的速率。 + + * `burstCapacity`(容量):允许用户在一秒钟内执行的最大请求数。这是桶中的水量。 + + * `keyResolverName`(限流依据):`whole`表示按网关每秒限流,`remoteAddress`表示按IP每秒限流。 + +* 滑动窗口算法 + + * `algorithmName`(算法名):`slidingWindow`。 + + * `replenishRate`(速率):单位时间内执行请求的速率,用于计算时间窗口大小。 + + * `burstCapacity`(容量):时间窗口内(单位时间内)最大的请求数量。 + + * `keyResolverName`(限流依据):`whole`表示按网关每秒限流,`remoteAddress`表示按IP每秒限流。 + + +## 2.5 示例 + +### 2.5.1 使用`RateLimiter`插件在网关集群环境中进行流量控制 + +#### 2.5.1.1 准备工作 + +- 在`10.10.10.10:9095`启动`ShenYu Admin` +- 在`10.10.10.20:9195`和`10.10.10.30:9195`启动`ShenYu Bootstrap`, 配置`ShenYu Bootstrap`配置同步`10.10.10.10:9095` +- 配置nginx,例如: + +```nginx +upstream shenyu_gateway_cluster { + ip_hash; + server 10.1.1.1:9195 max_fails=3 fail_timeout=10s weight=50; + server 10.1.1.2:9195 max_fails=3 fail_timeout=10s weight=50; +} + +server { + location / { + proxy_pass http://shenyu_gateway_cluster; + proxy_set_header HOST $host; + proxy_read_timeout 10s; + proxy_connect_timeout 10s; + } +} +``` + +#### 2.5.1.2 插件、选择器、规则配置 + +- 配置ratelimiter插件的redis的配置 + +- 配置插件的选择器 + +- 配置规则 + +![](/img/shenyu/plugin/ratelimiter/rule-example-zh.png) + +replenishRate为3, burstCapacity为10 + +#### 2.5.1.3 使用`Apache Jmeter`发送请求到Nginx + +* jmeter线程组配置 + +![](/img/shenyu/plugin/ratelimiter/jmeter-thread-group.png) + +* jmeter http request配置 + +![](/img/shenyu/plugin/ratelimiter/jmeter-http-request.png) + +#### 2.5.1.4 验证结果 + +![](/img/shenyu/plugin/ratelimiter/jmeter-result.png) + +# 3. 如何禁用插件 + +在 `shenyu-admin` --> 基础配置 --> 插件管理 --> `rateLimiter` 设置为关闭。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/fault-tolerance/resilience4j-plugin.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/fault-tolerance/resilience4j-plugin.md new file mode 100644 index 00000000000..083d327b380 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/fault-tolerance/resilience4j-plugin.md @@ -0,0 +1,79 @@ +--- +title: Resilience4j插件 +keywords: ["Resilience4j"] +description: resilience4j插件 +--- + +## 说明 + +* `resilience4j`插件是网关用来对流量进行限流与熔断的可选选择之一。 +* `resilience4j`为网关熔断限流提供能力。 + + +## 插件设置 + +请参考运维部署的内容,选择一种方式启动`shenyu-admin`。比如,通过 [本地部署](../../deployment/deployment-local) 启动`Apache ShenYu`后台管理系统。 + +* 在 基础配置 `-->` 插件管理 `-->` `resilience4j`,设置为开启。 如果用户不使用,可以将其关闭。 + + + + +## 在网关中引入 resilience4j 插件 + +* 在网关的 `pom.xml` 文件中添加 `resilience4j`的依赖。 + +```xml + + + org.apache.shenyu + shenyu-spring-boot-starter-plugin-resilience4j + ${project.version} + + +``` + +## Resilience4j 插件配置 + +关于选择器和规则配置的更多说明,请参考:[选择器和规则管理](../../user-guide/admin-usage/selector-and-rule), 这里只对部分字段进行了介绍。 + +#### 选择器配置 + +用于对流量第一次筛选,不需要特殊处理字段。 + + + +#### 规则配置 + +用于对流量最终筛选,有规则处理逻辑。 + + + + +* `resilience4j`处理详解: + + * `limitForPeriod`:每次刷新令牌的数量,默认值:`50`。 + + * `limitRefreshPeriod`:刷新令牌的时间间隔,单位`ms`,默认值:`500`。 + + * `timeoutDurationRate`:等待获取令牌的超时时间,单位`ms`,默认值:`5000`。 + + * `circuitEnable`:是否开启熔断,`0`:关闭,`1`:开启,默认值:`0`。 + + * `failureRateThreshold`:错误率百分比,达到这个阈值,熔断器才会开启,默认值:`50`。 + + * `fallbackUri`:降级处理的`uri`。 + + * `minimumNumberOfCalls`:开启熔断的最小请求数,超过这个请求数才开启熔断统计,默认值:`100`。 + + * `bufferSizeInHalfOpen`:半开状态下的环形缓冲区大小,必须达到此数量才会计算失败率,默认值:`10`。 + + * `slidingWindowSize`:滑动窗口大小,默认值:`100`。 + + * `slidingWindowType`:滑动窗口类型,`0`:基于计数,`1`:基于时间,默认值:`0`。 + + * `timeoutDuration`:熔断超时时间,单位`ms`,默认值:`30000`。 + + * `waitIntervalInOpen`:熔断器开启持续时间,单位`ms`,默认值:`60000`。 + + * `automaticTransitionFromOpenToHalfOpenEnabled`:是否自动从`open`状态转换为`half-open`状态,`true`:是,`false`:否,默认值:`false`。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/fault-tolerance/sentinel-plugin.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/fault-tolerance/sentinel-plugin.md new file mode 100644 index 00000000000..0c6d2f7072b --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/fault-tolerance/sentinel-plugin.md @@ -0,0 +1,216 @@ +--- +title: Sentinel插件 +keywords: ["Sentinel"] +description: sentinel插件 +--- + +# 1. 概述 + +## 1.1 插件名称 + +* Sentinel插件 + +## 1.2 适用场景 + +* `sentinel`插件是网关用来对流量进行限流与熔断的可选选择之一。 +* `sentinel`插件为网关熔断限流提供能力。 + +## 1.3 插件功能 + +* 流量控制 +* 请求熔断和服务降级 + +## 1.4 插件代码 + +* 核心包 `shenyu-plugin-sentinel`. + +* 核心类 `org.apache.shenyu.plugin.sentinel.SentinelPlugin` + +## 1.5 添加自哪个shenyu版本 + +* 2.4.0 + +# 2. 如何使用插件 + +## 2.1 插件使用流程图 + +![](/img/shenyu/plugin/plugin_use_zh.jpg) + +## 2.2 导入pom + +* 在网关的 `pom.xml` 文件中添加 `sentinel` 依赖。 + +```xml + + + org.apache.shenyu + shenyu-spring-boot-starter-plugin-sentinel + ${project.version} + + +``` + +## 2.3 启用插件 + +* 在 基础配置 `-->` 插件管理 `-->` `sentinel`,设置为开启。 + +## 2.4 配置插件 + +### 2.4.1 插件配置 + +### 2.4.2 选择器配饰 + +用于对流量第一次筛选,不需要特殊处理字段。 + + + +### 2.4.3 规则配置 + +用于对流量最终筛选,有规则处理逻辑。 + + + +| field | default value | field type | desc | +|-----------------------------------------------------|--------------------|------------|----------------------------------------------------------------------------------------------------------------------------| +| degradeRuleCount | | Doule | 降级阈值 | +| degradeRuleEnable | 1(enabled) | Integer | (是否开启流控 (1或0) ) :是否开启`sentinel`的流控。 | +| degradeRuleGrade | 0(slow call ratio) | Integer | (断路器策略): 支持秒级RT/秒级Error Ratio/分钟级Error Count策略。 | +| degradeRuleMinRequestAmount | 5 | Integer | 断路器最小请求量。 | +| degradeRuleSlowRatioThreshold | 1.0d | Double | 退化的慢比率阈值。 | +| degradeRuleStatIntervals | 1 | Integer | 降级的状态间隔。 | +| degradeRuleTimeWindow | | Integer | 退化时间(单位:秒)。 | +| flowRuleControlBehavior | 0(direact reject) | Integer | 效果(直接拒绝/排队/慢启动/冷启动+匀速器),不支持调用关系流控。 | +| flowRuleControlBehavior-direct rejection by default | | | direct rejection by default (直接拒绝) | +| flowRuleControlBehavior-warm up | | | warm up (冷启动) | +| flowRuleControlBehavior-constant speed queuing | | | constant speed queuing (匀速排队,漏桶算法 ) | +| flowRuleControlBehavior-preheating uniformly queued | | | 冷启动+匀速器,除了让流量缓慢增加,还还控制的了请求的间隔时间,让请求均匀速度通过。) | +| flowRuleMaxQueueingTimeMs | 500ms | Integer | 最大排队等待时长(在 “preheating uniformly queued“, “constant speed queuing“ 模式生效)。 | +| flowRuleWarmUpPeriodSec | 10 | Integer | 冷启动预热时长(秒) (在 “preheating uniformly queued” “warm up” 模式下生效) | +| flowRuleCount | | Integer | 哨兵流控制计数。 | +| flowRuleEnable | 1(enabled) | Integer | 是否开启哨兵流控功能。 | +| flowRuleGrade | 1(QPS) | Integer | 限流阈值的类型(QPS 或 Thread Count)。 | +| fallbackUri | | String | 断路后降级的uri。 | + +## 2.5 示例 + +### 2.5.1 使用sentinel进行流量控制 + +#### 2.5.1.1 插件配置 + +* 在 基础配置 `-->` 插件管理 `-->` `sentinel`,设置为开启。 + +#### 2.5.1.2 选择器配置 + +![](/img/shenyu/plugin/sentinel/example-selector-zh.png) + +#### 2.5.1.3 规则配置 + +关于选择器和规则配置的更多说明,请参考:[选择器和规则管理](../../user-guide/admin-usage/selector-and-rule), 这里只对部分字段进行了介绍。 + +![](/img/shenyu/plugin/sentinel/example-rule-zh.png) + +使用qps限流策略,并且qps为10,拒绝策略为直接拒绝。 + +代码如下: + +```java +@RestController +@RequestMapping("/order") +@ShenyuSpringMvcClient("/order") +public class OrderController { + + /** + * Save order dto. + * + * @param orderDTO the order dto + * @return the order dto + */ + @PostMapping("/save") + @ShenyuSpringMvcClient("/save") + public OrderDTO save(@RequestBody final OrderDTO orderDTO) { + orderDTO.setName("hello world save order"); + return orderDTO; + } +} +``` + +#### 2.5.1.4 通过`Apache Jmeter`请求网关 + +* Jmeter线程组配置 + +![](/img/shenyu/plugin/sentinel/sentinel-flow-control-config.png) + +* Jmeter http请求配置 + +![](/img/shenyu/plugin/sentinel/sentinel-flow-control-http.png) + +#### 2.5.1.5 验证结果 + +![](/img/shenyu/plugin/sentinel/sentinel-flow-control.png) + +### 2.5.2 使用sentinel进行熔断降级控制 + +#### 2.5.2.1 插件配置 + +* 在 基础配置 `-->` 插件管理 `-->` `sentinel`,设置为开启。 + +#### 2.5.2.2 选择器配置 + +![](/img/shenyu/plugin/sentinel/example-selector-zh.png) + +#### 2.5.2.3 规则配置 + +![](/img/shenyu/plugin/sentinel/example-circuitbreaker-rule.png) + +当degrade strategy为`exception number`时,`degradeRuleSlowRatioThreshold`无效。 当单位时间内的最小请求数为 5,且请求发生的异常大于 3 时,将触发断路器。 + +当degrade strategy为`slow call ratio`时,`degradeRuleSlowRatioThreshold`有效,`degradeRuleCount`表示RT(例如200)。 + + +代码如下: + +```java +@RestController +@RequestMapping("/order") +@ShenyuSpringMvcClient("/order") +public class OrderController { + + /** + * Save order dto. + * + * @param orderDTO the order dto + * @return the order dto + */ + @PostMapping("/save") + @ShenyuSpringMvcClient("/save") + public OrderDTO save(@RequestBody final OrderDTO orderDTO) { + + Random random = new Random(); + int num = random.nextInt(100); + if (num > 40) { + throw new RuntimeException("num great than 20"); + } + orderDTO.setName("hello world save order"); + return orderDTO; + } + +} +``` + +#### 2.5.2.4 通过`Apache Jmeter`请求网关 + +* Jmeter线程组配置 + +![](/img/shenyu/plugin/sentinel/sentinel-flow-control-config.png) + +* Jmeter http请求配置 + +![](/img/shenyu/plugin/sentinel/sentinel-flow-control-http.png) + +#### 2.5.2.5 验证结果 + +![](/img/shenyu/plugin/sentinel/example-circuitbreaker.png) + +# 3. 如何禁用插件 + +* 在 基础配置 `-->` 插件管理 `-->` `sentinel`,设置为关闭。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/http-process/_category_.json b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/http-process/_category_.json new file mode 100644 index 00000000000..ce33bac3bfa --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/http-process/_category_.json @@ -0,0 +1,4 @@ +{ + "label": "Http处理", + "position": 1 +} diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/http-process/contextpath-plugin.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/http-process/contextpath-plugin.md new file mode 100644 index 00000000000..053ea88dfd7 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/http-process/contextpath-plugin.md @@ -0,0 +1,124 @@ +--- +title: Context Path插件 +keywords: ["contextPath"] +description: contextPath插件 +--- + +# 1. 概述 + +## 1.1 插件名称 + +* 上下文路径插件 + +## 1.2 适用场景 + +* 不同的服务可以通过设置不同的上下文路径来做服务的流量治理 + +## 1.3 插件功能 + +* 设置服务的上下文路径 +* 在接口调用的时候插件统一给服务的接口地址加上前缀 + +## 1.4 插件代码 + +* 核心模块 ```shenyu-plugin-context-path``` +* 核心类 ```org.apache.shenyu.plugin.context.path.ContextPathPlugin``` + +## 1.5 添加自哪个 shenyu 版本 + +* 2.3.0 + +# 2. 如何使用插件 + +## 2.1 插件使用流程图 + +![](/img/shenyu/plugin/context-path/procedure-cn.png) + +## 2.2 导入 pom + +- 在网关的 `pom.xml` 文件中添加插件 maven 配置。 + +```xml + + org.apache.shenyu + shenyu-spring-boot-starter-gateway + ${project.version} + +``` + +## 2.3 启用插件 + +- 在 `shenyu-admin` --> 基础配置 --> 插件管理 --> `contextPath` 设置为开启。 + +![](/img/shenyu/plugin/context-path/enable-cn.png) + +## 2.4 配置插件 + +- 配置客户端项目的 contextPath + +![](/img/shenyu/plugin/context-path/client-project-config.png) + +- 选择器和规则设置,请参考:[选择器和规则管理](../../user-guide/admin-usage/selector-and-rule)。 +- shenyu-admin contextPath 插件配置,可以配置 contextPath 和 addPrefix:contextPath 定义了 contextPath 的值,addPrefix 定义了接口调用时需要自动增加的的前缀。 + +![](/img/shenyu/plugin/context-path/plugin-config-cn.png) + +## 2.5 示例 + +### 2.5.1 示例 设置服务的上下文路径 + +#### 2.5.1.1 参考[本地部署](https://shenyu.apache.org/zh/docs/deployment/deployment-local)启动 admin 和网关 + +#### 2.5.1.2 参考 2.2 导入 pom 并重启网关 + +#### 2.5.1.3 参考 2.3 启用插件 + +#### 2.5.1.4 客户端项目配置 contextPath + +客户端项目可以直接使用 [shenyu-examples-http](https://github.com/apache/shenyu/tree/master/shenyu-examples/shenyu-examples-http),并在 application.yml 中配置 contextPath。 + +![](/img/shenyu/plugin/context-path/client-project-config.png) + +配置完成后启动,可以看到 shenyu-admin 中多了一条 context 的 selector 和 rule 配置。 + +![](/img/shenyu/plugin/context-path/context-path-selector-and-rule-cn.png) + +#### 2.5.1.5 接口调用 + +![](/img/shenyu/plugin/context-path/invoke-interface.png) + +### 2.5.2 示例 增加前缀 + +#### 2.5.2.1 参考[本地部署](https://shenyu.apache.org/zh/docs/deployment/deployment-local)启动 admin 和网关 + +#### 2.5.2.2 参考 2.2 导入 pom 并重启网关 + +#### 2.5.2.3 参考 2.3 启用插件 + +#### 2.5.2.4 客户端项目配置 contextPath + +客户端项目可以直接使用 [shenyu-examples-http](https://github.com/apache/shenyu/tree/master/shenyu-examples/shenyu-examples-http),并在 application.yml 中配置 contextPath。 + +![](/img/shenyu/plugin/context-path/client-project-config.png) + +配置完成后启动,可以看到 shenyu-admin 中多了一条 context 的 selector 和 rule 配置。 + +![](/img/shenyu/plugin/context-path/context-path-selector-and-rule-cn.png) + +#### 2.5.2.5 修改 addPrefix 的值 + +![](/img/shenyu/plugin/context-path/add-prefix-cn.png) + +#### 2.5.2.6 修改选择器和条件配置中 uri 的值,删除掉 addPrefix 部分,由于本例使用了 http 协议的服务,因此需要修改 divide 插件。 + +![](/img/shenyu/plugin/context-path/remove-add-prefix-cn.png) + +#### 2.5.2.5 接口调用 + +![](/img/shenyu/plugin/context-path/invoke-interface-add-prefix.png) + +# 3. 如何禁用插件 + +- 在 `shenyu-admin` --> 基础配置 --> 插件管理 --> `contextPath` 设置为禁用。 + +![](/img/shenyu/plugin/context-path/disable-cn.png) diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/http-process/modifyresponse-plugin.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/http-process/modifyresponse-plugin.md new file mode 100644 index 00000000000..f0e71abce4e --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/http-process/modifyresponse-plugin.md @@ -0,0 +1,166 @@ +--- +title: ModifyResponse插件 +keywords: ["modifyResponse"] +description: modifyResponse插件 +--- + +# 1. 概述 + +## 1.1 插件名称 + +* 响应修改插件 + +## 1.2 适用场景 + +* 需要对接口的响应头部参数、响应HTTP状态码或响应体进行修改的场景 + +## 1.3 插件功能 + +* 修改HTTP响应状态码 +* 添加、设置、覆盖或者移除响应头部参数 +* 添加、覆盖或者移除响应体参数 + +## 1.4 插件代码 + +* 核心模块 ```shenyu-plugin-modify-response``` +* 核心类 ```org.apache.shenyu.plugin.modify.response.ModifyResponsePlugin``` + +## 1.5 添加自哪个 shenyu 版本 + +* 2.4.0 + +# 2. 如何使用插件 + +## 2.1 插件使用流程图 + +![](/img/shenyu/plugin/modify-response/procedure-cn.png) + +## 2.2 导入 pom + +- 在网关的 `pom.xml` 文件中添加插件 maven 配置。 + +```xml + + org.apache.shenyu + shenyu-spring-boot-starter-gateway + ${project.version} + +``` + +## 2.3 启用插件 + +- 在 `shenyu-admin` --> 基础配置 --> 插件管理 --> `modifyResponse` 设置为开启。 + +![](/img/shenyu/plugin/modify-response/enable-cn.png) + +## 2.4 配置插件 + +* 选择器和规则设置,请参考:[选择器和规则管理](../../user-guide/admin-usage/selector-and-rule)。 +* `shenyu-admin`插件列表 --> `HttpProcess` --> `modifyResponse`,先添加选择器,然后添加规则: + * 添加选择器 + ![](/img/shenyu/plugin/modify-response/plugin-selector-config-cn.png) + * 添加规则 + ![](/img/shenyu/plugin/modify-response/plugin-rule-config-cn.png) + +## 2.5 示例 + +客户端项目可以直接使用 [shenyu-examples-http](https://github.com/apache/shenyu/tree/master/shenyu-examples/shenyu-examples-http),注意该示例项目的`contextPath`为`/http`,需要在`shenyu-admin`和`shenyu-gateway`启动完成后启动。 + +### 2.5.1 示例 设置HTTP响应状态码 + +#### 2.5.1.1 参考[本地部署](https://shenyu.apache.org/zh/docs/deployment/deployment-local)启动 admin 和网关 + +#### 2.5.1.2 参考 2.2 导入 pom 并重启网关 + +#### 2.5.1.3 参考 2.3 启用插件 + +#### 2.5.1.4 参考 2.4 配置插件规则 + +配置插件规则: + +![](/img/shenyu/plugin/modify-response/status-code-rule-config-cn.png) + +#### 2.5.1.5 接口调用 + +![](/img/shenyu/plugin/modify-response//status-code-invoke-interface.png) + +### 2.5.2 示例 修改响应头部参数 + +#### 2.5.2.1 参考[本地部署](https://shenyu.apache.org/zh/docs/deployment/deployment-local)启动 admin 和网关 + +#### 2.5.2.2 参考 2.2 导入 pom 并重启网关 + +#### 2.5.2.3 参考 2.3 启用插件 + +#### 2.5.2.4 参考 2.4 配置插件规则 + +![](/img/shenyu/plugin/modify-response/header-rule-config-cn.png) + +#### 2.5.2.5 接口调用 + +![](/img/shenyu/plugin/modify-response/header-invoke-interface.png) + +### 2.5.3 示例 修改响应体 + +#### 2.5.3.1 参考[本地部署](https://shenyu.apache.org/zh/docs/deployment/deployment-local)启动 admin 和网关 + +#### 2.5.3.2 参考 2.2 导入 pom 并重启网关 + +#### 2.5.3.3 参考 2.3 启用插件 + +#### 2.5.3.4 参考 2.4 配置插件规则 + +配置插件规则: + +![](/img/shenyu/plugin/modify-response/body-rule-config-cn.png) + +#### 2.5.3.5 接口调用 + +![](/img/shenyu/plugin/modify-response/body-invoke-interface.png) + +## 3. 如何禁用插件 + +- 在 `shenyu-admin` --> 基础配置 --> 插件管理 --> `modifyResponse` 设置为禁用。 + +![](/img/shenyu/plugin/modify-response/disable-cn.png) + +## 4. 插件规则参数列表 + +对于HTTP响应状态码: + +* `statusCode`: 修改响应状态码 + +对于HTTP响应头部参数: + +* `addHeaders`: 添加响应头部参数,键值对形式 +* `setHeaders`: 设置响应头部参数,键值对形式 +* `replaceHeaderKeys`: 替换响应头部参数,其中`key`参数为需要被替换的`key`,`value`参数为替换后的值 +* `removeHeaderKeys`: 移除响应头部参数,其中`key`参数为需要被移除的`key` + +对于HTTP响应体: + +* `addBodyKeys`: 添加响应内容 +* `replaceBodyKeys`: 替换响应内容,其中`key`参数为需要被替换的`key`,`value`参数为替换后的值 +* `removeBodyKeys`: 移除响应内容,其中`key`参数为需要被移除的`key` + +修改响应体是基于`JSONPath`实现的,`$.`代表根目录。对于下面的配置: + +![](/img/shenyu/plugin/modify-response/body-rule-config-cn.png) + +插件开启前,响应内容为: + +```json +{ + "id": 3, + "name": "hello world findById" +} +``` + +插件开启后,响应内容为: + +```json +{ + "id2": 3, + "add": "4" +} +``` diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/http-process/parammapping-plugin.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/http-process/parammapping-plugin.md new file mode 100644 index 00000000000..446843f6c03 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/http-process/parammapping-plugin.md @@ -0,0 +1,109 @@ +--- +title: ParamMapping插件 +keywords: ["ParamMapping"] +description: ParamMapping插件 +--- + +# 1. 概述 + +## 1.1 插件名称 + +* paramMapping插件 + +## 1.2 适用场景 + +* 添加/删除/替换请求体中固定的参数 + +## 1.3 插件功能 + +* 用来对你的请求参数进行修改的插件。 + +## 1.4 插件代码 + +* 核心模块 `shenyu-plugin-param-mapping` + +* 核心类 `org.apache.shenyu.plugin.param.mapping.ParamMappingPlugin` + +## 1.5 添加自哪个shenyu版本 + +* Since ShenYu 2.4.0 + +# 2. 如何使用插件 + +## 2.1 插件使用流程图 + +![](/img/shenyu/plugin/plugin_use_zh.jpg) + +## 2.2 导入pom + +* 在网关的 `pom.xml` 文件中添加 `paramMapping` 的支持。 + +```xml + + + org.apache.shenyu + shenyu-spring-boot-starter-plugin-param-mapping + ${project.version} + + +``` + +## 2.3 启用插件 + +- 在 `shenyu-admin` --> 基础配置 --> 插件管理 --> `paramMapping` 设置为开启。 + +## 2.4 配置插件 + +### 2.4.1 插件配置 + +* 再使用插件时应该开启插件! + +### 2.4.2 选择器配置 + +* 选择器和规则设置,请参考:[选择器和规则管理](../../user-guide/admin-usage/selector-and-rule)。 + +* 只有匹配的请求,才会修改请求体。 + +### 2.4.3 规则配置 + +![](/img/shenyu/plugin/param-mapping/param-mapping.png) +* 参数解析: + * `addParameterKeys`: 在请求体中增加一个 `key-value` + * `replaceParameterKeys`: 替换请求体中的某一个 `key` ,`key` 是要被替换的值,`value` 是替换后的值 + * `removeParameterKeys`: 移除请求体中的某一个 `key` + +* 修改请求体是通过 `JSONPath` 来实现的, `$.` 代表根目录 + +## 2.5 示例 + +### 2.5.1 在请求中添加参数 + +#### 2.5.1.1 配置插件 + +* 使用该插件时应先开启插件! + +#### 2.5.1.2 选择器配置 + +#### 2.5.1.3 规则配置 + +![](/img/shenyu/plugin/param-mapping/param-mapping.png) + +上面的配置,插件开启前,请求内容为 + +```json +{"id":3,"data":{"value":"18","age":"36"}} +``` + +#### 2.5.1.4 验证结果 + +插件开启后,请求内容为 + +```json +{"name":"shenyu","userId":3,"data":{"age":"36"}} +``` + +上述操作,增加一个`name:shenyu`,把`id`替换为`userId`,移除`data`中的`value` 。 + +# 3. 如何禁用插件 + +- 在 `shenyu-admin` --> 基础配置 --> 插件管理 --> `paramMapping` 设置为关闭。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/http-process/redirect-plugin.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/http-process/redirect-plugin.md new file mode 100644 index 00000000000..9a853563fa6 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/http-process/redirect-plugin.md @@ -0,0 +1,53 @@ +--- +title: Redirect插件 +keywords: ["redirect"] +description: redirect插件 +--- + +## 说明 + +- Apache ShenYu 网关在对目标服务进行代理调用的时候,允许用户使用 `redirect` 插件来重定向请求。 + +## 插件设置 + +- 在 `shenyu-admin` --> 基础配置 --> 插件管理 --> `redirect`,设置为开启。 +- 如果用户不需要,可以把插件禁用。 + + + + + +## 插件使用 + +- 在网关的 `pom.xml` 文件中添加 `redirect` 的支持。 + +```xml + + + org.apache.shenyu + shenyu-spring-boot-starter-plugin-redirect + ${project.version} + + +``` + +- 选择器和规则,只有匹配的请求,才会进行转发和重定向,请参考:[选择器规则管理](../../user-guide/admin-usage/selector-and-rule)。 + +## 场景 + +> 顾名思义,`redirect` 插件就是对 `uri` 的重新转发和重定向。 + +#### 重定向 + +* 我们在 `Rule` 配置自定义路径时,应该为一个可达的服务路径。 +* 当匹配到请求后,根据自定义的路径,`Apache ShenYu`网关会进行 `308` 服务跳转。 + + + + +#### 网关自身接口转发 + +* 当满足匹配规则时,服务内部会使用 `DispatcherHandler` 内部接口转发。 +* 要实现网关自身接口转发,我们需要在配置路径使用 `/` 作为前缀开始,具体配置如下图。 + + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/http-process/request-plugin.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/http-process/request-plugin.md new file mode 100644 index 00000000000..22355e65b50 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/http-process/request-plugin.md @@ -0,0 +1,90 @@ +--- +title: Request插件 +keywords: ["RequestPlugin"] +description: RequestPlugin +--- + +# 1. 概述 + +## 1.1 插件名称 + +- Request(请求)插件 + +## 1.2 适用场景 + +- 请求插件能够对 `uri` 的请求参数进行自定义修改。 + +## 1.3 插件功能 + +- `Apache ShenYu` 网关在对目标服务进行代理调用的时候,允许用户使用 `request` 插件对请求参数、请求头以及 `Cookie` 来添加、修改、移除请求头。 + +## 1.4 插件代码 + +- 核心模块 ```shenyu-plugin-redirect``` +- 核心类 ```org.apache.shenyu.plugin.request.RequestPlugin``` + +## 1.5 添加自哪个 shenyu 版本 + +- 2.4.0 + +# 2. 如何使用插件 + +## 2.1 插件使用流程图 + + + +## 2.2 导入 pom + +- 在网关的 `pom.xml` 文件中添加插件 maven 配置,默认已经添加。 + +```xml + + + org.apache.shenyu + shenyu-spring-boot-starter-plugin-request + ${project.version} + + +``` + +## 2.3 启用插件 + +- 在 `shenyu-admin` --> 基础配置 --> 插件管理 --> `request` 设置为开启。 + + > 如果此处页面上存在需要配置 `ruleHandlePageType` 的选项,可以配置任一字符串,如:`custom`,对请求没有影响,后面版本会移除掉该选项。 + + + +## 2.4 配置插件 + +- 选择器和规则,只有匹配的请求,才会进行转发和重定向,请参考:[选择器规则管理](../../user-guide/admin-usage/selector-and-rule)。 +- `shenyu-admin`插件列表 --> `HttpProcess` --> `Request`,先添加选择器,然后添加规则: +- 添加选择器: + + + +- 添加规则: + + + +## 2.5 示例 + +### 2.5.1 添加请求参数 + +- 我们在 `规则` 配置自定义路径时,应该为一个可达的服务路径。 +- 当匹配到请求后,根据自定义的路径,`Apache ShenYu`网关会进行服务跳转。 +1. 参考[本地部署](https://shenyu.apache.org/zh/docs/deployment/deployment-local)启动 admin 和网关 +2. 参考2.2导入 pom 并重启网关 +3. 参考2.3启用插件 +4. 启动 [shenyu-examples-http](https://github.com/apache/shenyu/tree/master/shenyu-examples/shenyu-examples-http) 项目 +5. 参考2.4及[选择器规则管理](../../user-guide/admin-usage/selector-and-rule)配置插件规则 +6. 接口调用:[http-test-api.http](https://github.com/apache/shenyu/blob/master/shenyu-examples/shenyu-examples-http/src/main/http/http-test-api.http) +- 调用选择器和规则声明的接口,将会看到request插件中配置的请求参数。 + + + +# 3. 如何禁用插件 + +- 在 `shenyu-admin` --> 基础配置 --> 插件管理 --> `Request` 设置为禁用。 + + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/http-process/rewrite-plugin.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/http-process/rewrite-plugin.md new file mode 100644 index 00000000000..7488d92b5d8 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/http-process/rewrite-plugin.md @@ -0,0 +1,103 @@ +--- +title: Rewrite插件 +keywords: ["rewrite"] +description: rewrite插件 +--- + +# 1. 概述 + +## 1.1 插件名称 + +* Rewrite插件 + +## 1.2 适用场景 + +* 通过重写请求路径, 可以使用与目标服务不同的uri。 + +## 1.3 插件功能 + +* 该插件用于重写请求uri。 + +## 1.4 插件代码 + +* 核心模块 `shenyu-plugin-rewrite` + +* 核心类 `org.apache.shenyu.plugin.rewrite.RewritePlugin` + +## 1.5 添加自哪个Shenyu版本 + +* 2.4.0 + +# 2. 如何使用插件 + +## 2.1 插件使用流程图 + +![](/img/shenyu/plugin/rewrite/rewrite_use_zh.png) + +## 2.2 导入pom + +- 在网关的 `pom.xml` 文件中添加插件 maven 配置。 + +```xml + + org.apache.shenyu + shenyu-spring-boot-starter-plugin-rewrite + ${project.version} + +``` + +## 2.3 启用插件 + +- 在 `shenyu-admin` --> 基础配置 --> 插件管理 --> `rewrite` 设置为开启。 +![](/img/shenyu/plugin/rewrite/rewrite_open.png) + +## 2.4 配置插件 + +### 2.4.1 插件配置 + +* 在使用前要启用插件。 +* 如果不再使用插件需要禁用。 + +### 2.4.2 选择器配置 + +* 请参考: [选择器和规则管理](../../user-guide/admin-usage/selector-and-rule). + +### 2.4.3 规则配置 + +![](/img/shenyu/plugin/rewrite/rewrite_rule_config.png) + +* 参数解释: + * `regex` : 匹配uri中要重写部分的正则表达式。 + * `replace` : 替换的内容 + +## 2.5 示例 + +### 2.5.1 重新uri示例 + +#### 2.5.1.1 运行 `shenyu-examples-http` 项目 + +* 使用[shenyu-examples-http](https://github.com/apache/shenyu/tree/master/shenyu-examples/shenyu-examples-http), 参考[](../../quick-start/quick-start-http#运行shenyu-examples-http项目) + +#### 2.5.1.1 插件配置 + +* 参考[2.4.1](#241-插件配置)配置插件. + +#### 2.5.1.2 选择器配置 + +* 参考[2.4.2](#242-选择器配置)配置选择器 + +#### 2.5.1.3 规则配置 + +![](/img/shenyu/plugin/rewrite/rewrite_example_rule.png) + +请求 `/http/hello` 将被重写成`/hi`。 + +#### 2.5.1.4 验证结果 + +使用工具(如Postman)发起请求: + +![](/img/shenyu/plugin/rewrite/rewrite_example_result.png) + +# 3. 如何禁用插件 + +- 在 `shenyu-admin` --> 基础配置 --> 插件管理 --> `rewrite` 设置为关闭。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/mock/_category_.json b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/mock/_category_.json new file mode 100644 index 00000000000..e4f13a148a9 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/mock/_category_.json @@ -0,0 +1,4 @@ +{ + "label": "Mock", + "position": 8 +} diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/mock/mock-plugin.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/mock/mock-plugin.md new file mode 100644 index 00000000000..b0985dc4cb1 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/mock/mock-plugin.md @@ -0,0 +1,196 @@ +--- +title: Mock 插件 +keywords: ["mock"] +description: mock插件 +--- + +# 1. 概述 + +## 1.1 插件名称 + +* Mock插件 + +## 1.2 适用场景 + +* 为请求指定响应状态码和响应体方便进行测试。 + +## 1.3 插件功能 + +* 设置请求的响应状态码和响应体。 +* 支持配置 `${}` 占位符自动生成数据。 +* **注意:** mock 插件为了支持更加灵活的数据生成方式,支持用户使用 SpEL 表达式生mock数据。使用SpEL表达式可能会导致执行恶意脚本或应用破坏性程序的风险。我们建议您在使用时格外小心,尽可能在安全的环境中使用,例如内网环境,并遵循安全最佳实践。 + + +## 1.4 插件代码 + +* 核心模块 ```shenyu-plugin-mock``` +* 核心类 ```org.apache.shenyu.plugin.mock.MockPlugin``` + +## 1.5 添加自哪个 shenyu 版本 + +* 2.5.0 + +# 2. 如何使用插件 + +## 2.1 导入 pom + +- 在网关的 `pom.xml` 文件中添加插件 maven 配置。 + +```xml + + org.apache.shenyu + shenyu-spring-boot-starter-plugin-mock + ${project.version} + +``` + +## 2.2 启用插件 + +- 在 `shenyu-admin` --> 基础配置 --> 插件管理 --> `mock` 设置为开启。 + +![](/img/shenyu/plugin/mock/enable-mock-plugin-zh.png) + +## 2.3 配置插件 + +- 选择器和规则设置,请参考:[选择器和规则管理](../../user-guide/admin-usage/selector-and-rule)。 +- shenyu-admin mock 插件配置,支持配置 httpStatusCode 和 responseContent: + - httpStatusCode:配置请求的响应码。 + - responseContent:配置响应体内容,支持配置 `${}` 占位符生成随机数据 。 + +![](/img/shenyu/plugin/mock/mock-rule-configuration-zh.png) + +## 2.4 `${}` 支持的语法 + +**~~`${int|min-max}`~~** + + - **说明:** 生成 `min` 到 `max` 的随机整数,包含 `min` 和 `max` 。 + - **示例:** `${int|10-20}` + + +**~~`${double|min-max|format}`~~** + +- **说明:** 生成 `min` 到 `max` 的随机浮点数 ,包含 `min` 和 `max`,并按照 `format` 进行格式化。 +- **示例:** `${double|10-20}` , `${double|10-20.5|%.2f}` + +**~~`${email}`~~** + +- **说明:** 生成随机的邮箱地址。 + +**~~`${phone}`~~** + +- **说明:** 生成随机的13位手机号码。 + +**~~`${zh|min-max}`~~** + +- **说明:** 生成长度为 `min` 到 `max` (包含 `min` 和 `max`)的随机中文字符串。 +- **示例:** `${zh|10-20}` + +**~~`${en|min-max}`~~** + +- **说明:** 生成长度为 `min` 到 `max` (包含 `min` 和 `max`)的随机英文字符串。 +- **示例:** `${en|10-20}` + +**~~`${bool}`~~** + +- **说明:** 生成随机的`boolean` 类型的值 即 `true` 或 `false`。 + +**~~`${list|[arg1,arg2...]}`~~** + +- **说明:** 随机返回列表中的任意一个值 +- **示例:** `${list|[gril,boy]}` 会返回 girl 或 boy 中任意一个。 + +**~~`${current|format}`~~** + +- **说明:** 返回当前时间并使用 `format` 格式化,`format` 可缺省,默认是 `YYYY-MM-dd HH:mm:ss`。 +- **示例:** `${current}`,`${current|YYYY-MM-dd}` + +**~~`${array|item|length}`~~** + +- **说明:** 按照 `item` 格式定义生成长度为 `length` 的数组, `item` 中可以嵌套使用上述的所有数据生成规则,结果会自动添加`[]`。 +- **示例:** `${array|{"name":"test"}|3}` 会生成 `[{"name":"test"},{"name":"test"},{"name":"test"}]`,`${array|{"age":${int|18-65}}|3}` + +**${expression|expression}** + +目前支持spel表达式并内置了一些函数和参数,完全可替换旧的`${}`语法 + ++ **`${expression|#int(min,max)}`** + + + **说明:** 生成 `min` 到 `max` 的随机整数,包含 `min` 和 `max` 。 + + - **示例:** `${expression|#int(1,2)}` + ++ **`${expression|#double(min,max)}`** + + + **说明:** 生成 `min` 到 `max` 的随机浮点数 ,包含 `min` 和 `max`,并按照 `format` 进行格式化。 + + **示例:**`${expression|#double(10.5,12.0)}`,`${expression|#double(10.5,12.0,'¥%.2f')}` + ++ **`${expression|#email()}`** + + - **说明:** 生成随机的邮箱地址。 + ++ **`${expression|#phone()}`** + + - **说明:** 生成随机的13位手机号码。 + ++ **`${expression|zh(min,max)}`** + + - **说明:** 生成长度为 `min` 到 `max` (包含 `min` 和 `max`)的随机中文字符串。 + - **示例:** `${expression|#zh(1,10)}` + ++ **`${expression|en(min,max)}`** + + - **说明:** 生成长度为 `min` 到 `max` (包含 `min` 和 `max`)的随机英文字符串。 + - **示例:** `${expression|#en(1,10)}` + ++ **`${expression|#bool()}`** + + + **说明:** 生成随机的`boolean` 类型的值 即 `true` 或 `false`。 + ++ **`${expression|#oneOf(arg1,arg2...)}`** + + + **说明:** 随机返回列表中的任意一个值,不限制类型 + + **示例:** `${expression|#oneOf('shenyu','number',1)}` 会返回 'shneyu' 或 'number' 或者数值1。 + ++ **`${expression|current()}`** + + - **说明:** 返回当前时间并使用 `format` 格式化,`format` 可缺省,默认是 `YYYY-MM-dd HH:mm:ss`。 + - **示例:** `${expression|#current()}`,`${expression|#current('YYYY-MM-dd')}` + ++ **`${expression|#array(item,length)}`** + + - **说明:** 按照 `item` 格式定义生成长度为 `length` 的数组。 + + - **示例:** `expression|#array('shenyu',3)` 会生成 `["shenyu","shenyu","shenyu"]`. + + 也可嵌套使用`${expression|#array(#bool(),2)}`或者`${expression|#array(#array('shenyu',2),2)}` + ++ **`${expression|#req}`** + + + 说明:内置请求参数,可根据请求内容生成响应数据 + + 示例:`${expression|#req.method}`、`${expression|#req.queries['query_name']}`、`${req.queries.query_name}`、`${expression|#req.uri}`。当请求体为json时,可使用`jsonPath`,比如请求体为`{"name":"shenyu"}`,`${expression|#req.json.name}`将返回"shenyu" + ++ **`${expression|spel}`** + + + **说明**:直接使用Spel表达式生成数据 + + **示例**:`${expression|T(java.time.LocalDate).now()}`、`${expression|1==1}` + + 建议使用新的`${}`语法,旧的语法功能可能择期被移除。 + + 功能可替换查看表: + + | old | new | + | -------------------------- | ----------------------------------- | + | ${int\|min-max} | ${expression\|#int(min,max)} | + | ${double\|min-max\|format} | ${expression\|#double(min,max)} | + | ${email} | ${expression\|#email()} | + | ${phone} | ${expression\|#phone()} | + | ${zh\|min-max} | ${expression\|#zh(min,max)} | + | ${en\|min-max} | ${expression\|#en(min,max)} | + | ${list\|[arg1,arg2...]} | ${expression\|#oneOf(arg1,agr2...)} | + | ${current\|format} | ${expression\|#current(format)} | + | ${bool} | ${expression\|#bool()} | + | ${array\|item\|length} | ${expression#array(item,length)} | + + +**注意:不需要使用 `""` 包裹 `${}` ,mock插件会根据 `generator`的定义增加前缀和后缀。** + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/observability/_category_.json b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/observability/_category_.json new file mode 100644 index 00000000000..3019af60c74 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/observability/_category_.json @@ -0,0 +1,4 @@ +{ + "label": "可观测性", + "position": 5 +} diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/observability/logging-aliyun-sls.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/observability/logging-aliyun-sls.md new file mode 100644 index 00000000000..9a554695d72 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/observability/logging-aliyun-sls.md @@ -0,0 +1,140 @@ +--- +title: Aliyun-Sls插件 +keywords: ["logging"] +description: logging插件 +--- + +# 1. 概述 + +## 1.1 插件名称 + +* Aliyun sls 日志插件 + +## 1.2 适用场景 + +* 收集日志到`aliyun sls`日志平台,并通过`aliyun sls`日志平台进行数据分析 + +## 1.3 插件功能 + +* 网关接收客户端请求,向服务端转发请求,并将服务端结果返回给客户端.网关可以记录下每次请求对应的详细信息。 +* 插件便是记录访问日志并将访问日志发送到Aliyun sls的插件. + +## 1.4 插件代码 + +* 核心模块 `shenyu-plugin-logging-aliyun-sls` + +* 核心类 `org.apache.shenyu.plugin.aliyun.sls.LoggingAliYunSlsPlugin` +* 核心类 `org.apache.shenyu.plugin.aliyun.sls.client.AliyunSlsLogCollectClient` + +## 1.5 添加自哪个shenyu版本 + +ShenYu 2.5.0 + +# 2. 如何使用插件 + +## 2.1 插件使用流程图 + +![](/img/shenyu/plugin/plugin_use_zh.jpg) + +## 2.2 导入pom + +- 在ShenYu-Bootstrap导入对应的pom依赖。 + +```xml + + + org.apache.shenyu + shenyu-spring-boot-starter-plugin-logging-aliyun-sls + ${project.version} + + +``` + +## 2.3 启用插件 + +- 在 `shenyu-admin` --> 基础配置 --> 插件管理-> `loggingAliyunSls` ,设置为开启。 + +## 2.4 配置插件 + +### 2.4.1 插件配置 + +![](/img/shenyu/plugin/logging/logging-aliyun-sls/plugin-config-zh.jpg) + +| 配置项 | 类型 | 描述 | 备注 | +| :-------------- | :------ | :----------------------------------------------------------- | :----------------- | +| accessId | String | accessId | 必填 | +| accesskey | String | accesskey | 必填 | +| host | String | 主机名,例如::cn-guangzhou.log.aliyuncs.com | 必填 | +| projectName | String | 项目名 | 可选, 默认值:shenyu | +| logStoreName | String | 存储store名称 | 可选, 默认值:shenyu-logstore | +| topic | String | 日志存储topic | 可选, 默认值:shenyu-topic | +| ttlInDay | Integer | 每天的ttl次数 | 可选, 默认值:3 | +| shardCount | Integer | 阿里云日志的shard总数 | 可选, 默认值:10 | +| sendThreadCount | Integer | 发送日志的线程数 | 可选, 默认值:1 | +| ioThreadCount | Integer | io记录日志的线程数 | 可选, 默认值:1 | +| sampleRate | String | 样本消费速率 | 可选, 默认值:1 | +| maxRequestBody | Integer | 最大请求体 | 可选, 默认值:524288 | +| maxResponseBody | Integer | 最大响应体 | 可选, 默认值:524288 | +| bufferQueueSize | Integer | 消费队列大小 | 可选, 默认值:50000 | + +### 2.4.2 规则和选择器配置 + +* 插件和选择器配置。请查看: [Selector and rule config](../../user-guide/admin-usage/selector-and-rule.md). + + +## 2.5 Logging信息 + +采集的access log的字段如下: + +| 字段名称 | 含义 | 说明 | 备注 | +|:----------------------|:----------------------------------------------:|:------------------------------|:----| +| clientIp | 客户端IP | | | +| timeLocal | 请求时间字符串, 格式:yyyy-MM-dd HH:mm:ss.SSS | | | +| method | 请求方法(不同rpc类型不一样,http类的为:get,post等待,rpc类的为接口名称) | | | +| requestHeader | 请求头(json格式) | | | +| responseHeader | 响应头(json格式) | | | +| queryParams | 请求查询参数 | | | +| requestBody | 请求Body(二进制类型的body不会采集) | | | +| requestUri | 请求uri | | | +| responseBody | 响应body | | | +| responseContentLength | 响应body大小 | | | +| rpcType | rpc类型 | | | +| status | 响应码 | | | +| upstreamIp | 上游(提供服务的程序)IP | | | +| upstreamResponseTime | 上游(提供服务的程序)响应请求的耗时(毫秒ms) | | | +| userAgent | 请求的用户代理 | | | +| host | 请求的host | | | +| module | 请求的模块 | | | +| path | 请求的路径path | | | +| traceId | 请求的链路追踪ID | 需要接入链路追踪插件,如skywalking,zipkin | | + + +## 2.6 示例 + +### 2.6.1 通过阿里云sls日志平台收集日志 + +#### 2.6.1.1 插件配置 + +* 开启插件,并配置aliyun sls插件,配置如下: + +![](/img/shenyu/plugin/logging/logging-aliyun-sls/plugin-config-zh.jpg) + +#### 2.6.1.2 选择器配置 + +![](/img/shenyu/plugin/logging/logging-aliyun-sls/aliyun-sls-log-selector-zh.png) + +#### 2.6.1.3 规则配置 + +![](/img/shenyu/plugin/logging/logging-aliyun-sls/aliyun-sls-log-rule-zh.png) + +#### 2.6.1.4 发送请求 + +![](/img/shenyu/plugin/logging/logging-aliyun-sls/call-service.png) + +#### 2.6.1.5 aliyun sls 日志平台展示 + +![](/img/shenyu/plugin/logging/logging-aliyun-sls/aliyun-sls-log.jpg) + +# 3. 如何禁用插件 + +- 在 `shenyu-admin` --> 基础配置 --> 插件管理-> `loggingAliyunSls` ,设置为关闭。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/observability/logging-elasticsearch.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/observability/logging-elasticsearch.md new file mode 100644 index 00000000000..ee84de394d9 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/observability/logging-elasticsearch.md @@ -0,0 +1,184 @@ +--- +title: Logging-ElasticSearch插件 +keywords: ["Logging", "ElasticSearch"] +description: Logging-ElasticSearch插件 +--- + +# 1. 概述 + +## 1.1 插件名称 + +* Logging-ElasticSearch + +## 1.2 适用场景 + +* 通过shenyu网关收集http请求日志,通过其他平台(Kibana)查询或者展示日志。 + +## 1.3 插件功能 + +>`Apache ShenYu` 网关接收客户端请求,向服务端转发请求,并将服务端结果返回给客户端。网关可以记录下每次请求对应的详细信息, +> 列如: 请求时间、请求参数、请求路径、响应结果、响应状态码、耗时、上游IP、异常信息等待. +> ShenYu网关可以通过Logging-ElasticSearch插件记录访问日志并将访问日志发送到ElasticSearch数据库。 + +## 1.4 插件代码 + +* 核心模块 `shenyu-plugin-logging-elasticsearch` + +* 核心类 `org.apache.shenyu.plugin.logging.elasticsearch.LoggingElasticSearchPlugin` +* 核心类 `org.apache.shenyu.plugin.logging.elasticsearch.client.ElasticSearchLogCollectClient` + +## 1.5 添加自哪个shenyu版本 + +* ShenYu 2.5.0 + +## 1.6 技术方案 + +* 架构图 + +![](/img/shenyu/plugin/logging/logging-elasticsearch/logging-elasticsearch-arch.png) + +# 2. 如何使用插件 + +## 2.1 插件使用流程图 + +![](/img/shenyu/plugin/plugin_use_zh.jpg) + +## 2.2 导入pom + +* 在shenyu-bootstrap模块的 `pom.xml` 文件中添加 `Logging-ElasticSearch`的依赖。 + +```xml + + + org.apache.shenyu + shenyu-spring-boot-starter-plugin-logging-elasticsearch + ${project.version} + + +``` + +## 2.3 启用插件 + +* 在 `shenyu-admin`--> 基础配置 --> 插件管理-> `loggingElasticSearch` ,配置ElasticSearch参数,并设置为开启。 + +## 2.4 配置插件 + +### 2.4.1 开启插件,并配置elasticsearch,配置如下: + +![](/img/shenyu/plugin/logging/logging-elasticsearch/logging-elasticsearch-config-cn.png) + +* 各个配置项说明如下: + +| 配置项 | 类型 | 说明 | 备注 | +| :-------------- | :------ | :------------------------------------------------- | :-------------------- | +| config-item | type | description | remarks | +| host | String | 主机名 | 必须 | +| port | String | 端口号 | 必须 | +| sampleRate | String | 采样率,范围0~1,0:关闭,0.01:采集1%,1:采集100% | 可选,默认1,全部采集 | +| compressAlg | String | 压缩算法,默认不压缩,目前支持LZ4压缩 | 可选,默认不压缩 | +| maxResponseBody | Ingeter | 最大响应体大小,超过阈值将不采集响应体 | 可选,默认512KB | +| maxRequestBody | Ingeter | 最大请求体大小,超过阈值将不采集请求体 | 可选,默认512KB | +*除了host、port其它都是可选*,大部分情况下只需要配置这2项就可以了。 + +### 2.4.2 配置选择器和规则器 + +选择器和规则详细配置,请参考: [选择器和规则管理](../../user-guide/admin-usage/selector-and-rule)。 +另外有时候一个大网关集群对应多个应用程序(业务),不同应用程序(业务)对应不同的主题,相关隔离,这时候可以按选择器配置不同的主题(可选)和采样率(可选),配置项的含义如上表所示。 +操作如下图: + +![](/img/shenyu/plugin/logging/logging-elasticsearch/logging-elasticsearch-option.png) + +## 2.5 Logging信息 + +采集的access log的字段如下: + +| 字段名称 | 含义 | 说明 | 备注 | +| :-------------------- | :----------------------------------------------------------: | :---------------------------------------- | :--- | +| clientIp | 客户端IP | | | +| timeLocal | 请求时间字符串, 格式:yyyy-MM-dd HH:mm:ss.SSS | | | +| method | 请求方法(不同rpc类型不一样,http类的为:get,post等待,rpc类的为接口名称) | | | +| requestHeader | 请求头(json格式) | | | +| responseHeader | 响应头(json格式) | | | +| queryParams | 请求查询参数 | | | +| requestBody | 请求Body(二进制类型的body不会采集) | | | +| requestUri | 请求uri | | | +| responseBody | 响应body | | | +| responseContentLength | 响应body大小 | | | +| rpcType | rpc类型 | | | +| status | 响应码 | | | +| upstreamIp | 上游(提供服务的程序)IP | | | +| upstreamResponseTime | 上游(提供服务的程序)响应请求的耗时(毫秒ms) | | | +| userAgent | 请求的用户代理 | | | +| host | 请求的host | | | +| module | 请求的模块 | | | +| path | 请求的路径path | | | +| traceId | 请求的链路追踪ID | 需要接入链路追踪插件,如skywalking,zipkin | | + + +## 2.6 示例 + +### 2.6.1 通过ElasticSearch收集http请求日志 + +#### 2.6.1.1 安装ElasticSearch + +用户需要部署`ElasticSearch`服务来采集 + +##### 2.6.1.1.1 windows 环境下安装ElasticSearch + +- 到[下载地址](https://www.elastic.co/downloads/elasticsearch)选择windows版本进行下载 +- 下载安装包后解压,进入`bin`目录下,双击执行`elasticsearch.bat`进行启动 +- 默认启动端口为 `9200`,访问 `http://localhost:9200`,验证是否成功 + +![](/img/shenyu/plugin/logging/logging-elasticsearch/elasticsearch-success.png) + +##### 2.6.1.1.2 macos 环境下安装ElasticSearch + +- 到[下载地址](https://www.elastic.co/downloads/elasticsearch)选择macos版本进行下载 +- 下载安装包后解压,进入`bin`目录下,在终端执行启动命令: `./elasticsearch` +- 默认启动端口为 `9200`,访问 `http://localhost:9200`,验证是否成功 + +![](/img/shenyu/plugin/logging/logging-elasticsearch/elasticsearch-success.png) + +#### 2.6.1.2 安装Kibana + +##### 2.6.1.2.1 windows 环境下安装Kibana + +- 到[下载地址](https://www.elastic.co/cn/downloads/kibana)选择windows版本进行下载 +- 下载安装包后解压,进入`bin`目录下,双击执行`kibana.bat`进行启动 +- 默认启动端口为 `5601`,访问 `http://localhost:5601`,验证是否成功(前提是ElasticSearch已打开) + +![](/img/shenyu/plugin/logging/logging-elasticsearch/kibana-success.png) + +##### 2.6.1.2.2 macos 环境下安装Kibana + +- 到[下载地址](https://www.elastic.co/cn/downloads/kibana)选择windows版本进行下载 +- 下载安装包后解压,进入`bin`目录下,在终端执行启动命令: `./kibana` +- 默认启动端口为 `5601`,访问 `http://localhost:5601`,验证是否成功(前提是ElasticSearch已打开) + +![](/img/shenyu/plugin/logging/logging-elasticsearch/kibana-success.png) + +#### 2.6.1.3 插件配置 + +![](/img/shenyu/plugin/logging/logging-elasticsearch/logging-elasticsearch-config-cn.png) + +#### 2.6.1.4 选择器和规则的配置 + +* 选择器和规则详细配置,请参考: [选择器和规则管理](../../user-guide/admin-usage/selector-and-rule)。 + +#### 2.6.1.5 使用postman发起请求 + +![](/img/shenyu/plugin/logging/logging-elasticsearch/postman-request.png) + +#### 2.6.1.6 使用Kibana查询数据 + +![](/img/shenyu/plugin/logging/logging-elasticsearch/index.png) + +- 第一次使用插件会自动创建`shenyu-access-logging`索引 + +![](/img/shenyu/plugin/logging/logging-elasticsearch/data.png) + +- 利用es查询语句可以查询到请求的日志信息 + +# 3. 如何禁用插件 + +- 在 `shenyu-admin` --> 基础配置 --> 插件管理-> `LoggingElasticSearch` ,设置为关闭。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/observability/logging-huawei-lts.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/observability/logging-huawei-lts.md new file mode 100644 index 00000000000..9f02c60baa2 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/observability/logging-huawei-lts.md @@ -0,0 +1,170 @@ +--- +title: Logging-Huawei-Lts插件 +keywords: ["Logging", "HuaweiLts"] +description: Logging-HuaweiLts插件 +--- + +# 1. 概述 + +## 1.1 插件名称 + +- Huawei Lts 日志插件 + +## 1.2 适用场景 + +- 收集日志到`Huawei lts`日志平台,并通过`Huawei lts`日志平台进行数据分析 + +## 1.3 插件功能 + +- 网关接收客户端请求,向服务端转发请求,并将服务端结果返回给客户端.网关可以记录下每次请求对应的详细信息。 +- 插件便是记录访问日志并将访问日志发送到Huawei lts的插件. + +## 1.4 插件代码 + +- 核心模块 `shenyu-plugin-logging-huawei-lts` +- 核心类 `org.apache.shenyu.plugin.huawei.lts.LoggingHuaweiLtsPlugin +- 核心类 `org.apache.shenyu.plugin.huawei.lts.client.HuaweiLtsLogCollectClient + +## 1.5 添加自哪个shenyu版本 + +ShenYu 2.6.0 + +# 2. 如何使用插件 + +## 2.1 插件使用流程图 + +![](/img/shenyu/plugin/plugin_use_zh.jpg) + +## 2.2 导入pom + +- 在ShenYu-Bootstrap导入对应的pom依赖。 + +```xml + + + org.apache.shenyu + shenyu-spring-boot-starter-plugin-logging-huawei-lts + ${project.version} + + +``` + +## 2.3 启用插件 + +- 在 `shenyu-admin` --> 基础配置 --> 插件管理-> `loggingHuaweiLts` ,设置为开启。 + +## 2.4 配置插件 + +### 2.4.1 插件配置 + +### ![](/img/shenyu/plugin/logging/logging-huawei-lts/plugin-config-zh.png) + +| 配置项 | 描述 | 类型 | 备注 | +| ------------------------- | ------------------------------------------------------------ | ------- | ---- | +| projectId | 华为云帐号的项目ID(project id)。 | String | 必填 | +| accessKeyId | 华为云帐号的AK。 | String | 必填 | +| accessKeySecret | 华为云帐号的SK。 | String | 必填 | +| regionName | 云日志服务的区域。 | String | 必填 | +| logGroupId | LTS的日志组ID。 | String | 必填 | +| logStreamId | LTS的日志流ID。 | String | 必填 | +| totalSizeInBytes | 单个producer实例能缓存的日志大小上限。 | int | 选填 | +| maxBlockMs | 如果 producer 可用空间不足,调用者在 send 方法上的最大阻塞时间,单位为毫秒。默认为 60 秒(60000毫秒),建议为0秒。当maxBlockMs值>=0时,则阻塞到设置的时间,如果到达阻塞时间,还是不能获取到内存,即报错且丢弃日志。当maxBlockMs值=-1时,则一直阻塞到发送成功,且不会丢弃日志。 | long | 选填 | +| ioThreadCount | 执行日志发送任务的线程池大小。 | int | 选填 | +| batchSizeThresholdInBytes | 当一个 ProducerBatch 中缓存的日志大小大于等于 batchSizeThresholdInBytes 时,该 batch 将被发送。 | int | 选填 | +| batchCountThreshold | 当一个 ProducerBatch 中缓存的日志条数大于等于 batchCountThreshold 时,该 batch 将被发送。 | int | 选填 | +| lingerMs | 一个 ProducerBatch 从创建到可发送的逗留时间。 | int | 选填 | +| retries | 如果某个 ProducerBatch 首次发送失败,能够对其重试的次数,建议为 3 次。如果 retries 小于等于 0,该 ProducerBatch 首次发送失败后将直接进入失败队列。 | int | 选填 | +| baseRetryBackoffMs | 首次重试的退避时间。 | long | 选填 | +| maxRetryBackoffMs | 重试的最大退避时间。 | long | 选填 | +| giveUpExtraLongSingleLog | 超过1M的日志, 拆分后丢弃大于1M的数据。 | boolean | 选填 | +| enableLocalTest | 是否开启跨云上报日志 | boolean | 选填 | + +- 获取 `regionName` + +![](/img/shenyu/plugin/logging/logging-huawei-lts/huawei-lts-regionName.png) + +| **区域名称** | **RegionName** | +| ------------ | -------------- | +| 华北-北京二 | cn-north-2 | +| 华北-北京四 | cn-north-4 | +| 华北-北京一 | cn-north-1 | +| 华东-上海二 | cn-east-2 | +| 华东-上海一 | cn-east-3 | +| 华南-广州 | cn-south-1 | +| 华南-深圳 | cn-south-2 | +| 西南-贵阳一 | cn-southwest-2 | + +- 获取 `projectId` + + +![](/img/shenyu/plugin/logging/logging-huawei-lts/huawei-lts-projectId.png) + +- 获取 `accessKeyId`与`accessKeySecret` + +![](/img/shenyu/plugin/logging/logging-huawei-lts/huawei-lts-access.png) + +- 获取 `logGroupId`与`logStreamId` + +![](/img/shenyu/plugin/logging/logging-huawei-lts/huawei-lts-logGroupId.png) + +![](/img/shenyu/plugin/logging/logging-huawei-lts/huawei-lts-logStreamId.png) + +### 2.4.2 规则和选择器配置 + +- 插件和选择器配置。请查看: [Selector and rule config](https://shenyu.apache.org/zh/docs/user-guide/admin-usage/selector-and-rule). + +## 2.5 Logging信息 + +采集的access log的字段如下: + +| 字段名称 | 含义 | 说明 | 备注 | +| --------------------- | ------------------------------------------------------------ | ----------------------------------------- | ---- | +| clientIp | 客户端IP | | | +| timeLocal | 请求时间字符串, 格式:yyyy-MM-dd HH:mm:ss.SSS | | | +| method | 请求方法(不同rpc类型不一样,http类的为:get,post等待,rpc类的为接口名称) | | | +| requestHeader | 请求头(json格式) | | | +| responseHeader | 响应头(json格式) | | | +| queryParams | 请求查询参数 | | | +| requestBody | 请求Body(二进制类型的body不会采集) | | | +| requestUri | 请求uri | | | +| responseBody | 响应body | | | +| responseContentLength | 响应body大小 | | | +| rpcType | rpc类型 | | | +| status | 响应码 | | | +| upstreamIp | 上游(提供服务的程序)IP | | | +| upstreamResponseTime | 上游(提供服务的程序)响应请求的耗时(毫秒ms) | | | +| userAgent | 请求的用户代理 | | | +| host | 请求的host | | | +| module | 请求的模块 | | | +| path | 请求的路径path | | | +| traceId | 请求的链路追踪ID | 需要接入链路追踪插件,如skywalking,zipkin | | + +## 2.6 示例 + +### 2.6.1 通过华为云lts日志平台收集日志 + +#### 2.6.1.1 插件配置 + +- 开启插件,并配置 huawei lts插件,配置如下: + +![](/img/shenyu/plugin/logging/logging-huawei-lts/plugin-config-zh.png) + +#### 2.6.1.2 选择器配置 + +![](/img/shenyu/plugin/logging/logging-huawei-lts/huawei-lts-log-selector-zh.png) + +#### 2.6.1.3 规则配置 + +![](/img/shenyu/plugin/logging/logging-huawei-lts/huawei-lts-log-rule-zh.png) + +#### 2.6.1.4 发送请求 + +![](/img/shenyu/plugin/logging/logging-huawei-lts/call-service.png) + +#### 2.6.1.5 hauwei lts日志平台展示 + +![](/img/shenyu/plugin/logging/logging-huawei-lts/huawei-lts-log.png) + +# 3. 如何禁用插件 + +- 在 `shenyu-admin` --> 基础配置 --> 插件管理-> `loggingHuaweiLts` ,设置为关闭。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/observability/logging-kafka.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/observability/logging-kafka.md new file mode 100644 index 00000000000..2ca98cde3b3 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/observability/logging-kafka.md @@ -0,0 +1,156 @@ +--- +title: Logging-Kafka插件 +keywords: ["Logging", "Kafka"] +description: Logging-kafka插件 +--- + +# 1. 概述 + +## 1.1 插件名称 + +* Logging-Kafka Plugin + +## 1.2 适用场景 + +* 通过Kafka收集网关http请求日志,通过其他应用消费Kafka消息,并且对日志进行分析。 + +## 1.3 插件功能 + +>`Apache ShenYu` 网关接收客户端请求,向服务端转发请求,并将服务端结果返回给客户端.网关可以记录下每次请求对应的详细信息, +> 列如: 请求时间、请求参数、请求路径、响应结果、响应状态码、耗时、上游IP、异常信息等待. +> Logging-Kafka插件便是记录访问日志并将访问日志发送到Kafka集群的插件. + +## 1.4 插件代码 + +* 核心模块 `shenyu-plugin-logging-kafka`. + +* 核心类 `org.apache.shenyu.plugin.logging.kafka.LoggingKafkaPlugin` +* 核心类 `org.apache.shenyu.plugin.logging.kafka.client.KafkaLogCollectClient` + +## 1.5 添加自哪个shenyu版本 + +* ShenYu 2.5.0 + +## 1.6 技术方案 + +* 架构图 + ![](/img/shenyu/plugin/logging/logging-kafka/logging-kafka-arch.jpg) + +* 在 `Apache ShenYu` 网关里面进行 `Logging` 全程异步采集、异步发送 + +* 日志平台通过消费`Kafka`集群中的日志进行落库 + +# 2. 如何使用插件 + +## 2.1 插件使用流程图 + +![](/img/shenyu/plugin/logging/logging-console/loggingConsole-use-en.png) + +## 2.2 导入pom + +* 在网关的 `pom.xml` 文件中添加 `Logging-Kafka` 的依赖。 + +```xml + + + org.apache.shenyu + shenyu-spring-boot-starter-plugin-logging-kafka + ${project.version} + + +``` + +## 2.3 启用插件 + +* 在 `shenyu-admin`--> 基础配置 --> 插件管理-> `loggingKafka` ,配置kafka参数,并设置为开启。 + +## 2.4 配置插件 + +### 2.4.1 开启插件,并配置Kafka,配置如下 + +![](/img/shenyu/plugin/logging/logging-kafka/logging-kafka-config.jpg) + +* 各个配置项说明如下: + +| 配置项 | 类型 | 说明 | 备注 | +|:-------------------------------------|:-----------------------|:----------------------------------|:-------------------------------------| +| config-item | type | description | remarks | +| topic | String | 消息队列主题 | 必须 | +| namesrvAddr | String | 消息队列命名服务器地址 | 必须 | +| sampleRate | String | 采样率,范围0~1,0:关闭,0.01:采集1%,1:采集100% | 可选,默认1,全部采集 | +| compressAlg | String | 压缩算法,默认不压缩,目前支持LZ4压缩 | 可选,默认不压缩 | +| maxResponseBody | Ingeter | 最大响应体大小,超过阈值将不采集响应体 | 可选,默认512KB | +| maxRequestBody | Ingeter | 最大请求体大小,超过阈值将不采集请求体 | 可选,默认512KB | +*除了topic、namesrvAddr其它都是可选*,大部分情况下只需要配置这2项就可以了。默认的Group-id是"shenyu-access-logging"。 + +### 2.4.2 配置选择器和规则器 + +* 选择器和规则详细配置,请参考: [选择器和规则管理](../../user-guide/admin-usage/selector-and-rule)。 + +另外有时候一个大网关集群对应多个应用程序(业务),不同应用程序(业务)对应不同的主题,相关隔离,这时候可以按选择器配置不同的主题(可选)和采样率(可选),配置项的含义如上表所示。 +操作如下图: +![](/img/shenyu/plugin/logging/logging-option-topic.png) + + +## 2.5 Logging信息 + +采集的access log的字段如下: + +| 字段名称 | 含义 | 说明 | 备注 | +|:----------------------|:----------------------------------------------:|:------------------------------|:----| +| clientIp | 客户端IP | | | +| timeLocal | 请求时间字符串, 格式:yyyy-MM-dd HH:mm:ss.SSS | | | +| method | 请求方法(不同rpc类型不一样,http类的为:get,post等待,rpc类的为接口名称) | | | +| requestHeader | 请求头(json格式) | | | +| responseHeader | 响应头(json格式) | | | +| queryParams | 请求查询参数 | | | +| requestBody | 请求Body(二进制类型的body不会采集) | | | +| requestUri | 请求uri | | | +| responseBody | 响应body | | | +| responseContentLength | 响应body大小 | | | +| rpcType | rpc类型 | | | +| status | 响应码 | | | +| upstreamIp | 上游(提供服务的程序)IP | | | +| upstreamResponseTime | 上游(提供服务的程序)响应请求的耗时(毫秒ms) | | | +| userAgent | 请求的用户代理 | | | +| host | 请求的host | | | +| module | 请求的模块 | | | +| path | 请求的路径path | | | +| traceId | 请求的链路追踪ID | 需要接入链路追踪插件,如skywalking,zipkin | | + +## 2.6 示例 + +### 2.6.1 通过Kafka收集请求日志 + +#### 2.6.1.1 插件配置 + +开启插件,并配置Kafka,配置如下: + +![](/img/shenyu/plugin/logging/logging-kafka/logging-config-cn.png) + +#### 2.6.1.2 选择器配置 + +* 选择器和规则详细配置,请参考: [选择器和规则管理](../../user-guide/admin-usage/selector-and-rule)。 + +另外有时候一个大网关集群对应多个应用程序(业务),不同应用程序(业务)对应不同的主题,相关隔离,这时候可以按选择器配置不同的主题(可选)和采样率(可选),配置项的含义如上表所示。 +操作如下图: +![](/img/shenyu/plugin/logging/logging-kafka/logging-option-topic.png) + +#### 2.6.1.3 规则配置 + +![](/img/shenyu/plugin/logging/logging-kafka/log-rule-zh.png) + +#### 2.6.1.4 请求服务 + +![](/img/shenyu/plugin/logging/logging-rocketmq/call-service.png) + +#### 2.6.1.5 消费以及展示Logging + +由于各个日志平台有差异,如存储可用clickhouse,ElasticSearch等待,可视化有自研的或开源的Grafana、Kibana等。 +Logging-Kafka插件利用Kafka进行生产和消费解耦,同时以json格式输出日志,消费和可视化需要用户结合自身情况选择不同的技术栈来实现。 + +# 3. 如何禁用插件 + +- 在 `shenyu-admin` --> 基础配置 --> 插件管理-> loggingKafka ,设置为关闭。 + + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/observability/logging-plugin.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/observability/logging-plugin.md new file mode 100644 index 00000000000..c387bd8430d --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/observability/logging-plugin.md @@ -0,0 +1,117 @@ +--- +title: Logging插件 +keywords: ["logging"] +description: logging插件 +--- + +# 1. 概述 + +## 1.1 插件名称 + +* 请求日志记录插件 + +## 1.2 适用场景 + +* 开发时调试或者线上排查问题等情况下,需要在网关侧查看本次请求在转发过程中的相关信息,如请求头、请求参数或响应头、响应体等。 + +## 1.3 插件功能 + +* 通过logback或者log4j收集请求的url,请求头,请求体,响应信息和响应体,并将请求信息存储在本地。 + +## 1.4 插件代码 + +* 核心模块 `shenyu-pluign-logging-console`. + +* 核心类 `org.apache.shenyu.plugin.logging.console.LoggingConsolePlugin` + +## 1.5 添加自哪个shenyu版本 + +* ShenYu 2.4.0 + +# 2. 如何使用插件 + +## 2.1 插件使用流程图 + +![](/img/shenyu/plugin/logging/logging-console/loggingConsole-use-en.png) + +## 2.2 导入pom + +- 在ShenYu-Bootstrap导入对应的pom依赖。 + +```xml + + org.apache.shenyu + shenyu-spring-boot-starter-plugin-logging-console + ${project.version} + +``` + +## 2.3 启用插件 + +- 在 `shenyu-admin` --> 基础配置 --> 插件管理-> logging ,设置为开启。 + +## 2.4 配置插件 + +* 插件和选择器配置。请查看: [Selector and rule config](../../user-guide/admin-usage/selector-and-rule.md). + +## 2.5 示例 + +## 2.5.1 收集http请求信息 + +> 在你使用日志之前请在`ShenYuAdmin`开启日志插件. + +### 2.5.1.1 选择器配置 + +![](/img/shenyu/plugin/logging/logging-console/log-selector-zh.jpg) + +### 2.5.1.2 规则配置 + +![](/img/shenyu/plugin/logging/logging-console/log-rule-zh.jpg) + +### 2.5.1.3 调用服务 + +![](/img/shenyu/plugin/logging/logging-console/call-service.png) + +### 2.5.1.4 验证结果 + +如果请求成功,你将会在控制台看到如下信息。 + +``` +Request Uri: http://localhost:9195/test/payment +Request Method: POST + +[Request Headers Start] +Content-Type: application/json +Content-Length: 46 +Host: localhost:9195 +Connection: Keep-Alive +User-Agent: Apache-HttpClient/4.5.13 (Java/11.0.11) +Cookie: JSESSIONID=CD325CE813F61BB37783A1D0835959DD +Accept-Encoding: gzip,deflate +[Request Headers End] + +[Request Body Start] +{ + "userId": "11", + "userName": "xiaoming" +} +[Request Body End] + +Response Code: 200 OK + +[Response Headers Start] +transfer-encoding: chunked +Content-Length: 37 +Content-Type: application/json +[Response Headers End] + +[Response Body Start] +{"userId":"11","userName":"xiaoming"} +[Response Body End] +``` + +# 3. 如何禁用插件 + +- 在 `shenyu-admin` --> 基础配置 --> 插件管理-> logging ,设置为关闭。 + +![](/img/shenyu/plugin/logging/logging-console/unenable-log-plugin-zh.jpg) diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/observability/logging-pulsar.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/observability/logging-pulsar.md new file mode 100644 index 00000000000..8f713415613 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/observability/logging-pulsar.md @@ -0,0 +1,156 @@ +--- +title: Logging-Pulsar插件 +keywords: ["Logging", "Pulsar"] +description: Logging-pulsar插件 +--- + +# 1. 概述 + +## 1.1 插件名称 + +* Logging-Pulsar Plugin + +## 1.2 适用场景 + +* 通过Pulsar收集网关http请求日志,通过其他应用消费Pulsar消息,并且对日志进行分析。 + +## 1.3 插件功能 + +>`Apache ShenYu` 网关接收客户端请求,向服务端转发请求,并将服务端结果返回给客户端.网关可以记录下每次请求对应的详细信息, +> 列如: 请求时间、请求参数、请求路径、响应结果、响应状态码、耗时、上游IP、异常信息等待. +> Logging-Pulsar插件便是记录访问日志并将访问日志发送到Pulsar集群的插件. + +## 1.4 插件代码 + +* 核心模块 `shenyu-plugin-logging-pulsar`. + +* 核心类 `org.apache.shenyu.plugin.logging.pulsar.LoggingPulsarPlugin` +* 核心类 `org.apache.shenyu.plugin.logging.pulsar.client.PulsarLogCollectClient` + +## 1.5 添加自哪个shenyu版本 + +* ShenYu 2.5.1 + +## 1.6 技术方案 + +* 架构图 + ![](/img/shenyu/plugin/logging/logging-pulsar/logging-pulsar-arch.jpg) + +* 在 `Apache ShenYu` 网关里面进行 `Logging` 全程异步采集、异步发送 + +* 日志平台通过消费`Pulsar`集群中的日志进行落库 + +# 2. 如何使用插件 + +## 2.1 插件使用流程图 + +![](/img/shenyu/plugin/logging/logging-console/loggingConsole-use-zh.jpg) + +## 2.2 导入pom + +* 在网关的 `pom.xml` 文件中添加 `Logging-Pulsar` 的依赖。 + +```xml + + + org.apache.shenyu + shenyu-spring-boot-starter-plugin-logging-pulsar + ${project.version} + + +``` + +## 2.3 启用插件 + +* 在 `shenyu-admin`--> 基础配置 --> 插件管理-> `loggingPulsar` ,配置pulsar参数,并设置为开启。 + +## 2.4 配置插件 + +### 2.4.1 开启插件,并配置Pulsar,配置如下 + +![](/img/shenyu/plugin/logging/logging-pulsar/logging-pulsar-config.jpg) + +* 各个配置项说明如下: + +| 配置项 | 类型 | 说明 | 备注 | +|:-------------------------------------|:-----------------------|:----------------------------------|:-------------------------------------| +| config-item | type | description | remarks | +| topic | String | 消息队列主题 | 必须 | +| serviceUrl | String | 消息队列服务器地址 | 必须 | +| sampleRate | String | 采样率,范围0~1,0:关闭,0.01:采集1%,1:采集100% | 可选,默认1,全部采集 | +| compressAlg | String | 压缩算法,默认不压缩,目前支持LZ4压缩 | 可选,默认不压缩 | +| maxResponseBody | Ingeter | 最大响应体大小,超过阈值将不采集响应体 | 可选,默认512KB | +| maxRequestBody | Ingeter | 最大请求体大小,超过阈值将不采集请求体 | 可选,默认512KB | +*除了topic、namesrvAddr其它都是可选*,大部分情况下只需要配置这2项就可以了。默认的Group-id是"shenyu-access-logging"。 + +### 2.4.2 配置选择器和规则器 + +* 选择器和规则详细配置,请参考: [选择器和规则管理](../../user-guide/admin-usage/selector-and-rule)。 + +另外有时候一个大网关集群对应多个应用程序(业务),不同应用程序(业务)对应不同的主题,相关隔离,这时候可以按选择器配置不同的主题(可选)和采样率(可选),配置项的含义如上表所示。 +操作如下图: +![](/img/shenyu/plugin/logging/logging-option-topic.png) + + +## 2.5 Logging信息 + +采集的access log的字段如下: + +| 字段名称 | 含义 | 说明 | 备注 | +|:----------------------|:----------------------------------------------:|:------------------------------|:----| +| clientIp | 客户端IP | | | +| timeLocal | 请求时间字符串, 格式:yyyy-MM-dd HH:mm:ss.SSS | | | +| method | 请求方法(不同rpc类型不一样,http类的为:get,post等待,rpc类的为接口名称) | | | +| requestHeader | 请求头(json格式) | | | +| responseHeader | 响应头(json格式) | | | +| queryParams | 请求查询参数 | | | +| requestBody | 请求Body(二进制类型的body不会采集) | | | +| requestUri | 请求uri | | | +| responseBody | 响应body | | | +| responseContentLength | 响应body大小 | | | +| rpcType | rpc类型 | | | +| status | 响应码 | | | +| upstreamIp | 上游(提供服务的程序)IP | | | +| upstreamResponseTime | 上游(提供服务的程序)响应请求的耗时(毫秒ms) | | | +| userAgent | 请求的用户代理 | | | +| host | 请求的host | | | +| module | 请求的模块 | | | +| path | 请求的路径path | | | +| traceId | 请求的链路追踪ID | 需要接入链路追踪插件,如skywalking,zipkin | | + +## 2.6 示例 + +### 2.6.1 通过Pulsar收集请求日志 + +#### 2.6.1.1 插件配置 + +开启插件,并配置Pulsar,配置如下: + +![](/img/shenyu/plugin/logging/logging-pulsar/logging-config-cn.jpg) + +#### 2.6.1.2 选择器配置 + +* 选择器和规则详细配置,请参考: [选择器和规则管理](../../user-guide/admin-usage/selector-and-rule)。 + +另外有时候一个大网关集群对应多个应用程序(业务),不同应用程序(业务)对应不同的主题,相关隔离,这时候可以按选择器配置不同的主题(可选)和采样率(可选),配置项的含义如上表所示。 +操作如下图: +![](/img/shenyu/plugin/logging/logging-pulsar/logging-option-topic-cn.jpg) + +#### 2.6.1.3 规则配置 + +![](/img/shenyu/plugin/logging/logging-pulsar/log-rule.jpg) + +#### 2.6.1.4 请求服务 + +![](/img/shenyu/plugin/logging/logging-rocketmq/call-service.png) + +#### 2.6.1.5 消费以及展示Logging + +由于各个日志平台有差异,如存储可用clickhouse,ElasticSearch等待,可视化有自研的或开源的Grafana、Kibana等。 +Logging-Pulsar插件利用Pulsar进行生产和消费解耦,同时以json格式输出日志,消费和可视化需要用户结合自身情况选择不同的技术栈来实现。 + +# 3. 如何禁用插件 + +- 在 `shenyu-admin` --> 基础配置 --> 插件管理-> loggingPulsar ,设置为关闭。 + + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/observability/logging-rocketmq.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/observability/logging-rocketmq.md new file mode 100644 index 00000000000..56529cad1f7 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/observability/logging-rocketmq.md @@ -0,0 +1,167 @@ +--- +title: Logging-RocketMQ插件 +keywords: ["Logging", "RocketMQ"] +description: Logging-RocketMQ插件 +--- + +# 1. 概述 + +## 1.1 插件名称 + +* Logging-RocketMQ Plugin + +## 1.2 适用场景 + +* 通过rocketmq收集网关http请求日志,通过其他应用消费rocketmq消息,并且对日志进行分析。 + +## 1.3 插件功能 + +>`Apache ShenYu` 网关接收客户端请求,向服务端转发请求,并将服务端结果返回给客户端.网关可以记录下每次请求对应的详细信息, +> 列如: 请求时间、请求参数、请求路径、响应结果、响应状态码、耗时、上游IP、异常信息等待. +> Logging-RocketMQ插件便是记录访问日志并将访问日志发送到RocketMQ集群的插件. + +## 1.4 插件代码 + +* 核心模块 `shenyu-plugin-logging-rocketmq`. + +* 核心类 `org.apache.shenyu.plugin.logging.rocketmq.LoggingRocketMQPlugin` +* 核心类 `org.apache.shenyu.plugin.logging.rocketmq.client.RocketMQLogCollectClient` + +## 1.5 添加自哪个shenyu版本 + +* ShenYu 2.5.0 + +## 1.6 技术方案 + +* 架构图 + ![](/img/shenyu/plugin/logging/shenyu-agent-logging-arch.png) + +* 在 `Apache ShenYu` 网关里面进行 `Logging` 全程异步采集、异步发送 + +* 日志平台通过消费`RocketMQ`集群中的日志进行落库,再使用`Grafana`、`Kibana`或者其它可视化平台展示 + +# 2. 如何使用插件 + +## 2.1 插件使用流程图 + +![](/img/shenyu/plugin/plugin_use_zh.jpg) + +## 2.2 导入pom + +* 在网关的 `pom.xml` 文件中添加 `Logging-RocketMQ` 的依赖。 + +```xml + + + org.apache.shenyu + shenyu-spring-boot-starter-plugin-logging-rocketmq + ${project.version} + + +``` + +## 2.3 启用插件 + +* 在 `shenyu-admin`--> 基础配置 --> 插件管理-> `loggingRocketMQ` ,配置rocketMQ参数,并设置为开启。 + +## 2.4 配置插件 + +### 2.4.1 开启插件,并配置rocketmq,配置如下 + +![](/img/shenyu/plugin/logging/logging-config.png) + +* 各个配置项说明如下: + +| 配置项 | 类型 | 说明 | 备注 | +|:-------------------------------------|:-----------------------|:----------------------------------|:-------------------------------------| +| config-item | type | description | remarks | +| topic | String | 消息队列主题 | 必须 | +| namesrvAddr | String | 消息队列命名服务器地址 | 必须 | +| producerGroup | String | 日志消息生产者组 | 必须 | +| sampleRate | String | 采样率,范围0~1,0:关闭,0.01:采集1%,1:采集100% | 可选,默认1,全部采集 | +| compressAlg | String | 压缩算法,默认不压缩,目前支持LZ4压缩 | 可选,默认不压缩 | +| maxResponseBody | Ingeter | 最大响应体大小,超过阈值将不采集响应体 | 可选,默认512KB | +| maxRequestBody | Ingeter | 最大请求体大小,超过阈值将不采集请求体 | 可选,默认512KB | +*除了topic、namesrvAddr, producerGroup其它都是可选*,大部分情况下只需要配置这3项就可以了。 + +### 2.4.2 配置选择器和规则器 + +* 选择器和规则详细配置,请参考: [选择器和规则管理](../../user-guide/admin-usage/selector-and-rule)。 + +另外有时候一个大网关集群对应多个应用程序(业务),不同应用程序(业务)对应不同的主题,相关隔离,这时候可以按选择器配置不同的主题(可选)和采样率(可选),配置项的含义如上表所示。 +操作如下图: +![](/img/shenyu/plugin/logging/logging-option-topic.png) + + +## 2.5 Logging信息 + +采集的access log的字段如下: + +| 字段名称 | 含义 | 说明 | 备注 | +|:----------------------|:----------------------------------------------:|:------------------------------|:----| +| clientIp | 客户端IP | | | +| timeLocal | 请求时间字符串, 格式:yyyy-MM-dd HH:mm:ss.SSS | | | +| method | 请求方法(不同rpc类型不一样,http类的为:get,post等待,rpc类的为接口名称) | | | +| requestHeader | 请求头(json格式) | | | +| responseHeader | 响应头(json格式) | | | +| queryParams | 请求查询参数 | | | +| requestBody | 请求Body(二进制类型的body不会采集) | | | +| requestUri | 请求uri | | | +| responseBody | 响应body | | | +| responseContentLength | 响应body大小 | | | +| rpcType | rpc类型 | | | +| status | 响应码 | | | +| upstreamIp | 上游(提供服务的程序)IP | | | +| upstreamResponseTime | 上游(提供服务的程序)响应请求的耗时(毫秒ms) | | | +| userAgent | 请求的用户代理 | | | +| host | 请求的host | | | +| module | 请求的模块 | | | +| path | 请求的路径path | | | +| traceId | 请求的链路追踪ID | 需要接入链路追踪插件,如skywalking,zipkin | | + +## 2.6 示例 + +### 2.6.1 通过RocketMQ收集请求日志 + +#### 2.6.1.1 插件配置 + +开启插件,并配置rocketmq,配置如下: + +![](/img/shenyu/plugin/logging/logging-config.png) + +#### 2.6.1.2 选择器配置 + +* 选择器和规则详细配置,请参考: [选择器和规则管理](../../user-guide/admin-usage/selector-and-rule)。 + +另外有时候一个大网关集群对应多个应用程序(业务),不同应用程序(业务)对应不同的主题,相关隔离,这时候可以按选择器配置不同的主题(可选)和采样率(可选),配置项的含义如上表所示。 +操作如下图: +![](/img/shenyu/plugin/logging/logging-option-topic.png) + +#### 2.6.1.3 规则配置 + +![](/img/shenyu/plugin/logging/logging-rocketmq/log-rule-zh.jpg) + +#### 2.6.1.4 请求服务 + +![](/img/shenyu/plugin/logging/logging-rocketmq/call-service.png) + +#### 2.6.1.5 消费以及展示Logging + +由于各个日志平台有差异,如存储可用clickhouse,ElasticSearch等待,可视化有自研的或开源的Grafana、Kibana等。 +Logging-RocketMQ插件利用RocketMQ进行生产和消费解耦,同时以json格式输出日志,消费和可视化需要用户结合自身情况选择不同的技术栈来实现。 + +#### 2.6.1.6 面板展示 + +用户可根据自身情况选择可视化实现。 +下面展示下 `Grafana` 效果: +[Grafana沙盒体验](https://play.grafana.org) + +![](/img/shenyu/plugin/logging/grafana-loki-gateway.png) + +# 3. 如何禁用插件 + +- 在 `shenyu-admin` --> 基础配置 --> 插件管理-> loggingRocketMQ ,设置为关闭。 + +![](/img/shenyu/plugin/logging/logging-rocketmq/logging-rocket-disabled-zh.jpg) + + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/observability/logging-tencent-cls.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/observability/logging-tencent-cls.md new file mode 100644 index 00000000000..57208853f16 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/observability/logging-tencent-cls.md @@ -0,0 +1,144 @@ +--- +title: Logging-Tencent-Cls插件 +keywords: ["Logging"] +description: logging插件 +--- + +# 1. 概述 + +## 1.1 插件名称 + +* Tencent cls 日志插件 + +## 1.2 适用场景 + +* 收集日志到`Tencent cls`日志平台,并通过`Tencent cls`日志平台进行数据分析 + +## 1.3 插件功能 + +* 网关接收客户端请求,向服务端转发请求,并将服务端结果返回给客户端.网关可以记录下每次请求对应的详细信息。 +* 插件便是记录访问日志并将访问日志发送到Tencent cls的插件. + +## 1.4 插件代码 + +* 核心模块 `shenyu-plugin-logging-tencent-cls` + +* 核心类 `org.apache.shenyu.plugin.tencent.cls.LoggingTencentClsPlugin` +* 核心类 `org.apache.shenyu.plugin.tencent.cls.client.TencentClsLogCollectClient` + +## 1.5 添加自哪个shenyu版本 + +ShenYu 2.5.1 + +# 2. 如何使用插件 + +## 2.1 插件使用流程图 + +![](/img/shenyu/plugin/plugin_use_zh.jpg) + +## 2.2 导入pom + +- 在ShenYu-Bootstrap导入对应的pom依赖。 + +```xml + + + org.apache.shenyu + shenyu-spring-boot-starter-plugin-logging-tencent-cls + ${project.version} + + +``` + +## 2.3 启用插件 + +- 在 `shenyu-admin` --> 基础配置 --> 插件管理-> `loggingTencentCls` ,设置为开启。 + +## 2.4 配置插件 + +### 2.4.1 插件配置 + +![](/img/shenyu/plugin/logging/logging-tencent-cls/plugin-config-zh.jpg) + +| 配置项 | 类型 | 备注 | 描述 | +|:--------------------|:--------|:-----------------------|:--------------------------------------------------------------------------------------------------------------------------------| +| secretId | String | 必填 | secretId | +| secretKey | String | 必填 | secretKey | +| endpoint | String | 必填 | 主机名,例如:ap-guangzhou.cls.tencentcs.com | +| topic | String | 可选, 默认值:shenyu-topic | 日志存储topic | +| sendThreadCount | String | 可选, 默认值:1 | 日志消费回调核心线程数 | +| TotalSizeInBytes | Integer | 默认为 104857600 | 实例能缓存的日志大小上限, | +| MaxSendThreadCount | Integer | 默认为 50 个 | client能并发的最多"goroutine"的数量, | +| MaxBlockSec | Integer | 默认为 60000 毫秒 | 如果client可用空间不足,调用者在 send 方法上的最大阻塞时间。
如果超过这个时间后所需空间仍无法得到满足,send 方法会抛出TimeoutException。如果您希望 send 方法一直阻塞直到所需空间得到满足,可将该值设为负数。 | +| MaxBatchSize | Integer | 默认为 512 * 1024 (512KB) | 当一个Batch中缓存的日志大小大于等于 batchSizeThresholdInBytes 时,该 batch 将被发送,最大可设置成 5MB | +| MaxBatchCount | Integer | 默认为 4096 | 当一个Batch中缓存的日志条数大于等于 batchCountThreshold 时,该 batch 将被发送最大可设置成 40960 | +| LingerMs | Integer | 默认为 2000 毫秒 | Batch从创建到可发送的逗留时间,最小可设置成 100 毫秒 | +| Retries | Integer | 默认为 10 次 | 如果某个Batch首次发送失败,能够对其重试的次数,如果 retries 小于等于 0,该 ProducerBatch 首次发送失败后将直接进入失败队列 | +| MaxReservedAttempts | Integer | 默认只保留最近的 11 次 | 每个Batch每次被尝试发送都对应着一个Attemp,此参数用来控制返回给用户的 attempt 个数,默认只保留最近的 11 次 attempt 信息。该参数越大能让您追溯更多的信息,但同时也会消耗更多的内存 | +| BaseRetryBackoffMs | Integer | 默认为 100 毫秒 | 首次重试的退避时间 client采样指数退避算法,第 N 次重试的计划等待时间为 baseRetryBackoffMs * 2^(N-1 | +| MaxRetryBackoffMs | Integer | 默认为 50 秒 | 重试的最大退避时间 | + +- 获取 `topic` + +![](/img/shenyu/plugin/logging/logging-tencent-cls/tencent-topic.png) + +### 2.4.2 规则和选择器配置 + +* 插件和选择器配置。请查看: [Selector and rule config](../../user-guide/admin-usage/selector-and-rule.md). + +## 2.5 Logging信息 + +采集的access log的字段如下: + +| 字段名称 | 含义 | 说明 | 备注 | +|:----------------------|:----------------------------------------------:|:------------------------------|:----| +| clientIp | 客户端IP | | | +| timeLocal | 请求时间字符串, 格式:yyyy-MM-dd HH:mm:ss.SSS | | | +| method | 请求方法(不同rpc类型不一样,http类的为:get,post等待,rpc类的为接口名称) | | | +| requestHeader | 请求头(json格式) | | | +| responseHeader | 响应头(json格式) | | | +| queryParams | 请求查询参数 | | | +| requestBody | 请求Body(二进制类型的body不会采集) | | | +| requestUri | 请求uri | | | +| responseBody | 响应body | | | +| responseContentLength | 响应body大小 | | | +| rpcType | rpc类型 | | | +| status | 响应码 | | | +| upstreamIp | 上游(提供服务的程序)IP | | | +| upstreamResponseTime | 上游(提供服务的程序)响应请求的耗时(毫秒ms) | | | +| userAgent | 请求的用户代理 | | | +| host | 请求的host | | | +| module | 请求的模块 | | | +| path | 请求的路径path | | | +| traceId | 请求的链路追踪ID | 需要接入链路追踪插件,如skywalking,zipkin | | + + +## 2.6 示例 + +### 2.6.1 通过腾讯云cls日志平台收集日志 + +#### 2.6.1.1 插件配置 + +* 开启插件,并配置 tencent cls插件,配置如下: + +![](/img/shenyu/plugin/logging/logging-tencent-cls/plugin-config-zh.jpg) + +#### 2.6.1.2 选择器配置 + +![](/img/shenyu/plugin/logging/logging-tencent-cls/tencent-cls-log-selector-zh.png) + +#### 2.6.1.3 规则配置 + +![](/img/shenyu/plugin/logging/logging-tencent-cls/tencent-cls-log-rule-zh.png) + +#### 2.6.1.4 发送请求 + +![](/img/shenyu/plugin/logging/logging-tencent-cls/call-service.png) + +#### 2.6.1.5 tencent sls 日志平台展示 + +![](/img/shenyu/plugin/logging/logging-tencent-cls/tencent-cls-log.jpg) + +# 3. 如何禁用插件 + +- 在 `shenyu-admin` --> 基础配置 --> 插件管理-> `loggingTencentCls` ,设置为关闭。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/observability/metrics-plugin.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/observability/metrics-plugin.md new file mode 100644 index 00000000000..3e8241c63e8 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/observability/metrics-plugin.md @@ -0,0 +1,245 @@ +--- +title: Metrics插件 +keywords: ["Metrics"] +description: Metrics插件 +--- + +## 说明 + +* `Metrics插件`插件是网关用来监控自身运行状态(`JVM`相关),请求的响应迟延,`QPS`、`TPS`等相关`metrics`。 + +## 技术方案 + +* 流程图 + ![](/img/shenyu/plugin/monitor/shenyu-metrics.png) + +* 异步或者同步的方式,在 `Apache ShenYu` 网关里面进行 `metrics` 埋点。 + +* `prometheus` 服务端通过 `http` 请求来拉取 `metrics`,再使用 `Grafana` 展示。 + + +## 插件使用 + +* 在网关的 `pom.xml` 文件中添加 `metrics` 的依赖。 + +```xml + + + org.apache.shenyu + shenyu-spring-boot-starter-plugin-metrics + ${project.version} + + +``` + +* 在网关的配置yaml文件中编辑如下内容: + +```yml +shenyu: + metrics: + enabled: false #设置为 true 表示开启 + name : prometheus + host: 127.0.0.1 #暴露的ip + port: 8090 #暴露的端口 + jmxConfig: #jmx配置 + props: + jvm_enabled: true #开启jvm的监控指标 +``` + +## metrics信息 + +* 所有的`JVM`,线程,内存,等相关信息都会埋点,可以在 `Grafana` 面板中,新增一个 `JVM` 模块,则会完全展示 具体请看:https://github.com/prometheus/jmx_exporter + +* 另外还有如下自定义的 `metrics` + +| 名称 | 类型 |标签名称 | 说明 | +|:------------------------ |:--------------------- |:-------------|:-------------------- | +|shenyu_request_total |Counter | none | 收集ShenYu网关的所有请求 | +|shenyu_request_throw_total |Counter | none | 收集ShenYu网关的所有异常请求 | +|shenyu_request_type_total |Counter | path,type | 收集ShenYu网关监视器的所有匹配请求 | +|shenyu_execute_latency_millis |histogram | none | 收集ShenYu网关执行时间间隔 | + +### jmx 指标 + +| name | type | labals | help | +|:-------------------------------:|:-------:|:------:|:--------------------------------------------------------------:| +| jmx_config_reload_success_total | counter | | 成功重新加载配置的次数. | +| jmx_config_reload_failure_total | counter | | 重新加载配置失败的次数. | +| jmx_scrape_duration_seconds | gauge | | 此 JMX 抓取所用的秒数. | +| jmx_scrape_error | gauge | | 如果此抓取失败,则非零. | +| jmx_scrape_cached_beans | gauge | | 有缓存匹配规则的bean的数量 | +| jmx_scrape_duration_seconds | gauge | | 此 JMX 抓取所花费的秒数. | + +### jvm 指标 + +#### StandardExports + +| name | type | labels | help | +|:-----------------------------:|:-------:|:------:|:------------------------------------------------------:| +| process_cpu_seconds_total | counter | | 用户和系统CPU总计所用的秒数. | +| process_start_time_seconds | gauge | | 自 unix 元年(1970-01-01)以来进程的开始时间. | +| process_open_fds | gauge | | 打开的文件描述符的数量. | +| process_max_fds | gauge | | 打开的文件描述符的最大数量. | +| process_virtual_memory_bytes | gauge | | 虚拟内存的字节数. | +| process_resident_memory_bytes | gauge | | 常驻内存的字节数. | + +#### MemoryPoolsExports + +| name | type | labels | help | +|:------------------------------------------:|:-----:|:----------------------:|:-----------------------------------------------------------------:| +| jvm_memory_objects_pending_finalization | gauge | {area="heap\|nonheap"} | 在终结器队列中等待的对象数. | +| jvm_memory_bytes_used | gauge | {area="heap\|nonheap"} | 给定 JVM 内存区域的已用字节数. | +| jvm_memory_bytes_committed | gauge | {area="heap\|nonheap"} | 给定 JVM 内存区域的已提交字节数. | +| jvm_memory_bytes_max | gauge | {area="heap\|nonheap"} | 给定 JVM 内存区域的最大字节数. | +| jvm_memory_bytes_init | gauge | {area="heap\|nonheap"} | 给定 JVM 内存区域的初始字节数. | +| jvm_memory_pool_bytes_used | gauge | {pool} | 给定 JVM 内存池的已用字节数. | +| jvm_memory_pool_bytes_committed | gauge | {pool} | 给定 JVM 内存池的已提交字节数. | +| jvm_memory_pool_bytes_max | gauge | {pool} | 给定 JVM 内存池的最大字节数. | +| jvm_memory_pool_bytes_init | gauge | {pool} | 给定 JVM 内存池的初始字节数. | +| jvm_memory_pool_collection_used_bytes | gauge | {pool} | 给定 JVM 内存池最后一次 GC 后的已用字节数. | +| jvm_memory_pool_collection_committed_bytes | gauge | {pool} | 给定 JVM 内存池的最后一次 GC 后的已提交字节数. | +| jvm_memory_pool_collection_max_bytes | gauge | {pool} | 给定 JVM 内存池的最后一次 GC 后的最大字节数. | +| jvm_memory_pool_collection_init_bytes | gauge | {pool} | 给定 JVM 内存池的最后一次 GC 后的初始字节数. | + +#### MemoryAllocationExports + +| name | type | labels | help | +|:-------------------------------------:|:-------:|:------:|:------------------------------------------------------------------------------------------:| +| jvm_memory_pool_allocated_bytes_total | counter | {pool} | 给定 JVM 内存池中分配的总字节数.(只有 GC 的时候才会更新) | +| | | | | +| | | | | + +#### BufferPoolsExports + +| name | type | labels | help | +|:------------------------------:|:-----:|:------:|:------------------------------------------:| +| jvm_buffer_pool_used_bytes | gauge | {pool} | 给定 JVM 缓冲池的已用字节数. | +| jvm_buffer_pool_capacity_bytes | gauge | {pool} | 给定 JVM 缓冲池的字节容量. | +| jvm_buffer_pool_used_buffers | gauge | {pool} | 给定 JVM 缓冲池的已用缓冲区. | + +#### GarbageCollectorExports + +| name | type | labels | help | +|:-------------------------:|:-------:|:------:|:-------------------------------------------------------:| +| jvm_gc_collection_seconds | summary | {gc} | 在给定的 JVM 垃圾收集器中花费的秒数. | + +#### ThreadExports + +| name | type | labels | help | +|:------------------------------:|:-------:|:-------:|:------------------------------------------------------------------------------------------------------:| +| jvm_threads_current | gauge | | JVM 的当前线程数 | +| jvm_threads_daemon | gauge | | JVM 的守护进程线程数 | +| jvm_threads_peak | gauge | | JVM 的峰值线程数 | +| jvm_threads_started_total | counter | | JVM 的已启动的线程数 | +| jvm_threads_deadlocked | gauge | | 处于死锁状态的 JVM 线程循环等待获取对象监视器或可拥有的同步器 | +| jvm_threads_deadlocked_monitor | gauge | | 处于死锁等待获取对象监视器的 JVM 线程周期 | +| jvm_threads_state | gauge | {state} | 状态为{state}的线程数 | + +#### ClassLoadingExports + +| name | type | labels | help | +|:--------------------------:|:-------:|:------:|:---------------------------------------------------------------------------------------:| +| jvm_classes_loaded | gauge | | 当前在 JVM 中加载的类的数量 | +| jvm_classes_loaded_total | counter | | 自 JVM 开始执行以来已加载的类总数 | +| jvm_classes_unloaded_total | counter | | 自 JVM 开始执行以来已卸载的类总数 | + +#### VersionInfoExports + +| name | type | labels | help | +|:----:|:----:|:---------------------------------------------------------------------------------:|:---------------:| +| jvm | info | {version(java.runtime.version),vendor(java.vm.vendor),runtime(java.runtime.name)} | JVM 版本信息 | + + +## 收集 metrics + +用户需部署`Prometheus` 服务来采集 + +### Windows 环境下安装Prometheus + +* 选择对应环境的 [下载地址](https://prometheus.io/download/) 安装 +* 修改配置文件:`prometheus.yml` + + ```yaml + scrape_configs: + - job_name: 'Apache ShenYu' + # metrics_path defaults to '/metrics' + # scheme defaults to 'http'. + static_configs: + - targets: ['localhost:8090'] # metrics of apache shenyu are exposed on port 8090 by default + ``` + +**注:** `job_name`跟`monitor`插件配置的`metricsName`相对应 + +* 配置完成之后,在 `windows` 下可以直接双击 `prometheus.exe` 启动即可,默认启动端口为 `9090` ,访问 http://localhost:9090/ ,点击`status`->`Targets`,验证是否成功。 + +![](/img/shenyu/monitor/request-metric-6.png) + +### MacOS 环境下安装Prometheus + +* 使用brew 安装 prometheus,安装完成后`prometheus` 在`homebrew`下的 `Cellar` 文件夹中。 + +``` +brew install prometheus +``` + +* 在prometheus.yml文件所在位置执行如下命令即可启动prometheus。 + +``` +prometheus --config.file=prometheus.yml & +``` + +访问 `http://localhost:9090/` 验证是否正常启动。 + +## 面板展示 + +推荐使用 `Grafana`,用户可以自定义查询来个性化显示面板盘。 + +下面介绍如何安装 `Grafana` + +### windows环境下安装Grafana + + +* 安装 `Grafana` + +[下载地址](https://dl.grafana.com/oss/release/grafana-7.4.2.windows-amd64.zip) 解压进入 `bin` 目录然后双击 `grafana-server.exe` 运行 访问 `http://localhost:3000/?orgId=1` admin/admin 验证是否成功 + + +### macos环境下安装Grafana + +* 使用brew 安装 grafana 。 + +``` +brew install grafana +``` + +* 以服务方式启动grafana + +``` +brew services start grafana +``` + +访问 `http://localhost:3000/` 验证是否正常启动。 + +### 使用Grafana查看监控数据 + +配置数据源,选择prometheus,注意数据源名字为prometheus。 + +![](/img/shenyu/monitor/request-metric-7.png) + +![](/img/shenyu/monitor/request-metric-8.png) + +* 配置自定义metric面板`request_total`、`http_request_total` + +点击 `Create` - `Import` 输入`dashboards` 的 [面板json配置](https://shenyu.apache.org/img/shenyu/monitor/request_metric_dashboard.json) + +最终自定义 `Http` 请求监控面板效果如下: + +![](/img/shenyu/monitor/request-metric-1.png) + +![](/img/shenyu/monitor/request-metric-2.png) + +![](/img/shenyu/monitor/request-metric-3.png) + +![](/img/shenyu/monitor/request-metric-4.png) + +![](/img/shenyu/monitor/request-metric-5.png) diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/proxy/_category_.json b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/proxy/_category_.json new file mode 100644 index 00000000000..00828e0e3d1 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/proxy/_category_.json @@ -0,0 +1,4 @@ +{ + "label": "协议代理", + "position": 2 +} diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/proxy/divide-plugin.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/proxy/divide-plugin.md new file mode 100644 index 00000000000..97ae4c6d2a5 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/proxy/divide-plugin.md @@ -0,0 +1,145 @@ +--- +title: Divide插件 +keywords: ["divide"] +description: divide插件 +--- + +# 1. 概述 + +## 1.1 插件名称 + +* `divide`插件 + +## 1.2 适用场景 + +* 处理 `http协议` 请求 +* 支持流量治理,例如a/b 测试、灰度测试 +* 服务负载均衡 +* 设置接口的超时时间 + +## 1.3 插件功能 + +* 支持根据 uri、header、query 等请求信息做流量的治理 +* 支持设置请求的负载均衡策略,同时支持服务预热,目前支持三种策略:ip hash(带虚拟节点的一致性哈希)、round-robbin(加权轮询)、random(加权随机) +* 支持设置接口级别请求头最大值、请求体最大值、请求超时时间 +* 支持设置超时重试策略和重试次数,目前重试策略支持:current(重试之前失败的服务器)和failover(重试其它服务器) + +## 1.4 插件代码 + +* 核心模块 ```shenyu-plugin-divide``` +* 核心类 ```org.apache.shenyu.plugin.divide.DividePlugin``` + +# 2. 如何使用插件 + +## 2.1 插件使用流程图 + +![](/img/shenyu/plugin/divide/procedure-cn.png) + +## 2.2 导入 pom + +- 在网关的 `pom.xml` 文件中添加插件 maven 配置。 + +```xml + + org.apache.shenyu + shenyu-spring-boot-starter-gateway + ${project.version} + +``` + +## 2.3 启用插件 + +- 在 `shenyu-admin` --> 基础配置 --> 插件管理 --> `divide` 设置为开启。 + +![](/img/shenyu/plugin/divide/enable-cn.png) + +## 2.4 配置插件 + +### 2.4.1 在客户端项目配置文件中配置接入参数 + + * 客户端接入方式和服务器地址,下面的示例使用了 http 接入方式,目前客户端支持的接入的方式有以下几种:http、zookeeper、etcd、nacos、consul,详细的接入配置参数请参考[客户端接入配置](../../user-guide/property-config/register-center-access.md)。 + * 客户端配置,包含协议名称以及服务的路由地址,这里请使用 http 协议,并且必须配置 contextPath 的值作为每个服务的路由地址。 + +```yaml + shenyu: + register: + registerType: http + serverLists: http://localhost:9095 + props: + username: admin + password: 123456 + client: + http: # http 协议 + props: + contextPath: /http # 每个服务的路由地址 +``` + +### 2.4.2 在 shenyu-admin 配置文件中配置 upstream 有效性的检测参数 + +下面的示例使用了 http 接入方式,目前客户端支持的接入的方式有以下几种:http、zookeeper、etcd、nacos、consul,详细的接入配置参数请参考[客户端接入配置](../../user-guide/property-config/register-center-access.md)。 + +> 只有 http 类型的注册中心才支持 upstream 检测 + +```yaml + shenyu: + register: + registerType: http # 只有 http 类型的注册中心才支持检测 upstream + serverLists: + props: + checked: true # 默认为 ture,设置为 false,不检测 + zombieCheckTimes: 5 # 僵尸 upstream 最大检测次数,超过 5 次不再检测其有效性,默认为 5 + scheduledTime: 10 # 定时检测时间间隔,默认 10 秒 + zombieRemovalTimes: 60 # upstream 多少秒不在线认定为僵尸 upstream,默认 60 秒 +``` + +### 2.4.3 在 shenyu-admin 配置 divide 插件的选择器和规则信息 + +客户端启动之后会在 shenyu-admin -> 插件列表 -> Proxy -> Divide 自动注册[选择器和规则](../../user-guide/admin-usage/selector-and-rule)信息。 +![](/img/shenyu/plugin/divide/select-and-rule-cn.png) + +#### 2.4.3.1 选择器的配置 + +divide 选择器示例,通用选择器配置请参考[选择器和规则](../../user-guide/admin-usage/selector-and-rule)。 + +![](/img/shenyu/plugin/divide/selector-cn.png) + +##### 2.4.3.1.1 选择器处理信息配置 + +- `host`:填写 `localhost`,该字段暂时没使用。 +- `ip:port`:`ip` 与端口,这里填写你真实服务的 `ip` + 端口。 +- `protocol`::`http` 协议,填写 `http://` 或者 `https://`,不填写默认为:`http://` +- `startupTime`: 启动时间,单位毫秒。 +- `weight`:负载均衡权重,服务启动自动注册的默认值为 50。 +- `warmupTime`:预热时间,单位毫秒,在预热中的服务器会计算瞬时权重,计算值会小于实际配置的权重,以保护刚启动的服务器,服务启动注册的默认值为 10。举个例子预热时间 100 毫秒,目前启动了 50 毫秒,配置的权重 50, 实际的权重是 25。 +- `status`:开启或关闭,开始状态此处理器才有效。 + +#### 2.4.3.2 规则的处理信息配置 + +divide 规则示例,通用规则配置请参考[选择器和规则](../../user-guide/admin-usage/selector-and-rule)。 + +![](/img/shenyu/plugin/divide/rule-cn.png) + +##### 2.4.3.2.1 规则处理信息配置 + +- `loadStrategy`:如果`http`客户端是一个集群,`Apache ShenYu`网关调用时采取哪种负载均衡策略,当前支持 `roundRobin`、`random` 和 `hash`。 +- `timeout`:调用`http`客户端的超时时间。 +- `retryCount`:调用`http`客户端超时失败的重试次数。 +- `headerMaxSize`:请求`header`的最大值。 +- `requestMaxSize`:请求体的最大值。 +- `retryStrategy`:从`2.4.3版本`开始支持,失败后的重试策略,默认`current`以保持对低版本的兼容。 比如下游有3个服务`http://localhost:1111`、`http://localhost:1112`和`http://localhost:1113`,假设第一次负载均衡到`http://localhost:1111`并且`调用失败`。使用`current`策略会继续重试调用`http://localhost:1111`;使用`failover`策略会通过`负载均衡`重试调用到其他服务如`http://localhost:1112`,此时如果又失败了,则调用到`http://localhost:1113`,直到没有可用的服务为止。 + +## 2.5 示例 + +### 2.5.1 示例 A/B 测试 + +待补充 + +### 2.5.2 示例 灰度测试 + +待补充 + +# 3. 如何禁用插件 + +- 在 `shenyu-admin` --> 基础配置 --> 插件管理 --> `divide` 设置为禁用。 + +![](/img/shenyu/plugin/divide/disable-cn.png) diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/proxy/dubbo-plugin.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/proxy/dubbo-plugin.md new file mode 100644 index 00000000000..a1e47c35421 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/proxy/dubbo-plugin.md @@ -0,0 +1,129 @@ +--- +title: Dubbo插件 +keywords: ["dubbo"] +description: dubbo插件 +--- + +## 说明 + +* `dubbo`插件是将 `http协议` 转换成 `dubbo协议` 的插件,也是网关实现`dubbo`泛化调用的关键。 +* `dubbo`插件需要配合元数据才能实现`dubbo`的调用。 +* `apache dubbo` 和 `alibaba dubbo`,都是使用该一插件。 + +## 插件设置 + +* 引入相关依赖,开启插件,请参考:[Dubbo快速开始](../../quick-start/quick-start-dubbo) 。 + +* `Dubbo`应用客户端接入,请参考:[Dubbo服务接入](../../user-guide/proxy/dubbo-proxy.md) 。 + +* 选择器和规则配置,请参考:[选择器和规则管理](../../user-guide/admin-usage/selector-and-rule)。 + +* 自`2.4.3版本`起dubbo插件新增字段及含义: + + + + * `corethreads`:业务线程池核心线程数。 + + * `queues`:业务线程池阻塞队列长度,0表示`无界阻塞队列`。 + + * `threadpool`:业务线程池类型,有`fixed`、`eager`、`cached`、`limited`和`shared`共5种类型,前面4种与dubbo官方提供的线程池一一对应,不多解释,这里单独说下`shared`,正如其名,`所有proxy插件`共用一个`shared`线程池,这样做的好处是能够减少线程池数量,进而降低内存、提高资源利用率。 + + * `threads`:业务线程池最大线程数。 + +## 插件详解 + +客户端接入`Apache ShenYu`网关后,会自动注册选择器和规则信息,关于选择器和规则配置,请参考:[选择器和规则管理](../../user-guide/admin-usage/selector-and-rule) 。 + +#### 选择器处理 + + + +选择器处理,即`handle`字段,是网关匹配到流量以后,可以进行处理的操作。更多信息请参考插件管理中的 [插件处理管理](../../user-guide/admin-usage/plugin-handle-explanation) 。 + +* 处理配置详解: + + * `host`:host地址。 + + * `ip:port`:ip+port地址。 + + * `protocol`:协议默认值为'http'。 + + * `group`:dubbo服务的组。 + + * `version`:dubbo服务版本号。 + + * `weight`:服务实例的权重。 + + * `warmupTime`:服务预热时间。 + + * `startupTime`:服务开启时间。 + + * `status`:true: 服务节点可用,false: 服务节点不可用. + + * `gray`:灰度状态. + +灰度路由 + +如果您想在dubbo插件中使用灰色路由,可以单击“灰色”按钮。 + +* 灰度发布可以在发布新版本应用时,自定义控制新版本应用流量比重,渐进式完成新版本应用的全量上线,最大限度地控制新版本发布带来的业务风险,降低故障带来的影响面,同时支持快速回滚。 + +当开启灰度是,网关的负载平衡算法将从当前节点列表中选择一个节点进行路由,并且您可以通过修改节点权重以更改负载平衡算法中节点的权重。 + +需要注意的是,如果您的业务实例没有使用'shenyu-client-apache-dubbo'或者'shenyu-client-alibaba-dubbo'的客户端进行业务注册发现,您应该在当前选择器页面上手动添加节点信息进行灰度路由。 + +#### 规则处理 + + + +规则处理,即`handle`字段,是网关对流量完成最终匹配后,可以进行处理的操作。更多信息请参考插件管理中的 [插件处理管理](../../user-guide/admin-usage/plugin-handle-explanation) 。 + +* 处理配置详解: + + * `loadbalance`:负载均衡策略,如果选择灰度节点失败,将会使用默认的负载均衡方式。 + +* Apache ShenYu将获得相应服务的真实IP,并从dubbo注册中心发起rpc代理调用。 + +## 元数据 + +每一个`dubbo`接口方法,都会对应一条元数据,当`dubbo`应用客户端接入到`Apache ShenYu`网关时,会自动注册,可以在 `shenyu-admin`后台管理系统的基础配置 `-->` 元数据管理中查看。 + + + +* 应用名称:该条元数据所属的应用名称。 + +* 方法名称:需要调用的方法名。 + +* 路径:`http`请求路径。 + +* 路径描述:对该路径的说明,方便查看。 + +* 参数类型:`dubbo`接口的参数类型列表,此处有两种声明方式。例如一个接口为 `update(Integer id, String name, Integer age)` + + 方式一、类型列表 + + ```yaml + java.lang.Integer,java.lang.String,java.lang.Integer + ``` + + * 按照接口的参数类型顺序,通过半角逗号分隔。 + * 请求传参时需**严格按照参数类型顺序传参**,没有值的用 `null`占位 。请求体示例:`{"id":1,"name": null,"age":18}` + + 方式二、名称映射 + + ```yaml + {"id":"java.lang.Integer","name":"java.lang.String","age":"java.lang.Integer"} + ``` + + * 使用 `"参数名":"参数类型"`表示一个参数,按接口参数类型顺序设置,半角逗号分隔。 + * 请求时无需关注顺序,也无需使用null占位。请求体示例: `{"name":"Mike","id":1}` + +* Rpc扩展参数:`dubbo`接口的其他配置,支持`json`格式,字段如下: + +```yaml +{"timeout":10000,"group":"",version":"","loadbalance":"","retries":1} +``` + +* 服务接口:`dubbo`接口的全限定类名 + +* `Rpc`类型:此处选择 `dubbo`。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/proxy/grpc-plugin.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/proxy/grpc-plugin.md new file mode 100644 index 00000000000..a3c9cb2a435 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/proxy/grpc-plugin.md @@ -0,0 +1,81 @@ +--- +title: gRPC插件 +keywords: ["gRPC"] +description: gRPC插件 +--- + + +## 说明 + +`gRPC`插件是网关用于处理 `gRPC协议`请求的核心处理插件。 + +## 插件设置 + +* 引入相关依赖,开启插件,请参考:[gRPC快速开始](../../quick-start/quick-start-grpc) 。 + +* `gRPC`应用客户端接入,请参考:[gRPC服务接入](../../user-guide/proxy/grpc-proxy.md) 。 + +* 自`2.4.3版本`起grpc插件新增字段及含义: + + * `threadpool`:业务线程池类型,有`cached`和`shared`共2种类型。 + + `cached`相当于grpc官方提供的默认线程池; + + `shared`线程池,正如其名,`所有proxy插件`共用一个`shared`线程池,这样做的好处是能够减少线程池数量,进而降低内存、提高资源利用率。 + + +## 插件讲解 + + +客户端接入`Apache ShenYu`网关后,会自动注册选择器和规则信息,可以在插件列表 `->` rpc proxy `->` grpc 中查看。 关于选择器和规则配置,请参考:[选择器和规则管理](../../user-guide/admin-usage/selector-and-rule)。 + + + +#### 选择器处理 + + + + +选择器处理,即`handle`字段,是网关匹配到流量以后,可进行的处理操作。 + +* 处理配置详解: + + + * `ip:port`:`ip` 与端口,这里填写你真实服务的 `ip` + 端口。 + + * `protocol`:`http` 协议,一般填写 `http://` 或者 `https://` ,不填写默认为:`http://` + + * `weight`:服务权重。 + + * `status`:开启或关闭。 + + +## 元数据 + +每一个`grpc`接口方法,都会对应一条元数据,当`gRPC`应用客户端接入到`Apache ShenYu`网关时,会自动注册,可以在 `shenyu-admin`后台管理系统的基础配置 `-->` 元数据管理中查看。 + + + + +* 应用名称:该条元数据所属的应用名称。 + +* 方法名称:需要调用的方法名。 + +* 路径:`http`请求路径。 + +* 路径描述:对该路径的说明,方便查看。 + +* 参数类型:`grpc`接口的参数类型列表,按照接口的参数类型顺序,通过半角逗号分隔。 + +* Rpc扩展参数:`grpc`接口的其他配置,支持`json`格式,字段如下: + +```json +{ + "timeout": 5000, + "methodType": "BIDI_STREAMING" +} +``` + +* 服务接口:`grpc`接口的全限定类名 + +* `Rpc`类型:此处选择 `grpc`。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/proxy/motan-plugin.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/proxy/motan-plugin.md new file mode 100644 index 00000000000..b1b4b448005 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/proxy/motan-plugin.md @@ -0,0 +1,59 @@ +--- +title: Motan插件 +keywords: ["Motan"] +description: Motan插件 +--- + +## 说明 + +`Motan`插件是网关用于处理 `Motan协议`请求的核心处理插件。 + +## 插件设置 + +* 引入相关依赖,开启插件,请参考:[Motan快速开始](../../quick-start/quick-start-motan) 。 + +* `Motan`应用客户端接入,请参考:[Motan服务接入](../../user-guide/proxy/motan-proxy.md) 。 + + +## 插件讲解 + +客户端接入`Apache ShenYu`网关后,会自动注册选择器和规则信息,可以在插件列表 `->` rpc proxy `->` motan 中查看。 关于选择器和规则配置,请参考:[选择器和规则管理](../../user-guide/admin-usage/selector-and-rule)。 + +#### 元数据 + +每一个`motan`接口方法,都会对应一条元数据,当`motan`应用客户端接入到`Apache ShenYu`网关时,会自动注册,可以在 `shenyu-admin`后台管理系统的基础配置 `-->` 元数据管理中查看。 + + + +* 应用名称:该条元数据所属的应用名称。 + +* 方法名称:需要调用的方法名。 + +* 路径:`motan`请求路径。 + +* 路径描述:对该路径的说明,方便查看。 + +* 参数类型:`motan`接口的参数类型列表,按照接口的参数类型顺序,通过半角逗号分隔。 + +* Rpc扩展参数:描述了一个`motan`服务中每个接口信息。比如,下面是`motan`服务的接口信息: + +```json +{ + "methodInfo": [ + { + "methodName": "hello", + "params": [ + { + "left": "java.lang.String", + "right": "name" + } + ] + } + ], + "group": "motan-shenyu-rpc" +} +``` + +* 服务接口:`motan`服务接口全限定名。 + +* `Rpc`类型:下拉选择 `motan`。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/proxy/mqtt-plugin.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/proxy/mqtt-plugin.md new file mode 100644 index 00000000000..777a67f957a --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/proxy/mqtt-plugin.md @@ -0,0 +1,50 @@ +--- +title: Mqtt 插件 +keywords: ["Mqtt"] +description: Mqtt 插件 +--- + +## 描述 + +* 当前 MQTT 协议实现为 3.1 版本,实现的标识值为 `connect`、`publish`、`subscribe`、`unsubscribe`、`disconnect`、`PingReq`、`PingResp`,以及 QoS 0。 + +* 缺少 retain、Qos(1,2) 实现,以及集群模式。 + +* 具体请看 http://public.dhe.ibm.com/software/dw/webservices/ws-mqtt/mqtt-v3r1.html 内容 + +## 引入 Mqtt 网关的插件支持 + +* 在网关的 pom.xml 文件中引入这些依赖项。 + +```xml + + + org.apache.shenyu + shenyu-spring-boot-starter-plugin-mqtt + ${project.version} + +``` + +## 插件配置 + +* port:Mqtt监听端口。 + +* bossGroupThreadCount:Netty主线程池大小,默认为1。 + +* maxPayloadSize:最大有效载荷大小。 + +* workerGroupThreadCount:Netty子线程池大小,默认为12。 + +* username:用户名,默认为`shenyu`。 + +* password:密码,默认为`shenyu`。 + +* isEncryptPassword:是否加密密码,默认为 false 。 + +* encryptMode:加密模式,目前仅支持MD5,其他加密方式可以自行实现,相关可以参考`org.apache.shenyu.protocol.mqtt.utils.EncryptUtil`这个加密工具类的实现。 + +* leakDetectorLevel:资源泄露检测级别,默认DISABLED。 + +## 注意 + +* Mqtt插件没有选择器配置和规则配置。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/proxy/sofa-plugin.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/proxy/sofa-plugin.md new file mode 100644 index 00000000000..d51a93c4957 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/proxy/sofa-plugin.md @@ -0,0 +1,206 @@ +--- +title: Sofa插件 +keywords: ["sofa"] +description: sofa插件 +--- + +# 1. 概述 + +## 1.1 插件名称 + +- sofa插件 + +## 1.2 适用场景 + +- 协议转换,将 http 协议的请求转换成 sofa 框架协议的服务处理的插件 +- 服务负载均衡 + +## 1.3 插件功能 + +- 将 http 协议的请求转换成 sofa 框架协议 + +## 1.4 插件代码 + +- 核心模块`shenyu-plugin-sofa` +- 核心类`org.apache.shenyu.plugin.sofa.SofaPlugin` + +## 1.5 添加自哪个shenyu版本 + +- 2.3.0 + +# 2. 如何使用插件 + +## 2.1 插件使用流程图 + +![image-20220827001111840](/img/shenyu/plugin/sofa/procedure_chart_zh.png) + +## 2.2 导入pom + +```xml + + com.alipay.sofa + rpc-sofa-boot-starter + ${rpc-sofa-boot-starter.version} + + + org.apache.shenyu + shenyu-spring-boot-starter-client-sofa + ${project.version} + + + guava + com.google.guava + + + +``` + +## 2.3 在客户端项目中配置 + +1. 在 application.yml 中配置 sofa 的配置 + +```yaml +com: + alipay: + sofa: + rpc: + registry-address: zookeeper://127.0.0.1:2181 # consul # nacos + bolt-port: 8888 +shenyu: + register: + registerType: http #zookeeper #etcd #nacos #consul + serverLists: http://localhost:9095 #localhost:2181 #http://localhost:2379 #localhost:8848 + props: + username: admin + password: 123456 + client: + sofa: + props: + contextPath: /sofa + ipAndPort: sofa + appName: sofa + port: 8888 +``` + +2. 在 resources 目录下xml 文件中配置 sofa 服务暴露的服务接口 + +```xml + + + + + + + + + + +``` + +3. 在接口上添加`@ShenyuSofaClient`注解 + +```java +@ShenyuSofaClient("/demo") +@Service +public class SofaClientMultiParamServiceImpl implements SofaClientMultiParamService { + + @Override + @ShenyuSofaClient("/findByIdsAndName") + public SofaSimpleTypeBean findByIdsAndName(final List ids, final String name) { + return new SofaSimpleTypeBean(ids.toString(), "hello world shenyu sofa param findByIdsAndName :" + name); + } +} +``` + +## 2.4 启用插件 + +- 在 `shenyu-admin` --> 基础配置 --> 插件管理-> `sofa` ,设置为开启。 + + ![image-20220827003924276](/img/shenyu/plugin/sofa/enable_sofa_zh.png) + + +## 2.5 配置插件 + +### 2.5.1 配置注册中心参数 + +![image-20220827004626827](/img/shenyu/plugin/sofa/sofa_registry_config_zh.png) + +- `protocol`: 注册中心协议,目前支持 zookeeper、consul、nacos。 +- `register`: 注册中心的服务 IP 和 PORT。 +- `threadpool`:业务线程池类型,有`fixed`、`eager`、`cached`、`limited`和`shared`共5种类型,前面4种与dubbo官方提供的线程池一一对应,不多解释,这里单独说下`shared`,正如其名,`所有proxy插件`共用一个`shared`线程池,这样做的好处是能够减少线程池数量,进而降低内存、提高资源利用率。 +- `corethreads`:业务线程池核心线程数。 +- `threads`:业务线程池最大线程数。 +- `queues`:业务线程池阻塞队列长度,0表示`无界阻塞队列`。 + +### 2.5.2 选择器配置 + +> 流量需要经过选择器匹配。 + +![image-20220827004904249](/img/shenyu/plugin/sofa/selector_config_zh.png) + +- 通过`@ShenyuSofaClient`注解自动配置选择器。 + +### 2.5.3 规则配置 + +> 流量经过选择器匹配成功之后,会进入规则来进行最终的流量匹配。 + +![image-20220827004945226](/img/shenyu/plugin/sofa/rule_config_zh.png) + +- 通过`@ShenyuSofaClient`注解自动配置选择器。 + +### 2.5.4 元数据配置 + +> 当`sofa` 应用客户端接入到`Apache ShenYu`网关时,会自动注册,可以在 `shenyu-admin`后台管理系统的基础配置 `-->` 元数据管理中查看,每一个`sofa`接口方法,都会对应一条元数据。 + +![image-20220827005042417](/img/shenyu/plugin/sofa/metadata_config_zh.png) + +- 应用名称:该条元数据所属的应用名称。 + +- 方法名称:需要调用的方法名。 + +- 路径:`http`请求路径。 + +- 路径描述:对该路径的说明,方便查看。 + +- 参数类型:按照接口的参数类型顺序。 + +- Rpc扩展参数:接口的扩展参数配置,`json`格式。 + + 示例:`{"loadbalance":"hash","retries":3,"timeout":-1}` + + - `loadbalance`:负载均衡策略,当前支持 roundRobin、random 和 hash。 + - `retries`:调用客户端超时失败的重试次数。 + - `timeout`:调用客户端的超时时间。 + +- 服务接口:`sofa`接口的全限定类名。 +- `Rpc`类型:下拉选择 `sofa`。 + +## 2.6 示例 + +### 2.6.1 使用 ShenYu 访问 sofa 服务 + +#### 2.6.1.1 准备工作 + +- 启动 `Zookeeper` 服务注册发现中心 +- 启动 `ShenYu Admin`。 +- 启动 `Shenyu Bootstrap`。 + +#### 2.6.1.2 插件配置 + +- 打开插件,在 `shenyu-admin` --> 基础配置 --> 插件管理-> `sofa` ,设置为开启,并且根据需要调整注册中心配置。 +- 根据实际情况调整 [shenyu-examples-sofa](https://github.com/apache/shenyu/tree/master/shenyu-examples/shenyu-examples-sofa) 项目中 application.yml 配置并启动。 + +#### 2.6.2.6 请求服务并且验证结果 + +![image-20220828012420068](/img/shenyu/plugin/sofa/check_request_zh.png) + +# 3. 如何禁用插件 + +- 在 shenyu-admin --> 基础配置 --> 插件管理 --> 关闭 sofa 插件状态 + +![image-20220827010106265](/img/shenyu/plugin/sofa/close_sofa_zh.png) diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/proxy/spring-cloud-plugin.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/proxy/spring-cloud-plugin.md new file mode 100644 index 00000000000..697d1bdfed8 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/proxy/spring-cloud-plugin.md @@ -0,0 +1,320 @@ +--- +title: Spring Cloud插件 +keywords: ["SpringCloud"] +description: Spring Cloud插件 +--- + + +# 1. 概述 + +## 1.1 插件名称 + +* SpringCloud插件 + +## 1.2 适用场景 + +* 用来将`http协议` 转成 `Spring Cloud协议`。 +* 用于SpringCloud微服务灰度流量控制。 + +## 1.3 插件功能 + +* 将`http协议` 转成 `Spring Cloud协议`。 + +## 1.4 插件代码 + +* 核心模块 `shenyu-plugin-springcloud` + +* 核心类 `org.apache.shenyu.plugin.springcloud.SpringCloudPlugin` + +## 1.5 添加自哪个shenyu版本 + +* 2.4.0 + +# 2. 如何使用插件 + +* 引入相关依赖,开启插件,请参考:[Spring Cloud快速开始](../../quick-start/quick-start-springcloud) 。 + +* `Spring Cloud`应用客户端接入,请参考:[Spring Cloud服务接入](../../user-guide/proxy/spring-cloud-proxy.md) 。 + +## 2.1 插件使用流程图 + +![](/img/shenyu/plugin/plugin_use_zh.jpg) + +## 2.2 导入pom + +* Eureka Registry + +```xml + + org.apache.shenyu + shenyu-spring-boot-starter-plugin-springcloud + ${project.version} + + + + org.springframework.cloud + spring-cloud-starter-netflix-eureka-client + ${eureka-client.version} + + + + org.springframework.cloud + spring-cloud-commons + ${spring-cloud-commons.version} + + + + org.apache.shenyu + shenyu-spring-boot-starter-plugin-httpclient + ${project.version} + +``` + +* Nacos Registry + +```xml + + org.apache.shenyu + shenyu-spring-boot-starter-plugin-springcloud + ${project.version} + + + + com.alibaba.cloud + spring-cloud-starter-alibaba-nacos-discovery + ${nacos-discovery.version} + + + + org.springframework.cloud + spring-cloud-commons + ${spring-cloud-commons.version} + + + + org.apache.shenyu + shenyu-spring-boot-starter-plugin-httpclient + ${project.version} + +``` + +## 2.3 在ShenYu Bootstrap配置SpringCloud + +### 2.3.1 配置SpringCloud的Eureka服务注册发现 + +```yaml +spring: + cloud: + discovery: + enabled: true + +eureka: + client: + enabled: true + serviceUrl: + defaultZone: http://localhost:8761/eureka/ + instance: + prefer-ip-address: true +``` + +### 2.3.2 配置SpringCloud的Nacos服务注册发现 + +```yaml +spring: + cloud: + discovery: + enabled: true + nacos: + discovery: + server-addr: 127.0.0.1:8848 # Spring Cloud Alibaba Dubbo use this. + enabled: true + namespace: ShenyuRegisterCenter +``` + +### 2.3.3 配置SpringCloud插件负载均衡 + +> *注意* +> +> 在ShenYu 2.5.0(包括)之后,ShenYu使用自有的`shenyu-loadbalancer`作为负载均衡客户端,你只需要在springcloud插件的规则配置中配置负载均衡。 +> 如果你没有配置负载均衡,将使用默认的`roundRobin`算法。 +> +> 在ShenYu 2.4.3(包括)之前,ShenYu使用`Ribbon`作为负载均衡客户端,你必须如下配置负载均衡。 + +```yaml +spring: + cloud: + loadbalancer: + ribbon: + enabled: true +``` + +## 2.4 启用插件 + +- 在 `shenyu-admin` --> 基础配置 --> 插件管理-> `springCloud` ,设置为开启。 + + + +## 2.5 配置插件 + +### 2.5.1 插件配置 + +* 你必须配置你的服务注册发现中心并将插件打开。 + +### 2.5.2 选择器和灰度流量配置 + +![](/img/shenyu/plugin/springcloud/selector_zh_2.png) + +* 灰度路由 + +如果您想在springCloud插件中使用灰色路由,可以单击“灰色”按钮。 + +![](/img/shenyu/plugin/springcloud/gray_zh_2.png) + +* 灰度发布可以在发布新版本应用时,自定义控制新版本应用流量比重,渐进式完成新版本应用的全量上线,最大限度地控制新版本发布带来的业务风险,降低故障带来的影响面,同时支持快速回滚。 + +当开启灰度是,网关的负载平衡算法将从当前节点列表中选择一个节点进行路由,并且您可以通过修改节点权重以更改负载平衡算法中节点的权重。 + + + +需要注意的是,如果您的业务实例没有使用`shenyu-client-springcloud`的客户端进行业务注册发现,您应该在当前选择器页面上手动添加节点信息进行灰度路由。 + +* 处理配置详解: + + * `serviceId`:serviceId。 + + * `gray`:启用灰度路由。 + + * `protocol`:协议默认值为'http://'。 + + * `upstreamUrl`: 服务器节点地址。 + + * `weight`: 服务器节点权重。 + + * `status`:true:服务器可用,false:服务器不可用。 + + * `timestamp`:节点的启动时间。 + + * `warmup`:节点的预热时间,参与负载均衡计算。 + + +### 2.5.3 规则配置 + +规则处理,即`handle`字段,是网关对流量完成最终匹配后,可以进行处理的操作。更多信息请参考插件管理中的 [插件处理管理](../../user-guide/admin-usage/plugin-handle-explanation) 。 + +* 使用 `shenyu-client-springcloud` 的规则配置 + +![](/img/shenyu/plugin/springcloud/rule_zh_2.png) + +* 规则配置详解: + + * `timeout`:设置请求超时时间。 + * `loadbalance`:负载均衡算法,有三个可选项:`roundRobin`,`random`,`hash` + +* 未使用 `shenyu-client-springcloud` 的规则配置 + +![](/img/shenyu/plugin/springcloud/rule_zh.png) + +* 规则配置详解: + + * `path`:请求路径。 + * `timeout`:设置请求超时时间。 + +### 2.5.4 SpringCloud服务实例缓存配置 + +你能在`shenyu-bootstrap.yml`文件中修改如下配置: + +```yaml +shenyu: + springCloudCache: + enabled: false +``` + +此配置将帮助您在每次心跳时从springcloud注册中心获取serviceInstance(通过监听springcloud心跳事件) + +* 当您使用nacos或者eureka作为注册中心时,您可以将springcloud serviceInstance缓存设置为`false`。 +* 当您使用zookeeper或者consul作为注册中心时,您可以将springcloud serviceInstance缓存设置为`true`。 + +## 2.6 示例 + +### 2.6.1 使用ShenYu访问SpringCloud服务 + +#### 2.6.1.1 准备工作 + +- 启动 `Eureka` 或 `Nacos` 服务注册发现中心, 如果你使用eureka, 启动 `shenyu-examples-eureka`即可 +- 启动 `ShenYu Admin` +- 启动 `shenyu-examples-springcloud` + +#### 2.6.1.2 插件配置 + +- 在 `shenyu-admin` --> 基础配置 --> 插件管理-> `springCloud` ,设置为开启。 + +- 在`ShenYu Bootstrap`配置服务注册发现中心, 请查看 [2.3 在ShenYu Bootstrap配置SpringCloud](#2.3 在ShenYu Bootstrap配置SpringCloud) + +#### 2.6.1.3 选择器配置 + +![](/img/shenyu/plugin/springcloud/selector_zh_2.png) + +如果你想使用注册到ShenYu的灰度流量,你必须配置灰度路由。 + +![](/img/shenyu/plugin/springcloud/gray_zh_2.png) + +#### 2.6.1.4 规则配置 + +如果你使用`shenyu-client-springcloud`注册服务到`ShenYu`,你可以不用配置规则,如果你想改变规则,请查看[2.5.3 规则配置](#2.5.3 规则配置) + +#### 2.6.1.5 请求服务并且验证结果 + +![](/img/shenyu/plugin/springcloud/springcloud-request.png) + +### 2.6.2 使用ShenYu访问未注册到ShenYu的SpringCloud服务 + +#### 2.6.2.1 准备工作 + +- 启动 `Eureka` 或 `Nacos` 服务注册发现中心, 如果你使用eureka, 启动 `shenyu-examples-eureka`即可 +- 启动 `ShenYu Admin` +- 启动 `shenyu-examples-springcloud` + +#### 2.6.2.2 插件配置 + +- 在 `shenyu-admin` --> 基础配置 --> 插件管理-> `springCloud` ,设置为开启。 + +- 在`ShenYu Bootstrap`配置服务注册发现中心, 请查看 [2.3 在ShenYu Bootstrap配置SpringCloud](#2.3 在ShenYu Bootstrap配置SpringCloud) + +#### 2.6.2.3 选择器配置 + +![](/img/shenyu/plugin/springcloud/selector_zh_2.png) + +如果你想使用未注册到ShenYu的灰度流量,你必须配置灰度流量相关的配置 + +![](/img/shenyu/plugin/springcloud/gray_zh_2.png) + +#### 2.6.2.4 规则配置 + +![](/img/shenyu/plugin/springcloud/rule_zh.png) + +你必须在规则配置中配置`path`字段,`path`字段为你的服务uri,例如:`/springcloud/new/feature/gateway/not`, `timeout`为你的服务允许的超时时间。 + +#### 2.6.2.5 通过配置访问未注册的服务 + +##### 2.6.2.5.1 在请求头使用 `rpc_type`字段进行访问 + +``` +### shengyu getway proxy not support +POST http://localhost:9195/springcloud/new/feature/gateway/not +Accept: application/json +Content-Type: application/json +rpc_type: springCloud +``` + +##### 2.6.2.5.2 在ShenYuAdmin 添加元信息 + +![](/img/shenyu/plugin/springcloud/springcloud_metadata_zh.png) + +#### 2.6.2.6 请求服务并且验证结果 + +![](/img/shenyu/plugin/springcloud/springcloud-request-unregistered.png) + + +# 3. 如何禁用插件 + +- 在 `shenyu-admin` --> 基础配置 --> 插件管理-> `springCloud` ,设置为关闭。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/proxy/tars-plugin.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/proxy/tars-plugin.md new file mode 100644 index 00000000000..af85792d937 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/proxy/tars-plugin.md @@ -0,0 +1,169 @@ +--- +title: Tars插件 +keywords: ["Tars"] +description: Tars插件 +--- + +# 1. 概述 + +## 1.1 插件名称 + +- Tars插件 + +## 1.2 适用场景 + +- 协议转换,将 http 协议的请求转换成 Tars 框架协议的服务处理的插件 +- 服务负载均衡 + +## 1.3 插件功能 + +- 将 http 协议的请求转换成 Tars 框架协议 + +## 1.4 插件代码 + +- 核心模块`shenyu-plugin-tars` +- 核心类`org.apache.shenyu.plugin.tars.TarsPlugin` + +## 1.5 添加自哪个shenyu版本 + +- 2.3.0 + +# 2. 如何使用插件 + +## 2.1 插件使用流程图 + +![produce_chart_zh](/img/shenyu/plugin/tars/produce_chart_zh.png) + +## 2.2 导入pom + +```xml + + org.apache.shenyu + shenyu-spring-boot-starter-client-tars + ${shenyu.version} + +``` + +## 2.3 在客户端项目中配置 + +1. 在 application.yml 中配置 Tars 的配置 + +```yaml +shenyu: + register: + registerType: http #zookeeper #etcd #nacos #consul + serverLists: http://localhost:9095 #localhost:2181 #http://localhost:2379 #localhost:8848 + props: + username: admin + password: 123456 + client: + tars: + props: + contextPath: /tars + appName: tars + port: 21715 + host: 192.168.41.103 # client IP +``` + +2. 在接口上添加`@ShenyuTarsService`和`@ShenyuTarsClient`注解 + +```java +@TarsServant("HelloObj") +@ShenyuTarsService(serviceName = "ShenyuExampleServer.ShenyuExampleApp.HelloObj") +public class HelloServantImpl implements HelloServant { + + @Override + @ShenyuTarsClient("/hello") + public String hello(final int no, final String name) { + return String.format("hello no=%s, name=%s, time=%s", no, name, System.currentTimeMillis()); + } +} +``` + + + +## 2.4 启用插件 + +- 在 `shenyu-admin` --> 基础配置 --> 插件管理-> `tars` ,设置为开启。 + +![enable_tars_zh](/img/shenyu/plugin/tars/enable_tars_zh.png) + +## 2.5 配置插件 + +### 2.5.1 配置插件 + +![plugin_config_zh](/img/shenyu/plugin/tars/plugin_config_zh.png) + +- `multiSelectorHandle`:设置为可以多个选择器处理,在选择器列表可配置多个选择器处理服务。 +- `multiRuleHandle`:设置为可以多个规则处理,在规则列表配置多个处理规则,建议配置为 single rule。 +- `threadpool`:业务线程池类型,有`fixed`、`eager`、`cached`、`limited`和`shared`共5种类型,前面4种与dubbo官方提供的线程池一一对应,不多解释,这里单独说下`shared`,正如其名,`所有proxy插件`共用一个`shared`线程池,这样做的好处是能够减少线程池数量,进而降低内存、提高资源利用率。 +- `corethreads`:业务线程池核心线程数。 +- `threads`:业务线程池最大线程数。 +- `queues`:业务线程池阻塞队列长度,0表示`无界阻塞队列`。 + +### 2.5.2 选择器配置 + +> 流量需要经过选择器匹配。 + +![selector_config_zh](/img/shenyu/plugin/tars/selector_config_zh.png) + +- 通过`@ShenyuTarsClient`注解自动配置选择器。 + +### 2.5.3 规则配置 + +> 流量经过选择器匹配成功之后,会进入规则来进行最终的流量匹配。 + +![rule_config_zh](/img/shenyu/plugin/tars/rule_config_zh.png) + +- 通过`@ShenyuTarsClient`注解自动配置规则。 + +### 2.5.4 元数据配置 + +> 当`Tars` 应用客户端接入到`Apache ShenYu`网关时,会自动注册,可以在 `shenyu-admin`后台管理系统的基础配置 `-->` 元数据管理中查看,每一个`Tars`接口方法,都会对应一条元数据。 + +![metadata_config_zh](/img/shenyu/plugin/tars/metadata_config_zh.png) + +- 应用名称:该条元数据所属的应用名称。 + +- 方法名称:需要调用的方法名。 + +- 路径:`http`请求路径。 + +- 路径描述:对该路径的说明,方便查看。 + +- 参数类型:按照接口的参数类型顺序。 + +- Rpc扩展参数:接口的扩展参数配置,`json`格式。 + + 示例:`{"loadbalance":"hash","retries":3,"timeout":-1}` + + - `loadbalance`:负载均衡策略,当前支持 roundRobin、random 和 hash。 + - `retries`:调用客户端超时失败的重试次数。 + - `timeout`:调用客户端的超时时间。 + +- 服务接口:`Tars`接口的全限定类名。 +- `Rpc`类型:自动注册默认为 `tars`。 + +## 2.6 示例 + +### 2.6.1 使用 ShenYu 访问 Tars 服务 + +#### 2.6.1.1 准备工作 + +- 启动 `ShenYu Admin`。 +- 启动 `Shenyu Bootstrap`。 + +#### 2.6.1.2 插件配置 + +- 打开插件,在 `shenyu-admin` --> 基础配置 --> 插件管理-> `tars` ,设置为开启。 +- 根据实际情况调整 [shenyu-examples-tars](https://github.com/apache/shenyu/tree/master/shenyu-examples/shenyu-examples-tars) 项目中 application.yml 和 ShenyuExampleServer.ShenyuExampleApp.config.conf 文件并启动。 + +#### 2.6.2.6 请求服务并且验证结果 + +![check_request_zh](/img/shenyu/plugin/tars/check_request_zh.png) + +# 3. 如何禁用插件 + +- 在 shenyu-admin --> 基础配置 --> 插件管理 --> 关闭 Tars 插件状态 + +![close_tars_zh](/img/shenyu/plugin/tars/close_tars_zh.png) diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/proxy/tcp-plugin.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/proxy/tcp-plugin.md new file mode 100644 index 00000000000..01483ddb25b --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/proxy/tcp-plugin.md @@ -0,0 +1,149 @@ +--- +title: Tcp插件 +keywords: [ "Tcp" ] +description: Tcp插件 +--- + +# 1. 概述 + +## 1.1 插件名称 + +- TCP插件 + +## 1.2 适用场景 + +- 处理 TCP 协议请求,将其转发到后端其他 TCP 协议的服务 +- 服务负载均衡 + +## 1.3 插件功能 + +* 支持根据配置的 upstream list 做 TCP 代理; +* upstream list 可在 admin 模块自行配置,热同步到 gateway; +* 支持设置请求的负载均衡策略,目前支持 shenyu 负载均衡模块的策略; +* 支持配置开启端口进行监听,可配置 reactor-netty 参数; +* 支持开启多个代理选择器 + +> __注意__: 负载均衡作用与gateway建立连接时,当连接建立,后续的流量继续保持负载均衡模块已经选定的upstream + +## 1.4 插件代码 + +- 核心模块:`shenyu-plugin-tcp` `shenyu-protocol-tcp` + +## 1.5 添加自哪个shenyu版本 + +- 2.6.0 + +# 2. 如何使用插件 + +## 2.1 启用插件 + +- 初次使用时,启动 admin server,在 `shenyu-admin` --> 基础配置 --> 插件管理 中, 搜索 tcp 插件 并且点击“资源”激活 TCP 插件模块 + +![init-tcp-zh](/img/shenyu/plugin/tcp/init_tcp_zh.png) + +- 在 `shenyu-admin` --> 基础配置 --> 插件管理 --> `tcp`,设置为开启 + +![start-tcp-zh](/img/shenyu/plugin/tcp/start_tcp_zh.png) + +## 2.2 配置插件 + +- TCP 插件是以代理选择器(proxy-selector)为单位创建的,因此配置插件即是配置代理选择器的属性。 创建代理选择器时,点击页面的“添加选择器按钮”,在弹出的选择器表单中,即可对选择器属性进行配置: + +![selector_props](/img/shenyu/plugin/tcp/selector_props.png) + + 默认配置如下: + +```json +{ + "loadBalance": "random", + "bossGroupThreadCount": "1", + "workerGroupThreadCount": "12", + "clientMaxConnections": "20", + "clientMaxIdleTimeMs": "30000", + "clientMaxLifeTimeMs": "60000", + "clientPendingAcquireTimeout": "5", + "clientPendingAcquireMaxCount": "5" +} +``` + +- `loadBalanceAlgorithm` : shenyu负载均衡算法,默认为random +- `bossGroupThreadCount` , `workerGroupThreadCount`: +ReactorNetty TcpServer 配置,详情见 `shenyu-protocol-tcp#TcpBootstrapServer#start` +- `clientMaxConnections` , `clientMaxIdleTimeMs` , `clientMaxLifeTimeMs` , `clientPendingAcquireTimeout` , +`clientPendingAcquireMaxCount`: ReactorNetty `ConnectionProvider` 配置,详情见 `shenyu-protocol-tcp#ConnectionContext` + + +用户可以在`shenyu-admin` --> 基础配置 --> 插件处理管理 中,搜索 tcp 插件,对默认配置进行修改编辑: + +![plugin_handle_zh](/img/shenyu/plugin/tcp/plugin_handle_zh.png) + +## 2.3 配置服务发现 + +TCP 插件支持插件级别、选择器级别两种级别的服务发现配置: + +服务发现 详情 见 [discovery-mode](../discovery/discovery-mode.md) + +① 用户点击页面上的“服务发现配置”按钮,便可以在弹出的表单中配置插件级别的服务发现。配置完成后,再次打开表单,可以修改或删除之前的配置。 +插件级别discovery配置后,选择器的discovery设置默认与插件级别保持一致: + +![discovery_config](/img/shenyu/plugin/tcp/discovery_config.png) + +② 如果用户没有配置插件级别的服务发现,在每次创建代理选择器(proxy-selector)时,都可以对该选择器的discovery进行配置: + +![selector_discovery](/img/shenyu/plugin/tcp/selector_discovery.png) + + +目前,TCP 插件支持 Zookeeper 模式和 Local 模式的服务发现。 + +### 2.3.1 Zookeeper 模式 + +- 当服务发现的类型选择zookeeper时,需要填写 Discovery-Zookeeper 配置 培训详情见 [discovery-mode](../discovery/discovery-mode.md) + +- zookeeper模式下,discovery模块会自动监听用户的 zookeeper 注册中心,自动维护 discovery_upstream + +![zookeeper.png](/img/shenyu/plugin/tcp/zookeeper.png) + + +### 2.3.2 Local 模式 + +- 当服务发现的类型选择local时,需要手动填写服务下游列表。如图所示,服务下游列表为可编辑表格, +双击每一个单元格可以进行表格内容的修改: + +![local_selector_zh.png](/img/shenyu/plugin/tcp/local_selector_zh.png) + + +## 2.4 配置选择器 + +- 除了上文中的服务发现配置外,创建选择器时,还需要填写选择器的“基本配置”部分,包括名称与代理端口等。为了提升填写的便捷性, +可以点击“复制选择器”,拷贝已经创建的选择器的部分信息。 + +> __注意__:选择器的名称唯一标识选择器,不能重复 + +![selector_basic.png](/img/shenyu/plugin/tcp/selector_basic.png) + +- 创建完选择器后,选择器以卡片的形式展现,鼠标悬停于卡片上,将会展示选择器的创建时间、更新时间与属性。 +卡片下方有三个图标按钮,从左至右依次为同步、编辑与删除选择器: + +![card_list_zh.png](/img/shenyu/plugin/tcp/card_list_zh.png) + +- 如果当前 admin 的 UpstreamList 与 gateway 出现差异时,可以点击“同步”图标,强制同步到gateway。 + +## 2.5 日志 + +- shenyu-gateway 端口启动log + +![gateway_start_port_log.png](/img/shenyu/plugin/tcp/gateway_start_port_log.png) + +- shenyu-gateway 代理列表同步log + +![gateway_upstream_list.png](/img/shenyu/plugin/tcp/gateway_upstream_list.png) + +## 2.6 示例 + +以代理 redis 为例,使用 `redis-cli -p {forwardPort}` 访问 + +![connection.png](/img/shenyu/plugin/tcp/redis_connection.png) + + + + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/proxy/websocket-plugin.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/proxy/websocket-plugin.md new file mode 100644 index 00000000000..edf99a40655 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/proxy/websocket-plugin.md @@ -0,0 +1,277 @@ +--- +title: Websocket插件 +keywords: ["Websocket"] +description: Websocket插件 +--- + +# 1. 概述 + +## 1.1 插件名称 + +* Websocket 插件 + +## 1.2 适用场景 + +* 转发场景,处理 websocket协议 请求,将其转发到后端其他 websocket 协议的服务 +* 服务负载均衡 + +## 1.3 插件功能 + +* 支持根据 host、uri、query 等请求信息做流量的治理 +* 支持设置请求的负载均衡策略,同时支持服务预热,目前支持三种策略:ip hash(带虚拟节点的一致性哈希)、round-robbin(加权轮询)、random(加权随机) +* 支持设置接口级别请求超时时间 +* 支持设置超时重试次数 + +## 1.4 插件代码 + +* 核心模块 ```shenyu-plugin-websocket``` +* 核心类 ```org.apache.shenyu.plugin.websocket.WebSocketPlugin``` + +## 1.5 添加自哪个shenyu版本 + +- 2.4.3 + +# 2. 如何使用插件 + +## 2.1 插件使用流程图 + +![image-20220725162054383](/img/shenyu/plugin/websocket/procedure_chart_zh.png) + +**名词解释** +- shenyu 网关:包含 shenyu-admin 和 shenyu-bootstrap 服务。 +- 客户端项目:后端真实 websocket 服务 + +**流程解释** +1. 启动 shenyu 网关服务:参照运维部署,启动 shenyu-admin 和 shenyu-bootstrap,确保 shenyu 网关服务正常 +2. 在 shenyu-admin 中启用 websocket 插件:在 shenyu-admin 插件管理的页面中开启 websocket 插件 +3. 配置和启动客户端项目:启动客户端项目(后端真实 websocket 服务),并将服务信息配置到 shenyu 网关中,分为手动配置和自动配置两种方式 +4. 检查转发是否正常:检查转发能否成功 + +## 2.2 启用插件 + +- 在 shenyu-admin --> 基础配置 --> 插件管理 --> websocket 设置为开启。 + +![image-20220724223435359](/img/shenyu/plugin/websocket/enable_websocket_zh.png) + + +## 2.3 配置客户端服务 + +### 2.3.1 手动配置 + +> 在 shenyu-admin 页面上手动配置客户端服务,后端服务不需要任何改动,即可实现 websocket 协议转发 + +1. Websocket 插件中添加选择器 + +![image-20220725142728044](/img/shenyu/plugin/websocket/add_selector_zh.png) + +2. Websocket 插件中添加规则 + +![image-20220725142951481](/img/shenyu/plugin/websocket/add_rule_zh.png) + +3. 启动客户端项目(后端 websocket 服务) + +4. 测试服务转发是否成功 + +- 测试代码见附件5.1 + +![image-20220726222003131](/img/shenyu/plugin/websocket/test_result_en.png) + +### 2.3.2 自动配置 + +> 如果某些场景你需要通过自动配置来减少工作量,可以在后端服务中增加注解,实现自动配置服务到 shenyu 网关中 + +1. 在后端服务项目中的 pom.xml 文件中添加插件 maven 配置。 + +```xml + + org.apache.shenyu + shenyu-spring-boot-starter-plugin-websocket + ${project.version} + +``` + +2. 使用`@ShenyuSpringWebSocketClient`注解,该注解会将 websocket 服务自动注册到 shenyu 网关 +3. 调整插件配置,配置参数详情见 2.4.1 +4. 启动客户端项目(后端 websocket 服务),示例代码见 2.5 示例 +5. 检查 shenyu-admin 页面中插件列表服务注册信息是否注册成功 +6. 测试服务转发是否成功 + +- 测试代码见附件5.1 + +![image-20220726221945414](/img/shenyu/plugin/websocket/test_result_en.png) + +## 2.4 配置插件 + +### 2.4.1 在客户端项目中配置文件中配置接入参数 + +* 客户端接入方式和服务器地址,参数为: `shenyu.register.*`,下面的示例使用了 http 接入方式,目前客户端支持的接入的方式有以下几种:http、zookeeper、etcd、nacos、consul,详细的接入配置参数请参考[客户端接入配置](../../user-guide/property-config/register-center-access.md)。 +* 客户端配置,参数为: `shenyu.client.websocket.*`,包含服务的名称、路由地址以及端口,必须配置 contextPath 的值作为每个服务的路由地址。 + +```yaml +shenyu: + register: + registerType: http + serverLists: http://localhost:9095 + props: + username: admin + password: 123456 + client: + websocket: + props: + contextPath: /ws-annotation + appName: ws-annotation + port: 8001 # 需要和服务端口保持一致 +``` + +### 2.4.2 在 shenyu-admin 配置 websocket 插件的选择器和规则信息 + +使用自动配置的方式,在客户端启动之后会在 shenyu-admin -> 插件列表 -> Proxy -> Websocket 自动注册[选择器和规则](../../user-guide/admin-usage/selector-and-rule.md)信息。 +![image-20220725222628106](/img/shenyu/plugin/websocket/auto_register_zh.png) + +#### 2.4.2.1 选择器的配置 + +Websocket 选择器示例,通用选择器配置请参考[选择器和规则](../../user-guide/admin-usage/selector-and-rule.md)。 + +![image-20220725222913298](/img/shenyu/plugin/websocket/config_selectors_zh.png) + +##### 2.4.2.1.1 选择器处理信息配置 + +- `host`:填写 `localhost`,该字段暂时没使用。 +- `ip:port`:`ip` 与端口,这里填写你真实服务的 `ip` + 端口。 +- `protocol`::`ws` 协议,不填写默认为:`ws://` +- `startupTime`: 启动时间,单位毫秒。 +- `weight`:负载均衡权重,服务启动自动注册的默认值为 50。 +- `warmupTime`:预热时间,单位毫秒,在预热中的服务器会计算瞬时权重,计算值会小于实际配置的权重,以保护刚启动的服务器,服务启动注册的默认值为 10。举个例子预热时间 100 毫秒,目前启动了 50 毫秒,配置的权重 50, 实际的权重是 25。 +- `status`:开启或关闭,开始状态此处理器才有效。 + +#### 2.4.2.2 规则的配置 + +Websocket 规则示例,通用规则配置请参考[选择器和规则](../../user-guide/admin-usage/selector-and-rule.md)。 + +![image-20220725223225388](/img/shenyu/plugin/websocket/config_rules_zh.png) + +##### 2.4.2.2.1 规则处理信息配置 + +- `loadStrategy`:如果 websocket 客户端是一个集群,Apache ShenYu 网关调用时采取哪种负载均衡策略,当前支持 roundRobin、random 和 hash。 +- `timeout`:调用客户端的超时时间。 +- `retryCount`:调用客户端超时失败的重试次数。 + +## 2.5 示例 + +### 2.5.1 Spring Annotation Websocket使用示例 + +[shenyu-example-spring-annotation-websocket](https://github.com/apache/shenyu/tree/master/shenyu-examples/shenyu-examples-websocket/shenyu-example-spring-annotation-websocket) + +### 2.5.2 Spring Native Websocket 使用示例 + +[shenyu-example-spring-native-websocket](https://github.com/apache/shenyu/tree/master/shenyu-examples/shenyu-examples-websocket/shenyu-example-spring-native-websocket) + +### 2.5.3 Spring Reactive Websocket 使用示例 + +[shenyu-example-spring-reactive-websocket](https://github.com/apache/shenyu/tree/master/shenyu-examples/shenyu-examples-websocket/shenyu-example-spring-reactive-websocket) + +# 3. 如何禁用插件 + +- 在 shenyu-admin --> 基础配置 --> 插件管理 --> 关闭 websocket 插件状态 + +![image-20220725141221131](/img/shenyu/plugin/websocket/close_websocket_zh.png) + +# 4. 常见问题 + +**4.1 websocket 建立连接出现 1002 错误** + +可能原因:客户端服务不正常,shenyu 网关和客户端项目不能建立正常连接,请检查网关到客户端的网络、客户端服务是否正常 + +**4.2 多个客户端服务在 websocket 选择器中展示为空** + +可能原因:基础配置-> 插件管理 -> websocket -> multiSelectorHandle 选项选择 multiple handle + +![image-20220726222250136](/img/shenyu/plugin/websocket/questions_multiSelectorHandle_zh.png) + +# 5. 附件 + +## 5.1 websocket调试代码 + +- 创建一个名为 websocket.html 的文件,复制下面的代码到文件中 +- 使用谷歌浏览器打开 websocket.html + +```html + + + + + Shenyu WebSocket Test + + + +
+
+ + +
+
+ + + +``` diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/security/_category_.json b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/security/_category_.json new file mode 100644 index 00000000000..5ad8cb287a1 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/security/_category_.json @@ -0,0 +1,4 @@ +{ + "label": "安全性", + "position": 4 +} diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/security/casdoor.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/security/casdoor.md new file mode 100644 index 00000000000..a3b09f5d30b --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/security/casdoor.md @@ -0,0 +1,72 @@ +--- +title: Casdoor插件 +keywords: ["Casdoor"] +description: Casdoor插件 +--- + +ShenYu 有Casdoor插件去使用Casdoor + +## 第一步.部署Casdoor + +首先,我们需要部署Casdoor. + +我们可以参考Casdoor官方文档去部署它. + +在成功部署之后,我们需要确保: + +* Casdoor服务成功在 **http://localhost:8000**上运行 + +* 打开你喜爱的浏览器浏览 **http://localhost:7001**,你可以看到Casdoor的登陆页面 + +* 输入`admin`和`123`去测试登录是否成功 + + 登陆成功之后,我们就可以使用casdoor. + +## 第二步.设置Casdoor应用 + +### 1.创建或应用一个存在的组织 + +### 2.添加我们的回调url + + ![casdoor_config](/img/shenyu/plugin/casdoor/casdoor_config.png) + +### 3.在证书的编辑页面,我们能看到我们的`Certificate` + + ![casdoor_cert](/img/shenyu/plugin/casdoor/casdoor_cert.png) + +## 第三步.运用Casdoor插件在Shenyu + +### 1.设置Casdoor插件在Shenyu + + ![casdoor_configPlugin](/img/shenyu/plugin/casdoor/casdoor_configPlugin.png) + +注意:因为Shenyu只有单行输入框所以我们需要增加\n在每一行的证书. + + ![casdoor_cert2](/img/shenyu/plugin/casdoor/casdoor_cert2.png) + +我们可以在复制他们并将它们粘贴到Shenyu的Casdoor配置中的certificate这一项中 + +**我们不需要保存我们加\n的内容在Casdoor的证书设置处**,因为这只是为了复制方便. + +#### 2.设置Shenyu Casdoor的插件配置 + + ![casdoor_casdoor](/img/shenyu/plugin/casdoor/casdoor_casdoor.png) + +​我们可以设置你所拥有的casdoor配置在Shenyu配置中 + +### 3.得到服务和运用 + +#### 3.1 直接访问页面 + + ![casdoor_faillogin](/img/shenyu/plugin/casdoor/casdoor_faillogin.png) + +#### 3.2 使用Casdoor登录 + + ![casdoor_login](/img/shenyu/plugin/casdoor/casdoor_login.png) + ![casdoor_successlogin](/img/shenyu/plugin/casdoor/casdoor_successlogin.png) + +#### 3.3携带token在Headers,你可以访问该页面 + + ![casdoor_token](/img/shenyu/plugin/casdoor/casdoor_token.png) + +#### 3.4 我们可以保存name,id和organization在Headers以至于你可以运用他们在下一次 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/security/cryptor-request-plugin.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/security/cryptor-request-plugin.md new file mode 100644 index 00000000000..dcbb1a55d8f --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/security/cryptor-request-plugin.md @@ -0,0 +1,64 @@ +--- +title: CryptorRequest 插件 +keywords: ["CryptorRequest"] +description: CryptorRequest 插件 +--- + +## 说明 + +* `cryptorRequest` 插件是通过 `fieldNames` 去匹配 `requestBody` 里面的参数进行 `解密` 处理,替换当前 `requestBody` 内容。 + +## 插件设置 + +1. 在 `shenyu-admin` --> 基础配置 --> 插件管理 --> `cryptorRequest` 设置为开启。 + + + +2. 打开 `selector` 配置需要匹配的流量。 + +3. 打开 `selector` 对应的 `Rules` 配置。 + + + +* strategyName: 解密算法名称。当前基于 shenyu 的 SPI 机制,可自定义加解密算法, + 需要实现 `org.apache.shenyu.plugin.cryptor.strategy.CryptorStrategy` 接口。 + + 同时找到 `resources/META-INF/shenyu/` 底下的 `org.apache.shenyu.plugin.cryptor.strategy.CryptorStrategy` 文件, + 写上算法名称以及实现的 `CryptorStrategy` 接口的 class 的包名。 + +* fieldNames: 匹配的参数名,支持解析多层次的 json 格式匹配,使用 `.` 分割,例如 data.id 。 + +```json5 + { + data: { + "id": "" + } + } +``` + +* decryptKey: 密钥,用于解密数据。 + +* encryptKey: 密钥,用于加密数据。 + +* way: 选择加密或解密。 + +## 插件使用 + +* 在网关的 `pom.xml` 文件中添加 `cryptorRequest` 的支持。 + +```xml + + + org.apache.shenyu + shenyu-spring-boot-starter-plugin-cryptor + ${project.version} + + +``` + +## 场景 + +防互联网黑产,恶意获取数据。提高数据安全性。 + + + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/security/cryptor-response-plugin.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/security/cryptor-response-plugin.md new file mode 100644 index 00000000000..1f530ae3ca9 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/security/cryptor-response-plugin.md @@ -0,0 +1,64 @@ +--- +title: CryptorResponse 插件 +keywords: ["CryptorResponse"] +description: CryptorResponse 插件 +--- + +## 说明 + +* `CryptorResponse` 插件是通过 `fieldNames` 去匹配 `responseBody` 里面的参数进行 `加密` 处理,替换当前 `fieldNames` 对应内容。 + +## 插件设置 + +1. 在 `shenyu-admin` --> 基础配置 --> 插件管理 --> `cryptorResponse` 设置为开启。 + + + +2. 打开 `selector` 配置需要匹配的流量。 + +3. 打开 `selector` 对应的 `Rules` 配置。 + + + +* strategyName: 解密算法名称。当前基于 shenyu 的 SPI 机制,可自定义加解密算法, + 需要实现 `org.apache.shenyu.plugin.cryptor.strategy.CryptorStrategy` 接口。 + + 同时找到 `resources/META-INF/shenyu/` 底下的 `org.apache.shenyu.plugin.cryptor.strategy.CryptorStrategy` 文件, + 写上算法名称以及实现的 `CryptorStrategy` 接口的 class 的包名。 + +* fieldNames: 匹配的参数名,支持解析多层次的 json 格式匹配,使用 `.` 分割,例如 data.id 。 + +```json5 + { + data: { + "id": "" + } + } +``` + +* decryptKey: 密钥,用于解密数据。 + +* encryptKey: 密钥,用于加密数据。 + +* way: 选择加密或解密。 + +## 插件使用 + +* 在网关的 `pom.xml` 文件中添加 `cryptorResponse` 的支持。 + +```xml + + + org.apache.shenyu + shenyu-spring-boot-starter-plugin-cryptor + ${project.version} + + +``` + +## 场景 + +防互联网黑产,恶意获取数据。提高数据安全性。 + + + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/security/jwt-plugin.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/security/jwt-plugin.md new file mode 100644 index 00000000000..ce594023d9b --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/security/jwt-plugin.md @@ -0,0 +1,157 @@ +--- + +title: JWT插件 +keywords: ["JWT"] +description: JWT插件 +---------------- + +# 1.概述 + +## 1.1 插件名称 + +* `jwt` 插件 + +## 1.2 适用场景 + +* 需要在网关统一鉴权。 + + +## 1.3 插件功能 + +* `jwt` 插件,是针对 `http` 请求头的 `token`属性或者是 `authorization` 属性携带值进行鉴权判断,兼容 `OAuth2.0` 。 + +## 1.4 插件代码 + +* 核心模块为 `shenyu-plugin-jwt`. +* 核心类为 `org.apache.shenyu.plugin.jwt.JwtPlugin`. + +## 1.5 添加自哪个ShenYu版本 + +* 自从 ShenYu 2.4.0 + +# 2.如何使用插件 + +## 2.1 插件使用流程图 + +![](/img/shenyu/plugin/plugin_use_zh.jpg) + +## 2.2 导入pom + +```xml + + org.apache.shenyu + shenyu-spring-boot-starter-plugin-jwt + ${project.version} + +``` + +## 2.3 启用插件 + +- 在 `shenyu-admin` 基础配置 --> 插件管理 --> `jwt` ,设置为开启。 + +## 2.4 配置插件 + +### 2.4.1 Config plugin in ShenYu-Admin + +* 在ShenYu-Admin配置jwt插件的私钥,该私钥必须大于256位 。 +* `secretKey` : 该私钥为使用jwt时生成token,并且他是必须的。 + +![](/img/shenyu/plugin/jwt/jwt-plugin-config-zh.jpg) + +### 2.4.2 Selector config + +* 插件选择器和规则的配置请查看: [插件和规则配置](../../user-guide/admin-usage/selector-and-rule.md). + +### 2.4.3 Rule Config + +![](/img/shenyu/plugin/jwt/jwt-plugin-rule-handle-zh.jpg) + +* convert是jwt的转化 +* jwtVal: jwt 请求体的名称 +* headerVal: jwt请求头的名称 + +自定义转化算法请查看:[自定义JWT插件转化算法](../../developer/custom-jwt-covert-algorithm.md) + +## 2.5 示例 + +### 2.5.1 使用jwt插件进行权限认证 + +#### 2.5.1.1 配置jwt插件 + +![](/img/shenyu/plugin/jwt/jwt-plugin-config-zh.jpg) + +#### 2.5.1.2 配置选择器 + +![](/img/shenyu/plugin/jwt/jwt-plugin-selector-config-zh.jpg) + +#### 2.5.1.3 配置规则 + +![](/img/shenyu/plugin/jwt/jwt-plugin-rule-handle-zh.jpg) + +#### 2.5.1.4 在网页中生成jwt token + +* 在你的浏览器中打开 `https://jwt.io/` , 并且填充对应的参数 。 +* 在 `https://jwt.io/` 的页面配置jwt请求头。 +* 在 `https://jwt.io/` 的页面配置jwt参数体。 +* 在 `https://jwt.io/` 的页面配置jwt签名参数。 + +![](/img/shenyu/plugin/jwt/jwt-web.jpg) + +#### 2.5.1.5 使用Java代码生成jwt token + +```java +public final class JwtPluginTest { + + public void generateJwtCode() { + final String secreteKey = "shenyu-test-shenyu-test-shenyu-test"; + Map map = new HashMap<>(); + map.put("id", "1"); + map.put("name", "xiaoming"); + Date date = new Date(); + date.setTime(1655524800000L); + String token = Jwts.builder() + .setIssuedAt(date) + .setExpiration(new Date()) + .setClaims(map) + .signWith(Keys.hmacShaKeyFor(secreteKey.getBytes(StandardCharsets.UTF_8)), SignatureAlgorithm.HS256) + .compact(); + System.out.println(token); + } +} +``` + +#### 2.5.1.6 请求服务 + +##### 2.5.1.6.1 使用token方式请求服务 + +* 在你的请求头中附带 `token: eyJhbGciOiJIUzI1NiJ9.eyJuYW1lIjoieGlhb21pbmciLCJpZCI6IjEifQ.LdRzGlB49alhq204chwF7pf3C0z8ZpuowPvoQdJmSRw` 字段并发起请求。 + +##### 2.5.1.6.2 使用认证方式请求服务 + +* 在你的请求头中附带 `Authorization: Bearer eyJhbGciOiJIUzI1NiJ9.eyJuYW1lIjoieGlhb21pbmciLCJpZCI6IjEifQ.LdRzGlB49alhq204chwF7pf3C0z8ZpuowPvoQdJmSRw` 并发起请求。 + +#### 2.5.1.7 验证请求结果 + +* 错误的签名 + +``` +{ + "code": 401, + "message": "Illegal authorization" +} +``` + +* 正确的签名 + +``` +{ + "id": "123", + "name": "hello world save order" +} +``` + +# 3.如何禁用插件 + +* 在 `shenyu-admin` 基础配置 --> 插件管理 --> `jwt` ,设置为关闭。 + +![](/img/shenyu/plugin/jwt/jwt-plugin-close_zh.jpg) diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/security/oauth2-plugin.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/security/oauth2-plugin.md new file mode 100644 index 00000000000..9840f916ebe --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/security/oauth2-plugin.md @@ -0,0 +1,57 @@ +--- +title: OAuth2插件 +keywords: ["OAuth2"] +description: OAuth 2插件 +--- + +## 说明 + +- `OAuth2` 插件使用 `Webflux OAuth2` 实现,用于支持 `OAuth` 协议。 + +## 插件设置 + +请参考运维部署的内容,选择一种方式启动`shenyu-admin`。比如,通过 [本地部署](../../deployment/deployment-local) 启动`Apache ShenYu`后台管理系统。 + +* 在 `shenyu-admin` 基础配置 --> 插件管理 --> `oauth2` ,设置为开启。如果用户不想使用此功能,请在 `admin` 后台停用此插件。 + + + +## 插件使用 + +- 在网关的pom文件中添加`oauth2`的支持 + +```xml + + + org.apache.shenyu + shenyu-spring-boot-starter-plugin-oauth2 + ${project.version} + + + +``` + +- 在`shenyu-bootstrap`模块配置`oauth2` + +```yml + +spring: + security: + oauth2: + client: + registration: + <这里填入你的 client-registration-id>: + client-id: <这里填入你的 client-id> + client-secret: <这里填入你的 client-secret> + # 下面这部分是授权服务器的配置 + provider: + <这里填入你的 client-registration-id>: + authorization-uri: <这里填入你的 authorization-uri> + token-uri: <这里填入 access-token-uri> + user-info-uri: <这里填入 user-info-uri> + jwk-set-uri: <这里填入 jwk-set-uri> +``` + +- 在网关的配置文件中配置 `spring.security.oauth2` 的相关配置,详细配置说明可参考 [Spring Webflux OAuth2](https://docs.spring.io/spring-security/site/docs/current/reference/html5/#webflux-oauth2) +- 配置选择器和规则作为您需要 `OAuth2` 授权的请求地址,默认放行所有请求。关于选择器和规则配置的更多说明,请参考:[选择器和规则管理](../../user-guide/admin-usage/selector-and-rule) + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/security/sign-plugin.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/security/sign-plugin.md new file mode 100644 index 00000000000..17292f1be32 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/security/sign-plugin.md @@ -0,0 +1,525 @@ +--- +title: Sign插件 +keywords: ["sign"] +description: sign插件 +--- + + +# 1. 概述 + +## 1.1 插件名称 + +* Sign插件 + +## 1.2 适用场景 + +* 支持请求头进行鉴权 +* 支持请求体进行鉴权 + +## 1.3 插件功能 + +* 用来对请求进行签名认证 + +## 1.4 插件代码 + +* 核心模块: `shenyu-plugin-sign` + +* 核心类: `org.apache.shenyu.plugin.sign.SignPlugin` + +## 1.5 添加自哪个shenyu版本 + +* ShenYu 2.4.0 + +# 2. 如何使用插件 + +## 2.1 插件使用流程图 + +![](/img/shenyu/plugin/plugin_use_zh.jpg) + +## 2.2 导入pom + +* 在网关的 `pom.xml` 文件中添加 `sign` 的支持。 + +```xml + + + org.apache.shenyu + shenyu-spring-boot-starter-plugin-sign + ${project.version} + + +``` + +## 2.3 启用插件 + +- 在 `shenyu-admin` 基础配置 --> 插件管理 --> `sign` ,设置为开启。 + +## 2.4 插件的鉴权配置(1.0.0) + +### 2.4.1 AK/SK配置 + +#### 2.4.1.1 说明 + +- 管理和控制经过 `Apache ShenYu` 网关的请求的权限。 +- 生成的 `AK/SK` ,配合 `sign` 插件使用,实现基于`URI`级别的精准权限管控。 + +#### 2.4.1.2 使用教程 + +第一步,我们可以直接在 `基础配置` --> `认证管理` 新增一条认证信息 。 + + + +第二步,配置这条认证信息 。 + + + +- 应用名称:这个账号关联的应用名称,可手动填写或下拉选择(数据来自元数据管理中配置的应用名称)。 +- 手机号:仅作为信息记录,在shenyu中无实际使用逻辑。 +- APP参数:当请求的context path与应用名称相同时,向header中添加该值,键为 `appParam`。 +- 用户ID:给该用户取一个名字,仅作为信息记录,在shenyu中无实际使用逻辑。 +- 拓展信息:仅作为信息记录,在shenyu中无实际使用逻辑。 +- 路径认证:开启后,该账号仅允许访问以下配置的资源路径。 +- 资源路径:允许访问的资源路径,支持路径匹配,如 `/order/**` 。 + +点击确认后,生成一条认证信息,该信息包含 `AppKey` 和 `加密秘钥` ,即 `Sign` 插件中的 `AK/SK` 。 + +#### 2.4.1.3 路径操作 + +对已创建的认证信息,可以在认证信息列表的末尾进行 `路径操作` 。 + + + +- 左侧为可配置的路径列表,右侧为允许该账号访问的路径列表 。 +- 勾选资源路径,点击中间的 `>` 或 `<` 将勾选的数据移动到对应列表中 。 +- 左侧可配置路径列表可在账号信息行末尾点击 `编辑`,在弹框中的 `资源路径` 中进行添加 。 + +### 2.4.2 网关技术实现 + +* 采用 `AK/SK` 鉴权技术方案。 +* 采用鉴权插件,责任链的模式来完成。 +* 当鉴权插件开启,并配置所有接口鉴权时候生效。 + +### 2.4.3 鉴权使用指南 + +* 第一步:AK/SK由网关来进行分配,比如分配给你的AK为: `1TEST123456781` SK为:`506EEB535CF740D7A755CB4B9F4A1536` + +* 第二步:确定好你要访问的网关路径 比如 `/api/service/abc` + +* 第三步:构造参数(以下是通用参数) + +| 字段 | 值 | 描述 | +| -------- | -----: | :----: | +| timestamp | 当前时间戳(String类型) | 当前时间的毫秒数(网关会过滤掉5分钟之前的请求) | +| path | /api/service/abc | 就是你需要访问的接口路径(根据你访问网关接口自己变更) | +| version | 1.0.0 | 当前鉴权算法为1.0.0 | + +对上述3个字段进行 `key` 的自然排序,然后进行字段与字段值拼接最后再拼接上 `SK` ,代码示例。 + +#### 2.4.3.1 无请求体的签名参数验证 + +第一步:首先构造一个 `Map` 。 + +```java +Map map = Maps.newHashMapWithExpectedSize(3); +//timestamp为毫秒数的字符串形式 String.valueOf(LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli()) +map.put("timestamp","1571711067186"); //值应该为毫秒数的字符串形式 +map.put("path", "/api/service/abc"); +map.put("version", "1.0.0"); +``` + +第二步:进行 `Key` 的自然排序,然后 `Key`,`Value`值拼接最后再拼接分配给你的 `SK`。 + +```java +List storedKeys = Arrays.stream(map.keySet() + .toArray(new String[]{})) + .sorted(Comparator.naturalOrder()) + .collect(Collectors.toList()); +final String sign = storedKeys.stream() + .map(key -> String.join("", key, map.get(key))) + .collect(Collectors.joining()).trim() + .concat("506EEB535CF740D7A755CB4B9F4A1536"); +``` + +* 你得到的 `sign` 值应该为:`path/api/service/abctimestamp1571711067186version1.0.0506EEB535CF740D7A755CB4B9F4A1536` + +第三步:进行 `MD5` 加密后转成大写。 + +```java +DigestUtils.md5DigestAsHex(sign.getBytes()).toUpperCase() +``` + +* 最后得到的值为:`A021BF82BE342668B78CD9ADE593D683` + +#### 2.4.3.2 有请求体,请求头的签名参数验证 + +第一步: 首先构造一个 `Map` 。并且该`map`必须存储请求体的每个节点信息 + +```java + + Map map = Maps.newHashMapWithExpectedSize(3); + //timestamp is string format of millisecond. String.valueOf(LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli()) + map.put("timestamp","1660659201000"); // Value should be string format of milliseconds + map.put("path", "/http/order/save"); + map.put("version", "1.0.0"); + // if your request body is:{"id":123,"name":"order"} + map.put("id", "1"); + map.put("name", "order") +``` + +第二步:进行 `Key` 的自然排序,然后 `Key`,`Value`值拼接最后再拼接分配给你的 `SK`。 + +```java +List storedKeys = Arrays.stream(map.keySet() + .toArray(new String[]{})) + .sorted(Comparator.naturalOrder()) + .collect(Collectors.toList()); +final String sign = storedKeys.stream() + .map(key -> String.join("", key, map.get(key))) + .collect(Collectors.joining()).trim() + .concat("2D47C325AE5B4A4C926C23FD4395C719"); +``` + +* 你得到的 `sign` 值应该为:`id123nameorderpath/http/order/savetimestamp1660659201000version1.0.02D47C325AE5B4A4C926C23FD4395C719` + +第三步:进行 `MD5` 加密后转成大写。 + +```java +DigestUtils.md5DigestAsHex(sign.getBytes()).toUpperCase() +``` + +* 最后得到的值为: `35FE61C21F73E9AAFC46954C14F299D7`. + +### 2.4.4 请求网关 + +* 假如你访问的路径为:`/api/service/abc`。 + +* 访问地址 :http:网关的域名`/api/service/abc`。 + +* 设置`header`头,`header`头参数为: + +| 字段 | 值 | 描述 | +| -------- | -----: | :----: | +| timestamp | `1571711067186` | 上述你进行签名的时候使用的时间值 | +| appKey | `1TEST123456781` | 分配给你的AK值 | +| sign | `A90E66763793BDBC817CF3B52AAAC041` | 上述得到的签名值 | +| version | `1.0.0` | 写死,就为这个值 | + +* 签名插件会默认过滤 `5` 分钟之前的请求 + +* 如果认证不通过会返回 `code` 为 `401`, `message` 可能会有变动。 + +```json +{ + "code": 401, + "message": "sign is not pass,Please check you sign algorithm!", + "data": null +} +``` + +### 2.4.5 插件配置 + +![](/img/shenyu/plugin/sign/sign_open_zh.jpg) + +### 2.4.6 选择器配置 + +![](/img/shenyu/plugin/sign/selector-zh.png) + +* 只有匹配的请求,才会进行签名认证。 + +* 插件选择器和规则的配置请查看: [插件和规则配置](../../user-guide/admin-usage/selector-and-rule.md). + +### 2.4.7 规则配置 + +![](/img/shenyu/plugin/sign/rule-en.png) + +* close(signRequestBody): 仅使用请求头生成签名 +* open(signRequestBody): 使用请求头、请求体共同生成签名 + +## 2.5 插件的鉴权配置(2.0.0) + +此鉴权算法是2.0.0版本,和版本1.0.0只有**鉴权使用指南**和**请求网关**有所不同,其余皆相同。 + +### 2.5.1 鉴权使用指南 + +​ 版本2.0.0鉴权算法,主要是根据算法生成一个`Token`,发送请求的时候,请求头参数`ShenYu-Authorization`放入这个`Token`值。为了与版本1.0.0作出区分,保留了请求头的version参数,此时它的值应为`2.0.0`。 + +#### 2.5.1.1 准备工作 + +前两步骤与此前1.0.0相同: + +* 第一步:AK/SK由网关来进行分配,比如分配给你的AK为: `1TEST123456781` SK为:`506EEB535CF740D7A755CB4B9F4A1536` +* 第二步:确定好你要访问的网关路径 比如 `/api/service/abc` + +#### 2.5.1.2 Token生成 + +* 构造计算参数 + + 构造json参数parameters: + + ```json + { + "alg":"MD5", + "appKey":"506EEB535CF740D7A755CB4B9F4A1536", + "timestamp":"1571711067186" + } + ``` + + **alg**: 签名算法(结果统一为大写的HEX字符串) + + + MD5: MD5-HASH(data+key) + + HMD5:HMAC-MD5 + + HS256:HMAC-SHA-256 + + HS512:HMAC-SHA-512 + + **appKey**:appKey,用于查询匹配密钥 + + **timestamp**:时间戳,长度13 + + + +* 签名值计算 + + 生成签名值`signature`,算法使用的是alg参数中的签名算法 + + ```tex + signature = sign( + base64Encoding(parameters) + Relative URL + Body*, + secret + ); + * indicate Optional , it depends on config + Relative URL = path [ "?" query ] eg: /apache/shenyu/pulls?name=小明 + ``` + + **sign**: `parameters`参数中对应的签名算法 + + **Relative URL:**相对URL,Path加上query的部分,(不包含fragment,服务端收不到)。 + + **Body:**body为可选项,依赖Handler配置 + + **secret:**`parameters`中appkey所对应的密钥 + +* 生成Token + + > token = base64Encoding(parameters) + '.' + base64Encoding(signature) + + 把Token放入到请求头`ShenYu-Authorization`参数即可。 + +详细计算示例请看示例章节。 + +### 2.5.2请求网关 + +| 字段 | 值 | 描述 | +| ------------- | ------- |----------------------------------------------| +| ShenYu-Authorization | Token | 上述算法计算得到的Token值 | +| version | `2.0.0` | 写死,就为这个值 | + +>请使用的Authorization字段的用户尽快更换为ShenYu-Authorization,避免与应用Authorization冲突 + +## 2.6 示例 + +### 2.6.1 使用sign插件进行签名验证(1.0.0) + +#### 2.6.1.1 插件配置 + +![](/img/shenyu/plugin/sign/sign_open_zh.jpg) + +#### 2.6.1.2 选择器配置 + +![](/img/shenyu/plugin/sign/example-selector-zh.png) + +#### 2.6.1.3 规则配置 + +![](/img/shenyu/plugin/sign/example-rule-zh.png) + +#### 2.6.1.4 添加AppKey/SecretKey + +![](/img/shenyu/plugin/sign/example-sign-auth-zh.png) + +#### 2.6.1.5 Request Service and check result + +* 构造请求参数,请查看`Authentication Guide`目录, + +```java +public class Test1 { + public static void main(String[] args) { + Map map = Maps.newHashMapWithExpectedSize(3); + //timestamp为毫秒数的字符串形式 String.valueOf(LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli()) + map.put("timestamp","1660658725000"); //值应该为毫秒数的字符串形式 + map.put("path", "/http/order/save"); + map.put("version", "1.0.0"); + + List storedKeys = Arrays.stream(map.keySet() + .toArray(new String[]{})) + .sorted(Comparator.naturalOrder()) + .collect(Collectors.toList()); + final String sign = storedKeys.stream() + .map(key -> String.join("", key, map.get(key))) + .collect(Collectors.joining()).trim() + .concat("2D47C325AE5B4A4C926C23FD4395C719"); + System.out.println(sign); + + System.out.println(DigestUtils.md5DigestAsHex(sign.getBytes()).toUpperCase()); + } +} +``` + +* 无请求体签名: `path/http/order/savetimestamp1571711067186version1.0.02D47C325AE5B4A4C926C23FD4395C719` +* 无请求体签名结果: `9696D3E549A6AEBE763CCC2C7952DDC1` + +![](/img/shenyu/plugin/sign/result.png) + +```java +public class Test2 { + public static void main(String[] args) { + Map map = Maps.newHashMapWithExpectedSize(3); + //timestamp为毫秒数的字符串形式 String.valueOf(LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli()) + map.put("timestamp","1660659201000"); //值应该为毫秒数的字符串形式 + map.put("path", "/http/order/save"); + map.put("version", "1.0.0"); + map.put("id", "123"); + map.put("name", "order"); + + List storedKeys = Arrays.stream(map.keySet() + .toArray(new String[]{})) + .sorted(Comparator.naturalOrder()) + .collect(Collectors.toList()); + final String sign = storedKeys.stream() + .map(key -> String.join("", key, map.get(key))) + .collect(Collectors.joining()).trim() + .concat("2D47C325AE5B4A4C926C23FD4395C719"); + System.out.println(sign); + + System.out.println(DigestUtils.md5DigestAsHex(sign.getBytes()).toUpperCase()); + } +} +``` + +* 有请求体签名为:`id123nameorderpath/http/order/savetimestamp1660659201000version1.0.02D47C325AE5B4A4C926C23FD4395C719` +* 附带请求体签名结果:`35FE61C21F73E9AAFC46954C14F299D7` + +![](/img/shenyu/plugin/sign/result-with-body.png) + + + +### 2.6.2 使用sign插件进行签名验证(2.0.0) + +所有配置部分皆相同,我们直接看计算请求头的参数部分和发送请求部分 + +#### 2.6.2.1 Request Service and check result + ++ 算法实现 + + 假定我们使用的签名算法名称为MD5,按照前面的算法就是把data数据和key进行拼接,然后进行hash计算。 + + 现在我们按照上面描述进行算法实现。 + + + + ```java + private static String sign(final String signKey, final String base64Parameters, final URI uri, final String body) { + + String data = base64Parameters + + getRelativeURL(uri) + + Optional.ofNullable(body).orElse(""); + + return DigestUtils.md5Hex(data+signKey).toUpperCase(); + } + + private static String getRelativeURL(final URI uri) { + if (Objects.isNull(uri.getQuery())) { + return uri.getPath(); + } + return uri.getPath() + "?" + uri.getQuery(); + } + ``` + ++ 不包含请求体校验演示 + + ```java + public static void main(String[] args) { + + String appSecret = "2D47C325AE5B4A4C926C23FD4395C719"; + + URI uri = URI.create("/http/order/save"); + + String parameters = JsonUtils.toJson(ImmutableMap.of( + "alg","MD5", + "appKey","BD7980F5688A4DE6BCF1B5327FE07F5C", + "timestamp","1673708353996")); + + String base64Parameters = Base64.getEncoder() + .encodeToString(parameters.getBytes(StandardCharsets.UTF_8)); + + String signature = sign(appSecret,base64Parameters,uri,null); + + String Token = base64Parameters+"."+signature; + + System.out.println(Token); + + } + ``` + + Token的计算结果为 + + ```tex + eyJhbGciOiJNRDUiLCJhcHBLZXkiOiJCRDc5ODBGNTY4OEE0REU2QkNGMUI1MzI3RkUwN0Y1QyIsInRpbWVzdGFtcCI6IjE2NzM3MDgzNTM5OTYifQ==.33ED53DF79CA5B53C0BF2448B670AF35 + ``` + + 发送请求: + + ![image-20230114230500887](/img/shenyu/plugin/sign/version2_sign_request.png) + + + + + ++ 包含请求体校验演示 + + 计算Token + + ```java + public static void main(String[] args) { + String appSecret = "2D47C325AE5B4A4C926C23FD4395C719"; + + URI uri = URI.create("/http/order/save"); + + String parameters = JsonUtils.toJson(ImmutableMap.of( + "alg","MD5", + "appKey","BD7980F5688A4DE6BCF1B5327FE07F5C", + "timestamp","1673708905488")); + + String base64Parameters = Base64.getEncoder() + .encodeToString(parameters.getBytes(StandardCharsets.UTF_8)); + + String requestBody = "{\"id\":123,\"name\":\"order\"}"; + + String signature = sign(appSecret,base64Parameters,uri,requestBody); + + String Token = base64Parameters+"."+signature; + + System.out.println(Token); + + } + ``` + + Token的计算结果为: + + ```tex + eyJhbGciOiJNRDUiLCJhcHBLZXkiOiJCRDc5ODBGNTY4OEE0REU2QkNGMUI1MzI3RkUwN0Y1QyIsInRpbWVzdGFtcCI6IjE2NzM3MDg5MDU0ODgifQ==.FBCEB6D816644A98378635050AB85EF1 + ``` + + + + ![image-20230114231032837](/img/shenyu/plugin/sign/request_body.png) + + ![image-20230114230922598](/img/shenyu/plugin/sign/version2_sign_request_with_body.png) + + + +# 3. 如何禁用插件 + +- 在 `shenyu-admin` 基础配置 --> 插件管理 --> `sign` ,设置为关闭。 + +# 4. 签名认证算法扩展 + +* 请参考开发者文档中的 [扩展签名算法](../../developer/custom-sign-algorithm)。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/security/waf-plugin.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/security/waf-plugin.md new file mode 100644 index 00000000000..ffbafd988cf --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/plugin-center/security/waf-plugin.md @@ -0,0 +1,75 @@ +--- +title: Waf插件 +keywords: ["waf"] +description: waf插件 +--- + +## 说明 + +* `Waf` 插件,是网关的用来对流量实现防火墙功能的核心实现。 + +## 插件设置 + +请参考运维部署的内容,选择一种方式启动`shenyu-admin`。比如,通过 [本地部署](../../deployment/deployment-local) 启动`Apache ShenYu`后台管理系统。 + +* 在 `shenyu-admin` 基础配置 --> 插件管理 --> `waf` ,设置为开启。如果用户不想使用此功能,请在 `admin` 后台停用此插件。 + + + +* 插件编辑里面新增配置模式。 + +```yaml +{"model":"black"} +# model 可选值为 black, mixed +# 默认为 black 黑名单模式,设置值为 mixed 则为混合模式,下面会专门进行讲解 +``` + +## 在网关中引入 Waf 插件 + +* 在网关的 `pom.xml` 文件中添加 `waf` 的依赖。 + +```xml + + + org.apache.shenyu + shenyu-spring-boot-starter-plugin-waf + ${project.version} + + +``` + +## Waf 插件配置 + +关于选择器和规则配置的更多说明,请参考:[选择器和规则管理](../../user-guide/admin-usage/selector-and-rule), 这里只对部分字段进行了介绍。 + +`Waf`插件规则配置页面: + + + +被 `Waf` 拒绝访问的请求,响应头状态码为:`403`。 + +#### 黑名单模式 + +- 当 `model` 设置为 `black` 黑名单模式的时候,只有匹配的流量才会执行拒绝策略,不匹配的,直接会跳过。 +- 此时规则配置中的 `处理` 配置失效,可配置为空。 + +#### 混合模式 + +* 当 `model` 设置为 `mixed` 混合模式的时候,所有的流量都会通过 `waf` 插件,针对不同的匹配流量,用户可以设置是拒绝,还是通过。 + +* 此时规则配置中的 `处理` 配置必选: + + * `permission`:匹配到该规则的处理逻辑。`reject`: 拒绝访问,`allow`: 允许访问。 + + * `statusCode`:被拒绝访问时,响应体中`code`字段的值, `不会修改响应头的状态码`。 + 例如设置为:`statusCode=10001`,被拒绝的响应体如下: + + ```json + {"code":10001,"message":"You are forbidden to visit"} + ``` + +## 场景 + +* `Waf`插件也是 `Apache ShenYu` 的前置插件,主要用来拦截非法请求,或者异常请求,并且给与相关的拒绝策略。 +* 当面对重放攻击时,你可以根据 `ip` 或者 `host` 来进行匹配,拦截掉非法的 `ip` 与 `host`,设置 `reject` 策略。 +* 关于如何确定 `ip` 与 `host` 值,请看 [parsing-ip-and-host](../../developer/custom-parsing-ip-and-host) diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/quick-start/_category_.json b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/quick-start/_category_.json new file mode 100644 index 00000000000..a15cc14d2d4 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/quick-start/_category_.json @@ -0,0 +1,4 @@ +{ + "label": "快速开始", + "position": 4 +} diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/quick-start/quick-start-dubbo.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/quick-start/quick-start-dubbo.md new file mode 100644 index 00000000000..d00d87904d9 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/quick-start/quick-start-dubbo.md @@ -0,0 +1,180 @@ +--- +title: Dubbo快速开始 +description: Dubbo快速开始 +--- + +本文档演示如何将`Dubbo`服务接入到`Apache ShenYu`网关。您可以直接在工程下找到本文档的[示例代码](https://github.com/apache/shenyu/tree/master/shenyu-examples/shenyu-examples-dubbo) 。 + +## 环境准备 + +请参考运维部署的内容,选择一种方式启动`shenyu-admin`。比如,通过 [本地部署](../deployment/deployment-local) 启动`Apache ShenYu`后台管理系统。 + +启动成功后,需要在基础配置`->`插件管理中,把`dubbo` 插件设置为开启,并设置你的注册地址,请确保注册中心在你本地已经开启。 + +![](/img/shenyu/quick-start/dubbo/dubbo-enable-zh.jpg) + + +启动网关,如果是通过源码的方式,直接运行`shenyu-bootstrap`中的`ShenyuBootstrapApplication`。 + +> 注意,在启动前,请确保网关已经引入相关依赖。 + +如果客户端是`apache dubbo`,注册中心使用`zookeeper`,请参考如下配置: + +```java + + + org.apache.shenyu + shenyu-spring-boot-starter-client-apache-dubbo + ${project.version} + + + org.apache.dubbo + dubbo + 2.7.5 + + + + org.apache.curator + curator-client + 4.0.1 + + + log4j + log4j + + + + + org.apache.curator + curator-framework + 4.0.1 + + + org.apache.curator + curator-recipes + 4.0.1 + + + +``` + +如果客户端是`alibaba dubbo`,注册中心使用`zookeeper`,请参考如下配置: + + +```java + + + org.apache.shenyu + shenyu-spring-boot-starter-client-alibaba-dubbo + ${project.version} + + + com.alibaba + dubbo + ${alibaba.dubbo.version} + + + org.apache.curator + curator-client + ${curator.version} + + + log4j + log4j + + + + + org.apache.curator + curator-framework + ${curator.version} + + + org.apache.curator + curator-recipes + ${curator.version} + + +``` + +## 运行shenyu-examples-dubbo项目 + +下载 [shenyu-examples-dubbo](https://github.com/apache/shenyu/tree/master/shenyu-examples/shenyu-examples-dubbo) . + +修改 `spring-dubbo.xml` 中的注册地址为你本地(注意区分`dubbo`的版本是`apache dubbo`还是`alibaba dubbo`),如: + +```xml + +``` + +运行相应的`main`方法启动项目,(注意区分`dubbo`的版本是`apache dubbo`还是`alibaba dubbo`)。 + +成功启动会有如下日志: + +```shell +2021-02-06 20:58:01.807 INFO 3724 --- [pool-2-thread-1] o.d.s.client.common.utils.RegisterUtils : dubbo client register success: {"appName":"dubbo","contextPath":"/dubbo","path":"/dubbo/insert","pathDesc":"Insert a row of data","rpcType":"dubbo","serviceName":"org.dromara.shenyu.examples.dubbo.api.service.DubboTestService","methodName":"insert","ruleName":"/dubbo/insert","parameterTypes":"org.dromara.shenyu.examples.dubbo.api.entity.DubboTest","rpcExt":"{\"group\":\"\",\"version\":\"\",\"loadbalance\":\"random\",\"retries\":2,\"timeout\":10000,\"url\":\"\"}","enabled":true} +2021-02-06 20:58:01.821 INFO 3724 --- [pool-2-thread-1] o.d.s.client.common.utils.RegisterUtils : dubbo client register success: {"appName":"dubbo","contextPath":"/dubbo","path":"/dubbo/findAll","pathDesc":"Get all data","rpcType":"dubbo","serviceName":"org.dromara.shenyu.examples.dubbo.api.service.DubboTestService","methodName":"findAll","ruleName":"/dubbo/findAll","parameterTypes":"","rpcExt":"{\"group\":\"\",\"version\":\"\",\"loadbalance\":\"random\",\"retries\":2,\"timeout\":10000,\"url\":\"\"}","enabled":true} +2021-02-06 20:58:01.833 INFO 3724 --- [pool-2-thread-1] o.d.s.client.common.utils.RegisterUtils : dubbo client register success: {"appName":"dubbo","contextPath":"/dubbo","path":"/dubbo/findById","pathDesc":"Query by Id","rpcType":"dubbo","serviceName":"org.dromara.shenyu.examples.dubbo.api.service.DubboTestService","methodName":"findById","ruleName":"/dubbo/findById","parameterTypes":"java.lang.String","rpcExt":"{\"group\":\"\",\"version\":\"\",\"loadbalance\":\"random\",\"retries\":2,\"timeout\":10000,\"url\":\"\"}","enabled":true} +2021-02-06 20:58:01.844 INFO 3724 --- [pool-2-thread-1] o.d.s.client.common.utils.RegisterUtils : dubbo client register success: {"appName":"dubbo","contextPath":"/dubbo","path":"/dubbo/findByListId","pathDesc":"","rpcType":"dubbo","serviceName":"org.dromara.shenyu.examples.dubbo.api.service.DubboMultiParamService","methodName":"findByListId","ruleName":"/dubbo/findByListId","parameterTypes":"java.util.List","rpcExt":"{\"group\":\"\",\"version\":\"\",\"loadbalance\":\"random\",\"retries\":2,\"timeout\":10000,\"url\":\"\"}","enabled":true} +2021-02-06 20:58:01.855 INFO 3724 --- [pool-2-thread-1] o.d.s.client.common.utils.RegisterUtils : dubbo client register success: {"appName":"dubbo","contextPath":"/dubbo","path":"/dubbo/findByIdsAndName","pathDesc":"","rpcType":"dubbo","serviceName":"org.dromara.shenyu.examples.dubbo.api.service.DubboMultiParamService","methodName":"findByIdsAndName","ruleName":"/dubbo/findByIdsAndName","parameterTypes":"java.util.List,java.lang.String","rpcExt":"{\"group\":\"\",\"version\":\"\",\"loadbalance\":\"random\",\"retries\":2,\"timeout\":10000,\"url\":\"\"}","enabled":true} +2021-02-06 20:58:01.866 INFO 3724 --- [pool-2-thread-1] o.d.s.client.common.utils.RegisterUtils : dubbo client register success: {"appName":"dubbo","contextPath":"/dubbo","path":"/dubbo/batchSave","pathDesc":"","rpcType":"dubbo","serviceName":"org.dromara.shenyu.examples.dubbo.api.service.DubboMultiParamService","methodName":"batchSave","ruleName":"/dubbo/batchSave","parameterTypes":"java.util.List","rpcExt":"{\"group\":\"\",\"version\":\"\",\"loadbalance\":\"random\",\"retries\":2,\"timeout\":10000,\"url\":\"\"}","enabled":true} +2021-02-06 20:58:01.876 INFO 3724 --- [pool-2-thread-1] o.d.s.client.common.utils.RegisterUtils : dubbo client register success: {"appName":"dubbo","contextPath":"/dubbo","path":"/dubbo/findByArrayIdsAndName","pathDesc":"","rpcType":"dubbo","serviceName":"org.dromara.shenyu.examples.dubbo.api.service.DubboMultiParamService","methodName":"findByArrayIdsAndName","ruleName":"/dubbo/findByArrayIdsAndName","parameterTypes":"[Ljava.lang.Integer;,java.lang.String","rpcExt":"{\"group\":\"\",\"version\":\"\",\"loadbalance\":\"random\",\"retries\":2,\"timeout\":10000,\"url\":\"\"}","enabled":true} +2021-02-06 20:58:01.889 INFO 3724 --- [pool-2-thread-1] o.d.s.client.common.utils.RegisterUtils : dubbo client register success: {"appName":"dubbo","contextPath":"/dubbo","path":"/dubbo/saveComplexBeanTestAndName","pathDesc":"","rpcType":"dubbo","serviceName":"org.dromara.shenyu.examples.dubbo.api.service.DubboMultiParamService","methodName":"saveComplexBeanTestAndName","ruleName":"/dubbo/saveComplexBeanTestAndName","parameterTypes":"org.dromara.shenyu.examples.dubbo.api.entity.ComplexBeanTest,java.lang.String","rpcExt":"{\"group\":\"\",\"version\":\"\",\"loadbalance\":\"random\",\"retries\":2,\"timeout\":10000,\"url\":\"\"}","enabled":true} +2021-02-06 20:58:01.901 INFO 3724 --- [pool-2-thread-1] o.d.s.client.common.utils.RegisterUtils : dubbo client register success: {"appName":"dubbo","contextPath":"/dubbo","path":"/dubbo/batchSaveAndNameAndId","pathDesc":"","rpcType":"dubbo","serviceName":"org.dromara.shenyu.examples.dubbo.api.service.DubboMultiParamService","methodName":"batchSaveAndNameAndId","ruleName":"/dubbo/batchSaveAndNameAndId","parameterTypes":"java.util.List,java.lang.String,java.lang.String","rpcExt":"{\"group\":\"\",\"version\":\"\",\"loadbalance\":\"random\",\"retries\":2,\"timeout\":10000,\"url\":\"\"}","enabled":true} +2021-02-06 20:58:01.911 INFO 3724 --- [pool-2-thread-1] o.d.s.client.common.utils.RegisterUtils : dubbo client register success: {"appName":"dubbo","contextPath":"/dubbo","path":"/dubbo/saveComplexBeanTest","pathDesc":"","rpcType":"dubbo","serviceName":"org.dromara.shenyu.examples.dubbo.api.service.DubboMultiParamService","methodName":"saveComplexBeanTest","ruleName":"/dubbo/saveComplexBeanTest","parameterTypes":"org.dromara.shenyu.examples.dubbo.api.entity.ComplexBeanTest","rpcExt":"{\"group\":\"\",\"version\":\"\",\"loadbalance\":\"random\",\"retries\":2,\"timeout\":10000,\"url\":\"\"}","enabled":true} +2021-02-06 20:58:01.922 INFO 3724 --- [pool-2-thread-1] o.d.s.client.common.utils.RegisterUtils : dubbo client register success: {"appName":"dubbo","contextPath":"/dubbo","path":"/dubbo/findByStringArray","pathDesc":"","rpcType":"dubbo","serviceName":"org.dromara.shenyu.examples.dubbo.api.service.DubboMultiParamService","methodName":"findByStringArray","ruleName":"/dubbo/findByStringArray","parameterTypes":"[Ljava.lang.String;","rpcExt":"{\"group\":\"\",\"version\":\"\",\"loadbalance\":\"random\",\"retries\":2,\"timeout\":10000,\"url\":\"\"}","enabled":true} +``` + +注意:当您需要同时暴露`多个协议`时,请不要配置`shenyu.client.dubbo.props.port`。 + +## 测试 + +`shenyu-examples-dubbo`项目成功启动之后会自动把加 `@ShenyuDubboClient` 注解的接口方法注册到网关。 + + +打开`插件列表 -> rpc proxy -> dubbo`可以看到插件规则配置列表: + + +![](/img/shenyu/quick-start/dubbo/rule-list.jpg) + +下面使用`postman`模拟`http`的方式来请求你的`dubbo`服务: + +![](/img/shenyu/quick-start/dubbo/postman-findbyid.jpg) + +复杂多参数示例:对应接口实现类为`org.apache.shenyu.examples.alibaba.dubbo.service.impl.DubboMultiParamServiceImpl#batchSaveAndNameAndId` + +```java +@Override +@ShenyuDubboClient(path = "/batchSaveAndNameAndId") +public DubboTest batchSaveAndNameAndId(List dubboTestList, String id, String name) { + DubboTest test = new DubboTest(); + test.setId(id); + test.setName("hello world shenyu alibaba dubbo param batchSaveAndNameAndId :" + name + ":" + dubboTestList.stream().map(DubboTest::getName).collect(Collectors.joining("-"))); + return test; +} +``` + +![](/img/shenyu/quick-start/dubbo/postman-multiparams.jpg) + +当你的参数不匹配时会报如下异常: + +```java +2021-02-07 22:24:04.015 ERROR 14860 --- [:20888-thread-3] o.d.shenyu.web.handler.GlobalErrorHandler : [e47b2a2a] Resolved [ShenyuException: org.apache.dubbo.remoting.RemotingException: java.lang.IllegalArgumentException: args.length != types.length + java.lang.IllegalArgumentException: args.length != types.length + at org.apache.dubbo.common.utils.PojoUtils.realize(PojoUtils.java:91) + at org.apache.dubbo.rpc.filter.GenericFilter.invoke(GenericFilter.java:82) + at org.apache.dubbo.rpc.protocol.ProtocolFilterWrapper$1.invoke(ProtocolFilterWrapper.java:81) + at org.apache.dubbo.rpc.filter.ClassLoaderFilter.invoke(ClassLoaderFilter.java:38) + at org.apache.dubbo.rpc.protocol.ProtocolFilterWrapper$1.invoke(ProtocolFilterWrapper.java:81) + at org.apache.dubbo.rpc.filter.EchoFilter.invoke(EchoFilter.java:41) + at org.apache.dubbo.rpc.protocol.ProtocolFilterWrapper$1.invoke(ProtocolFilterWrapper.java:81) + at org.apache.dubbo.rpc.protocol.dubbo.DubboProtocol$1.reply(DubboProtocol.java:150) + at org.apache.dubbo.remoting.exchange.support.header.HeaderExchangeHandler.handleRequest(HeaderExchangeHandler.java:100) + at org.apache.dubbo.remoting.exchange.support.header.HeaderExchangeHandler.received(HeaderExchangeHandler.java:175) + at org.apache.dubbo.remoting.transport.DecodeHandler.received(DecodeHandler.java:51) + at org.apache.dubbo.remoting.transport.dispatcher.ChannelEventRunnable.run(ChannelEventRunnable.java:57) + at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) + at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) + at java.lang.Thread.run(Thread.java:748) + ] for HTTP POST /dubbo/batchSaveAndNameAndId +``` diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/quick-start/quick-start-grpc.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/quick-start/quick-start-grpc.md new file mode 100644 index 00000000000..fb0910a1fcb --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/quick-start/quick-start-grpc.md @@ -0,0 +1,175 @@ +--- +title: gRPC快速开始 +description: gRPC快速开始 +--- + +本文档演示如何将`gRPC`服务接入到`Apache ShenYu`网关。您可以直接在工程下找到本文档的 [示例代码](https://github.com/apache/shenyu/tree/master/shenyu-examples/shenyu-examples-grpc) 。 + +## 环境准备 + +请参考运维部署的内容,选择一种方式启动`shenyu-admin`。比如,通过 [本地部署](../deployment/deployment-local) 启动`Apache ShenYu`后台管理系统。 + +启动成功后,需要在基础配置`->`插件管理中,把`gRPC` 插件设置为开启。 + + + +启动网关,如果是通过源码的方式,直接运行`shenyu-bootstrap`中的`ShenyuBootstrapApplication`。 + +> 注意,在启动前,请确保网关已经引入相关依赖。 + +引入网关对`gRPC`的代理插件,在网关的 `pom.xml` 文件中增加如下依赖: + +```xml + + + org.apache.shenyu + shenyu-spring-boot-starter-plugin-grpc + ${project.version} + + +``` + +## 运行 shenyu-examples-grpc 项目 + +下载 [shenyu-examples-grpc](https://github.com/apache/shenyu/tree/master/shenyu-examples/shenyu-examples-grpc) + +在 `shenyu-examples-grpc` 下执行以下命令生成 `java` 代码: + +```shell +mvn protobuf:compile //编译消息对象 +mvn protobuf:compile-custom //依赖消息对象,生成接口服务 +``` + +或者,如果你是通过 `IntelliJ IDEA` 打开 `Apache ShenYu` 工程,首先在`maven root`下`install`整个项目 + +然后在 `Maven` 工具栏中选中 `protobuf:compile` 和 `protobuf:compile-custom`,然后右键 `Run Maven Build` 一键生成 `proto` 文件对应的 `java`代码。 + +然后让`idea`识别生成的`target`文件夹 + + +运行 `org.apache.shenyu.examples.grpc.ShenyuTestGrpcApplication` 中的 `main` 方法启动项目。 + +成功启动会有如下日志,表示将 `gRPC` 服务成功注册到 `shenyu-admin` 中。 + +```shell +2021-06-18 19:33:32.866 INFO 11004 --- [or_consumer_-19] o.a.s.r.client.http.utils.RegisterUtils : grpc client register success: {"appName":"127.0.0.1:8080","contextPath":"/grpc","path":"/grpc/clientStreamingFun","pathDesc":"clientStreamingFun","rpcType":"grpc","serviceName":"stream.StreamService","methodName":"clientStreamingFun","ruleName":"/grpc/clientStreamingFun","parameterTypes":"io.grpc.stub.StreamObserver","rpcExt":"{\"timeout\":5000,\"methodType\":\"CLIENT_STREAMING\"}","enabled":true,"host":"172.20.10.6","port":8080,"registerMetaData":false} +2021-06-18 19:33:32.866 INFO 11004 --- [or_consumer_-17] o.a.s.r.client.http.utils.RegisterUtils : grpc client register success: {"appName":"127.0.0.1:8080","contextPath":"/grpc","path":"/grpc/echo","pathDesc":"echo","rpcType":"grpc","serviceName":"echo.EchoService","methodName":"echo","ruleName":"/grpc/echo","parameterTypes":"echo.EchoRequest,io.grpc.stub.StreamObserver","rpcExt":"{\"timeout\":5000,\"methodType\":\"UNARY\"}","enabled":true,"host":"172.20.10.6","port":8080,"registerMetaData":false} +2021-06-18 19:33:32.866 INFO 11004 --- [or_consumer_-20] o.a.s.r.client.http.utils.RegisterUtils : grpc client register success: {"appName":"127.0.0.1:8080","contextPath":"/grpc","path":"/grpc/bidiStreamingFun","pathDesc":"bidiStreamingFun","rpcType":"grpc","serviceName":"stream.StreamService","methodName":"bidiStreamingFun","ruleName":"/grpc/bidiStreamingFun","parameterTypes":"io.grpc.stub.StreamObserver","rpcExt":"{\"timeout\":5000,\"methodType\":\"BIDI_STREAMING\"}","enabled":true,"host":"172.20.10.6","port":8080,"registerMetaData":false} +2021-06-18 19:33:32.866 INFO 11004 --- [or_consumer_-21] o.a.s.r.client.http.utils.RegisterUtils : grpc client register success: {"appName":"127.0.0.1:8080","contextPath":"/grpc","path":"/grpc/unaryFun","pathDesc":"unaryFun","rpcType":"grpc","serviceName":"stream.StreamService","methodName":"unaryFun","ruleName":"/grpc/unaryFun","parameterTypes":"stream.RequestData,io.grpc.stub.StreamObserver","rpcExt":"{\"timeout\":5000,\"methodType\":\"UNARY\"}","enabled":true,"host":"172.20.10.6","port":8080,"registerMetaData":false} +2021-06-18 19:33:32.866 INFO 11004 --- [or_consumer_-18] o.a.s.r.client.http.utils.RegisterUtils : grpc client register success: {"appName":"127.0.0.1:8080","contextPath":"/grpc","path":"/grpc/serverStreamingFun","pathDesc":"serverStreamingFun","rpcType":"grpc","serviceName":"stream.StreamService","methodName":"serverStreamingFun","ruleName":"/grpc/serverStreamingFun","parameterTypes":"stream.RequestData,io.grpc.stub.StreamObserver","rpcExt":"{\"timeout\":5000,\"methodType\":\"SERVER_STREAMING\"}","enabled":true,"host":"172.20.10.6","port":8080,"registerMetaData":false} +``` + +## 简单测试 + +`shenyu-examples-grpc`项目成功启动之后会自动把加 `@ShenyuGrpcClient` 注解的接口方法注册到网关。 + +打开 `插件列表 -> rpc proxy -> grpc` 可以看到插件规则配置列表。 + + + + +下面使用 `postman` 模拟 `http` 的方式来请求你的 `gRPC` 服务。 +请求参数如下: + +```json +{ + "data": [ + { + "message": "hello grpc" + } + ] +} +``` + + + +当前是以 `json` 的格式传递参数,`key`的名称默认是`data`,你可以在 `GrpcConstants.JSON_DESCRIPTOR_PROTO_FIELD_NAME` 中进行重置;`value`的传入则根据你定义的 `proto` 文件。 + +## 流式调用 + +`Apache ShenYu` 可以支持 `gRPC` 的流式调用,下面展示的是 `gRPC` 四种方法类型的调用。 在流式调用中,你可以通过数组的形式传递多个参数。 + +- `UNARY` + +请求参数如下: + +```json +{ + "data": [ + { + "text": "hello grpc" + } + ] +} +``` + +通过`postman` 模拟 `http` 请求,发起`UNARY`调用。 + + + +- `CLIENT_STREAMING` + +请求参数如下: + +```json +{ + "data": [ + { + "text": "hello grpc" + }, + { + "text": "hello grpc" + }, + { + "text": "hello grpc" + } + ] +} +``` + +通过`postman` 模拟 `http` 请求,发起`CLIENT_STREAMING`调用。 + + + +- `SERVER_STREAMING` + +请求参数如下: + +```json +{ + "data": [ + { + "text": "hello grpc" + } + ] +} +``` + +通过`postman` 模拟 `http` 请求,发起`SERVER_STREAMING`调用。 + + + +- `BIDI_STREAMING` + +请求参数如下: + +```json +{ + "data": [ + { + "text": "hello grpc" + }, + { + "text": "hello grpc" + }, + { + "text": "hello grpc" + } + ] +} +``` + +通过`postman` 模拟 `http` 请求,发起`BIDI_STREAMING`调用。 + + + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/quick-start/quick-start-http.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/quick-start/quick-start-http.md new file mode 100644 index 00000000000..a438fd8ef20 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/quick-start/quick-start-http.md @@ -0,0 +1,81 @@ +--- +title: Http快速开始 +description: Http快速开始 +--- + +本文档演示如何将`Http`服务接入到`Apache ShenYu`网关。您可以直接在工程下找到本文档的[示例代码](https://github.com/apache/shenyu/tree/master/shenyu-examples/shenyu-examples-http) 。 + +## 环境准备 + +请参考运维部署的内容,选择一种方式启动`shenyu-admin`。比如,通过 [本地部署](../deployment/deployment-local) 启动`Apache ShenYu`后台管理系统。 + +启动成功后,需要在基础配置`->`插件管理中,把`divide` 插件设置为开启。在`Apache ShenYu`网关中,`Http`请求是由`divide`插件进行处理。 + + + + + +启动网关,如果是通过源码的方式,直接运行`shenyu-bootstrap`中的`ShenyuBootstrapApplication`。 + +> 注意,在启动前,请确保网关已经引入相关依赖。 + +引入网关对`Http`的代理插件,在网关的 `pom.xml` 文件中增加如下依赖: + +```xml + + + org.apache.shenyu + shenyu-spring-boot-starter-plugin-divide + ${project.version} + + + + org.apache.shenyu + shenyu-spring-boot-starter-plugin-httpclient + ${project.version} + +``` + + +## 运行shenyu-examples-http项目 + +下载 [shenyu-examples-http](https://github.com/apache/shenyu/tree/master/shenyu-examples/shenyu-examples-http) + +运行`org.apache.shenyu.examples.http.ShenyuTestHttpApplication`main方法启动项目。 + +从`2.4.3`开始,用户可以不配置`shenyu.client.http.props.port`。 + +成功启动会有如下日志: + +```shell +2021-02-10 00:57:07.561 INFO 3700 --- [pool-1-thread-1] o.d.s.client.common.utils.RegisterUtils : http client register success: {"appName":"http","context":"/http","path":"/http/test/**","pathDesc":"","rpcType":"http","host":"192.168.50.13","port":8188,"ruleName":"/http/test/**","enabled":true,"registerMetaData":false} +2021-02-10 00:57:07.577 INFO 3700 --- [pool-1-thread-1] o.d.s.client.common.utils.RegisterUtils : http client register success: {"appName":"http","context":"/http","path":"/http/order/save","pathDesc":"Save order","rpcType":"http","host":"192.168.50.13","port":8188,"ruleName":"/http/order/save","enabled":true,"registerMetaData":false} +2021-02-10 00:57:07.587 INFO 3700 --- [pool-1-thread-1] o.d.s.client.common.utils.RegisterUtils : http client register success: {"appName":"http","context":"/http","path":"/http/order/path/**/name","pathDesc":"","rpcType":"http","host":"192.168.50.13","port":8188,"ruleName":"/http/order/path/**/name","enabled":true,"registerMetaData":false} +2021-02-10 00:57:07.596 INFO 3700 --- [pool-1-thread-1] o.d.s.client.common.utils.RegisterUtils : http client register success: {"appName":"http","context":"/http","path":"/http/order/findById","pathDesc":"Find by id","rpcType":"http","host":"192.168.50.13","port":8188,"ruleName":"/http/order/findById","enabled":true,"registerMetaData":false} +2021-02-10 00:57:07.606 INFO 3700 --- [pool-1-thread-1] o.d.s.client.common.utils.RegisterUtils : http client register success: {"appName":"http","context":"/http","path":"/http/order/path/**","pathDesc":"","rpcType":"http","host":"192.168.50.13","port":8188,"ruleName":"/http/order/path/**","enabled":true,"registerMetaData":false} +2021-02-10 00:57:08.023 INFO 3700 --- [ main] o.s.b.web.embedded.netty.NettyWebServer : Netty started on port(s): 8188 +2021-02-10 00:57:08.026 INFO 3700 --- [ main] o.d.s.e.http.ShenyuTestHttpApplication : Started ShenyuTestHttpApplication in 2.555 seconds (JVM running for 3.411) +``` + + + +## 测试Http请求 + +`shenyu-examples-http`项目成功启动之后会自动把加 `@ShenyuSpringMvcClient` 注解的接口方法注册到网关。 + +打开`插件列表 -> Proxy -> divide`可以看到插件规则配置列表: + + +![](/img/shenyu/quick-start/http/rule-list.png) + +下面使用`postman`模拟`http`的方式来请求你的`http`服务: + +![](/img/shenyu/quick-start/http/postman-test.png) + +下面使用`IDEA HTTP Client Plugin`模拟`http`的方式来请求你的`http`服务[本地访问,不使用`shenyu`代理]: + +![](/img/shenyu/quick-start/http/idea-http-test-local.png) + +下面使用`IDEA HTTP Client Plugin`模拟`http`的方式来请求你的`http`服务[使用`shenyu`代理]: + +![](/img/shenyu/quick-start/http/idea-http-test-proxy.png) diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/quick-start/quick-start-motan.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/quick-start/quick-start-motan.md new file mode 100644 index 00000000000..fe859270351 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/quick-start/quick-start-motan.md @@ -0,0 +1,95 @@ +--- +title: Motan快速开始 +description: Motan快速开始 +--- + + +本文档演示如何将`Motan`服务接入到`Apache ShenYu`网关。您可以直接在工程下找到本文档的[示例代码](https://github.com/apache/shenyu/tree/master/shenyu-examples/shenyu-examples-motan) 。 + +## 环境准备 + +请参考运维部署的内容,选择一种方式启动`shenyu-admin`。比如,通过 [本地部署](../deployment/deployment-local) 启动`Apache ShenYu`后台管理系统。 + +启动成功后,需要在基础配置`->`插件管理中,把`motan` 插件设置为开启。 + + + + + +启动网关,如果是通过源码的方式,直接运行`shenyu-bootstrap`中的`ShenyuBootstrapApplication`。 + +> 注意,在启动前,请确保网关已经引入相关依赖。 +> 本地已经成功启动zookeeper。 + +引入网关对`Motan`的代理插件,在网关的 `pom.xml` 文件中增加如下依赖: + +```xml + + + org.apache.shenyu + shenyu-spring-boot-starter-plugin-motan + ${project.version} + + + + com.weibo + motan-core + 1.1.9 + + + + com.weibo + motan-registry-zookeeper + 1.1.9 + + + + com.weibo + motan-transport-netty4 + 1.1.9 + + + + com.weibo + motan-springsupport + 1.1.9 + +``` + + +## 运行shenyu-examples-motan项目 + +下载 [shenyu-examples-motan](https://github.com/apache/shenyu/tree/master/shenyu-examples/shenyu-examples-motan) 。 + +运行`org.apache.shenyu.examples.motan.service.TestMotanApplication`main方法启动项目。 + +成功启动会有如下日志: + +```shell +2021-07-18 16:46:25.388 INFO 96 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8081 (http) with context path '' +2021-07-18 16:46:25.393 INFO 96 --- [ main] o.a.s.e.m.service.TestMotanApplication : Started TestMotanApplication in 3.89 seconds (JVM running for 4.514) +2021-07-18 16:46:25.396 INFO 96 --- [ main] info : [ZookeeperRegistry] Url (null) will set to available to Registry [zookeeper://localhost:2181/default_rpc/com.weibo.api.motan.registry.RegistryService/1.0/service] +2021-07-18 16:46:25.399 INFO 96 --- [ Thread-6] o.a.s.c.c.s.ShenyuClientShutdownHook : hook Thread-0 will sleep 3000ms when it start +2021-07-18 16:46:25.399 INFO 96 --- [ Thread-6] o.a.s.c.c.s.ShenyuClientShutdownHook : hook SpringContextShutdownHook will sleep 3000ms when it start +2021-07-18 16:46:25.445 INFO 96 --- [ntLoopGroup-3-2] info : NettyChannelHandler channelActive: remote=/192.168.1.8:49740 local=/192.168.1.8:8002 +2021-07-18 16:46:25.445 INFO 96 --- [ntLoopGroup-3-1] info : NettyChannelHandler channelActive: remote=/192.168.1.8:49739 local=/192.168.1.8:8002 +2021-07-18 16:46:25.925 INFO 96 --- [or_consumer_-17] o.a.s.r.client.http.utils.RegisterUtils : motan client register success: {"appName":"motan","contextPath":"/motan","path":"/motan/hello","pathDesc":"","rpcType":"motan","serviceName":"org.apache.shenyu.examples.motan.service.MotanDemoService","methodName":"hello","ruleName":"/motan/hello","parameterTypes":"java.lang.String","rpcExt":"{\"methodInfo\":[{\"methodName\":\"hello\",\"params\":[{\"left\":\"java.lang.String\",\"right\":\"name\"}]}],\"group\":\"motan-shenyu-rpc\"}","enabled":true,"host":"192.168.220.1","port":8081,"registerMetaData":false} + +``` + + + +## 测试Http请求 + +`shenyu-examples-motan`项目成功启动之后会自动把加 `@ShenyuMotanClient` 注解的接口方法注册到网关,并添加选择器和规则,如果没有,可以手动添加。 + +打开`插件列表 -> rpc proxy -> motan`可以看到插件规则配置列表: + + + + +下面使用`postman`模拟`http`的方式来请求你的`motan`服务: + + + + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/quick-start/quick-start-sofa.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/quick-start/quick-start-sofa.md new file mode 100644 index 00000000000..1246db31304 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/quick-start/quick-start-sofa.md @@ -0,0 +1,136 @@ +--- +title: Sofa快速开始 +description: Sofa快速开始 +--- + +本文档演示如何将`Sofa`服务接入到`Apache ShenYu`网关。您可以直接在工程下找到本文档的[示例代码](https://github.com/apache/shenyu/tree/master/shenyu-examples/shenyu-examples-sofa) 。 + +## 环境准备 + +请参考运维部署的内容,选择一种方式启动`shenyu-admin`。比如,通过 [本地部署](../deployment/deployment-local) 启动`Apache ShenYu`后台管理系统。 + +启动成功后,需要在基础配置`->`插件管理中,把`sofa` 插件设置为开启,并设置你的注册地址,请确保注册中心在你本地已经开启。 + + + +启动网关,如果是通过源码的方式,直接运行`shenyu-bootstrap`中的`ShenyuBootstrapApplication`。 + +> 注意,在启动前,请确保网关已经引入相关依赖。 + +如果客户端是`sofa`,注册中心使用`zookeeper`,请参考如下配置: + +```xml + + + com.alipay.sofa + sofa-rpc-all + 5.7.6 + + + org.apache.curator + curator-client + 4.0.1 + + + org.apache.curator + curator-framework + 4.0.1 + + + org.apache.curator + curator-recipes + 4.0.1 + + + + org.apache.shenyu + shenyu-spring-boot-starter-plugin-sofa + ${project.version} + + + +``` + +## 运行shenyu-examples-sofa项目 + +下载 [shenyu-examples-sofa](https://github.com/apache/shenyu/tree/master/shenyu-examples/shenyu-examples-sofa) + +设置`application.yml`的`zk`注册地址,如: + +```xml +com: + alipay: + sofa: + rpc: + registry-address: zookeeper://127.0.0.1:2181 +``` + +运行`org.apache.shenyu.examples.sofa.service.TestSofaApplication`main方法启动sofa服务。 + +成功启动会有如下日志: + +```shell +2021-02-10 02:31:45.599 INFO 2156 --- [pool-1-thread-1] o.d.s.client.common.utils.RegisterUtils : sofa client register success: {"appName":"sofa","contextPath":"/sofa","path":"/sofa/insert","pathDesc":"Insert a row of data","rpcType":"sofa","serviceName":"org.dromara.shenyu.examples.sofa.api.service.SofaSingleParamService","methodName":"insert","ruleName":"/sofa/insert","parameterTypes":"org.dromara.shenyu.examples.sofa.api.entity.SofaSimpleTypeBean","rpcExt":"{\"loadbalance\":\"hash\",\"retries\":3,\"timeout\":-1}","enabled":true} +2021-02-10 02:31:45.605 INFO 2156 --- [pool-1-thread-1] o.d.s.client.common.utils.RegisterUtils : sofa client register success: {"appName":"sofa","contextPath":"/sofa","path":"/sofa/findById","pathDesc":"Find by Id","rpcType":"sofa","serviceName":"org.dromara.shenyu.examples.sofa.api.service.SofaSingleParamService","methodName":"findById","ruleName":"/sofa/findById","parameterTypes":"java.lang.String","rpcExt":"{\"loadbalance\":\"hash\",\"retries\":3,\"timeout\":-1}","enabled":true} +2021-02-10 02:31:45.611 INFO 2156 --- [pool-1-thread-1] o.d.s.client.common.utils.RegisterUtils : sofa client register success: {"appName":"sofa","contextPath":"/sofa","path":"/sofa/findAll","pathDesc":"Get all data","rpcType":"sofa","serviceName":"org.dromara.shenyu.examples.sofa.api.service.SofaSingleParamService","methodName":"findAll","ruleName":"/sofa/findAll","parameterTypes":"","rpcExt":"{\"loadbalance\":\"hash\",\"retries\":3,\"timeout\":-1}","enabled":true} +2021-02-10 02:31:45.616 INFO 2156 --- [pool-1-thread-1] o.d.s.client.common.utils.RegisterUtils : sofa client register success: {"appName":"sofa","contextPath":"/sofa","path":"/sofa/batchSaveNameAndId","pathDesc":"","rpcType":"sofa","serviceName":"org.dromara.shenyu.examples.sofa.api.service.SofaMultiParamService","methodName":"batchSaveNameAndId","ruleName":"/sofa/batchSaveNameAndId","parameterTypes":"java.util.List,java.lang.String,java.lang.String#org.dromara.shenyu.examples.sofa.api.entity.SofaSimpleTypeBean","rpcExt":"{\"loadbalance\":\"hash\",\"retries\":3,\"timeout\":-1}","enabled":true} +2021-02-10 02:31:45.621 INFO 2156 --- [pool-1-thread-1] o.d.s.client.common.utils.RegisterUtils : sofa client register success: {"appName":"sofa","contextPath":"/sofa","path":"/sofa/saveComplexBeanAndName","pathDesc":"","rpcType":"sofa","serviceName":"org.dromara.shenyu.examples.sofa.api.service.SofaMultiParamService","methodName":"saveComplexBeanAndName","ruleName":"/sofa/saveComplexBeanAndName","parameterTypes":"org.dromara.shenyu.examples.sofa.api.entity.SofaComplexTypeBean,java.lang.String","rpcExt":"{\"loadbalance\":\"hash\",\"retries\":3,\"timeout\":-1}","enabled":true} +2021-02-10 02:31:45.627 INFO 2156 --- [pool-1-thread-1] o.d.s.client.common.utils.RegisterUtils : sofa client register success: {"appName":"sofa","contextPath":"/sofa","path":"/sofa/findByArrayIdsAndName","pathDesc":"","rpcType":"sofa","serviceName":"org.dromara.shenyu.examples.sofa.api.service.SofaMultiParamService","methodName":"findByArrayIdsAndName","ruleName":"/sofa/findByArrayIdsAndName","parameterTypes":"[Ljava.lang.Integer;,java.lang.String","rpcExt":"{\"loadbalance\":\"hash\",\"retries\":3,\"timeout\":-1}","enabled":true} +2021-02-10 02:31:45.632 INFO 2156 --- [pool-1-thread-1] o.d.s.client.common.utils.RegisterUtils : sofa client register success: {"appName":"sofa","contextPath":"/sofa","path":"/sofa/findByStringArray","pathDesc":"","rpcType":"sofa","serviceName":"org.dromara.shenyu.examples.sofa.api.service.SofaMultiParamService","methodName":"findByStringArray","ruleName":"/sofa/findByStringArray","parameterTypes":"[Ljava.lang.String;","rpcExt":"{\"loadbalance\":\"hash\",\"retries\":3,\"timeout\":-1}","enabled":true} +2021-02-10 02:31:45.637 INFO 2156 --- [pool-1-thread-1] o.d.s.client.common.utils.RegisterUtils : sofa client register success: {"appName":"sofa","contextPath":"/sofa","path":"/sofa/saveTwoList","pathDesc":"","rpcType":"sofa","serviceName":"org.dromara.shenyu.examples.sofa.api.service.SofaMultiParamService","methodName":"saveTwoList","ruleName":"/sofa/saveTwoList","parameterTypes":"java.util.List,java.util.Map#org.dromara.shenyu.examples.sofa.api.entity.SofaComplexTypeBean","rpcExt":"{\"loadbalance\":\"hash\",\"retries\":3,\"timeout\":-1}","enabled":true} +2021-02-10 02:31:45.642 INFO 2156 --- [pool-1-thread-1] o.d.s.client.common.utils.RegisterUtils : sofa client register success: {"appName":"sofa","contextPath":"/sofa","path":"/sofa/batchSave","pathDesc":"","rpcType":"sofa","serviceName":"org.dromara.shenyu.examples.sofa.api.service.SofaMultiParamService","methodName":"batchSave","ruleName":"/sofa/batchSave","parameterTypes":"java.util.List#org.dromara.shenyu.examples.sofa.api.entity.SofaSimpleTypeBean","rpcExt":"{\"loadbalance\":\"hash\",\"retries\":3,\"timeout\":-1}","enabled":true} +2021-02-10 02:31:45.647 INFO 2156 --- [pool-1-thread-1] o.d.s.client.common.utils.RegisterUtils : sofa client register success: {"appName":"sofa","contextPath":"/sofa","path":"/sofa/findByListId","pathDesc":"","rpcType":"sofa","serviceName":"org.dromara.shenyu.examples.sofa.api.service.SofaMultiParamService","methodName":"findByListId","ruleName":"/sofa/findByListId","parameterTypes":"java.util.List","rpcExt":"{\"loadbalance\":\"hash\",\"retries\":3,\"timeout\":-1}","enabled":true} +2021-02-10 02:31:45.653 INFO 2156 --- [pool-1-thread-1] o.d.s.client.common.utils.RegisterUtils : sofa client register success: {"appName":"sofa","contextPath":"/sofa","path":"/sofa/saveComplexBean","pathDesc":"","rpcType":"sofa","serviceName":"org.dromara.shenyu.examples.sofa.api.service.SofaMultiParamService","methodName":"saveComplexBean","ruleName":"/sofa/saveComplexBean","parameterTypes":"org.dromara.shenyu.examples.sofa.api.entity.SofaComplexTypeBean","rpcExt":"{\"loadbalance\":\"hash\",\"retries\":3,\"timeout\":-1}","enabled":true} +2021-02-10 02:31:45.660 INFO 2156 --- [pool-1-thread-1] o.d.s.client.common.utils.RegisterUtils : sofa client register success: {"appName":"sofa","contextPath":"/sofa","path":"/sofa/findByIdsAndName","pathDesc":"","rpcType":"sofa","serviceName":"org.dromara.shenyu.examples.sofa.api.service.SofaMultiParamService","methodName":"findByIdsAndName","ruleName":"/sofa/findByIdsAndName","parameterTypes":"java.util.List,java.lang.String","rpcExt":"{\"loadbalance\":\"hash\",\"retries\":3,\"timeout\":-1}","enabled":true} +2021-02-10 02:31:46.055 INFO 2156 --- [ main] o.a.c.f.imps.CuratorFrameworkImpl : Starting +2021-02-10 02:31:46.059 INFO 2156 --- [ main] org.apache.zookeeper.ZooKeeper : Client environment:zookeeper.version=3.4.6-1569965, built on 02/20/2014 09:09 GMT +2021-02-10 02:31:46.059 INFO 2156 --- [ main] org.apache.zookeeper.ZooKeeper : Client environment:host.name=host.docker.internal +2021-02-10 02:31:46.059 INFO 2156 --- [ main] org.apache.zookeeper.ZooKeeper : Client environment:java.version=1.8.0_211 +2021-02-10 02:31:46.059 INFO 2156 --- [ main] org.apache.zookeeper.ZooKeeper : Client environment:java.vendor=Oracle Corporation +2021-02-10 02:31:46.059 INFO 2156 --- [ main] org.apache.zookeeper.ZooKeeper : Client environment:java.home=C:\Program Files\Java\jdk1.8.0_211\jre +2021-02-10 02:31:46.059 INFO 2156 --- [ main] org.apache.zookeeper.ZooKeeper : Client environment:java.class.path=C:\Program Files\Java\jdk1.8.0_211\jre\lib\charsets.jar;C:\Program Files\Java\jdk1.8.0_211\jre\lib\deploy.jar;C:\Program Files\Java\jdk1.8.0_211\jre\lib\ext\access-bridge-64.jar;C:\Program Files\Java\jdk1.8.0_211\jre\lib\ext\cldrdata.jar;C:\Program Files\Java\jdk1.8.0_211\jre\lib\ext\dnsns.jar;C:\Program Files\Java\jdk1.8.0_211\jre\lib\ext\jaccess.jar;C:\Program Files\Java\jdk1.8.0_211\jre\lib\ext\jfxrt.jar;C:\Program Files\Java\jdk1.8.0_211\jre\lib\ext\localedata.jar;C:\Program Files\Java\jdk1.8.0_211\jre\lib\ext\nashorn.jar;C:\Program Files\Java\jdk1.8.0_211\jre\lib\ext\sunec.jar;C:\Program Files\Java\jdk1.8.0_211\jre\lib\ext\sunjce_provider.jar;C:\Program Files\Java\jdk1.8.0_211\jre\lib\ext\sunmscapi.jar;C:\Program Files\Java\jdk1.8.0_211\jre\lib\ext\sunpkcs11.jar;C:\Program Files\Java\jdk1.8.0_211\jre\lib\ext\zipfs.jar;C:\Program Files\Java\jdk1.8.0_211\jre\lib\javaws.jar;C:\Program Files\Java\jdk1.8.0_211\jre\lib\jce.jar;C:\Program Files\Java\jdk1.8.0_211\jre\lib\jfr.jar;C:\Program Files\Java\jdk1.8.0_211\jre\lib\jfxswt.jar;C:\Program Files\Java\jdk1.8.0_211\jre\lib\jsse.jar;C:\Program Files\Java\jdk1.8.0_211\jre\lib\management-agent.jar;C:\Program Files\Java\jdk1.8.0_211\jre\lib\plugin.jar;C:\Program Files\Java\jdk1.8.0_211\jre\lib\resources.jar;C:\Program Files\Java\jdk1.8.0_211\jre\lib\rt.jar;D:\X\dlm_github\shenyu\shenyu-examples\shenyu-examples-sofa\shenyu-examples-sofa-service\target\classes;D:\SOFT\m2\repository\com\alipay\sofa\rpc-sofa-boot-starter\6.0.4\rpc-sofa-boot-starter-6.0.4.jar;D:\SOFT\m2\repository\com\alipay\sofa\rpc-sofa-boot-core\6.0.4\rpc-sofa-boot-core-6.0.4.jar;D:\SOFT\m2\repository\com\alipay\sofa\sofa-rpc-all\5.5.7\sofa-rpc-all-5.5.7.jar;D:\SOFT\m2\repository\com\alipay\sofa\bolt\1.4.6\bolt-1.4.6.jar;D:\SOFT\m2\repository\org\javassist\javassist\3.20.0-GA\javassist-3.20.0-GA.jar;D:\SOFT\m2\repository\io\netty\netty-all\4.1.43.Final\netty-all-4.1.43.Final.jar;D:\SOFT\m2\repository\com\alipay\sofa\hessian\3.3.6\hessian-3.3.6.jar;D:\SOFT\m2\repository\com\alipay\sofa\tracer-core\2.1.2\tracer-core-2.1.2.jar;D:\SOFT\m2\repository\io\opentracing\opentracing-api\0.22.0\opentracing-api-0.22.0.jar;D:\SOFT\m2\repository\io\opentracing\opentracing-noop\0.22.0\opentracing-noop-0.22.0.jar;D:\SOFT\m2\repository\io\opentracing\opentracing-mock\0.22.0\opentracing-mock-0.22.0.jar;D:\SOFT\m2\repository\io\opentracing\opentracing-util\0.22.0\opentracing-util-0.22.0.jar;D:\SOFT\m2\repository\com\alipay\sofa\lookout\lookout-api\1.4.1\lookout-api-1.4.1.jar;D:\SOFT\m2\repository\com\alipay\sofa\runtime-sofa-boot-starter\3.1.4\runtime-sofa-boot-starter-3.1.4.jar;D:\SOFT\m2\repository\org\apache\curator\curator-client\2.9.1\curator-client-2.9.1.jar;D:\SOFT\m2\repository\org\apache\zookeeper\zookeeper\3.4.6\zookeeper-3.4.6.jar;D:\SOFT\m2\repository\log4j\log4j\1.2.16\log4j-1.2.16.jar;D:\SOFT\m2\repository\jline\jline\0.9.94\jline-0.9.94.jar;D:\SOFT\m2\repository\io\netty\netty\3.7.0.Final\netty-3.7.0.Final.jar;D:\SOFT\m2\repository\com\google\guava\guava\16.0.1\guava-16.0.1.jar;D:\SOFT\m2\repository\org\apache\curator\curator-framework\2.9.1\curator-framework-2.9.1.jar;D:\SOFT\m2\repository\org\apache\curator\curator-recipes\2.9.1\curator-recipes-2.9.1.jar;D:\SOFT\m2\repository\org\jboss\resteasy\resteasy-jaxrs\3.0.12.Final\resteasy-jaxrs-3.0.12.Final.jar;D:\SOFT\m2\repository\org\jboss\spec\javax\annotation\jboss-annotations-api_1.1_spec\1.0.1.Final\jboss-annotations-api_1.1_spec-1.0.1.Final.jar;D:\SOFT\m2\repository\javax\activation\activation\1.1.1\activation-1.1.1.jar;D:\SOFT\m2\repository\org\apache\httpcomponents\httpclient\4.5.10\httpclient-4.5.10.jar;D:\SOFT\m2\repository\org\apache\httpcomponents\httpcore\4.4.12\httpcore-4.4.12.jar;D:\SOFT\m2\repository\commons-io\commons-io\2.1\commons-io-2.1.jar;D:\SOFT\m2\repository\net\jcip\jcip-annotations\1.0\jcip-annotations-1.0.jar;D:\SOFT\m2\repository\org\jboss\resteasy\resteasy-client\3.0.12.Final\resteasy-client-3.0.12.Final.jar;D:\SOFT\m2\repository\org\jboss\resteasy\resteasy-jackson-provider\3.0.12.Final\resteasy-jackson-provider-3.0.12.Final.jar;D:\SOFT\m2\repository\org\codehaus\jackson\jackson-core-asl\1.9.12\jackson-core-asl-1.9.12.jar;D:\SOFT\m2\repository\org\codehaus\jackson\jackson-mapper-asl\1.9.12\jackson-mapper-asl-1.9.12.jar;D:\SOFT\m2\repository\org\codehaus\jackson\jackson-jaxrs\1.9.12\jackson-jaxrs-1.9.12.jar;D:\SOFT\m2\repository\org\codehaus\jackson\jackson-xc\1.9.12\jackson-xc-1.9.12.jar;D:\SOFT\m2\repository\org\jboss\resteasy\resteasy-netty4\3.0.12.Final\resteasy-netty4-3.0.12.Final.jar;D:\SOFT\m2\repository\org\jboss\resteasy\resteasy-validator-provider-11\3.0.12.Final\resteasy-validator-provider-11-3.0.12.Final.jar;D:\SOFT\m2\repository\com\fasterxml\classmate\1.5.1\classmate-1.5.1.jar;D:\SOFT\m2\repository\org\jboss\resteasy\jaxrs-api\3.0.12.Final\jaxrs-api-3.0.12.Final.jar;D:\SOFT\m2\repository\org\jboss\resteasy\resteasy-multipart-provider\3.0.12.Final\resteasy-multipart-provider-3.0.12.Final.jar;D:\SOFT\m2\repository\org\jboss\resteasy\resteasy-jaxb-provider\3.0.12.Final\resteasy-jaxb-provider-3.0.12.Final.jar;D:\SOFT\m2\repository\com\sun\xml\bind\jaxb-impl\2.2.7\jaxb-impl-2.2.7.jar;D:\SOFT\m2\repository\com\sun\xml\bind\jaxb-core\2.2.7\jaxb-core-2.2.7.jar;D:\SOFT\m2\repository\javax\xml\bind\jaxb-api\2.3.1\jaxb-api-2.3.1.jar;D:\SOFT\m2\repository\javax\activation\javax.activation-api\1.2.0\javax.activation-api-1.2.0.jar;D:\SOFT\m2\repository\com\sun\istack\istack-commons-runtime\2.16\istack-commons-runtime-2.16.jar;D:\SOFT\m2\repository\com\sun\xml\fastinfoset\FastInfoset\1.2.12\FastInfoset-1.2.12.jar;D:\SOFT\m2\repository\javax\xml\bind\jsr173_api\1.0\jsr173_api-1.0.jar;D:\SOFT\m2\repository\javax\mail\mail\1.5.0-b01\mail-1.5.0-b01.jar;D:\SOFT\m2\repository\org\apache\james\apache-mime4j\0.6\apache-mime4j-0.6.jar;D:\SOFT\m2\repository\commons-logging\commons-logging\1.1.1\commons-logging-1.1.1.jar;D:\SOFT\m2\repository\com\alibaba\dubbo\2.4.10\dubbo-2.4.10.jar;D:\SOFT\m2\repository\org\jboss\netty\netty\3.2.5.Final\netty-3.2.5.Final.jar;D:\SOFT\m2\repository\com\101tec\zkclient\0.10\zkclient-0.10.jar;D:\SOFT\m2\repository\com\alibaba\nacos\nacos-api\1.0.0\nacos-api-1.0.0.jar;D:\SOFT\m2\repository\com\alibaba\fastjson\1.2.47\fastjson-1.2.47.jar;D:\SOFT\m2\repository\org\apache\commons\commons-lang3\3.9\commons-lang3-3.9.jar;D:\SOFT\m2\repository\com\alibaba\nacos\nacos-client\1.0.0\nacos-client-1.0.0.jar;D:\SOFT\m2\repository\com\alibaba\nacos\nacos-common\1.0.0\nacos-common-1.0.0.jar;D:\SOFT\m2\repository\commons-codec\commons-codec\1.13\commons-codec-1.13.jar;D:\SOFT\m2\repository\com\fasterxml\jackson\core\jackson-core\2.10.1\jackson-core-2.10.1.jar;D:\SOFT\m2\repository\com\fasterxml\jackson\core\jackson-databind\2.10.1\jackson-databind-2.10.1.jar;D:\SOFT\m2\repository\com\fasterxml\jackson\core\jackson-annotations\2.10.1\jackson-annotations-2.10.1.jar;D:\SOFT\m2\repository\io\prometheus\simpleclient\0.5.0\simpleclient-0.5.0.jar;D:\SOFT\m2\repository\org\springframework\spring-beans\5.2.2.RELEASE\spring-beans-5.2.2.RELEASE.jar;D:\SOFT\m2\repository\org\springframework\spring-core\5.2.2.RELEASE\spring-core-5.2.2.RELEASE.jar;D:\SOFT\m2\repository\org\springframework\spring-jcl\5.2.2.RELEASE\spring-jcl-5.2.2.RELEASE.jar;D:\SOFT\m2\repository\com\alipay\sofa\infra-sofa-boot-starter\3.1.4\infra-sofa-boot-starter-3.1.4.jar;D:\SOFT\m2\repository\com\alipay\sofa\common\log-sofa-boot-starter\1.0.18\log-sofa-boot-starter-1.0.18.jar;D:\SOFT\m2\repository\org\springframework\spring-context\5.2.2.RELEASE\spring-context-5.2.2.RELEASE.jar;D:\SOFT\m2\repository\org\springframework\spring-aop\5.2.2.RELEASE\spring-aop-5.2.2.RELEASE.jar;D:\SOFT\m2\repository\org\springframework\spring-expression\5.2.2.RELEASE\spring-expression-5.2.2.RELEASE.jar;D:\SOFT\m2\repository\com\alipay\sofa\common\sofa-common-tools\1.0.18\sofa-common-tools-1.0.18.jar;D:\SOFT\m2\repository\org\springframework\boot\spring-boot-starter-validation\2.2.2.RELEASE\spring-boot-starter-validation-2.2.2.RELEASE.jar;D:\SOFT\m2\repository\jakarta\validation\jakarta.validation-api\2.0.1\jakarta.validation-api-2.0.1.jar;D:\SOFT\m2\repository\org\hibernate\validator\hibernate-validator\6.0.18.Final\hibernate-validator-6.0.18.Final.jar;D:\SOFT\m2\repository\org\jboss\logging\jboss-logging\3.4.1.Final\jboss-logging-3.4.1.Final.jar;D:\SOFT\m2\repository\org\apache\tomcat\embed\tomcat-embed-el\9.0.29\tomcat-embed-el-9.0.29.jar;D:\SOFT\m2\repository\org\springframework\boot\spring-boot-autoconfigure\2.2.2.RELEASE\spring-boot-autoconfigure-2.2.2.RELEASE.jar;D:\SOFT\m2\repository\org\springframework\boot\spring-boot\2.2.2.RELEASE\spring-boot-2.2.2.RELEASE.jar;D:\X\dlm_github\shenyu\shenyu-examples\shenyu-examples-sofa\shenyu-examples-sofa-api\target\classes;D:\SOFT\m2\repository\org\projectlombok\lombok\1.18.10\lombok-1.18.10.jar;D:\X\dlm_github\shenyu\shenyu-spring-boot-starter\shenyu-spring-boot-starter-client\shenyu-spring-boot-starter-client-sofa\target\classes;D:\SOFT\m2\repository\org\springframework\boot\spring-boot-starter\2.2.2.RELEASE\spring-boot-starter-2.2.2.RELEASE.jar;D:\SOFT\m2\repository\org\springframework\boot\spring-boot-starter-logging\2.2.2.RELEASE\spring-boot-starter-logging-2.2.2.RELEASE.jar;D:\SOFT\m2\repository\ch\qos\logback\logback-classic\1.2.3\logback-classic-1.2.3.jar;D:\SOFT\m2\repository\ch\qos\logback\logback-core\1.2.3\logback-core-1.2.3.jar;D:\SOFT\m2\repository\org\apache\logging\log4j\log4j-to-slf4j\2.12.1\log4j-to-slf4j-2.12.1.jar;D:\SOFT\m2\repository\org\apache\logging\log4j\log4j-api\2.12.1\log4j-api-2.12.1.jar;D:\SOFT\m2\repository\org\slf4j\jul-to-slf4j\1.7.29\jul-to-slf4j-1.7.29.jar;D:\SOFT\m2\repository\jakarta\annotation\jakarta.annotation-api\1.3.5\jakarta.annotation-api-1.3.5.jar;D:\SOFT\m2\repository\org\yaml\snakeyaml\1.25\snakeyaml-1.25.jar;D:\X\dlm_github\shenyu\shenyu-client\shenyu-client-sofa\target\classes;D:\X\dlm_github\shenyu\shenyu-client\shenyu-client-common\target\classes;D:\X\dlm_github\shenyu\shenyu-common\target\classes;D:\SOFT\m2\repository\org\springframework\boot\spring-boot-starter-json\2.2.2.RELEASE\spring-boot-starter-json-2.2.2.RELEASE.jar;D:\SOFT\m2\repository\org\springframework\spring-web\5.2.2.RELEASE\spring-web-5.2.2.RELEASE.jar;D:\SOFT\m2\repository\com\fasterxml\jackson\datatype\jackson-datatype-jdk8\2.10.1\jackson-datatype-jdk8-2.10.1.jar;D:\SOFT\m2\repository\com\fasterxml\jackson\datatype\jackson-datatype-jsr310\2.10.1\jackson-datatype-jsr310-2.10.1.jar;D:\SOFT\m2\repository\com\fasterxml\jackson\module\jackson-module-parameter-names\2.10.1\jackson-module-parameter-names-2.10.1.jar;D:\SOFT\m2\repository\com\squareup\okhttp3\okhttp\3.14.4\okhttp-3.14.4.jar;D:\SOFT\m2\repository\com\squareup\okio\okio\1.17.2\okio-1.17.2.jar;D:\SOFT\m2\repository\com\google\code\gson\gson\2.8.6\gson-2.8.6.jar;D:\SOFT\m2\repository\org\slf4j\slf4j-api\1.7.29\slf4j-api-1.7.29.jar;D:\SOFT\m2\repository\org\slf4j\jcl-over-slf4j\1.7.29\jcl-over-slf4j-1.7.29.jar;C:\Program Files\JetBrains\IntelliJ IDEA 2019.3.3\lib\idea_rt.jar +2021-02-10 02:31:46.060 INFO 2156 --- [ main] org.apache.zookeeper.ZooKeeper : Client environment:java.library.path=C:\Program Files\Java\jdk1.8.0_211\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;C:\Program Files\Common Files\Oracle\Java\javapath;C:\ProgramData\Oracle\Java\javapath;C:\Program Files (x86)\Common Files\Oracle\Java\javapath;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Windows\System32\OpenSSH\;C:\Program Files\Java\jdk1.8.0_211\bin;C:\Program Files\Java\jdk1.8.0_211\jre\bin;D:\SOFT\apache-maven-3.5.0\bin;C:\Program Files\Go\bin;C:\Program Files\nodejs\;C:\Program Files\Python\Python38\;C:\Program Files\OpenSSL-Win64\bin;C:\Program Files\Git\bin;D:\SOFT\protobuf-2.5.0\src;D:\SOFT\zlib-1.2.8;c:\Program Files (x86)\Microsoft SQL Server\100\Tools\Binn\;c:\Program Files\Microsoft SQL Server\100\Tools\Binn\;c:\Program Files\Microsoft SQL Server\100\DTS\Binn\;C:\Program Files\Docker\Docker\resources\bin;C:\ProgramData\DockerDesktop\version-bin;D:\SOFT\gradle-6.0-all\gradle-6.0\bin;C:\Program Files\mingw-w64\x86_64-8.1.0-posix-seh-rt_v6-rev0\mingw64\bin;D:\SOFT\hugo_extended_0.55.5_Windows-64bit;C:\Users\DLM\AppData\Local\Microsoft\WindowsApps;C:\Users\DLM\go\bin;C:\Users\DLM\AppData\Roaming\npm;;C:\Program Files\Microsoft VS Code\bin;C:\Program Files\nimbella-cli\bin;. +2021-02-10 02:31:46.060 INFO 2156 --- [ main] org.apache.zookeeper.ZooKeeper : Client environment:java.io.tmpdir=C:\Users\DLM\AppData\Local\Temp\ +2021-02-10 02:31:46.060 INFO 2156 --- [ main] org.apache.zookeeper.ZooKeeper : Client environment:java.compiler= +2021-02-10 02:31:46.060 INFO 2156 --- [ main] org.apache.zookeeper.ZooKeeper : Client environment:os.name=Windows 10 +2021-02-10 02:31:46.060 INFO 2156 --- [ main] org.apache.zookeeper.ZooKeeper : Client environment:os.arch=amd64 +2021-02-10 02:31:46.060 INFO 2156 --- [ main] org.apache.zookeeper.ZooKeeper : Client environment:os.version=10.0 +2021-02-10 02:31:46.060 INFO 2156 --- [ main] org.apache.zookeeper.ZooKeeper : Client environment:user.name=DLM +2021-02-10 02:31:46.060 INFO 2156 --- [ main] org.apache.zookeeper.ZooKeeper : Client environment:user.home=C:\Users\DLM +2021-02-10 02:31:46.060 INFO 2156 --- [ main] org.apache.zookeeper.ZooKeeper : Client environment:user.dir=D:\X\dlm_github\shenyu +2021-02-10 02:31:46.061 INFO 2156 --- [ main] org.apache.zookeeper.ZooKeeper : Initiating client connection, connectString=127.0.0.1:21810 sessionTimeout=60000 watcher=org.apache.curator.ConnectionState@3e850122 +2021-02-10 02:31:46.069 INFO 2156 --- [27.0.0.1:21810)] org.apache.zookeeper.ClientCnxn : Opening socket connection to server 127.0.0.1/127.0.0.1:21810. Will not attempt to authenticate using SASL (unknown error) +2021-02-10 02:31:46.071 INFO 2156 --- [27.0.0.1:21810)] org.apache.zookeeper.ClientCnxn : Socket connection established to 127.0.0.1/127.0.0.1:21810, initiating session +2021-02-10 02:31:46.078 INFO 2156 --- [27.0.0.1:21810)] org.apache.zookeeper.ClientCnxn : Session establishment complete on server 127.0.0.1/127.0.0.1:21810, sessionid = 0x10005b0d05e0001, negotiated timeout = 40000 +2021-02-10 02:31:46.081 INFO 2156 --- [ain-EventThread] o.a.c.f.state.ConnectionStateManager : State change: CONNECTED +2021-02-10 02:31:46.093 WARN 2156 --- [ main] org.apache.curator.utils.ZKPaths : The version of ZooKeeper being used doesn't support Container nodes. CreateMode.PERSISTENT will be used instead. +2021-02-10 02:31:46.141 INFO 2156 --- [ main] o.d.s.e.s.service.TestSofaApplication : Started TestSofaApplication in 3.41 seconds (JVM running for 4.423) +``` + +## 测试 + +`shenyu-examples-sofa`项目成功启动之后会自动把加 `@ShenyuSofaClient` 注解的接口方法注册到网关。 + +打开`插件列表 -> rpc proxy -> sofa`可以看到插件规则配置列表: + + +![](/img/shenyu/quick-start/sofa/rule-list.png) + +下面使用`postman`模拟`http`的方式来请求你的`sofa`服务: + +![](/img/shenyu/quick-start/sofa/postman-findbyid.png) + +复杂多参数示例:对应接口实现类为`org.apache.shenyu.examples.sofa.service.impl.SofaMultiParamServiceImpl#batchSaveNameAndId` + +```java +@Override +@ShenyuSofaClient(path = "/batchSaveNameAndId") +public SofaSimpleTypeBean batchSaveNameAndId(final List sofaTestList, final String id, final String name) { + SofaSimpleTypeBean simpleTypeBean = new SofaSimpleTypeBean(); + simpleTypeBean.setId(id); + simpleTypeBean.setName("hello world shenyu sofa param batchSaveAndNameAndId :" + name + ":" + sofaTestList.stream().map(SofaSimpleTypeBean::getName).collect(Collectors.joining("-"))); + return simpleTypeBean; + } +``` + +![](/img/shenyu/quick-start/sofa/postman-multiparams.png) diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/quick-start/quick-start-springcloud.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/quick-start/quick-start-springcloud.md new file mode 100644 index 00000000000..812e4fd3f72 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/quick-start/quick-start-springcloud.md @@ -0,0 +1,164 @@ +--- +title: Spring Cloud快速开始 +description: Spring Cloud快速开始 +--- + +本文档演示如何将`Spring Cloud`服务接入到`Apache ShenYu`网关。您可以直接在工程下找到本文档的[示例代码](https://github.com/apache/shenyu/tree/master/shenyu-examples/shenyu-examples-springcloud) 。 + +## 环境准备 + +请参考运维部署的内容,选择一种方式启动`shenyu-admin`。比如,通过 [本地部署](../deployment/deployment-local) 启动`Apache ShenYu`后台管理系统。 + +启动成功后,需要在基础配置`->`插件管理中,把`springCloud` 插件设置为开启。 + + + + +启动网关,如果是通过源码的方式,直接运行`shenyu-bootstrap`中的`ShenyuBootstrapApplication`。 + +> 注意,在启动前,请确保网关已经引入相关依赖。 + +引入网关对`Spring Cloud`的代理插件,并添加相关注册中心依赖: + +```xml + + + org.apache.shenyu + shenyu-spring-boot-starter-plugin-springcloud + ${project.version} + + + + org.springframework.cloud + spring-cloud-commons + 2.2.0.RELEASE + + + + org.apache.shenyu + shenyu-spring-boot-starter-plugin-httpclient + ${project.version} + + + + org.springframework.cloud + spring-cloud-starter-netflix-eureka-client + 2.2.0.RELEASE + + + +``` + +`eureka`配置信息如下: + +```yml +eureka: + client: + serviceUrl: + defaultZone: http://localhost:8761/eureka/ + instance: + prefer-ip-address: true +``` + +特别注意: 请保证`springCloud`注册中心服务发现配置为开启 + +* 配置方式 + +```yml +spring: + cloud: + discovery: + enabled: true +``` + +* 代码方式 + +```java +@SpringBootApplication +@EnableDiscoveryClient +public class ShenyuBootstrapApplication { + + /** + * Main Entrance. + * + * @param args startup arguments + */ + public static void main(final String[] args) { + SpringApplication.run(ShenyuBootstrapApplication.class, args); + } +} +``` + +启动`shenyu-bootstrap`项目。 + +## 运行shenyu-examples-springcloud + +示例项目中我们使用 `eureka` 作为 `Spring Cloud`的注册中心。你可以使用本地的`eureka`,也可以使用示例中提供的应用。 + +下载 [shenyu-examples-eureka](https://github.com/apache/shenyu/tree/master/shenyu-examples/shenyu-examples-eureka) 、[shenyu-examples-springcloud](https://github.com/apache/shenyu/tree/master/shenyu-examples/shenyu-examples-springcloud) . + +启动`eureka`服务,运行`org.apache.shenyu.examples.eureka.EurekaServerApplication`main方法启动项目。 + +启动`spring cloud`服务,运行`org.apache.shenyu.examples.springcloud.ShenyuTestSpringCloudApplication`main方法启动项目。 + +从`2.4.3`开始,用户可以不配置`shenyu.client.springCloud.props.port`。 + +成功启动会有如下日志: + +```shell +2021-02-10 14:03:51.301 INFO 2860 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor' +2021-02-10 14:03:51.669 INFO 2860 --- [pool-1-thread-1] o.d.s.client.common.utils.RegisterUtils : springCloud client register success: {"appName":"springCloud-test","context":"/springcloud","path":"/springcloud/order/save","pathDesc":"","rpcType":"springCloud","ruleName":"/springcloud/order/save","enabled":true} +2021-02-10 14:03:51.676 INFO 2860 --- [pool-1-thread-1] o.d.s.client.common.utils.RegisterUtils : springCloud client register success: {"appName":"springCloud-test","context":"/springcloud","path":"/springcloud/order/path/**","pathDesc":"","rpcType":"springCloud","ruleName":"/springcloud/order/path/**","enabled":true} +2021-02-10 14:03:51.682 INFO 2860 --- [pool-1-thread-1] o.d.s.client.common.utils.RegisterUtils : springCloud client register success: {"appName":"springCloud-test","context":"/springcloud","path":"/springcloud/order/findById","pathDesc":"","rpcType":"springCloud","ruleName":"/springcloud/order/findById","enabled":true} +2021-02-10 14:03:51.688 INFO 2860 --- [pool-1-thread-1] o.d.s.client.common.utils.RegisterUtils : springCloud client register success: {"appName":"springCloud-test","context":"/springcloud","path":"/springcloud/order/path/**/name","pathDesc":"","rpcType":"springCloud","ruleName":"/springcloud/order/path/**/name","enabled":true} +2021-02-10 14:03:51.692 INFO 2860 --- [pool-1-thread-1] o.d.s.client.common.utils.RegisterUtils : springCloud client register success: {"appName":"springCloud-test","context":"/springcloud","path":"/springcloud/test/**","pathDesc":"","rpcType":"springCloud","ruleName":"/springcloud/test/**","enabled":true} +2021-02-10 14:03:52.806 WARN 2860 --- [ main] ockingLoadBalancerClientRibbonWarnLogger : You already have RibbonLoadBalancerClient on your classpath. It will be used by default. As Spring Cloud Ribbon is in maintenance mode. We recommend switching to BlockingLoadBalancerClient instead. In order to use it, set the value of `spring.cloud.loadbalancer.ribbon.enabled` to `false` or remove spring-cloud-starter-netflix-ribbon from your project. +2021-02-10 14:03:52.848 WARN 2860 --- [ main] iguration$LoadBalancerCaffeineWarnLogger : Spring Cloud LoadBalancer is currently working with default default cache. You can switch to using Caffeine cache, by adding it to the classpath. +2021-02-10 14:03:52.921 INFO 2860 --- [ main] o.s.c.n.eureka.InstanceInfoFactory : Setting initial instance status as: STARTING +2021-02-10 14:03:52.949 INFO 2860 --- [ main] com.netflix.discovery.DiscoveryClient : Initializing Eureka in region us-east-1 +2021-02-10 14:03:53.006 INFO 2860 --- [ main] c.n.d.provider.DiscoveryJerseyProvider : Using JSON encoding codec LegacyJacksonJson +2021-02-10 14:03:53.006 INFO 2860 --- [ main] c.n.d.provider.DiscoveryJerseyProvider : Using JSON decoding codec LegacyJacksonJson +2021-02-10 14:03:53.110 INFO 2860 --- [ main] c.n.d.provider.DiscoveryJerseyProvider : Using XML encoding codec XStreamXml +2021-02-10 14:03:53.110 INFO 2860 --- [ main] c.n.d.provider.DiscoveryJerseyProvider : Using XML decoding codec XStreamXml +2021-02-10 14:03:53.263 INFO 2860 --- [ main] c.n.d.s.r.aws.ConfigClusterResolver : Resolving eureka endpoints via configuration +2021-02-10 14:03:53.546 INFO 2860 --- [ main] com.netflix.discovery.DiscoveryClient : Disable delta property : false +2021-02-10 14:03:53.546 INFO 2860 --- [ main] com.netflix.discovery.DiscoveryClient : Single vip registry refresh property : null +2021-02-10 14:03:53.547 INFO 2860 --- [ main] com.netflix.discovery.DiscoveryClient : Force full registry fetch : false +2021-02-10 14:03:53.547 INFO 2860 --- [ main] com.netflix.discovery.DiscoveryClient : Application is null : false +2021-02-10 14:03:53.547 INFO 2860 --- [ main] com.netflix.discovery.DiscoveryClient : Registered Applications size is zero : true +2021-02-10 14:03:53.547 INFO 2860 --- [ main] com.netflix.discovery.DiscoveryClient : Application version is -1: true +2021-02-10 14:03:53.547 INFO 2860 --- [ main] com.netflix.discovery.DiscoveryClient : Getting all instance registry info from the eureka server +2021-02-10 14:03:53.754 INFO 2860 --- [ main] com.netflix.discovery.DiscoveryClient : The response status is 200 +2021-02-10 14:03:53.756 INFO 2860 --- [ main] com.netflix.discovery.DiscoveryClient : Starting heartbeat executor: renew interval is: 30 +2021-02-10 14:03:53.758 INFO 2860 --- [ main] c.n.discovery.InstanceInfoReplicator : InstanceInfoReplicator onDemand update allowed rate per min is 4 +2021-02-10 14:03:53.761 INFO 2860 --- [ main] com.netflix.discovery.DiscoveryClient : Discovery Client initialized at timestamp 1612937033760 with initial instances count: 0 +2021-02-10 14:03:53.762 INFO 2860 --- [ main] o.s.c.n.e.s.EurekaServiceRegistry : Registering application SPRINGCLOUD-TEST with eureka with status UP +2021-02-10 14:03:53.763 INFO 2860 --- [ main] com.netflix.discovery.DiscoveryClient : Saw local status change event StatusChangeEvent [timestamp=1612937033763, current=UP, previous=STARTING] +2021-02-10 14:03:53.765 INFO 2860 --- [nfoReplicator-0] com.netflix.discovery.DiscoveryClient : DiscoveryClient_SPRINGCLOUD-TEST/host.docker.internal:springCloud-test:8884: registering service... +2021-02-10 14:03:53.805 INFO 2860 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8884 (http) with context path '' +2021-02-10 14:03:53.807 INFO 2860 --- [ main] .s.c.n.e.s.EurekaAutoServiceRegistration : Updating port to 8884 +2021-02-10 14:03:53.837 INFO 2860 --- [nfoReplicator-0] com.netflix.discovery.DiscoveryClient : DiscoveryClient_SPRINGCLOUD-TEST/host.docker.internal:springCloud-test:8884 - registration status: 204 +2021-02-10 14:03:54.231 INFO 2860 --- [ main] o.d.s.e.s.ShenyuTestSpringCloudApplication : Started ShenyuTestSpringCloudApplication in 6.338 seconds (JVM running for 7.361) +``` + + +## 测试Http请求 + +`shenyu-examples-springcloud`项目成功启动之后会自动把加 `@ShenyuSpringCloudClient` 注解的接口方法注册到网关。 + +打开`插件列表 -> rpc proxy -> springCloud` 可以看到插件规则配置列表: + + +![](/img/shenyu/quick-start/springcloud/rule-list.png) + +下面使用`postman`模拟`http`的方式来请求你的`SpringCloud`服务: + +![](/img/shenyu/quick-start/springcloud/postman-test.png) + +使用 `IDEA HTTP Client` 插件模拟`http`的方式来请求你的`SpringCloud`服务[本地访问,不使用`shenyu`代理]: + +![](/img/shenyu/quick-start/springcloud/idea-http-test-local.png) + +使用 `IDEA HTTP Client` 插件模拟`http`的方式来请求你的`SpringCloud`服务[使用`shenyu`代理]: + +![](/img/shenyu/quick-start/springcloud/idea-http-test-proxy.png) diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/quick-start/quick-start-tars.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/quick-start/quick-start-tars.md new file mode 100644 index 00000000000..9bd090896a1 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/quick-start/quick-start-tars.md @@ -0,0 +1,116 @@ +--- +title: Tars快速开始 +description: Tars快速开始 +--- + +本文档演示如何将`Tars`服务接入到`Apache ShenYu`网关。您可以直接在工程下找到本文档的[示例代码](https://github.com/apache/shenyu/tree/master/shenyu-examples/shenyu-examples-tars) 。 + +## 环境准备 + +请参考运维部署的内容,选择一种方式启动`shenyu-admin`。比如,通过 [本地部署](../deployment/deployment-local) 启动`Apache ShenYu`后台管理系统。 + +启动成功后,需要在基础配置`->`插件管理中,把`tars` 插件设置为开启。 + + + +启动网关,如果是通过源码的方式,直接运行`shenyu-bootstrap`中的`ShenyuBootstrapApplication`。 + +> 注意,在启动前,请确保网关已经引入相关依赖。 + +引入网关对`tars`的依赖: + +```xml + + org.apache.shenyu + shenyu-spring-boot-starter-plugin-tars + ${project.version} + + + + com.tencent.tars + tars-client + 1.7.2 + +``` + +## 运行shenyu-examples-tars项目 + +下载[shenyu-examples-tars](https://github.com/apache/shenyu/tree/master/shenyu-examples/shenyu-examples-tars) + +修改`application.yml`中的`host`为你本地ip。 + +修改配置`src/main/resources/ShenyuExampleServer.ShenyuExampleApp.config.conf`: + +* 建议弄清楚 `config` 的主要配置项含义, 参考开发指南。 +* `config` 中的 `ip` 要注意提供成本机的。 +* `local=...`, 表示开放的本机给 `tarsnode` 连接的端口, 如果没有 `tarsnode`, 可以去掉这项配置。 +* `locator`: `registry`服务的地址,必须是有`ip`和 `port`的,如果不需要`registry`来定位服务,则不需要配置。 +* `node=tars.tarsnode.ServerObj@xxxx`,表示连接的 `tarsnode` 的地址,如果本地没有 `tarsnode`, 这项配置可以去掉。 + +更多config配置说明请参考 [Tars官方文档](https://github.com/TarsCloud/TarsJava/blob/master/docs/tars_java_user_guide.md) + +运行`org.apache.shenyu.examples.tars.ShenyuTestTarsApplication`main方法启动项目。 + +**注:** 服务启动时需要在启动命令中指定配置文件地址 **-Dconfig=xxx/ShenyuExampleServer.ShenyuExampleApp.config.conf** + +如果不加`-Dconfig`参数配置会可能会如下抛异常: + +```xml +com.qq.tars.server.config.ConfigurationException: error occurred on load server config + at com.qq.tars.server.config.ConfigurationManager.loadServerConfig(ConfigurationManager.java:113) + at com.qq.tars.server.config.ConfigurationManager.init(ConfigurationManager.java:57) + at com.qq.tars.server.core.Server.loadServerConfig(Server.java:90) + at com.qq.tars.server.core.Server.(Server.java:42) + at com.qq.tars.server.core.Server.(Server.java:38) + at com.qq.tars.spring.bean.PropertiesListener.onApplicationEvent(PropertiesListener.java:37) + at com.qq.tars.spring.bean.PropertiesListener.onApplicationEvent(PropertiesListener.java:31) + at org.springframework.context.event.SimpleApplicationEventMulticaster.doInvokeListener(SimpleApplicationEventMulticaster.java:172) + at org.springframework.context.event.SimpleApplicationEventMulticaster.invokeListener(SimpleApplicationEventMulticaster.java:165) + at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:139) + at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:127) + at org.springframework.boot.context.event.EventPublishingRunListener.environmentPrepared(EventPublishingRunListener.java:76) + at org.springframework.boot.SpringApplicationRunListeners.environmentPrepared(SpringApplicationRunListeners.java:53) + at org.springframework.boot.SpringApplication.prepareEnvironment(SpringApplication.java:345) + at org.springframework.boot.SpringApplication.run(SpringApplication.java:308) + at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226) + at org.springframework.boot.SpringApplication.run(SpringApplication.java:1215) + at org.apache.shenyu.examples.tars.ShenyuTestTarsApplication.main(ShenyuTestTarsApplication.java:38) +Caused by: java.lang.NullPointerException + at java.io.FileInputStream.(FileInputStream.java:130) + at java.io.FileInputStream.(FileInputStream.java:93) + at com.qq.tars.common.util.Config.parseFile(Config.java:211) + at com.qq.tars.server.config.ConfigurationManager.loadServerConfig(ConfigurationManager.java:63) + ... 17 more +The exception occurred at load server config +``` + +成功启动会有如下日志: + +```shell +[SERVER] server starting at tcp -h 127.0.0.1 -p 21715 -t 60000... +[SERVER] server started at tcp -h 127.0.0.1 -p 21715 -t 60000... +[SERVER] server starting at tcp -h 127.0.0.1 -p 21714 -t 3000... +[SERVER] server started at tcp -h 127.0.0.1 -p 21714 -t 3000... +[SERVER] The application started successfully. +The session manager service started... +[SERVER] server is ready... +2021-02-09 13:28:24.643 INFO 16016 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 55290 (http) with context path '' +2021-02-09 13:28:24.645 INFO 16016 --- [ main] o.d.s.e.tars.ShenyuTestTarsApplication : Started ShenyuTestTarsApplication in 4.232 seconds (JVM running for 5.1) +2021-02-09 13:28:24.828 INFO 16016 --- [pool-2-thread-1] o.d.s.client.common.utils.RegisterUtils : tars client register success: {"appName":"127.0.0.1:21715","contextPath":"/tars","path":"/tars/helloInt","pathDesc":"","rpcType":"tars","serviceName":"ShenyuExampleServer.ShenyuExampleApp.HelloObj","methodName":"helloInt","ruleName":"/tars/helloInt","parameterTypes":"int,java.lang.String","rpcExt":"{\"methodInfo\":[{\"methodName\":\"helloInt\",\"params\":[{},{}],\"returnType\":\"java.lang.Integer\"},{\"methodName\":\"hello\",\"params\":[{},{}],\"returnType\":\"java.lang.String\"}]}","enabled":true} +2021-02-09 13:28:24.837 INFO 16016 --- [pool-2-thread-1] o.d.s.client.common.utils.RegisterUtils : tars client register success: {"appName":"127.0.0.1:21715","contextPath":"/tars","path":"/tars/hello","pathDesc":"","rpcType":"tars","serviceName":"ShenyuExampleServer.ShenyuExampleApp.HelloObj","methodName":"hello","ruleName":"/tars/hello","parameterTypes":"int,java.lang.String","rpcExt":"{\"methodInfo\":[{\"methodName\":\"helloInt\",\"params\":[{},{}],\"returnType\":\"java.lang.Integer\"},{\"methodName\":\"hello\",\"params\":[{},{}],\"returnType\":\"java.lang.String\"}]}","enabled":true} +``` + + +## 测试 + +`shenyu-examples-tars`项目成功启动之后会自动把加 `@ShenyuTarsClient` 注解的接口方法注册到网关。 + +打开`插件列表 -> rpc proxy -> tars` 可以看到插件规则配置列表: + + +![](/img/shenyu/quick-start/tars/rule-list.png) + +下面使用`postman`模拟`http`的方式来请求你的`tars`服务: + +![](/img/shenyu/quick-start/tars/postman-test.png) + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/quick-start/quick-start-websocket.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/quick-start/quick-start-websocket.md new file mode 100644 index 00000000000..07eea4fcf33 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/quick-start/quick-start-websocket.md @@ -0,0 +1,147 @@ +--- +title: Websocket快速开始 +description: Websocket快速开始 +--- + +本文档演示如何将`Websocket`服务接入到`Apache ShenYu`网关。 + +## 环境准备 + +> 参考[运维部署](../deployment/deployment-local)的内容,部署 Shenyu 网关 + +1. 部署 `shenyu-admin` 服务 + +- 启动成功后,需要在页面的基础配置`->`插件管理中,把`Websocket` 插件设置为开启。 + + + +2. 部署 `shenyu-bootstrap` 服务 + +- 启动之后 `shenyu-bootstrap` 会根据 `shenyu.sync.websocket.url`配置的地址,通过 `websocket` 协议进行数据同步 + +> 注意:在启动前,请确保网关已经引入相关依赖,默认已引入该依赖。 + +引入网关对`Websocket`的代理插件,在网关的 `pom.xml` 文件中增加如下依赖: + +```xml + + + org.apache.shenyu + shenyu-spring-boot-starter-plugin-websocket + ${project.version} + +``` + + +## 运行shenyu-examples-websocket项目 + +1. 下载 [shenyu-examples-websocket](https://github.com/apache/shenyu/tree/master/shenyu-examples/shenyu-examples-websocket/shenyu-example-spring-annotation-websocket)(`native-websocket` 和 `reactive-websocket` 可以参考[shenyu-examples-websocket](https://github.com/apache/shenyu/tree/master/shenyu-examples/shenyu-examples-websocket) 下的子项目) + +2. 运行`org.apache.shenyu.examples.websocket.TestAnnotationWebsocketApplication` main方法启动项目。 + +- examples项目会根据 `shenyu.register.serverLists` 配置的地址,通过 `http` 协议将 websocket 服务的信息同步给 `shenyu-admin`, 之后再由 `shenyu-admin` 同步给 `shenyu-bootstrap`。 + +成功启动会有如下日志: + +```shell +2022-08-09 23:37:34.994 INFO 61398 --- [or_consumer_-21] o.a.s.r.client.http.utils.RegisterUtils : metadata client register success: {"appName":"ws-annotation","contextPath":"/ws-annotation","path":"/ws-annotation/myWs","rpcType":"websocket","ruleName":"/ws-annotation/myWs","enabled":true,"pluginNames":[],"registerMetaData":false,"timeMillis":1660059454701} +2022-08-09 23:37:35.019 INFO 61398 --- [or_consumer_-18] o.a.s.r.client.http.utils.RegisterUtils : uri client register success: {"protocol":"ws://","appName":"ws-annotation","contextPath":"/ws-annotation","rpcType":"websocket","host":"192.168.1.3","port":8001} +``` + +## 测试websocket请求 + +1. `shenyu-examples-websocket`项目成功启动之后会自动把加 `@ShenyuSpringWebSocketClient` 注解的接口方法注册到网关,并添加选择器和规则,可以通过访问 `shenyu-admin` 页面 -> 插件列表 -> Proxy -> Websocket 看到 `shenyu-examples-websocket` 服务注册的信息,如果没有,可以参考[Websocket插件](../plugin-center/proxy/websocket-plugin.md)手动添加配置。 + + + +2. 下面使用测试代码(见附件)模拟 `Websocket` 协议的请求方式来请求你的`Websocket`服务。 + + + +## 附件 + +**websocket调试代码** + +- 创建一个名为 websocket.html 的文件,复制下面的代码到文件中 +- 使用谷歌浏览器打开 websocket.html + +```html + + + + + Shenyu WebSocket Test + + + +
+
+ + +
+
+ + + +``` diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/_category_.json b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/_category_.json new file mode 100644 index 00000000000..74eb92f7051 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/_category_.json @@ -0,0 +1,4 @@ +{ + "label": "用户指南", + "position": 5 +} diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/admin-usage/_category_.json b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/admin-usage/_category_.json new file mode 100644 index 00000000000..7626d8d2011 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/admin-usage/_category_.json @@ -0,0 +1,4 @@ +{ + "label": "Admin使用", + "position": 1 +} diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/admin-usage/api-document.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/admin-usage/api-document.md new file mode 100644 index 00000000000..b0a9114f35f --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/admin-usage/api-document.md @@ -0,0 +1,86 @@ +--- +title: API文档管理 +keywords: ["api doc 接口 文档"] +description: API文档管理 +--- + +## 1. 背景与说明 + +前后端联调时,通常需要后端给出文档以详细说明接口的输入输出; + +后端开发完成后,需要测试接入网关是否成功。 + +为了减少割裂感、提升前后端开发的用户体验,需要在shenyu-admin中看到API文档,以及直接对API进行测试。 + +## 2. 使用流程 + +大体的流程如下: +- 后端开发在shenyu-admin中产出API文档。 +> 已经支持`远程拉取swagger`、`手动填写`、`客户端注册`3种方式。从功能完整性和使用体验上,目前更推荐`远程拉取swagger`,后2种方式将会在后面版本持续功能增强。 +- 前端在shenyu-admin中查看API文档并开始开发。 +> 联调期间开发人员(包括前后端)可以直接使用shenyu-admin中的接口调试功能发起API调用。 + +## 3. 设置全局的环境地址 + +实际使用中,可能你有多个网关地址(比如生产环境、测试环境,或者公网环境、内网环境),你可以在`Apache ShenYu`网关管理系统 --> 基础配置 --> 字典管理,配置多个网关地址。 + +![apidoc-env-cn](/img/shenyu/basicConfig/apiManagement/apidoc-env-cn.png) + +> 字典类型:填写值必须是`apidocEnv`; +> +> 字典编码:网关地址的编码标识,无实际含义,建议以 `ENV_LABEL_`作为前缀,比如 `ENV_LABEL_OFFLINE`; +> +> 字典名称:表示网关类型,比如填写 `测试环境`、`生产环境`。该值将会出现在API文档详情页面; +> +> 字典值:表示网关地址,比如 http://127.0.0.1:9195。该值将会出现在API文档详情页面; +> +> 字典描述或备注:该网关地址用于何种场景,做一个简短描述。该值将会出现在API文档详情页面; +> +> 排序:数值大小决定了网关地址的展示顺序; +> +> 状态:打开或关闭。 + +## 4. 支持多种方式聚合API文档 + +### 4.1 手动填写API文档 + +点击菜单 "文档 -> API文档", 展示的页面中新增数据。 + +##### 创建项目 + +如果你还没有创建过项目或者你要把新建的API归类到新项目,这时需要你创建一个项目。 + +![app-create-cn](/img/shenyu/basicConfig/apiManagement/app-create-cn.png) + +##### 增加API文档 + +![create-api-cn](/img/shenyu/basicConfig/apiManagement/create-api-cn.png) + +### 4.2 远程拉取swagger注册API文档 + + 通过远程拉取swaager文档自动注册API文档。请参考[远程拉取swagger注册API文档](../api-doc/swagger-apidoc.md) + +### 4.3 Shenyu客户端注解注册API文档 + + 通过Shenyu客户端注解自动注册API文档。请参考[客户端注册API文档](../api-doc/shenyu-annotation-apidoc.md) +> 若你没有查看完整接口文档详情的诉求,推荐使用这此方式。当你选择了这种自动注册方式,请关闭远程自动拉取swagger的注册方式,否则会有冲突。 + +## 5. 发布API + +如果该API从未发布到proxy插件或你不打算使用shenyu客户端提供的注解注册URI,shenyu-admin的发布API功能为你提供了另一种可选方式,它将自动注册该API到网关,跟你使用shenyu客户端的注解效果一样。 + +![publish-api-cn](/img/shenyu/basicConfig/apiManagement/publish-api-cn.png) + +点击保存后,你会看到,在选择器和规则下面插入了该API的注册数据。如下图所示: + +![api-published-divide-list-cn](/img/shenyu/basicConfig/apiManagement/api-published-divide-list-cn.png) + +## 6. 下线API(可选) + +> 特别注意:点击下线后,该API虽然在API文档列表仍然可见,但会从proxy插件和元数据管理列表中删除,在你重新发布该API前,网关不会代理该API,当你通过网关请求该API时,会报异常。 + +![offline-api-cn](/img/shenyu/basicConfig/apiManagement/offline-api-cn.png) + +## 7. 请求API(接口调试) + +![api-debug-cn](/img/shenyu/basicConfig/apiManagement/api-debug-cn.png) diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/admin-usage/data-permission.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/admin-usage/data-permission.md new file mode 100644 index 00000000000..3d9c3d6a53d --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/admin-usage/data-permission.md @@ -0,0 +1,54 @@ +--- +title: 数据权限管理 +keywords: ["用户 插件 数据权限"] +description: 用户插件数据管理 +--- + +## 背景与说明 + +为了实现插件所代理的不同 selector / rule 由不同的业务部门管理,需要对插件的 selector / rule 数据安全针对用户进行控制 +用户未配置数据权限时候,是拥有所有数据权限的, 只要配置了权限就会进行数据权限控制。如下图所示: + + + + +## 操作流程 + +大体的流程如下: +- 拥有管理用户权限的用户(包含 admin 用户) 新建用户。 +- 拥有管理用户数据权限的用户(包含 admin 用户)点击操作中的 `配置数据权限`。 +> 在此之前请确保插件列表中存在数据。如果没有则需要拥有管理插件权限的用户进行插件数据的增加。 + + +接下来我们看下具体操作: + +### 新建用户 + +在点击菜单 "系统管理 -> 用户管理" 展示的页面中新增数据。如下图所示: + + +### 编辑数据权限 + +#### 增加插件数据 + +在插件列表中增加数据,本文以 `divide` 为例 + + +#### 增加菜单权限 + +给默认的角色赋予 divide 插件的权限。 + + +默认的角色没有任何的菜单权限,如果赋予了用户,该用户将无法登录。将数据权限所在的菜单赋予该角色。 + +#### 配置用户的数据权限 + +新增用户后,我们看到普通用户之后会有一个编辑数据权限的按钮,可以对用户进行数据权限的管理。 + + +这里的出现列表就是当时在插件中新增的数据。 + +### 新用户登录 + +新用户登录后只能看到已经赋予权限的数据。 + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/admin-usage/dictionary-management.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/admin-usage/dictionary-management.md new file mode 100644 index 00000000000..929bee687c5 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/admin-usage/dictionary-management.md @@ -0,0 +1,30 @@ +--- +title: 字典管理 +keywords: ["字典"] +description: 字典管理详解 +--- + +本文档将介绍`Apache ShenYu`后台管理系统中字典管理的使用,字典管理主要用来维护和管理公用数据字典。 + +请参考运维部署的内容,选择一种方式启动`shenyu-admin`。比如,通过 [本地部署](../../deployment/deployment-local) 启动`Apache ShenYu`后台管理系统。 启动成功后,可以直接访问 http://localhost:9095 ,默认用户名和密码分别为: `admin` 和 `123456`。 + + +目前使用场景是在 [插件处理管理](./plugin-handle-explanation) 时,选择数据类型是 `下拉框` 时使用: + + + +在字典管理中,你可以新增字典类型,供其他地方使用: + + + +* 字典类型:在插件处理管理时,使用的字段名称。 +* 字典编码:标识字典数据。 +* 字典名称:在添加插件、选择器或规则时`handle`字段的名称。 +* 字典值:字典数据实际取值。 +* 字典描述或备注:描述信息。 +* 排序:字典数据顺序。 + +例如, `sentinel` 插件处理字段中的 `degradeRuleGrade`。当新增规则时,编辑 `degradeRuleGrade` 字段时,会自动从字典管理中查出 `type='degradeRuleGrade'` 的所有字典数据作为下拉选项: + + + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/admin-usage/plugin-handle-explanation.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/admin-usage/plugin-handle-explanation.md new file mode 100644 index 00000000000..99c7808114f --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/admin-usage/plugin-handle-explanation.md @@ -0,0 +1,51 @@ +--- +title: 插件配置 +keywords: ["插件"] +description: 插件配置 +--- + +本文档将介绍`Apache ShenYu`后台管理系统中插件的使用,包括插件管理和插件处理管理。 + + +请参考运维部署的内容,选择一种方式启动`shenyu-admin`。比如,通过 [本地部署](../../deployment/deployment-local) 启动`Apache ShenYu`后台管理系统。 启动成功后,可以直接访问 http://localhost:9095 ,默认用户名和密码分别为: `admin` 和 `123456`。 + +## 插件管理 + +在插件管理中,你可以对所有插件进行统一管理,比如关闭或开启插件: + + + +也可以对某些插件设置配置信息,比如给`Dubbo`插件设置注册中心: + + + +## 插件处理管理 + +在插件处理管理中,你可以对插件、选择器和规则添加`handle`字段。 + +比如给`springCloud`插件的规则列表新增一个字符串类型的字段`path`和一个数字类型的字段`timeout`。 + + +第一步,在 `插件处理管理` 界面新增/编辑`handle`字段: + +![](/img/shenyu/basicConfig/pluginHandle/plugin_handle_edit.png) + +第二步,填写字段信息: + +![](/img/shenyu/basicConfig/pluginHandle/plugin_handle_info.png) + +* 插件名:需要给哪个插件添加`handle`字段,下拉选择。 +* 字段:添加字段的名称。 +* 描述:字段描述信息。 +* 数据类型:数字、字符串、下拉框。如果选择了`下拉框`,则规则新增页面里输入框下拉选择是通过字段名称去字典表中查出所有可选项进行下来选择,所以需要提前在 [字典管理](./dictionary-management) 中录入信息。 +* 字段所属类型:插件、选择器、规则。 +* 排序:字段顺序。 +* 是否必填:是、否。 +* 默认值:为该字段指定一个默认值。 +* 输入提示:用户填写该字段时,出现的提示信息。 +* 校验规则(正则) :用户填写该字段时,使用校验规则。 + +第三步,在`插件列表 -> rpc proxy -> springCloud -> 添加规则`时,就可以输入`path`、`timeout`的信息: + +![](/img/shenyu/basicConfig/pluginHandle/springcloud_rule_handler.png) + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/admin-usage/role-management.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/admin-usage/role-management.md new file mode 100644 index 00000000000..6c1cb5094ed --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/admin-usage/role-management.md @@ -0,0 +1,47 @@ +--- +title: 用户资源管理 +keywords: ["用户 角色"] +description: 用户角色管理 +--- + +本篇主要是讲述 `admin` 控制台通过用户关联的角色,角色赋予菜单和按钮等资源的权限来管理 `admin` 的操作权限。 + + +## 资源管理 + +在菜单栏中 ”系统管理 >> 资源管理“ 中增加菜单和按钮。 + + + +admin 用户显示了 shenyu 网关所有的菜单和按钮。如果需要自定义增加和删除,先增加菜单,在相应的菜单下,增加按钮。通过点击菜单中右侧的编辑小图标进行菜单的编辑 + + +## 角色管理 + +通过菜单栏 ”系统管理 >> 角色管理“ 来关联角色和资源的权限。 默认会生成两个角色,一个超级管理员,一个普通用户。超级管理员为 admin 用户,不可更改,普通用户的角色可以更改其资源属性。 通过编辑相应的角色,赋予角色相应的菜单和按钮权限。 + + + + +## 用户管理 + +通过菜单栏 ”系统管理 >> 用户管理“ 来管理登录到 admin 的用户。默认为 admin 用户,它拥有所有菜单权限和数据权限,不可更改, 不可删除, 只能修改用户名和密码。 +可以通过按钮 ”新增数据“ 来增加用户。通过选择用户角色来管理该用户登录后所看到的菜单和按钮权限。当用户选择了多个角色时,取所有的角色的最大并集。更改用户的角色权限后,已经登录的用户只要刷新页面便能获得更改后的权限。 + +下面以新建用户为例,展示了新用户登录后的权限展示。 + +- 更改默认角色的权限 + + + +- 新增角色并赋予相应的资源权限 + + + +- 新建用户,并赋予相应的角色 + + + +- 用户登录后查看自身的菜单和按钮权限 + + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/admin-usage/selector-and-rule.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/admin-usage/selector-and-rule.md new file mode 100644 index 00000000000..f3f79b26acd --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/admin-usage/selector-and-rule.md @@ -0,0 +1,322 @@ +--- +title: 选择器和规则管理 +keywords: ["选择器", "规则"] +description: 选择器和规则管理 +--- + +本文档将介绍`Apache ShenYu`后台管理系统中选择器和规则的使用,关于选择器和规则的概念及设计请参考 [流量控制](../../design/flow-control)。 + +请参考运维部署的内容,选择一种方式启动`shenyu-admin`。比如,通过 [本地部署](../../deployment/deployment-local) 启动`Apache ShenYu`后台管理系统。 启动成功后,可以直接访问 `http://localhost:9095` ,默认用户名和密码分别为: `admin` 和 `123456`。 + +## 选择器 + +在插件列表中展示了当前的所有插件,可以给每个插件添加选择器和规则: + +![](/img/shenyu/basicConfig/pluginHandle/selector_example.png) + + +例如,给`divide`插件添加选择器: + +![](/img/shenyu/basicConfig/pluginHandle/selector_add.png) + +* 选择器详解: + + * 名称:给选择器取一个名字。 + * 类型:自定义流量(`custom flow`) 或 全流量(`full flow`)。自定义流量就是请求会走下面的匹配方式与条件。全流量则不走。 + * 匹配方式:`and`或者 `or` 是指下面多个条件是按照 并(`and`) 还是 或(`or`) 的方式来组合。 + * 条件: + * `uri`:根据 `uri` 的方式来筛选流量,`match` 的方式支持模糊匹配(`/**`) + * `header`:根据请求头里面的字段来筛选流量。 + * `query`:根据 `uri` 的查询条件来进行筛选流量。 + * `ip`:根据请求的真实 `ip` 来筛选流量。 + * `host`:根据请求的真实 `host` 来筛选流量。 + * `post`:根据请求上下文获取参数,不建议使用。 + * `cookie`:根据请求的 `cookie` 来筛选流量。 + * `req_method`:根据请求的方式来筛选流量。 + * 条件匹配: + * `match`:模糊匹配,建议和`uri`条件搭配,支持 `restful` 风格的匹配。(`/test/**`) + * `=`:前后值相等,才能匹配。 + * `regEx`:正则匹配,表示前面一个值去匹配后面的正则表达式。 + * `contains`:请求包含指定的值,才能匹配。 + * `TimeBefore`:指定时间之前。 + * `TimeAfter`:指定时间之后。 + * `exclude`: 是 `match` 方式的反选。 + * `startsWith`:请求前缀等于指定的值,才能匹配。在特定场景下,可替换 `match` (如用`/test/`来替换`/test/**`)以获得更好的性能。 + * `endsWith`:请求后缀等于指定的值,才能匹配。 + * `pathPattern`:是 `match` 的优化版,性能比`match`更好,但是不支持将`**`写在path中间(如`/api/**/xxx`)。 + * 继续后续选择器:后续选择器还是否执行。 + * 是否开启:打开才会生效。 + * 打印日志:打开时,当匹配上的时候,会打印匹配日志。 + * 执行顺序:当多个选择器的时候,执行顺序小的优先执行,值越小优先级越高。 + * 处理:即`handle`字段,在 [插件处理管理](./plugin-handle-explanation) 中进行设置。作用是:当请求流量匹配上该选择器时,做什么样的处理操作。 +* 上述图片中表示: 当请求的 `uri` 前缀是 `/http`,会转发到 `127.0.0.1:8080` 这个服务上。 +* 选择器建议:可以通过设置 `uri` 条件, `startsWith` 前缀(`/contextPath/`)匹配,进行第一道流量筛选。 +* 选择器(同规则)模糊匹配条件规则: + * `?` 匹配1个字符 + * `*` 匹配0个或多个字符 + * `**` 匹配0个或多个目录 + +## 规则 + +![](/img/shenyu/basicConfig/pluginHandle/rule_handle.png) + +* 当流量经过选择器匹配成功之后,会进入规则来进行最终的流量匹配。 + +* 规则是对流量最终执行逻辑的确认。 + +* 规则详解: + * 名称:给规则取一个名字。 + * 匹配方式:`and` 或者 `or` 是指下面多个条件的组合方式。 + * 条件: + * `uri`:根据 `uri` 的方式来筛选流量,`match` 的方式支持模糊匹配(`/**`) + * `header`:根据请求头里面的字段来筛选流量。 + * `query`:根据 `uri` 的查询条件来进行筛选流量。 + * `ip`:根据请求的真实 `ip` 来筛选流量。 + * `host`:根据请求的真实 `host` 来筛选流量。 + * `post`:不建议使用。 + * `cookie`:根据请求的 `cookie` 来筛选流量。 + * `req_method`:根据请求的 `req_method` 来筛选流量。 + * 条件匹配: + * `match`:模糊匹配,建议和`uri`条件搭配,支持 `restful` 风格的匹配。(`/test/**`) + * `=`:前后值相等,才能匹配。 + * `regEx`:正则匹配,表示前面一个值去匹配后面的正则表达式。 + * `contains`:请求包含指定的值,才能匹配。 + * `TimeBefore`:指定时间之前。 + * `TimeAfter`:指定时间之后。 + * `exclude`: 是 `match` 方式的反选。 + * `startsWith`:请求前缀等于指定的值,才能匹配。在特定场景下,可替换 `match` (如用`/test/`来替换`/test/**`)以获得更好的性能。 + * `endsWith`:请求后缀等于指定的值,才能匹配。 + * `pathPattern`:是 `match` 的优化版,性能比`match`更好,但是不支持将`**`写在path中间(如`/api/**/xxx`)。 + * 是否开启:打开才会生效。 + * 打印日志:打开时,当匹配上的时候,才会打印匹配日志。 + * 执行顺序:当多个规则的时候,执行顺序小的优先执行。 + * 处理:即`handle`字段,在 [插件处理管理](./plugin-handle-explanation) 中进行设置。每个插件的规则处理不一样,具体请查看每个对应插件的处理。 + +* 上图表示:当 `uri` 等于 `/http/order/save` 的时候能够匹配上该规则,就会执行该规则中,负载策略是 `random`,重试次数是 `3` 等处理操作。 + +* 规则建议:可以`uri` 条件, `match` 最真实的`uri路径`,进行流量的最终筛选 。 + +联合选择器,我们来表述一下:当一个请求的 `uri` 为 `/http/order/save`,会通过 `random` 的方式,转发到 `127.0.0.1:8080` 机器上。 + +## 匹配方式 + +匹配方式是指在选择器或规则匹配时,多个条件之间的匹配方式,当前支持 `and` 和 `or`。 + +* `and` + + `and`表示多个条件同时满足才能匹配上选择器或规则。 + + 下图中的示例表示,请求必须同时满足条件 `uri = /http/order/findById` 和 条件 `id = 100` 才能匹配上该条规则。 + + 比如一个真实的请求 `http://localhost:9195/http/order/findById?id=100` 能够同时满足上述两个条件,所以可以匹配上该条规则。 + +![](/img/shenyu/basicConfig/selectorRule/match-strategy-and-zh.png) + + +* `or` + + `or`表示多个条件中满足一个就能匹配上选择器或规则。 + + 下图中的示例表示,请求满足条件 `uri = /http/order/findById` 或者 条件 `id = 100` 就能匹配上该条规则。 + + 比如一个真实的请求 `http://localhost:9195/http/order/findById?id=99` 能够满足上述第一个条件 `uri = /http/order/findById`,所以也可以匹配上该条规则。 + +![](/img/shenyu/basicConfig/selectorRule/match-strategy-or-zh.png) + +## 条件参数 + +对选择器和规则中的条件参数设置再次进行解释。假如下面是一个 `HTTP` 请求的请求头: + +```shell +GET http://localhost:9195/http/order/findById?id=100 +Accept: application/json +Cookie: shenyu=shenyu_cookie +MyHeader: custom-header +``` + +在`ShenYu`中可以通过设置不同的条件参数从请求信息中获取真实数据。 + +- 如果条件参数是`uri`,那么获取到的真实数据是 `/http/order/findById`; +- 如果条件参数是`header`,字段名称是`MyHeader`,那么获取到的真实数据是 `custom-header`; +- 如果条件参数是`query`,字段名称是`id`,那么获取到的真实数据是 `100`; +- 如果条件参数是`ip`,那么获取到的真实数据 `0:0:0:0:0:0:0:1`; +- 如果条件参数是`host`,那么获取到的真实数据是 `0:0:0:0:0:0:0:1`; +- 如果条件参数是`post`,字段名称是`contextPath`,那么获取到的真实数据是 `/http`; +- 如果条件参数是`cookie`,字段名称是`shenyu`,那么获取到的真实数据是 `shenyu_cookie`; +- 如果条件参数是`req_method`,那么获取到的真实数据是 `GET`。 + + +* `uri` (推荐) + + * `uri` 匹配是根据你请求路径中的 `uri` 来进行匹配,在接入网关的时候,前端几乎不用做任何更改。 + + * 当使用 `match` 方式匹配时候,同 `springmvc` 模糊匹配原理相同。 + + * 在选择器中,推荐使用 `uri` 中的前缀来进行匹配,而在规则中,则使用具体路径来进行匹配。 + + * 使用该匹配方式的时候,填写匹配字段的值,图中的示例是`/http/**`。 + + ![](/img/shenyu/basicConfig/selectorRule/parameter-data-uri-zh.png) + +* `header` + + * `header` 是根据你的 `http` 请求头中的字段值来匹配。 + + * 使用该匹配方式的时候,需要填写字段名称和字段值,图中的示例分别是`MyHeader`和`custom-header`。 + + ![](/img/shenyu/basicConfig/selectorRule/parameter-data-header-zh.png) + +* `query` + + * 这个是根据你的 `uri` 中的查询参数来进行匹配,比如 `/test?id=1`,那么可以选择该匹配方式。 + + * 使用该匹配方式的时候,需要填写字段名称和字段值,图中的示例分别是`id`和`1`。 + + ![](/img/shenyu/basicConfig/selectorRule/parameter-data-query-zh.png) + +* `ip` + + * 这个是根据 `http` 调用方的 `ip` 来进行匹配。 + + * 尤其是在 `waf` 插件里面,如果发现一个 `ip`地址有攻击,可以新增一条匹配条件,填上该 `ip`,拒绝该 `ip` 的访问。 + + * 如果在 `Apache ShenYu` 前面使用了 `nginx` 代理,为了获取正确的 `ip`,可以参考 [自定义解析IP与Host](../../developer/custom-parsing-ip-and-host) 。 + + * 使用该匹配方式的时候,填写匹配字段的值,图中的示例是`192.168.236.75`。 + + ![](/img/shenyu/basicConfig/selectorRule/parameter-data-ip-zh.png) + + +* `host` + + * 这个是根据 `http` 调用方的 `host` 来进行匹配。 + + * 尤其是在 `waf` 插件里面,如果发现一个 `host` 地址有攻击,可以新增一条匹配条件,填上该 `host`,拒绝该 `host` 的访问。 + + * 如果在 `Apache ShenYu` 前面使用了 `nginx` 代理,为了获取正确的 `host`,可以参考 [自定义解析IP与Host](../../developer/custom-parsing-ip-and-host) 。 + + * 使用该匹配方式的时候,填写匹配字段的值,图中的示例是`localhost`。 + + ![](/img/shenyu/basicConfig/selectorRule/parameter-data-host-zh.png) + +* `post` + + * 从请求上下文(`org.apache.shenyu.plugin.api.context.ShenyuContext`)中获取条件参数,需要通过反射获取字段的值,不推荐使用此方式。 + + * 使用该匹配方式的时候,需要填写字段名称和字段值,图中的示例分别是`contextPath`和`/http`。 + + ![](/img/shenyu/basicConfig/selectorRule/parameter-data-post-zh.png) + + +* `cookie` + + * 这个是根据 `http` 调用方的请求头中`Cookie`作为条件参数进行匹配。 + + * 使用该匹配方式的时候,需要填写字段名称和字段值,图中的示例分别是`shenyu`和`shenyu_cookie`。 + + ![](/img/shenyu/basicConfig/selectorRule/parameter-data-cookie-zh.png) + +* `req_method` + + * 这个是根据 `http` 调用方的请求形式来进行匹配,比如`GET`、`POST`等。 + + * 使用该匹配方式的时候,填写匹配字段的值,图中的示例是`GET`。 + + ![](/img/shenyu/basicConfig/selectorRule/parameter-data-req_method-zh.png) + +如果想更深入理解条件参数的获取,请阅读相关源码,包名是`org.apache.shenyu.plugin.base.condition.data`: + +|条件参数 | 源码类 | +|:------------------------ |:----- | +|`uri` |`URIParameterData` | +|`header` |`HeaderParameterData` | +|`query` |`QueryParameterData` | +|`ip` |`IpParameterData` | +|`host` |`HostParameterData` | +|`post` |`PostParameterData` | +|`cookie` |`CookieParameterData` | +|`req_method` |`RequestMethodParameterData` | + + +## 条件匹配策略 + +通过条件参数能够获取到请求的真实数据。真实数据如何匹配上选择器或规则预设的条件数据,是通过条件匹配策略来实现。 + +* `match` + + `match` 的方式支持模糊匹配(`/**`)。假如你的选择器条件设置如下,那么请求 `/http/order/findById` 就可以匹配上。 + + ![](/img/shenyu/basicConfig/selectorRule/predicate-judge-match-zh.png) + +* `=` + + `=` 的方式表示请求的真实数据和预设的条件数据相等。假如你的选择器条件设置如下:请求`uri`等于`/http/order/findById`,那么请求 `/http/order/findById?id=1` 就可以匹配上。 + + ![](/img/shenyu/basicConfig/selectorRule/predicate-judge-equals-zh.png) + +* `regex` + + `regex` 的方式表示请求的真实数据能够满足预设条件的正则表达式才能匹配成功。假如你的规则条件设置如下:请求参数中包含`id`,并且是3位数字。那么请求 `/http/order/findById?id=900` 就可以匹配上。 + + ![](/img/shenyu/basicConfig/selectorRule/predicate-judge-regex-zh.png) + +* `contains` + + `contains` 的方式表示请求的真实数据包含预设的条件数据。假如你的规则条件设置如下:请求`uri`中包含`findById`。那么请求 `/http/order/findById?id=1` 就可以匹配上。 + + ![](/img/shenyu/basicConfig/selectorRule/predicate-judge-contains-zh.png) + +* `TimeBefore` + + `TimeBefore` 的方式表示请求时间在预设的条件时间之前才能匹配成功。假如你的规则条件设置如下:请求参数中包含`date`,并且`date`小于`2021-09-26 06:12:10`。那么请求 `/http/order/findById?id=100&date=2021-09-22 06:12:10` 就可以匹配上。 + + ![](/img/shenyu/basicConfig/selectorRule/predicate-judge-timebefore-zh.png) + +* `TimeAfter` + + `TimeAfter` 的方式表示请求时间在预设的条件时间之后才能匹配成功。假如你的规则条件设置如下:请求参数中包含`date`,并且`date`大于`2021-09-26 06:12:10`。那么请求 `/http/order/findById?id=100&date=2021-09-29 06:12:10` 就可以匹配上。 + + ![](/img/shenyu/basicConfig/selectorRule/predicate-judge-timeafter-zh.png) + +* `exclude` + + `exclude` 的方式是 `match` 方式的反选,`match` 有的功能也都有,但是是匹配过滤。假如你的选择器条件设置如下,那么请求 `/http/order/findById` 就会过滤这个。 + + ![](/img/shenyu/basicConfig/selectorRule/predicate-judge-exclude-zh.png) + +* `startsWith` + + `startsWith` 的方式表示请求的真实数据的前缀和预设的条件数据相等。假如你的规则条件设置如下:请求`uri`中前缀等于`/http/`。那么请求 `/http/order/findById?id=1` 就可以匹配上。 + + ![](/img/shenyu/basicConfig/selectorRule/predicate-judge-startswith-zh.png) + +* `endsWith` + + `endsWith` 的方式表示请求的真实数据的后缀和预设的条件数据相等。假如你的规则条件设置如下:请求`uri`中后缀等于`Id`。那么请求 `/http/order/findById?id=1` 就可以匹配上。 + + ![](/img/shenyu/basicConfig/selectorRule/predicate-judge-endswith-zh.png) + +* `pathPattern` + + 跟 `match` 类似, `pathPattern` 支持模糊匹配(`/**`)。假如你的规则条件设置如下,那么请求 `/http/order/findById` 就可以匹配上; + + 但是注意:不支持将`**`写在path中间(如`/api/**/xxx`)! + + ![](/img/shenyu/basicConfig/selectorRule/predicate-judge-pathpattern-zh.png) + +如果想更深入理解条件匹配策略,请阅读相关源码,包名是`org.apache.shenyu.plugin.base.condition.judge`: + +|匹配策略 | 源码类 | +|:------------------------ |:----- | +|`match` |`MatchPredicateJudge` | +|`=` |`EqualsPredicateJudge` | +|`regex` |`RegexPredicateJudge` | +|`contains` |`ContainsPredicateJudge` | +|`TimeBefore` |`TimerBeforePredicateJudge` | +|`TimeAfter` |`TimerAfterPredicateJudge` | +|`exclude` |`ExcludePredicateJudge` | +|`startsWith` |`StartsWithPredicateJudge` | +|`endsWith` |`EndsWithPredicateJudge` | +|`pathPattern` |`PathPatternPredicateJudge` | + +文中的示例是为了说明选择器和规则的使用,具体条件的设置需要根据实际情况选择。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/api-doc/_category_.json b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/api-doc/_category_.json new file mode 100644 index 00000000000..8934b1125d0 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/api-doc/_category_.json @@ -0,0 +1,4 @@ +{ + "label": "API文档聚合", + "position": 6 +} diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/api-doc/shenyu-annotation-apidoc.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/api-doc/shenyu-annotation-apidoc.md new file mode 100644 index 00000000000..0a41e4475f8 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/api-doc/shenyu-annotation-apidoc.md @@ -0,0 +1,38 @@ +--- +title: Shenyu客户端注册API文档 +keywords: ["api doc 接口 文档 register 注册"] +description: Shenyu客户端注册API文档 +--- + +此篇文介绍如何将 `API文档` 暴露到 `Apache ShenYu` 网关。 + +接入前,请正确启动 `shenyu-admin`。 + +## API文档暴露到网关 + +可以参考[shenyu-examples](https://github.com/apache/shenyu/tree/master/shenyu-examples)下面任意一个example的代码。 + +唯一需要做的就是在你的服务中的新增`@ApiModule`和`@ApiDoc`注解,以下是`shenyu-examples-http`中的例子: + +```java +@RestController +@RequestMapping("/order") +@ShenyuSpringMvcClient("/order") +@ApiModule(value = "order") +public class OrderController { + + @GetMapping("/findById") + @ShenyuSpringMvcClient("/findById") + @ApiDoc(desc = "findById") + public OrderDTO findById(@RequestParam("id") final String id) { + return build(id, "hello world findById"); + } + + private OrderDTO build(final String id, final String name) { + OrderDTO orderDTO = new OrderDTO(); + orderDTO.setId(id); + orderDTO.setName(name); + return orderDTO; + } +} +``` diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/api-doc/swagger-apidoc.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/api-doc/swagger-apidoc.md new file mode 100644 index 00000000000..f9ca7b5a6f1 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/api-doc/swagger-apidoc.md @@ -0,0 +1,57 @@ +--- +title: 拉取swagger注册API文档 +keywords: ["swagger api 接口 文档聚合"] +description: 远程拉取swagger 注册 API文档 +--- + +此篇文介绍如何将各个后端微服务的 `Swagger API文档` 聚合到 `Apache ShenYu` 网关管理系统。 + +## 1. 说明 + +远程拉取swagger文档,目前仅支持swaggger2.0,并且只支持 Divide 和 SpringCloud 两种代理插件。 + +## 2. 环境准备 + +### 2.1 启动`shenyu-admin` + +参考 `运维部署` , 选择一种方式启动`shenyu-admin`。 + +### 2.2 开启远程拉取swagger文档的全局开关 + +默认已开启。在`Apache ShenYu`网关管理系统 --> 基础配置 --> 字典管理, 找到字典编码为 `apidoc`的数据,修改 字典值: `true`。 +> 【注意】字典值:`true`表示开关已开启,`false`表示已关闭。若关闭后,`shenyu-admin`不会自动拉取各个微服务的swaggger文档。 + +![apidoc-dictionary-cn](/img/shenyu/api-doc/apidoc-dictionary-cn.png) + +## 3. 运行示例项目 + +3.1. 下载 [shenyu-examples-http-swagger2](https://github.com/apache/shenyu/tree/master/shenyu-examples/shenyu-examples-http-swagger2) + +3.2. 运行`org.apache.shenyu.examples.http.ShenyuTestSwaggerApplication` main方法启动项目。 + +examples项目会根据 `shenyu.register.serverLists` 配置的地址,通过 Shenyu client 注解(比如`@ShenyuSpringMvcClient`) 将服务启动信息同步给 `shenyu-admin`, 然后触发 `shenyu-admin` 远程拉取swagger文档并完成解析,最后聚合产出新的API文档。 + +## 4. 演示效果 + +### 4.1 API文档列表 + +在`Apache ShenYu`网关管理系统 --> 文档说明 --> API文档,你可以看到已经聚合好的API文档。 + +![apidoc-swagger-list-cn](/img/shenyu/api-doc/apidoc-swagger-list-cn.png) + +### 4.2 API详情效果 + +![apidoc-detail-cn](/img/shenyu/api-doc/apidoc-detail-cn.png) + +## 5. 如何自动更新API文档 + +### 5.1 重启项目 + +如上面示例那样,通过启动项目触发自动更新API文档。 + +### 5.2 修改proxy插件选择器的启动时间 + +在 proxy插件--> 选择器,找到目标服务,然后修改启动时间。 +> 注意:新设置的启动时间一定不能早于原启动时间,否则不会触发自动拉取并刷新API文档。 + +![app-proxy-startuptime-cn](/img/shenyu/api-doc/app-proxy-startuptime-cn.png) diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/discovery/_category_.json b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/discovery/_category_.json new file mode 100644 index 00000000000..66f64292a8b --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/discovery/_category_.json @@ -0,0 +1,4 @@ +{ + "label": "服务发现", + "position": 4 +} diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/discovery/discovery-mode.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/discovery/discovery-mode.md new file mode 100644 index 00000000000..38724ae89a6 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/discovery/discovery-mode.md @@ -0,0 +1,392 @@ +--- +title: 服务发现模块 +keywords: [ "Discovery" ] +description: 服务发现模块模块 +--- + +# 服务发现模块 + +## 1. 概述 + +### 1.1 模块名称 + +Discovery + +### 1.2 设计 + +- 模块设计图 +![discovery-design.png](/img/shenyu/plugin/discovery/discovery-design.png) + + + +- 数据库设计 + +![db-design.png](/img/shenyu/plugin/discovery/db-design.png) + + +### 1.3 模块功能 + +Discovery 模块赋予了 ShenYu 网关一种主动感知和响应被代理服务列表变化的能力。 +通过 Discovery 网关 admin 服务的主动监听,ShenYu 网关能够及时掌握被代理服务的变动情况。 +这一功能的设计具有灵活性,可以根据需要在**选择器级别**或**插件级别**进行配置。 +目前,已经引入了 Discovery 功能的插件包括 TCP 插件、Divide 插件、Websocket 插件和 gRPC 插件。 + + +### 1.4 监听模式 + +LOCAL, ZOOKEEPER, NACOS, EUREKA, ETCD + +- LOCAL 模式: 主要依靠手动维护 upstream 列表,并推送到网关; +- ZOOKEEPER 模式: 监听 ZooKeeper 中指定节点下临时节点的变化来获取数据; +- NACOS 模式:监听 Nacos 中指定服务名称下实例的变化来获取数据; +- EUREKA 模式: 监听 Eureka 中指定服务名称下实例的变化来获取数据; +- ETCD 模式:通过监听 etcd 中指定节点键值对的变化来获取数据。 + + +### 1.5 作用范围 + +- 插件级别:影响整个插件,所有该插件下的选择器都将默认采用当前的监听模式; +- 选择器级别:适用于当前选择器,对于当前插件下的不同选择器,可以使用不同的监听模式。 + +## 2. 使用 + +### 2.1 插件级别配置 + +#### 2.1.1 服务发现配置 + +- 在支持 Discovery 模块的插件中(当前只有 TCP 插件支持在admin控制台页面,进行插件级别 discovery 配置,其他插件可以通过 shenyu-client 进行插件级别 discovery 配置,见下文中的“配合Shenyu-client使用”), 点击 `服务发现配置`, 在弹出的表单中,选择需要的监听模式, + 并填写服务发现名称、注册服务器URL、注册中心配置参数等: + + +![config-discovery-plugin-zh.png](/img/shenyu/plugin/discovery/config-discovery-plugin-zh.png) + +![config-discovery-plugin-modal-zh.png](/img/shenyu/plugin/discovery/config-discovery-plugin-modal-zh.png) + +#### 2.1.2 在选择器中使用 + +- 点击 `添加选择器`,在新增选择器页面中,我们发现 `类型` 强制选择刚才配置的插件级监听模式,表示所添加的选择器也将采用相同的配置。 + 此时,仅需输入需要监听的 `监听节点` : + + ![add-selector-under-plugin-discovery-zh.png](/img/shenyu/plugin/discovery/add-selector-under-plugin-discovery-zh.png) + +- 这里的 `转换处理` 是指,ShenYu 规定的 upstream 注册数据是以下 JSON 格式传输,包括: + - url: upstream 的 url + - protocol: upstream 的通信协议 + - status: upstream 节点的状态 (0: healthy, 1: unhealthy) + - weight: 权重,计算负载均衡时使用 + + + ```json + { + "url": "127.0.0.1::6379", + "protocol": "tcp", + "status": 0, + "weight": 10 + } + ``` + +- 如果您的服务别名与ShenYu定义的JSON格式不匹配,您可以在 `转换处理` 中进行别名映射。 + 例如,如上图所示,如果您需要将"status"改为"healthy",而保留其他键不变, + 进行如下操作:起一个新的别名,将"status"映射为"healthy", + 同时保留原有JSON键的形式。 +- 进行选择器剩余的属性的配置,详情见具体插件对应的文档。 + +### 2.2 选择器级别配置 + +- 在支持 Discovery 模块的插件中,点击 `添加选择器`,在 `服务发现` 标签页中, + 配置类型、监听节点、服务器URL列表、注册中心参数等字段内容,配置内容仅对当前选择器有效,每次新增选择器需要重新配置。 + +![add-selector-zh.png](/img/shenyu/plugin/discovery/add-selector-zh.png) + +- 对于Divide、gRPC、Websocket插件,添加选择器页面有 `导入后台服务发现配置` 功能, + 指的是,如果服务接入 ShenYu 网关时配置了 shenyu-discovery 相关的属性(见配合shenyu-client使用),可以选择导入并沿用后台的配置,如下图我们首先点击 `导入后台服务发现配置` 查看后台配置: + +![config-import-zh.png](/img/shenyu/plugin/discovery/config-import-zh.png) + +- 如果确认导入,点击后台配置弹出框中的 `导入` 按钮后,后台的服务发现属性将会自动填充进表单, + 此时仅需要再配置监听节点: + +![after-import-zh.png](/img/shenyu/plugin/discovery/after-import-zh.png) + +> **注意**:如果确认导入后台配置,后台的服务发现属性将会自动填充进表单,并沿用之前的discovery对象, +此时,在表单中修改服务发现属性将无效,依然保持后台配置。 + +- 若选择了 LOCAL 模式,则无需接入注册中心,用户需要手动维护 upstream 列表。 + + +## 3. 不同模式下的配置 + +### 3.1 local模式 + +- local模式只支持**选择器级别**的配置。无需接入注册中心,用户需要手动维护 upstream 列表。这里的列表是一个可编辑表格, + 点击表格每行的 `编辑` 按钮,可以对 upstream 的每个参数进行修改: + +![local-selector-zh.png](/img/shenyu/plugin/discovery/local-selector-zh.png) + +### 3.2 ZooKeeper/Nacos/Eureka/Etcd模式 + +- ZooKeeper/Nacos/Eureka/Etcd模式下,支持插件级别和选择器级别的服务发现配置。 +- 针对每个模式下的注册中心属性,以zookeeper为例,用户可以在`shenyu-admin` --> 基础配置 --> 字典管理 中,搜索字典名称为“zookeeper”,对默认属性对应的字典值进行修改编辑 + (**注意**:不可修改字典类型和字典名称)。 +- 这些模式下,网关会动态地从注册中心获取服务实例信息,服务实例的新增、下线、修改等,将会实时显示在 upstream 列表中。 + + +![zk_dict.png](/img/shenyu/plugin/tcp/zk_dict_zh.png) + +## 4. 配合 Shenyu-client 使用 + +### 4.1 介绍 + +- 与 shenyu-client 配合使用需要依赖对应模式的注册中心中间件:zookeeper,nacos,etcd,eureka,这些模式可以通过Shenyu Admin实现自动感知服务的上线和下线。 +- 另外,如果您使用了 local 模式,则需要手动维护upstream列表。 +- shenyu-client 使用详见 shenyu-client 模块。 + +### 4.2 Local 模式示例 + +#### 4.2.1 使用shenyu-client + +- shenyu-client 默认为 Local模式,无需进行特殊的 discovery 配置,便可以自动把当前服务注册上去; +- 对于自动注册上来的服务,可以手动在页面的upstream列表进行添加、修改和删除: + +![local-selector-zh.png](/img/shenyu/plugin/discovery/local-selector-zh.png) + +#### 4.2.2 不使用shenyu-client + + +- 如果不使用shenyu-client,也可以手动在 `添加选择器` 的 `服务发现` 标签页上添加、修改、删除服务信息: + +![add-selector-local-zh.png](/img/shenyu/plugin/discovery/add-selector-local-zh.png) + +- 配置选择器其他信息: + +![add-selector-basic-zh.png](/img/shenyu/plugin/discovery/add-selector-basic-zh.png) + +- 配置规则: + +![rule-zh.png](/img/shenyu/plugin/discovery/rule-zh.png) + +- 测试连接 + +```text +curl http://localhost:9195/http/hello + +hello! I'm Shenyu-Gateway System. Welcome!% +``` + +### 4.2 Zookeeper模式示例 + +(以 Divide 插件为例) +- 添加依赖 + +```xml + + + org.apache.shenyu + shenyu-discovery-zookeeper + ${project.version} + + + + org.apache.shenyu + shenyu-spring-boot-starter-client-http + + +``` + +- application.yml 中添加如下配置 + +```yaml +shenyu: + discovery: + enable: true + type: zookeeper + serverList: ${your.zookeeper.ip}:{your.zookeeper.port} + registerPath: /shenyu/discovery/demo_http_common + props: + baseSleepTimeMilliseconds: 1000 + maxRetries: 4 + maxSleepTimeMilliseconds: 5000 + connectionTimeoutMilliseconds: 60000 + sessionTimeoutMilliseconds: 8 +``` + +- 启动服务 shenyu-examples-http +- 服务注册成功,在选择器页面可以看到自动注册上来的服务实例列表: + +![zk-selector-zh.png](/img/shenyu/plugin/discovery/zk-selector-zh.png) + +- 用户可以点击服务实例列表中的 `编辑`,对服务实例信息进行编辑(非Local模式下,URL由注册中心维护,不可手动编辑): + +![edit-zk-upstream-zh.png](/img/shenyu/plugin/discovery/edit-zk-upstream-zh.png) + +- 测试连接 + +```text +curl http://localhost:9195/http/hello + +hello! I'm Shenyu-Gateway System. Welcome!% +``` + +### 4.3 Etcd示例 + +- 添加依赖 + +```xml + + + org.apache.shenyu + shenyu-discovery-etcd + ${project.version} + + + + org.apache.shenyu + shenyu-spring-boot-starter-client-http + + +``` + +- application.yml 中添加如下配置 + +```yaml +shenyu: + discovery: + enable: true + protocol: http:// + type: etcd + serverList: http://${your.etcd.host}:${your.etcd.port} + registerPath: /shenyu/test/http_common + props: + etcdTimeout: 3000 + etcdTTL: 5 +``` + +- 启动服务 shenyu-examples-http,同样地,在选择器页面可以看到自动注册上来的服务实例列表,并可进行编辑: + +![etcd-selector-zh.png](/img/shenyu/plugin/discovery/etcd-selector-zh.png) + +- 测试连接 + +```text +curl http://localhost:9195/http/hello + +hello! I'm Shenyu-Gateway System. Welcome!% +``` + +### 4.4 Eureka示例 + +- 添加依赖 + +```xml + + + org.apache.shenyu + shenyu-discovery-eureka + ${project.version} + + + + org.apache.shenyu + shenyu-spring-boot-starter-client-http + + +``` + +- application.yml 中添加如下配置(此处的 `registerPath` 可以理解为需要监听的服务的名称) + +```yaml +shenyu: + discovery: + enable: true + protocol: http:// + type: eureka + serverList: http://${your.eureka.host}:${your.eureka.port}/eureka + registerPath: shenyu_discovery_demo_http_common + props: + eurekaClientRefreshInterval: 10 + eurekaClientRegistryFetchIntervalSeconds: 10 +``` + +- 启动服务 shenyu-examples-http,同样地,在选择器页面可以看到自动注册上来的服务实例列表,并可进行编辑: + +![eureka-selector-zh.png](/img/shenyu/plugin/discovery/eureka-selector-zh.png) + +- 测试连接 + +```text +curl http://localhost:9195/http/hello + +hello! I'm Shenyu-Gateway System. Welcome!% +``` + +### 4.5 Nacos示例 + +```xml + + + org.apache.shenyu + shenyu-discovery-eureka + ${project.version} + + + + org.apache.shenyu + shenyu-spring-boot-starter-client-http + + +``` + +- application.yml 中添加如下配置(此处的 `registerPath` 同样可以理解为需要监听的服务的名称) + +```yaml +shenyu: + discovery: + enable: true + protocol: http:// + type: nacos + serverList: ${your.nacos.host}:${your.nacos.port} + registerPath: shenyu_discovery_demo_http_common + props: + groupName: SHENYU_GROUP +``` + +- 启动服务 shenyu-examples-http,同样地,在选择器页面可以看到自动注册上来的服务实例列表,并可进行编辑: + +![nacos-selector-zh.png](/img/shenyu/plugin/discovery/nacos-selector-zh.png) + +- 测试连接 + +```text +curl http://localhost:9195/http/hello + +hello! I'm Shenyu-Gateway System. Welcome!% +``` + +> **注意**:通过shenyu-client配置服务发现,本质上是配置插件级别的服务发现,同一种服务发现模式下, +实际上只有一个discovery对象(即:只能够配置同一套类型-服务器URL-服务发现参数),监听节点可以有多个。 + + +![ws-selector-zh.png](/img/shenyu/plugin/discovery/ws-selector-zh.png) + +> **注意**:Divide插件和Grpc插件中,可以通过在application.yml文件中配置protocol来修改协议,Websocket +插件的协议默认均为ws + + + +## 5. 注意事项 + +- local 模式下,可以在服务列表页面上手动对 upstream 的所有参数进行修改; +- 非local模式下,可以对除URL、开始时间以外的参数进行手动修改; +- 手动修改服务实例的状态(status:open/close),权重(weight),仅对当前插件生效; +- 对于同一插件,后台通过shenyu-client配置discovery相关参数后,本质上是配置插件级别的服务发现, +控制台页面上可以手动添加选择器以配置选择器级别的服务发现,但实际上只有一个discovery对象(即:只能够配置同一套类型-服务器URL-服务发现参数),监听节点可以有多个。 + + + +## 6. 测试报告 + +[测试报告](https://www.yuque.com/eureca/pgotw1/hkqkk5laubspgwl3#UojLR) + + + + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/kubernetes-controller/_category_.json b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/kubernetes-controller/_category_.json new file mode 100644 index 00000000000..47a0b85e937 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/kubernetes-controller/_category_.json @@ -0,0 +1,4 @@ +{ + "label": "Kubernetes Controller", + "position": 5 +} diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/kubernetes-controller/build-deploy.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/kubernetes-controller/build-deploy.md new file mode 100644 index 00000000000..868fd5bbaa3 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/kubernetes-controller/build-deploy.md @@ -0,0 +1,120 @@ +--- +title: 构建和部署 Kubernetes 控制器 +description: 构建和部署 Kubernetes 控制器 +--- + +本篇介绍如何使用 ShenYu Kubernetes Controller。 + +## 构建 + +建议参考[自定义部署](../../deployment/deployment-custom.md)构建自定义网关,在网关的 Maven 依赖中加入 shenyu-kubernetes-controller 的依赖,网关即可集成 kubernetes 控制器。 + +```xml + + org.apache.shenyu + shenyu-spring-boot-starter-k8s + ${project.version} + +``` + +也可以直接使用官方构建的 docker 镜像(TODO,未完成) + +## 部署 + +K8s 部署文件可参考: + +```yaml +apiVersion: v1 +kind: Namespace +metadata: + name: shenyu-ingress +--- +apiVersion: v1 +automountServiceAccountToken: true +kind: ServiceAccount +metadata: + name: shenyu-ingress-controller + namespace: shenyu-ingress +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: shenyu-ingress-controller + namespace: shenyu-ingress + labels: + app: shenyu-ingress-controller + all: shenyu-ingress-controller +spec: + replicas: 1 + selector: + matchLabels: + app: shenyu-ingress-controller + template: + metadata: + labels: + app: shenyu-ingress-controller + spec: + containers: + - name: shenyu-ingress-controller + image: apache/shenyu-integrated-test-k8s-ingress:latest + ports: + - containerPort: 9195 + imagePullPolicy: IfNotPresent + serviceAccountName: shenyu-ingress-controller +--- +apiVersion: v1 +kind: Service +metadata: + name: shenyu-ingress-controller + namespace: shenyu-ingress +spec: + selector: + app: shenyu-ingress-controller + type: NodePort + ports: + - port: 9195 + targetPort: 9195 + nodePort: 30095 +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + name: shenyu-ingress-controller +rules: +- apiGroups: + - "" + resources: + - namespaces + - services + - endpoints + - secrets + - pods + verbs: + - get + - list + - watch +- apiGroups: + - networking.k8s.io + resources: + - ingresses + verbs: + - get + - list + - watch +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRoleBinding +metadata: + name: shenyu-ingress-controller + namespace: shenyu-ingress +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: ClusterRole + name: shenyu-ingress-controller +subjects: +- kind: ServiceAccount + name: shenyu-ingress-controller + namespace: shenyu-ingress +``` + +其中,Service 可以根据实际情况改成 `LoadBalancer` 类型。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/kubernetes-controller/config.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/kubernetes-controller/config.md new file mode 100644 index 00000000000..5e7604d24ce --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/kubernetes-controller/config.md @@ -0,0 +1,113 @@ +--- +title: Kubernetes 控制器配置 +description: Kubernetes 控制器配置 +--- + +本篇介绍 Kubernetes 控制器配置。 + +## 开启 HTTPS + +开启 HTTPS 需要在网关的 `application.yml` 文件中进行 `sni协议` 的相关配置: + +```yaml +shenyu: + netty: + http: + sni: + enabled: true + mod: k8s #k8s模式适用 + defaultK8sSecretNamespace: shenyu-ingress #默认secret资源的namespace + defaultK8sSecretName: default-cert #默认secret资源名字 +``` + +其中,默认secret资源必须要有,但是目前不会实际使用。 + +## Ingress 配置 + +ShenYu Kubernetes Controller 实现了 K8s 原生的 Ingress 标准,原生标准的使用见 [K8s 官方文档](https://kubernetes.io/docs/concepts/services-networking/ingress/) + +另外,Apache ShenYu 基于 Ingress 的 Annotation 字段进行了拓展,配置见下文表格: + +### 通用 + +| 名称 | 默认值 | 是否必填 | 说明 | +| --------------------------- | ------ | -------- | -------- | +| kubernetes.io/ingress.class | | 是 | 填shenyu | + +### Divide 插件(HTTP代理) + +| 名称 | 默认值 | 是否必填 | 说明 | +| ---------------------------------- | ------ | -------- | ------------------------------------------------------------ | +| shenyu.apache.org/loadbalancer | random | 否 | 负载均衡算法,可选hash、random、roundRobin、leastActive、p2c、shortestResponse | +| shenyu.apache.org/retry | 3 | 否 | 失败重试次数 | +| shenyu.apache.org/timeout | 3000 | 否 | 后端请求超时时间,单位毫秒 | +| shenyu.apache.org/header-max-size | 10240 | 否 | 请求头最大大小,单位byte | +| shenyu.apache.org/request-max-size | 102400 | 否 | 请求体最大大小,单位byte | + +### Dubbo插件 + +| 名称 | 默认值 | 是否必填 | 说明 | +| ---------------------------------------------- | -------- | -------- | ------------------------------------------------------------ | +| shenyu.apache.org/loadbalancer | random | 否 | 负载均衡算法,可选hash、random、roundRobin、leastActive、p2c、shortestResponse | +| shenyu.apache.org/retry | 3 | 否 | 失败重试次数 | +| shenyu.apache.org/timeout | 3000 | 否 | 后端请求超时时间,单位毫秒 | +| shenyu.apache.org/header-max-size | 10240 | 否 | 请求头最大大小,单位byte | +| shenyu.apache.org/request-max-size | 102400 | 否 | 请求体最大大小,单位byte | +| shenyu.apache.org/upstreams-protocol | dubbo:// | 否 | 指定upstream使用的protocol协议 | +| shenyu.apache.org/plugin-dubbo-enabled | | 否 | 确定是否启动dubbo插件 | +| shenyu.apache.org/zookeeper-register-address | | 是 | 指定zookeeper地址 | +| shenyu.apache.org/plugin-dubbo-app-name | | 是 | 指定元数据的应用名称 | +| shenyu.apache.org/plugin-dubbo-path | | 是 | 指定元数据的请求路径 | +| shenyu.apache.org/plugin-dubbo-rpc-type | | 是 | 指定元数据的rpc类型(dubbo,sofa,tars,springCloud,motan,grpc) | +| shenyu.apache.org/plugin-dubbo-service-name | | 是 | 指定元数据的接口名称 | +| shenyu.apache.org/plugin-dubbo-method-name | | 是 | 指定元数据的方法名称 | +| shenyu.apache.org/plugin-dubbo-rpc-expand | | 否 | 指定元数据的rpc扩展参数(json对象) | +| shenyu.apache.org/plugin-dubbo-parameter-types | | 是 | 指定元数据的参数类型 | + +### Motan插件 + +| 名称 | 默认值 | 是否必填 | 说明 | +| ---------------------------------------------- | ------ | -------- | ------------------------------------------------------------ | +| shenyu.apache.org/loadbalancer | random | 否 | 负载均衡算法,可选hash、random、roundRobin、leastActive、p2c、shortestResponse | +| shenyu.apache.org/retry | 3 | 否 | 失败重试次数 | +| shenyu.apache.org/timeout | 3000 | 否 | 后端请求超时时间,单位毫秒 | +| shenyu.apache.org/header-max-size | 10240 | 否 | 请求头最大大小,单位byte | +| shenyu.apache.org/request-max-size | 102400 | 否 | 请求体最大大小,单位byte | +| shenyu.apache.org/plugin-motan-enabled | | 是 | 确定是否启动motan插件 | +| shenyu.apache.org/zookeeper-register-address | | 是 | 指定zookeeper地址 | +| shenyu.apache.org/plugin-motan-app-name | | 是 | 指定元数据的应用名称 | +| shenyu.apache.org/plugin-motan-path | | 是 | 指定元数据的请求路径 | +| shenyu.apache.org/plugin-motan-rpc-type | | 是 | 指定元数据的rpc类型(dubbo,sofa,tars,springCloud,motan,grpc) | +| shenyu.apache.org/plugin-motan-service-name | | 是 | 指定元数据的接口名称 | +| shenyu.apache.org/plugin-motan-method-name | | 是 | 指定元数据的方法名称 | +| shenyu.apache.org/plugin-motan-rpc-expand | | 否 | 指定元数据的rpc扩展参数(json对象) | +| shenyu.apache.org/plugin-motan-parameter-types | | 是 | 指定元数据的参数类型 | + +### SpringCloud插件 + +| 名称 | 默认值 | 是否必填 | 说明 | +| ----------------------------------------------------- | ------ | -------- | ------------------------------------------------------------ | +| shenyu.apache.org/loadbalancer | random | 否 | 负载均衡算法,可选hash、random、roundRobin、leastActive、p2c、shortestResponse | +| shenyu.apache.org/retry | 3 | 否 | 失败重试次数 | +| shenyu.apache.org/timeout | 3000 | 否 | 后端请求超时时间,单位毫秒 | +| shenyu.apache.org/header-max-size | 10240 | 否 | 请求头最大大小,单位byte | +| shenyu.apache.org/request-max-size | 102400 | 否 | 请求体最大大小,单位byte | +| shenyu.apache.org/plugin-spring-cloud-enabled | | 是 | 确定是否启动springCloud插件 | +| shenyu.apache.org/zookeeper-register-address | | 是 | 指定zookeeper地址 | +| shenyu.apache.org/plugin-spring-cloud-app-name | | 是 | 指定元数据的应用名称 | +| shenyu.apache.org/plugin-spring-cloud-path | | 是 | 指定元数据的请求路径 | +| shenyu.apache.org/plugin-spring-cloud-rpc-type | | 是 | 指定元数据的rpc类型(dubbo,sofa,tars,springCloud,motan,grpc) | +| shenyu.apache.org/plugin-spring-cloud-service-name | | 是 | 指定元数据的接口名称 | +| shenyu.apache.org/plugin-spring-cloud-method-name | | 是 | 指定元数据的方法名称 | +| shenyu.apache.org/plugin-spring-cloud-rpc-expand | | 否 | 指定元数据的rpc扩展参数(json对象) | +| shenyu.apache.org/plugin-spring-cloud-parameter-types | | 是 | 指定元数据的参数类型 | + +### WebSocket插件 + +| 名称 | 默认值 | 是否必填 | 说明 | +| ---------------------------------- | ------ | -------- | ------------------------------------------------------------ | +| shenyu.apache.org/loadbalancer | random | 否 | 负载均衡算法,可选hash、random、roundRobin、leastActive、p2c、shortestResponse | +| shenyu.apache.org/retry | 3 | 否 | 失败重试次数 | +| shenyu.apache.org/timeout | 3000 | 否 | 后端请求超时时间,单位毫秒 | +| shenyu.apache.org/header-max-size | 10240 | 否 | 请求头最大大小,单位byte | +| shenyu.apache.org/request-max-size | 102400 | 否 | 请求体最大大小,单位byte | diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/property-config/_category_.json b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/property-config/_category_.json new file mode 100644 index 00000000000..dd5083760b4 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/property-config/_category_.json @@ -0,0 +1,4 @@ +{ + "label": "属性配置", + "position": 2 +} diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/property-config/admin-property-config.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/property-config/admin-property-config.md new file mode 100644 index 00000000000..83a6223f6d0 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/property-config/admin-property-config.md @@ -0,0 +1,260 @@ +--- +title: Admin属性配置 +keywords: ["配置"] +description: Admin属性配置 +--- + +本篇主要讲解如何在 `admin`端配置 `ShenYu` 的相关属性。 + + + + + +### 属性配置 + +```yaml +shenyu: + register: + registerType: http #http #zookeeper #etcd #nacos #consul + serverLists: #localhost:2181 #http://localhost:2379 #localhost:8848 + props: + sessionTimeout: 5000 + connectionTimeout: 2000 + checked: true + zombieCheckTimes: 5 + scheduledTime: 10 + nacosNameSpace: ShenyuRegisterCenter + sync: + websocket: + enabled: true + messageMaxSize: 10240 + allowOrigins: ws://localhost:9095;ws://localhost:9195; +# zookeeper: +# url: localhost:2181 +# sessionTimeout: 5000 +# connectionTimeout: 2000 +# http: +# enabled: true +# nacos: +# url: localhost:8848 +# namespace: 1c10d748-af86-43b9-8265-75f487d20c6c +# username: +# password: +# acm: +# enabled: false +# endpoint: acm.aliyun.com +# namespace: +# accessKey: +# secretKey: +# etcd: +# url: http://localhost:2379 +# consul: +# url: http://localhost:8500 + aes: + secret: + key: 2095132720951327 + iv: 6075877187097700 + ldap: + enabled: false + url: ldap://xxxx:xxx + bind-dn: cn=xxx,dc=xxx,dc=xxx + password: xxxx + base-dn: ou=xxx,dc=xxx,dc=xxx + object-class: person + login-field: cn + jwt: + expired-seconds: 86400000 + shiro: + white-list: + - / + - /favicon.* + - /static/** + - /index** + - /plugin + - /platform/** + - /websocket + - /configs/** + - /shenyu-client/** + - /error + - /actuator/health + - /swagger-ui.html + - /webjars/** + - /swagger-resources/** + - /v2/api-docs + - /csrf + swagger: + enable: true +``` + + +### 属性详解 + +##### shenyu.register 配置 + +这是客户端接入的相关配置,客户端接入原理请参考:[客户端接入原理](../../design/register-center-design) ,客户端接入配置请参考: [客户端接入配置](register-center-access.md) 。 + +|名称 | 类型 | 默认值 | 是否必填 | 说明 | +|:------------------------ |:----- |:-------: |:-------:|:----------------------------| +|registerType |String | http | 必填 |使用哪种方式进行服务注册,当前支持 `http`、`zookeeper`、`etcd`、`consul`和`nacos` 。| +|serverLists |String | 无 | 非必填 |配置中心的地址。使用`http`方式时,不需要填写,其他类型需要填写。集群时,多个地址用 `,` 分开 。| +|props | | | | 使用不同注册类型时,属性取值不同。| + + + + +- `props`配置 + +使用不同的注册类型时,属性取值不同。 + +当注册类型为`http`时,支持的属性配置如下: + +|名称 | 类型 | 默认值 | 是否必填 | 说明 | +|:------------------------ |:----- |:-------: |:-------:|:----------------------------| +|checked |boolean | false | 否 |是否开启检测| +|zombieCheckTimes |int | 5 | 否 |失败几次后剔除服务| +|scheduledTime |int | 10 | 否 | 定时检测间隔时间 (秒)| + +当注册类型为`zookeeper`时,支持的属性配置如下: + +|名称 | 类型 | 默认值 | 是否必填 | 说明 | +|:------------------------ |:----- |:-------: |:-------:|:----------------------------| +|sessionTimeout | int | 30000 | 否 |session超时时间(毫秒)| +|connectionTimeout | int | 3000 | 否 |连接超时时间(毫秒)| + +当注册类型为`etcd`时,暂时没有属性配置。 + +当注册类型为`nacos`时,支持的属性配置如下: + +|名称 | 类型 | 默认值 | 是否必填 | 说明 | +|:------------------------ |:----- |:-------: |:-------:|:----------------------------| +|nacosNameSpace | String | 无 | 是 |命名空间| +|username | String | 空字符串 | 否 |用户名| +|password | String | 空字符串 | 否 |密码| +|accessKey | String | 空字符串 | 否 |accessKey| +|secretKey | String | 空字符串 | 否 |secretKey| + +当注册类型为`consul`时,支持的属性配置如下: + +|名称 | 类型 | 默认值 | 是否必填 | 说明 | +|:------------------------ |:----- |:-------: |:-------:|:----------------------------| +|delay | int | 1 | 否 |对`Metadata`的监控每次轮询的间隔时长,单位为秒,默认`1`秒。| +|wait-time | int | 55 | 否 |对`Metadata`的监控单次请求的等待时间(长轮询机制),单位为秒,默认`55`秒。| +|metadata-path | String | `shenyu/register` | 否 |`Metadata`路径名称,默认是`shenyu/register`。| + + + +##### shenyu.sync 配置 + +`Admin`端和网关使用数据同步的相关配置。 + +使用`websocket`进行数据同步的属性配置如下: + + +|名称 | 类型 | 默认值 | 是否必填 | 说明 | +|:------------------------ |:----- |:-------: |:-------:|:----------------------------| +|enabled | boolean | true | 否 |是否启用`websocket`进行数据同步| +|messageMaxSize | int | 0 | 否 |设置`websocket`缓冲区大小,单位为bytes| +|allowOrigins | String | 空字符串 | 否 |设置允许的 `origins`, 多个参数以`;`分隔| + +使用`zookeeper`进行数据同步的属性配置如下:/ + + +|名称 | 类型 | 默认值 | 是否必填 | 说明 | +|:------------------------ |:----- |:-------: |:-------:|:----------------------------| +|url | String | 无 | 是 |`zookeeper`的连接地址| +|sessionTimeout | int | 无 | 是 |`session`的超时时间(毫秒)| +|connectionTimeout | int | 无 | 是 |连接超时时间(毫秒)| + + +使用`http长轮询`进行数据同步的属性配置如下: + +|名称 | 类型 | 默认值 | 是否必填 | 说明 | +|:------------------------ |:----- |:-------: |:-------:|:----------------------------| +|enabled | boolean | true | 否 |是否启用| +|refreshInterval | int | 5 (分钟) | 否 |定时从数据库获取数据并加载到内存| +|notifyBatchSize | int | 100 | 否 |批量通知客户端| + + +使用`nacos`进行数据同步的属性配置如下: + +|名称 | 类型 | 默认值 | 是否必填 | 说明 | +|:------------------------ |:----- |:-------: |:-------:|:----------------------------| +|url | String | 无 | 是 |`nacos`连接地址| +|namespace | String | 无 | 是 |命名空间| +|username | String | 无 | 否 |用户名| +|password | String | 无 | 否 |密码| +|acm | | | 否 |阿里云ACM服务配置| + +- `acm`配置 + +|名称 | 类型 | 默认值 | 是否必填 | 说明 | +|:------------------------ |:----- |:-------: |:-------:|:----------------------------| +|enabled | boolean | false | 否 |是否启用| +|endpoint | String | 无 | 是 |ACM服务地址| +|namespace | String | 无 | 否 |namespace| +|accessKey | String | 无 | 否 |accessKey| +|secretKey | String | 无 | 否 |secretKey| + + +使用`etcd`进行数据同步的属性配置如下: + +|名称 | 类型 | 默认值 | 是否必填 | 说明 | +|:------------------------ |:----- |:-------: |:-------:|:----------------------------| +|url | String | 无 | 是 |`etcd`连接地址| + + + +使用`consul`进行数据同步的属性配置如下: + +|名称 | 类型 | 默认值 | 是否必填 | 说明 | +|:------------------------ |:----- |:-------: |:-------:|:----------------------------| +|url | String | 无 | 是 |`consul`连接地址| + + +##### shenyu.aes.secret 配置 + +`aes`加密算法的相关配置。 + + +|名称 | 类型 | 默认值 | 是否必填 | 说明 | +|:------------------------ |:----- |:-------: |:-------:|:----------------------------| +|key | String | `2095132720951327` | 否 |key| +|iv | String | 无 | 否 |初始向量| + + +##### shenyu.ldap 配置 + +`Spring`中`ldap`的相关配置。 + + +|名称 | 类型 | 默认值 | 是否必填 | 说明 | +|:------------------------ |:----- |:-------: |:-------:|:----------------------------| +|enabled | boolean | true | 否 |是否启用| +|url | String | 无 | 是 |`ldap`连接地址| +|bind-dn | String | 无 | 否 | UserDn | +|password | String | 无 | 否 |密码| +|base-dn | String | 无 | 否 | searchBase | +|object-class | String | `person` | 否 | filter | +|login-field | String | `cn` | 否 | searchBase| +|connectTimeout | int | 3000 | 否 |连接超时时间(毫秒)| +|readTimeout | int | 3000 | 否 |读取操作超时时间(毫秒)| + + +##### shenyu.jwt 配置 + +`jwt`的相关配置如下: + + +|名称 | 类型 | 默认值 | 是否必填 | 说明 | +|:------------------------ |:----- |:-------: |:-------:|:----------------------------| +| expired-seconds | long | 24 *60* 60 * 1000L | 否 |过期时间(毫秒)| + + +##### shenyu.shiro 配置 + +`shiro`的相关配置如下: + + +|名称 | 类型 | 默认值 | 是否必填 | 说明 | +|:------------------------ |:----- |:-------: |:-------:|:----------------------------| +| white-list | List | 无 | 否 |白名单列表| diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/property-config/client-property-config.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/property-config/client-property-config.md new file mode 100644 index 00000000000..0e5a1e6ea60 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/property-config/client-property-config.md @@ -0,0 +1,90 @@ +--- +title: 客户端属性配置 +keywords: ["配置"] +description: Client属性配置 +--- + +本篇主要讲解如何在客户端接入时配置 `ShenYu` 的相关属性。 + +在你的微服务中设置`shenyu`属性,比如,在[shenyu-examples-http](https://github.com/apache/shenyu/tree/master/shenyu-examples/shenyu-examples-http) 中相关配置如下: + + + +### 属性配置 + +```yaml +shenyu: + client: + registerType: http #zookeeper #etcd #nacos #consul + serverLists: http://localhost:9095 #localhost:2181 #http://localhost:2379 #localhost:8848 + props: + contextPath: /http + appName: http + port: 8189 + nacosNameSpace: ShenyuRegisterCenter + +``` + + +### 属性详解 + +##### shenyu.client 配置 + +这是客户端接入的相关配置,客户端接入原理请参考:[客户端接入原理](../../design/register-center-design) ,客户端接入配置请参考: [客户端接入配置](register-center-access.md) 。 + +|名称 | 类型 | 默认值 | 是否必填 | 说明 | +|:------------------------ |:----- |:-------: |:-------:|:----------------------------| +|registerType |String | http | 必填 |使用哪种方式进行服务注册,当前支持 `http`、`zookeeper`、`etcd`、`consul`和`nacos` 。| +|serverLists |String | 无 | 必填 |配置中心的地址。集群时,多个地址用 `,` 分开 。| +|props | | | | 使用不同注册类型时,属性取值不同。| + + +- `props`配置 + +微服务由不同协议构建时,属性配置略有不同,通用属性如下: + + +|名称 | 类型 | 默认值 | 是否必填 | 说明 | +|:------------------------ |:----- |:-------: |:-------:|:----------------------------| +|contextPath |String | 无 | 是 |服务在网关中的路由前缀| +|appName |String | 无 | 是 |服务名称。`springcloud`服务无需配置,请通过`spring.application.name`配置。| +|host |String | 无 | 是 | 服务地址| +|port |int | 无 | 是 | 服务端口| +|isFull |boolean | false | 否 | 是否代理整个服务,目前适用于`springmvc`/`springcloud`| +|ipAndPort |String | 无 | 否 | 服务的IP和端口地址,目前适用于`gRPC`。| +|shutdownWaitTime |int | 3000 | 否 | 服务停止等待时间(毫秒)| +|delayOtherHooksExecTime |int | 2000 | 否 | `hook`执行时间(毫秒)| +|applicationShutdownHooksClassName |String | `java.lang.ApplicationShutdownHooks` | 否 | `hook`执行类| +|applicationShutdownHooksFieldName |String | `hooks` | 否 | `hook`执行字段| + + +使用不同的注册类型时,属性取值不同。 +当注册类型为`http`时,暂未提供其他属性配置。 + + + +当注册类型为`zookeeper`时,支持的属性配置如下: + +|名称 | 类型 | 默认值 | 是否必填 | 说明 | +|:------------------------ |:----- |:-------: |:-------:|:----------------------------| +|sessionTimeout | int | 30000 | 否 |session超时时间(毫秒)| +|connectionTimeout | int | 3000 | 否 |连接超时时间(毫秒)| + +当注册类型为`etcd`时,支持的属性配置如下: + +|名称 | 类型 | 默认值 | 是否必填 | 说明 | +|:------------------------ |:----- |:-------: |:-------:|:----------------------------| +|etcdTimeout | int | 30000 | 否 |etcd超时时间(毫秒)| +|etcdTTL | int | 5 | 否 |租约生存时间(秒)| + +当注册类型为`nacos`时,支持的属性配置如下: + +|名称 | 类型 | 默认值 | 是否必填 | 说明 | +|:------------------------ |:----- |:-------: |:-------:|:----------------------------| +|nacosNameSpace | String | 无 | 是 |命名空间| +|username | String | 空字符串 | 否 |用户名| +|password | String | 空字符串 | 否 |密码| +|accessKey | String | 空字符串 | 否 |accessKey| +|secretKey | String | 空字符串 | 否 |secretKey| + +当注册类型为`consul`时,暂未提供其他属性配置。请通过`spring.cloud.consul`进行配置。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/property-config/gateway-property-config.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/property-config/gateway-property-config.md new file mode 100644 index 00000000000..13b103bbe42 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/property-config/gateway-property-config.md @@ -0,0 +1,642 @@ +--- +title: 网关属性配置 +keywords: ["配置"] +description: 网关属性配置 +--- + +本篇主要讲解如何在 `Apache Shenyu` 网关配置 `ShenYu` 的相关属性。 + + + +### 属性配置 + +```yaml +shenyu: + selectorMatchCache: + ## selector L1 cache + cache: + enabled: false + initialCapacity: 10000 # initial capacity in cache + maximumSize: 10000 # max size in cache + ## selector L2 cache, use trie as L2 cache + trie: + enabled: false + cacheSize: 128 # the number of plug-ins + matchMode: antPathMatch + ruleMatchCache: + ## rule L1 cache + cache: + enabled: true + initialCapacity: 10000 # initial capacity in cache + maximumSize: 65536 # max size in cache + ## rule L2 cache, use trie as L2 cache + trie: + enabled: false + cacheSize: 1024 # the number of selectors + matchMode: antPathMatch + netty: + http: + webServerFactoryEnabled: true + selectCount: 1 + workerCount: 4 + accessLog: false + serverSocketChannel: + soRcvBuf: 87380 + soBackLog: 128 + soReuseAddr: true + connectTimeoutMillis: 30000 + writeBufferHighWaterMark: 65536 + writeBufferLowWaterMark: 32768 + writeSpinCount: 16 + autoRead: false + allocType: "pooled" + messageSizeEstimator: 8 + singleEventExecutorPerGroup: true + socketChannel: + soKeepAlive: false + soReuseAddr: false + soLinger: -1 + tcpNoDelay: true + soRcvBuf: 87380 + soSndBuf: 16384 + ipTos: 0 + allowHalfClosure: false + connectTimeoutMillis: 30000 + writeBufferHighWaterMark: 65536 + writeBufferLowWaterMark: 32768 + writeSpinCount: 16 + autoRead: false + allocType: "pooled" + messageSizeEstimator: 8 + singleEventExecutorPerGroup: true + instance: + enabled: false + registerType: zookeeper #etcd #consul + serverLists: localhost:2181 #http://localhost:2379 #localhost:8848 + props: +# httpclient: +# strategy: webClient +# connectTimeout: 45000 +# responseTimeout: 3000 +# readerIdleTime: 3000 +# writerIdleTime: 3000 +# allIdleTime: 3000 +# readTimeout: 3000 +# writeTimeout: 3000 +# wiretap: false +# keepAlive: false +# pool: +# type: ELASTIC +# name: proxy +# maxConnections: 16 +# acquireTimeout: 45000 +# maxIdleTime: 3000 +# proxy: +# host: +# port: +# username: +# password: +# nonProxyHostsPattern: +# ssl: +# useInsecureTrustManager: false +# keyStoreType: PKCS12 +# keyStorePath: classpath:keystore.p12 +# keyStorePassword: 123456 +# keyStoreProvider: +# keyPassword: 123456 +# trustedX509Certificates: +# handshakeTimeout: +# closeNotifyFlushTimeout: +# closeNotifyReadTimeout: +# defaultConfigurationType: + sync: + websocket: + urls: ws://localhost:9095/websocket + allowOrigin: ws://localhost:9195 +# zookeeper: +# url: localhost:2181 +# sessionTimeout: 5000 +# connectionTimeout: 2000 +# http: +# url: http://localhost:9095 +# nacos: +# url: localhost:8848 +# namespace: 1c10d748-af86-43b9-8265-75f487d20c6c +# username: +# password: +# acm: +# enabled: false +# endpoint: acm.aliyun.com +# namespace: +# accessKey: +# secretKey: +# etcd: +# url: http://localhost:2379 +# consul: +# url: http://localhost:8500 +# waitTime: 1000 +# watchDelay: 1000 + cross: + enabled: true + allowedHeaders: + allowedMethods: "*" + allowedAnyOrigin: false + allowedOrigin: + # format : schema://prefix spacer domain + # Access-Control-Allow-Origin: "http://a.apache.org,http://b.apache.org" + spacer: "." + domain: apache.org + prefixes: + - a # a.apache.org + - b # b.apache.org + origins: + - c.apache.org + - d.apache.org + - http://e.apache.org + originRegex: ^http(|s)://(.*\.|)abc.com$ + allowedExpose: "" + maxAge: "18000" + allowCredentials: true + switchConfig: + local: true + file: + enabled: true + maxSize : 10 + exclude: + enabled: false + paths: + - /favicon.ico + fallback: + enabled: false + paths: + - /fallback/hystrix + - /fallback/resilience4j + health: + enabled: false + paths: + - /actuator/health + - /health_check + alert: + enabled: true + admins: localhost:9095 + extPlugin: + path: + enabled: true + threads: 1 + scheduleTime: 300 + scheduleDelay: 30 + scheduler: + enabled: false + type: fixed + threads: 16 + upstreamCheck: + enabled: false + timeout: 3000 + healthyThreshold: 1 + unhealthyThreshold: 1 + interval: 5000 + printEnabled: true + printInterval: 60000 + ribbon: + serverListRefreshInterval: 10000 + metrics: + enabled: false + name : prometheus + host: 127.0.0.1 + port: 8090 + jmxConfig: + props: + jvm_enabled: true + sharedPool: + enable: true + prefix: "shenyu-shared" + corePoolSize: 200 + maximumPoolSize: 2000 + keepAliveTime: 60000 + maxWorkQueueMemory: 1073741824 # 1GB + maxFreeMemory: 268435456 # 256MB +``` + +### 属性详解 + + + +##### shenyu.matchCache 配置 + +* 选择器匹配缓存配置 + +| 字段 | 类型 | 默认值 | 是否必填 | 说明 | +|-----------------|---------|---------|----------|-----------------------------------| +| enabled | Boolean | false | No | 是否开启选择器缓存 | +| initialCapacity | Integer | 10000 | No | 选择器缓存初始化容量 | +| maximumSize | Integer | 10000 | No | 选择器缓存最大数量 | + +* 选择器前缀树缓存配置 + +| 字段 | 类型 | 默认值 | 是否必填 | 说明 | +|--------------|---------|--------------|----------|-----------------------------------------------------------------------------------| +| enabled | Boolean | false | No | 是否开启选择器前缀树缓存 | +| cacheSize | Integer | 512 | No | 前缀树缓存大小 | +| matchMode | String | antPathMatch | Yes | shenyu路径匹配模式,shenyu支持两种匹配模式: `antPathMatch` and `pathPattern` | + + +* 规则匹配缓存配置 + +| 字段 | 类型 | 默认值 | 是否必填 | 说明 | +|-----------------|---------|---------|----------|-----------| +| enabled | Boolean | false | No | 是否开启选择器缓存 | +| initialCapacity | Integer | 10000 | No | 规则缓存初始化容量 | +| maximumSize | Integer | 10000 | No | 规则缓存最大数量 | + +* 规则前缀树缓存配置 + +| 字段 | 类型 | 默认值 | 是否必填 | 说明 | +|--------------|---------|--------------|----------|---------------------------------------------------------------| +| enabled | Boolean | false | No | 是否开启规则前缀树缓存 | +| cacheSize | Integer | 512 | No | 前缀树缓存大小 | +| matchMode | String | antPathMatch | Yes | shenyu路径匹配模式,shenyu支持两种匹配模式: `antPathMatch` and `pathPattern` | + + +shenyu默认开启L1和L2缓存, shenyu前缀树支持两种匹配模式,我们非常建议您使用`pathPattern`作为默认的匹配模式。 + +> pathPattern: org.springframework.web.util.pattern.PathPatternParser +> antPathMatch: org.springframework.util.AntPathMatcher + +当您将`matchRestful`标记为true时,我们建议将所有缓存标记为`false`,以避免匹配冲突。 + + +##### shenyu.NettyTcpProperties 配置 + +Apache ShenYu reactor-netty 配置 + +| 名称 | 类型 | 默认值 | 是否必填 | 说明 | +|:------------------------------|:----- |:-------:|:--------:|:------------------------------------------------------------| +| webServerFactoryEnabled | Boolean | true | 否 | 是否开启自定义参数,true-开启,false-可以自行配置NettyReactiveWebServerFactory | +| selectCount | Integer | 1 | 否 | Netty 选择器数 | +| workerCount | Integer | 4 | 否 | Netty 工作线程数 | +| accessLog | Boolean | false | 否 | netty request parameters. | +| **ServerSocketChannelConfig** | | | | | +| soRcvBuf | Integer | -- | 否 | Socket参数,TCP数据接收缓冲区大小,默认由系统决定 | +| soBackLog | Integer | 128 | 否 | Socket参数,服务端接受连接的队列长度 | +| soReuseAddr | Boolean | true | 否 | Socket 参数,是否复用地址,reactor-netty中默认值为true | +| connectTimeoutMillis | Integer | 30000 | 否 | Netty 参数,连接超时时间 | +| writeBufferHighWaterMark | Integer | 65536 | 否 | Netty 参数,通道水位线上限 | +| writeBufferLowWaterMark | Integer | 32768 | 否 | Netty 参数,通道水位线下限 | +| writeSpinCount | Integer | 16 | 否 | Netty参数,一个Loop写操作执行的最大次数 | +| autoRead | Boolean | false | 否 | Netty参数,自动读取,reactor-netty中默认值为false,且只能为false | +| allocType | String | pooled | 否 | Netty参数,ByteBuf的分配器 | +| messageSizeEstimator | Integer | 8 | 否 | Netty参数, 消息大小估算器, 用于估算ByteBuf,ByteBufHolder和FileRegion大小 | +| singleEventExecutorPerGroup | Boolean | true | 否 | Netty参数, 单线程执行ChannelPipeline中的事件 | +| **SocketChannelConfig** | | | | | +| soKeepAlive | Boolean | false | 否 | Socket 参数,是否启用心跳保活机制 | +| soReuseAddr | Boolean | true | 否 | Socket 参数,是否复用地址,reactor-netty中默认值为true | +| soLinger | Integer | -1 | 否 | Socket 参数,关闭 Socket 的延迟时间 | +| tcpNoDelay | Boolean | true | 否 | Socket 参数,是否启用 Nagle 算法 | +| soRcvBuf | Integer | -- | 否 | Socket参数,TCP数据接收缓冲区大小,默认由系统决定 | +| soSndBuf | Integer | -- | 否 | Socket参数,TCP数据发送缓冲区大小,默认由系统决定 | +| ipTos | Integer | 0 | 否 | IP参数,设置IP头部的Type-of-Service字段,用于描述IP包的优先级和QoS选项 | +| allowHalfClosure | Boolean | false | 否 | Netty参数,一个连接的远端关闭时本地端是否关闭 | +| connectTimeoutMillis | Integer | 30000 | 否 | Netty 参数,连接超时时间 | +| writeBufferHighWaterMark | Integer | 65536 | 否 | Netty 参数,通道水位线上限 | +| writeBufferLowWaterMark | Integer | 32768 | 否 | Netty 参数,通道水位线下限 | +| writeSpinCount | Integer | 16 | 否 | Netty参数,一个Loop写操作执行的最大次数 | +| autoRead | Boolean | false | 否 | Netty参数,自动读取,reactor-netty中默认值为false,且只能为false | +| allocType | String | pooled | 否 | Netty参数,ByteBuf的分配器 | +| messageSizeEstimator | Integer | 8 | 否 | Netty参数, 消息大小估算器, 用于估算ByteBuf,ByteBufHolder和FileRegion大小 | +| singleEventExecutorPerGroup | Boolean | true | 否 | Netty参数, 单线程执行ChannelPipeline中的事件 | + + + +##### shenyu.register 配置 + +Apache ShenYu 网关注册到注册中心的相关配置,注册中心配置请参考 [注册中心配置](register-center-instance.md) + +| 名称 | 类型 | 默认值 | 是否必填 | 说明 | +| :----------- | :-----: | :------------: | :------: | :---------------------------------------- | +| enabled | boolean | false | 是 | 是否启动 | +| registerType | String | zookeeper | 是 | 使用哪个注册中心,目前支持zookeeper、etcd | +| serverLists | String | localhost:2181 | 是 | 注册中心的地址。若使用集群,用 `,` 分隔 | +| props | | | | 使用不同注册类型时,属性取值不同。 | + +- `props`配置 + +使用不同的注册中心时,属性取值不同 + +当注册类型为 `zookeeper` 时,支持的属性配置如下: + +|名称 | 类型 | 默认值 | 是否必填 | 说明 | +|:------------------------ |:----- |:-------: |:-------:|:----------------------------| +|sessionTimeout | int | 30000 | 否 |session超时时间(毫秒)| +|connectionTimeout | int | 3000 | 否 |连接超时时间(毫秒)| + +当注册类型为 `etcd` 时,支持的属性配置如下: + +|名称 | 类型 | 默认值 | 是否必填 | 说明 | +|:------------------------ |:----- |:-------: |:-------:|:----------------------------| +|etcdTimeout | int | 30000 | 否 |etcd超时时间(毫秒)| +|etcdTTL | int | 5 | 否 |租约生存时间(秒)| + + + +##### shenyu.httpclient 配置 + +Apache ShenYu 网关中代理Http及SpringCloud协议后,用于发送代理请求的HttpClient配置 + +| 名称 | 类型 | 默认值 | 是否必填 | 说明 | +| :-------------- | :-----: | :-------: | :------: | :----------------------------------------------------------- | +| strategy | String | webClient | No | HttpClientPlugin实现策略(默认使用webClient):
- `webClient`:使用WebClientPlugin
- `netty`:使用NettyHttpClientPlugin | +| connectTimeout | int | 45000 | No | 连接超时时间 (毫秒),默认值为 `45000`。 | +| responseTimeout | int | 3000 | No | 结果超时时间 (毫秒),默认值为 `3000`。 | +| readerIdleTime | int | 3000 | No | 指定读空闲超时时间 (毫秒),默认值为 `3000`。 | +| writerIdleTime | int | 3000 | No | 指定写空闲超时时间 (毫秒),默认值为 `3000`。 | +| allIdleTime | int | 3000 | No | 指定读和写超时时间 (毫秒),默认值为 `3000`。 | +| readTimeout | int | 3000 | No | 读取超时 (毫秒),默认值为 `3000`。 | +| writeTimeout | int | 3000 | No | 输出超时 (millisecond),默认值为 `3000`。 | +| wiretap | Boolean | false | No | 启用 Netty HttpClient 的窃听调试,默认值为 `false`。 | +| keepAlive | Boolean | false | No | 启用或禁用请求的 Keep-Alive 支持,默认值为 `false`。 | +| pool | | | | HttpClient 连接池配置 | +| proxy | | | | HttpClient 代理配置 | +| ssl | | | | HttpClient SSL配置 | + +- `pool` config + +HttpClient连接池配置 + +| 名称 | 类型 | 默认值 | 是否必填 | 说明 | +| :------------- | :----: | :------------------------: | :------: | :----------------------------------------------------------- | +| type | String | ELASTIC | No | HttpClient连接池类型,默认值为`ELASTIC`。
- `ELASTIC`: 连接池可以按需缓存和增长。
- `FIXED`: 连接池缓存并重用,有固定的最大连接数。
- `DISABLED`: 连接池总是会创建一个新的连接。 | +| name | String | proxy | No | 连接池映射名称,默认为`proxy`。 | +| maxConnections | int | 2*可用处理器数,最小值为16 | No | 仅适用于 `FIXED` 类型,在现有连接上开始挂起获取之前的最大连接数。
默认值为可用处理器数*2。
(最小值为 16) | +| acquireTimeout | int | 45000 | No | 仅适用于 `FIXED` 类型,等待获取连接的最长时间(毫秒)。默认值为 45000 | +| maxIdleTime | int | Null | No | Channel 空闲多久关闭,如果为空,没有最大空闲关闭时间。 | + +- `Proxy` 配置 + +Netty HttpClient 代理的相关配置 + +| 名称 | 类型 | 默认值 | 是否必填 | 说明 | +| :------------------- | :----: | :----: | :------: | :---------------------------------- | +| host | String | Null | No | Netty HttpClient 代理配置的主机名。 | +| port | String | Null | No | Netty HttpClient 的代理配置端口。 | +| username | String | Null | No | Netty HttpClient 代理配置的用户名。 | +| password | String | Null | No | Netty HttpClient 代理配置的密码。 | +| nonProxyHostsPattern | String | Null | No | 直连的主机列表的正则表达式 (Java)。 | + +- `SSL` 配置 + +网关路由可以同时支持路由到http和https的后端服务,以下为SSL相关配置: + +| 名称 | 类型 | 默认值 | 是否必填 | 说明 | +| :----------------------- | :-----: | :----: | :------: | :----------------------------------------------------------- | +| useInsecureTrustManager | Boolean | false | 否 | 是否信任所有下游证书,默认`false`。 | +| keyStoreType | String | PKCS12 | 否 | SSL 证书类型。 | +| keyStorePath | String | | 否 | SSL 证书路径,可以放在 classpath 下。 | +| keyStorePassword | String | | 否 | SSL 证书密码。 | +| keyStoreProvider | String | | 否 | SSL 证书提供者。 | +| keyPassword | String | | 否 | SSL 证书Key的密码。 | +| trustedX509Certificates | Array | Null | 否 | 配置自己的信任的证书列表。 | +| handshakeTimeout | int | 10000 | 否 | SSL握手超时时间(毫秒),默认值为 `10000`。 | +| closeNotifyFlushTimeout | int | 3000 | 否 | SSL close_notify 刷新超时(毫秒)默认值为 `3000`。 | +| closeNotifyReadTimeout | int | 0 | 否 | SSL close_notify 读取超时(毫秒)默认值为 `0`。 | +| defaultConfigurationType | String | TCP | 否 | SslContextBuilder 的默认配置, 默认为 TCP.
- H2: SslProvider 将根据 OpenSsl.isAlpnSupported()、SslProvider.HTTP2_CIPHERS、ALPN 支持、HTTP/1.1 和 HTTP/2 支持进行设置
- TCP: SslProvider 将根据 OpenSsl.isAvailable() 设置
- NONE: 不会有默认配置 | + + + +##### 过滤器相关配置 + +- `shenyu.file` 配置 + +文件过滤器的相关配置 + +| 名称 | 类型 | 默认值 | 是否必填 | 说明 | +| :------ | :------ | :----: | :------: | :------------------- | +| enabled | Boolean | false | 否 | 是否开启文件大小过滤 | +| maxSize | Integer | 10 | 否 | 上传文件最大值(单位:MB) | + + +- `shenyu.cross` 配置 + +跨域相关配置 + +| 名称 | | 类型 | 默认值 | 是否必填 | 说明 | +| :------ | :------ | :----: | :------: | :--------------- | :--------------: | +| enabled | | Boolean | false | 否 | 是否支持跨域请求 | +| allowedHeaders | | String | x-requested-with, authorization, Content-Type, Authorization, credential, X-XSRF-TOKEN, token, username, client | 否 | 允许的Header头,多个请用 "," 分割。新的"allowedHeaders"会在默认值基础上,去除重复的追加到"Access-Control-Allow-Headers"。 | +| allowedMethods | | String | "*" | 否 | 允许的方法 | +| allowedAnyOrigin | | Boolean | false | 否 | 是否允许任意Origin,为true时直接将`Access-Control-Allow-Origin`设置值与Origin相同,即`request.getHeaders().getOrigin()`,同时丢弃`allowedOrigin`配置 | +| allowedOrigin | | AllowedOriginConfig | - | 否 | 设置允许的请求来源 | +| | spacer | String | "." | 否 | 设置允许访问的子域名,需要搭配 domain、prefixes 一起使用 | +| | domain | String | 无 | 否 | 设置允许访问的子域名,需要搭配 spacer、prefixes 一起使用 | +| | prefixes | Set | 无 | 否 | 设置允许访问的子域名,需要搭配 spacer、domain 一起使用 | +| | origins | Set | null | 否 | 设置允许访问的域名,可单独使用 | +| | originRegex | String | 无 | 否 | 设置允许正则匹配的域名访问,可单独使用 | +| allowedExpose | | String | "" | 否 | 允许的Expose | +| maxAge | | String | "18000" | 否 | 最大年龄 (ms) | +| allowCredentials | | Boolean | true | 否 | 允许认证 | + + +- `shenyu.exclude` 配置 + +拒绝指定请求经过网关的相关配置 + +| 名称 | 类型 | 默认值 | 是否必填 | 说明 | +| :------ | :------ | :----: | :------: | :----------------------------------------- | +| enabled | Boolean | false | 否 | 是否拒绝指定请求经过网关 | +| paths | Array | 无 | 是 | 匹配该列表的请求不经过网关(支持路径匹配) | + +- `shenyu.fallback` 配置 + +熔断响应的相关配置 + +| 名称 | 类型 | 默认值 | 是否必填 | 说明 | +| :------ | :------ | :----: | :------: | :----------------- | +| enabled | Boolean | false | 否 | 是否开启熔断响应 | +| paths | Array | 无 | 是 | 服务熔断请求的地址 | + +- `shenyu.health` 配置 + +服务健康状态的相关配置 + +| 名称 | 类型 | 默认值 | 是否必填 | 说明 | +| :------ | :------ |:----------------------------------------:| :------: | :------------------- | +| enabled | Boolean | false | 否 | 是否开启健康检测 | +| paths | Array | `"/actuator/health"` 、`"/health_check"` | 否 | 设置服务健康监测路径 | + +- `shenyu.local` 配置 + +本地转发相关配置 + +| 名称 | 类型 | 默认值 | 是否必填 | 说明 | +| :-------- | :------ | :----: | :------: | :--------------------------------- | +| enabled | Boolean | false | 否 | 是否开启本地转发 | +| sha512Key | String | 无 | 是 | 秘钥,根据秘钥判断是否需要本地转发 | + + + +##### shenyu.switchConfig 配置 + + `ShenYu`开关配置 + +| 名称 | 类型 | 默认值 | 是否必填 | 说明 | +| :---- | :------ | :----: | :------: | :------------------------------------------------- | +| local | Boolean | true | 否 | 是否开启本地模式,如果开启,本地操作数据,默认开启 | + + + +##### shenyu.sync 配置 + +网关和`Admin`端使用数据同步的相关配置 + +使用`websocket`进行数据同步的属性配置如下: + +| 名称 | 类型 | 默认值 | 是否必填 | 说明 | +| :---------- | :----- | :----: | :------: | :------------------------------------------------- | +| urls | String | 无 | 是 | `Admin`的websocket服务地址,多个地址用 `,` 分开 。 | +| allowOrigin | String | 无 | 否 | 设置允许的 `origins`, 多个参数以`;`分隔 | + + + +使用`zookeeper`进行数据同步的属性配置如下: + +| 名称 | 类型 | 默认值 | 是否必填 | 说明 | +| :---------------- | :----- | :----: | :------: | :-------------------------- | +| url | String | 无 | 是 | `zookeeper`的连接地址 | +| sessionTimeout | int | 无 | 是 | `session`的超时时间(毫秒) | +| connectionTimeout | int | 无 | 是 | 连接超时时间(毫秒) | + + + +使用`http长轮询`进行数据同步的属性配置如下: + +| 名称 | 类型 | 默认值 | 是否必填 | 说明 | +| :--- | :----- | :----: | :------: | :---------------- | +| url | String | 无 | 是 | `Admin`的服务地址 | + + + +使用`nacos`进行数据同步的属性配置如下: + +| 名称 | | 类型 | 默认值 | 是否必填 | 说明 | +| :-------- | --------- | :------ | :----: | :------: | :---------------- | +| url | | String | 无 | 是 | `nacos`连接地址 | +| namespace | | String | 无 | 是 | 命名空间 | +| username | | String | 无 | 否 | 用户名 | +| password | | String | 无 | 否 | 密码 | +| acm | | Object | - | 否 | 阿里云ACM服务配置 | +| | enabled | boolean | false | 否 | 是否启用 | +| | endpoint | String | 无 | 是 | ACM服务地址 | +| | namespace | String | 无 | 否 | namespace | +| | accessKey | String | 无 | 否 | accessKey | +| | secretKey | String | 无 | 否 | secretKey | + + + +使用`etcd`进行数据同步的属性配置如下: + +| 名称 | 类型 | 默认值 | 是否必填 | 说明 | +| :--- | :----- | :----: | :------: | :------------- | +| url | String | 无 | 是 | `etcd`连接地址 | + + + +使用`consul`进行数据同步的属性配置如下: + +| 名称 | 类型 | 默认值 | 是否必填 | 说明 | +| :--------- | :----- | :----: | :------: | :------------------------------------------- | +| url | String | 无 | 是 | `consul`连接地址 | +| waitTime | int | 无 | 是 | 请求consul服务拉取配置信息的超时时间(毫秒) | +| watchDelay | int | 无 | 是 | 同步间隔(毫秒) | + + + +##### shenyu.extPlugin 配置 + +Apache ShenYu对于动态加载自定义插件的配置 + +|名称 | 类型 | 默认值 | 是否必填 | 说明 | +|:------------------------ |:----- |:-------: |:-------:|:----------------------------| +| enabled | Boolean | true | 否 | 是否开启动态加载自定义插件,默认开启 | +| path | String | | 否 | 动态加载自定义插件的路径,如果没配,默认为相对于当前网关路径下的 :/ext/lib,用户也可以使用-Dplugin-ext指定 | +| threads | Integer | 1 | 否 | 动态加载自定义插件的线程数 | +| scheduleTime | Integer | 300 | 否 | 动态加载自定义插件的间隔时间 ,单元:秒| +| scheduleDelay | Integer | 30 | 否 | 网关启动多久后去动态加载,单元:秒| + + + +##### shenyu.scheduler 配置 + +Apache ShenYu 调度线程模型配置 + +|名称 | 类型 | 默认值 | 是否必填 | 说明 | +|:------------------------ |:----- |:-------: |:-------:|:----------------------------| +| enabled | Boolean | false | 否 | 是否开启使用调度线程 | +| type | String | fixed | 否 | 调度线程池类型,默认为fixed,不配置或者其他则为弹性线程池| +| threads | Integer | Math.max((Runtime.getRuntime().availableProcessors() << 1) + 1, 16) | 否 | 固定线程池类型时候的线程数量 | + + + +##### shenyu.upstreamCheck 配置 + +Apache ShenYu 动态检测upstream的配置 + +|名称 | 类型 | 默认值 | 是否必填 | 说明 | +|:------------------------ |:----- |:-------: |:-------:|:----------------------------| +| enabled | Boolean | false | 否 | 是否检测 | +| timeout | Integer | 3000 | 否 | 超时配置 (ms) | +| healthyThreshold | Integer | 1 | 否 | 健康因子 | +| unhealthyThreshold | Integer | 1 | 否 | 不健康因子 | +| interval | Integer | 5000 | 否 | 检测的调度间隔时间| +| printEnabled | Boolean | true | 否 | 是否打印日志 | +| printInterval | Integer | 60000 | 否 | 打印日志的间隔调度时间 | + + + +##### shenyu.ribbon 配置 + +Apache ShenYu 轮询间隔配置 + +|名称 | 类型 | 默认值 | 是否必填 | 说明 | +| :------------------------ | :------ | :-----: | :------: | :----------------------------------------------------------- | +| serverListRefreshInterval | Integer | 10000 | 否 | 调整刷新时间间隔参数,参考`com.netflix.client.config.CommonClientConfigKey#ServerListRefreshInterval` | + + + +##### shenyu.metrics 配置 + +Apache ShenYu Metrics 配置,网关用来监控自身运行状态 + +|名称 | | 类型 | 默认值 | 是否必填 | 说明 | +|:------------------------ |:----- |:-------: |:-------:|:----------------------------|------------------------- | +| enabled | | Boolean | false | 否 | 是否开启metrics,true 表示开启 | +| name | | String | 无 | 否 | 名称 | +| host | | String | 无 | 否 | 网关服务对采集服务暴露的ip | +| port | | Integer | 无 | 否 | 网关服务对采集服务暴露的端口 | +| jmxConfig | | String | 无 | 否 | jmx配置 | +| props | | - | | 否 | 属性值 | +| | jvm_enabled | Boolean | 无 | 否 | 开启jvm的监控指标 | + + + +##### shenyu.sharedPool 配置 + + Apache ShenYu 共享线程池配置 + +|名称 | 类型 | 默认值 | 是否必填 | 说明 | +| :----------------- | ------- | :----------------------------------------------------- | :------: | :-----------------------------------: | +| enabled | Boolean | false | 否 | 是否开启共享线程池 | +| prefix | String | "shenyu-shared" | 否 | 线程池名称前缀 | +| corePoolSize | Integer | 200 | 否 | 线程池核心线程数 | +| maximumPoolSize | Integer | Integer.MAX_VALUE | 否 | 线程池最大线程数 | +| keepAliveTime | Long | 60000L | 否 | 多余的空闲线程keepAlive时间,单位毫秒 | +| maxWorkQueueMemory | Long | 当前JVM最大可用内存的80% | 否 | 最大使用内存,单位字节 | +| maxFreeMemory | Integer | 无 | 否 | 最大剩余内存,单位字节 | + +##### shenyu.alert 配置 + +Apache ShenYu 网关告警通知配置 + +| Name | Type | Default | Required | Description | +|:------------------| ------- |:--------------------------------------------------------|:--------:|:-------------------:| +| enabled | Boolean | false | 否 | 是否开启告警消息通知 | +| admins | String | "localhost:9095" | 否 | ShenYu Admin 服务地址列表 | + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/property-config/register-center-access.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/property-config/register-center-access.md new file mode 100644 index 00000000000..9bc42753601 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/property-config/register-center-access.md @@ -0,0 +1,119 @@ +--- +title: 客户端接入配置 +description: 客户端接入配置 +--- + +> *注意* +> 在Apache ShenYu version 2.6.1, ShenYu注册中心只支持http类型,中间件注册类型已经被移除。 +> 所以,请使用http注册类型来注册你的服务。 +> ShenYu注册中心不是微服务注册中心,它只是将元数据、选择器数据、规则数据注册到shenyu-admin,然后shenyu-admin将数据同步到shenyu-gateway。 + +应用客户端接入是指将你的微服务接入到`Apache ShenYu`网关,当前支持`Http`、 `Dubbo`、 `Spring Cloud`、 `gRPC`、 `Motan`、 `Sofa`、 `Tars`等协议的接入。 + + +将应用客户端接入到`Apache ShenYu`网关是通过注册中心来实现的,涉及到客户端注册和服务端同步数据。注册类型支持`Http`。 + + +本篇文章介绍将应用客户端接入到`Apache ShenYu`网关,应该如何配置。相关原理请参考设计文档中的 [客户端接入原理](../../design/register-center-design) 。 + + + + + +### Http方式注册配置 + +#### shenyu-admin配置 + +在 `yml`文件中配置注册类型为`http`,配置信息如下: + +```yaml +shenyu: + register: + enabled: true + registerType: http + props: + checked: true #是否开启检测 + zombieCheckTimes: 5 #失败几次后剔除服务 + scheduledTime: 10 #定时检测间隔时间 (秒) +``` + + + + +#### shenyu-client配置 + +下面展示的是`http`服务作为客户端接入到`Apache ShenYu`网关时,通过`Http`方式注册配置信息。其他客户端接入时(`Dubbo`、 `Spring Cloud`等),配置方式同理。 + +在微服务中的 `yml`文件配置注册方式设置为`http`,并填写`shenyu-admin`服务地址列表,配置信息如下: + +```yaml +shenyu: + register: + enabled: true + registerType: http + serverLists: http://localhost:9095 + props: + username: admin + password: 123456 + client: + http: + props: + contextPath: /http + appName: http + port: 8188 + isFull: false +# registerType : 服务注册类型,填写 http +# serverList: 为http注册类型时,填写Shenyu-Admin项目的地址,注意加上http://,多个地址用英文逗号分隔 +# port: 你本项目的启动端口,目前springmvc/tars/grpc需要进行填写 +# contextPath: 为你的这个mvc项目在shenyu网关的路由前缀, 比如/order ,/product 等等,网关会根据你的这个前缀来进行路由. +# appName:你的应用名称,不配置的话,会默认取 `spring.application.name` 的值 +# isFull: 设置true 代表代理你的整个服务,false表示代理你其中某几个controller;目前适用于springmvc/springcloud +``` + + + + +### 同时注册多种服务类型 + +> 以同时注册http和dubbo服务举例。 +在`yml`参考如下配置即可: + +```yaml +shenyu: + register: + registerType: http + serverLists: localhost + props: + username: admin + password: 123456 + client: + http: + props: + contextPath: /http + appName: http + port: 8188 + isFull: false + dubbo: + props: + contextPath: /dubbo + appName: dubbo + port: 28080 + props: + nacosNameSpace: ShenyuRegisterCenter +# registerType : 服务注册类型,填写 nacos +# serverList: 为nacos注册类型时,填写nacos地址,多个地址用英文逗号分隔 +# http.port: 你本项目的启动Http端口,目前springmvc/SpringCloud需要进行填写 +# http.contextPath: 为你的这个mvc项目在shenyu网关的路由前缀,比如/order ,/product 等等,网关会根据你的这个前缀来进行路由. +# http.appName:你的应用名称,不配置的话,会默认取 `spring.application.name` 的值 +# http.isFull: 设置true 代表代理你的整个服务,false表示代理你其中某几个controller;目前适用于springmvc/springcloud +# dubbo.contextPath: 为你的项目中对应dubbo接口的contextPath +# dubbo.port: dubbo服务端口 +# dubbo.appName: dubbo应用名称 +# nacosNameSpace: nacos的命名空间 +``` + + +总结,本文主要介绍了如何将你的微服务(当前支持`Http`、 `Dubbo`、 `Spring Cloud`、 `gRPC`、 `Motan`、 `Sofa`、 `Tars`等协议)接入到`Apache ShenYu`网关。介绍了注册中心的原理,`Apache ShenYu`网关支持的注册中心有`Http`方式。介绍了以`http`服务作为客户端接入到`Apache ShenYu`网关时,使用不同方式注册配置信息。 + + + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/property-config/register-center-instance.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/property-config/register-center-instance.md new file mode 100644 index 00000000000..9dfa3a1b1c2 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/property-config/register-center-instance.md @@ -0,0 +1,66 @@ +--- +title: 注册中心配置 +description: 注册中心配置 +--- + +本篇将介绍如何将网关实例注册到注册中心。`Apache ShenYu` 网关目前支持注册到 `zookeeper`、`etcd`。 + +### 添加Maven依赖 + +首先,在网关的 `pom.xml` 文件中引入如下依赖。 + +```xml + + + org.apache.shenyu + shenyu-spring-boot-starter-registry + ${project.version} + + +``` + +### 使用zookeeper + +> 请注意,从 ShenYu 2.5.0 起将不再支持 Zookeeper 3.4.x 或更低版本。如果您已经使用了 Zookeeper 3.4.x 或更低的版本,您需要使用更高的 Zookeeper 版本并重新初始化数据。 + +在网关的 `yml` 文件中添加如下配置: + +```yaml +registry: + enabled: true + registerType: zookeeper + serverLists: localhost:2181 #配置成你的 zookeeper 地址,集群环境请使用(,)分隔 + props: + sessionTimeout: 3000 #可选,默认3000 + connectionTimeout: 3000 #可选,默认3000 +``` + +### 使用etcd + +在网关的 `yml` 文件中添加如下配置: + +```yaml +registry: + enabled: true + registerType: etcd + serverLists: http://localhost:2379 #配置成你的 etcd 地址,集群环境请使用(,)分隔。 + props: + etcdTimeout: 3000 #可选,默认3000 + etcdTTL: 5 #可选,默认5 +``` + +### 使用consul + +在网关的 `yml` 文件中添加如下配置: + +```yaml +registry: + enabled: true + registerType: consul + serverLists: localhost:8848 #配置成你的 consul 地址,集群环境请使用(,)分隔。 + props: + consulTimeout: 3000 #可选,默认3000 + consulTTL: 3000 #可选,默认3000 +``` + +> 配置完成后,启动网关,就会成功注册到相应注册中心。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/property-config/use-data-sync.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/property-config/use-data-sync.md new file mode 100644 index 00000000000..f202e6f3950 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/property-config/use-data-sync.md @@ -0,0 +1,377 @@ +--- +title: 数据同步配置 +description: 使用不同的数据同步策略 +--- + +本篇主要讲解如何配置数据同步策略,数据同步是指在 `shenyu-admin` 后台操作数据以后,使用何种策略将数据同步到 `Apache ShenYu` 网关。`Apache ShenYu` 网关当前支持`ZooKeeper`、`WebSocket`、`Http长轮询`、`Nacos`、`Etcd` 和 `Consul`进行数据同步。 + + + + +数据同步原理请参考设计文档中的 [数据同步原理](../../design/data-sync) 。 + +### WebSocket同步配置(默认方式,推荐) + +* `Apache ShenYu`网关配置 + + 首先在 `pom.xml` 文件中引入以下依赖: + +```xml + + + org.apache.shenyu + shenyu-spring-boot-starter-sync-data-websocket + ${project.version} + +``` + + + +然后在 `yml` 文件中进行如下配置: + +```yaml +shenyu: + sync: + websocket : + # urls:是指 shenyu-admin的地址,如果有多个,请使用(,)分割。 + urls: ws://localhost:9095/websocket + allowOrigin: ws://localhost:9195 +``` + + + +* `shenyu-admin 配置` + + 在 `yml` 文件中进行如下配置: + +```yml +shenyu: + sync: + websocket: + enabled: true +``` + + + +当建立连接以后会全量获取一次数据,以后的数据都是增量的更新与新增,性能好。而且也支持断线重连 (默认`30`秒)。推荐使用此方式进行数据同步,也是`Apache ShenYu`默认的数据同步策略。 + +### Zookeeper同步配置 + +> 请注意,从 ShenYu 2.5.0 起将不再支持 Zookeeper 3.4.x 或更低版本。如果您已经使用了 Zookeeper 3.4.x 或更低的版本,您需要使用更高的 Zookeeper 版本并重新初始化数据。 + +* `Apache ShenYu`网关配置 + + 首先在 `pom.xml` 文件中引入以下依赖: + + ```xml + + + org.apache.shenyu + shenyu-spring-boot-starter-sync-data-zookeeper + ${project.version} + + ``` + + + + +然后在 `yml` 文件中进行如下配置: + +```yaml +shenyu: + sync: + zookeeper: + url: localhost:2181 + # url: 配置成你的 zookeeper 地址,集群环境请使用(,)分隔 + sessionTimeout: 5000 + connectionTimeout: 2000 +``` + + + + +* `shenyu-admin` 配置 + +在 `yml` 文件中进行如下配置: + +```yaml +shenyu: + sync: + zookeeper: + url: localhost:2181 + # url: 配置成你的 zookeeper 地址,集群环境请使用(,)分隔 + sessionTimeout: 5000 + connectionTimeout: 2000 +``` + + + + +使用`zookeeper`同步机制也是非常好的,时效性也高,但是要处理`zookeeper`环境不稳定,集群脑裂等问题。 + + + +### Http长轮询同步配置 + +* `Apache ShenYu`网关配置 + +首先在 `pom.xml` 文件中引入以下依赖: + +```xml + + + org.apache.shenyu + shenyu-spring-boot-starter-sync-data-http + ${project.version} + +``` + + + + +然后在 `yml` 文件中进行如下配置: + +```yaml +shenyu: + sync: + http: + url: http://localhost:9095 + # url: 配置成你的 shenyu-admin 的 ip 与端口地址,多个admin集群环境请使用(,)分隔。 +``` + + + + +* `shenyu-admin` 配置 + +在 `yml` 文件中进行如下配置: + +```yaml +shenyu: + sync: + http: + enabled: true +``` + + + + +使用`Http长轮询`进行数据同步,会让网关很轻量,但时效性略低。它是根据分组`key`来拉取,如果数据量过大,过多,会有一定的影响。原因是一个组下面的一个小地方更改,都会拉取整个组的数据。 + + +### Nacos同步配置 + +* `Apache ShenYu`网关配置 + +首先在 `pom.xml` 文件中引入以下依赖: + +```xml + + + org.apache.shenyu + shenyu-spring-boot-starter-sync-data-nacos + ${project.version} + +``` + + + + +然后在 `yml` 文件中进行如下配置: + +```yaml +shenyu: + sync: + nacos: + url: localhost:8848 + # url: 配置成你的 nacos地址,集群环境请使用(,)分隔。 + namespace: 1c10d748-af86-43b9-8265-75f487d20c6c + username: + password: + acm: + enabled: false + endpoint: acm.aliyun.com + namespace: + accessKey: + secretKey: + # 其他参数配置,请参考 naocs官网。 +``` + + + + +* `shenyu-admin` 配置 + +在 `yml` 文件中进行如下配置: + +```yaml +shenyu: + sync: + nacos: + url: localhost:8848 + # url: 配置成你的 nacos地址,集群环境请使用(,)分隔。 + namespace: 1c10d748-af86-43b9-8265-75f487d20c6c + username: + password: + acm: + enabled: false + endpoint: acm.aliyun.com + namespace: + accessKey: + secretKey: + # 其他参数配置,请参考 naocs官网。 +``` + + + + +### Etcd 同步配置 + +* `Apache ShenYu`网关配置 + +首先在 `pom.xml` 文件中引入以下依赖: + +```xml + + + org.apache.shenyu + shenyu-spring-boot-starter-sync-data-etcd + ${project.version} + + + io.grpc + grpc-grpclb + + + io.grpc + grpc-netty + + + +``` + + + + +然后在 `yml` 文件中进行如下配置: + +```yaml +shenyu: + sync: + etcd: + url: http://localhost:2379 + # url: 配置成你的 etcd,集群环境请使用(,)分隔。 +``` + + + + +* `shenyu-admin` 配置 + +在 `yml` 文件中进行如下配置: + +```yaml +shenyu: + sync: + etcd: + url: http://localhost:2379 + # url: 配置成你的 etcd,集群环境请使用(,)分隔。 +``` + + + +### Consul 同步配置 + +* `Apache ShenYu`网关配置 + +首先在 `pom.xml` 文件中引入以下依赖: + +```xml + + + org.apache.shenyu + shenyu-spring-boot-starter-sync-data-consul + ${project.version} + +``` + + + + +然后在 `yml` 文件中进行如下配置: + +```yaml +shenyu: + sync: + consul: + url: http://localhost:8500 + waitTime: 1000 # 查询等待时间 + watchDelay: 1000 # 数据同步间隔时间 +``` + + + + +* `shenyu-admin` 配置 + +在 `yml` 文件中进行如下配置: + +```yaml +shenyu: + sync: + consul: + url: http://localhost:8500 +``` + + + + + +> 在`Apache ShenYu`网关和`shenyu-admin` 重新配置数据同步策略后,需要重启服务。 +> +> `Apache ShenYu`网关 和 `shenyu-admin` 必须使用相同的同步策略。 + +### Apollo同步配置 + +Apollo仅支持Java [8,17)版本,如果您要使用apollo作为数据同步中心,请确保您的JDK版本在[8,17)之间。 + +* `Apache ShenYu`网关配置 + +从`https://repo1.maven.org/maven2/org/apache/shenyu/shenyu-spring-boot-starter-sync-data-apollo/` 下载对应版本的jar包,然后将jar包放到`/lib`目录下。 + +在yaml文件中添加如下配置: + +```yaml +shenyu: + sync: + apollo: + appId: shenyu + meta: http://localhost:8080 + env: dev + clusterName: test + namespace: application +``` + +* `Apache ShenYu Admin` 配置 + +从`https://repo1.maven.org/maven2/org/apache/shenyu/shenyu-admin-listener-apollo/` 下载对应版本的jar包,然后将jar包放到`/lib`目录下。 + +在yaml文件中添加如下配置: + +```yaml +shenyu: + sync: + apollo: + meta: http://localhost:8080 + appId: shenyu + portalUrl: http://localhost:8070 + env: dev + clusterName: test + namespace: application + token: 0fff5645fc74ee5e0d63a6389433c8c8afc0beea31eed0279ecc1c8961d12da9 +``` + + + +> 在`Apache ShenYu`网关和`shenyu-admin` 重新配置数据同步策略后,需要重启服务。 +> `Apache ShenYu`网关 和 `shenyu-admin` 必须使用相同的同步策略。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/proxy/_category_.json b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/proxy/_category_.json new file mode 100644 index 00000000000..3b3cf7f0ca7 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/proxy/_category_.json @@ -0,0 +1,4 @@ +{ + "label": "快速接入", + "position": 4 +} diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/proxy/dubbo-proxy.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/proxy/dubbo-proxy.md new file mode 100644 index 00000000000..34b54105c57 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/proxy/dubbo-proxy.md @@ -0,0 +1,439 @@ +--- +title: Dubbo服务接入 +keywords: ["Dubbo"] +description: Dubbo服务接入 +--- + + +## 说明 + +* 此篇文章是介绍 `dubbo` 服务接入到 `Apache ShenYu` 网关,`Apache ShenYu` 网关使用 `dubbo` 插件来接入`Dubbo`服务。 +* 当前支持 `alibaba dubbo(< 2.7.x)` 以及 `apache dubbo (>=2.7.x)`。 +* 接入前,请正确启动 `shenyu-admin`,并开启`dubbo`插件,在网关端和`Dubbo`服务端引入相关依赖。可以参考前面的 [Dubbo快速开始](../../quick-start/quick-start-dubbo)。 + + +应用客户端接入的相关配置请参考:[客户端接入配置](../property-config/register-center-access.md)。 + +数据同步的相关配置请参考:[数据同步配置](../property-config/use-data-sync.md)。 + +## 在网关中引入 dubbo 插件 + +* 在网关的 `pom.xml` 文件中增加如下依赖: + + * `alibaba dubbo` 用户, `dubbo` 版本换成你的,引入你需要的注册中心依赖,以下是参考。 + + ```xml + + + org.apache.shenyu + shenyu-spring-boot-starter-client-alibaba-dubbo + ${project.version} + + + + com.alibaba + dubbo + 2.6.5 + + + org.apache.curator + curator-client + 4.0.1 + + + org.apache.curator + curator-framework + 4.0.1 + + + org.apache.curator + curator-recipes + 4.0.1 + + ``` + + * `apache dubbo` 用户,`dubbo` 版本换成你的,引入你需要的注册中心依赖,如下是参考。 + + ```xml + + + org.apache.shenyu + shenyu-spring-boot-starter-client-apache-dubbo + ${project.version} + + + + + org.apache.dubbo + dubbo + 2.7.5 + + + + org.apache.dubbo + dubbo-registry-nacos + 2.7.5 + + + com.alibaba.nacos + nacos-client + 1.1.4 + + + + + + org.apache.curator + curator-client + 4.0.1 + + + org.apache.curator + curator-framework + 4.0.1 + + + org.apache.curator + curator-recipes + 4.0.1 + + + ``` + + +* 重启网关服务。 + +## dubbo 服务接入网关 + +可以参考:[shenyu-examples-dubbo](https://github.com/apache/shenyu/tree/master/shenyu-examples/shenyu-examples-dubbo) + +* alibaba dubbo 用户 + +如果是`springboot`构建,引入以下依赖: + +```xml + + org.apache.shenyu + shenyu-spring-boot-starter-client-alibaba-dubbo + ${shenyu.version} + +``` + + +如果是`spring`构建,引入以下依赖: + +```xml + + org.apache.shenyu + shenyu-client-alibaba-dubbo + ${shenyu.version} + +``` + +并在你的 `bean` 定义的 `xml` 文件中新增如下 : + +```xml + + + + + + + + + + + + + + + + + + + + + + +``` + + +* apache dubbo 用户 + +如果是`springboot`构建,引入以下依赖: + + ```xml + + org.apache.shenyu + shenyu-spring-boot-starter-client-apache-dubbo + ${shenyu.version} + + ``` + +需要在你的 `客户端项目` 定义的 `application.yml` 文件中新增如下: + +```yaml +dubbo: + registry: + address: dubbo注册中心地址 + +shenyu: + register: + registerType: shenyu服务注册类型 #http #zookeeper #etcd #nacos #consul + serverLists: shenyu服务注册地址 #http://localhost:9095 #localhost:2181 #http://localhost:2379 #localhost:8848 + client: + dubbo: + props: + contextPath: /你的contextPath + appName: 你的应用名称 +``` + + +如果是`spring`构建,引入以下依赖: + +```xml + + org.apache.shenyu + shenyu-client-apache-dubbo + ${shenyu.version} + +``` + +需要在你的 `bean` 定义的 `xml` 文件中新增如下 : + +```xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +``` + +需要在你的 `客户端项目` 定义的 `application.yml` 文件中新增如下: + +```yaml +dubbo: + registry: + address: dubbo注册中心地址 + port: dubbo服务端口号 +``` + +## dubbo 插件设置 + +* 首先在 `shenyu-admin` 插件管理中,把`dubbo` 插件设置为开启。 + +* 其次在 `dubbo` 插件中配置你的注册地址,或者其他注册中心的地址。 + +```yaml +{"register":"zookeeper://localhost:2181"} or {"register":"nacos://localhost:8848"} +``` + +## 接口注册到网关 + +* 在 `dubbo` 服务实现类的方法上加上 `@ShenyuDubboClient` 注解,表示该接口方法注册到网关。 + +* 启动你的提供者,成功启动后,进入后台管理系统的`插件列表 -> rpc proxy -> dubbo`,会看到自动注册的选择器和规则信息。 + + +## dubbo用户请求及参数说明 + +可以通过 `http` 的方式来请求你的 `dubbo` 服务。`Apache ShenYu` 网关需要有一个路由前缀,这个路由前缀就是你接入项目进行配置 `contextPath` + +> 比如你有一个 order服务 它有一个接口,它的注册路径 /order/test/save +> 现在就是通过 post 方式请求网关:http://localhost:9195/order/test/save +> 其中 localhost:9195 为网关的 ip 端口,默认端口是 9195 ,/order 是你 dubbo 接入网关配置的 contextPath + + +* 参数传递: + + * 通过 `http`协议, `post` 方式访问网关,通过在`http body`中传入`json`类型参数。 + + * 更多参数类型传递,可以参考 [shenyu-examples-dubbo](https://github.com/apache/shenyu/tree/master/shenyu-examples/shenyu-examples-dubbo) 中的接口定义,以及参数传递方式。 + +* 单个 `java bean`参数类型(默认) + +* 多参数类型支持,在网关的`yaml` 配置中新增如下配置: + +```yaml +shenyu: + dubbo: + parameter: multi +``` + +* 自定义实现多参数支持: + + * 在你搭建的网关项目中,新增一个类 `MyDubboParamResolveService`,实现 `org.apache.shenyu.web.dubbo.DubboParamResolveService`接口。 + + ```java + public interface DubboParamResolveService { + + /** + * Build parameter pair. + * this is Resolve http body to get dubbo param. + * + * @param body the body + * @param parameterTypes the parameter types + * @return the pair + */ + Pair buildParameter(String body, String parameterTypes); + } + ``` + + * `body` 为 `http` 中 `body` 传的 `json` 字符串。 + + * `parameterTypes`: 匹配到的方法参数类型列表,如果有多个,则使用 `,` 分割。 + + * `Pair` 中,`left` 为参数类型,`right` 为参数值,这是 `dubbo` 泛化调用的标准 + + * 把你的类注册成 `Spring` 的 `bean`,覆盖默认的实现。 + + ```java + @Bean + public DubboParamResolveService myDubboParamResolveService() { + return new MyDubboParamResolveService(); + } + ``` + +## 服务治理 + +* 标签路由 + * 请求时在 `header` 中添加 `Dubbo_Tag_Route`,并设置对应的值,之后当前请求就会路由到指定 `tag` 的 `provider`,只对当前请求有效。 +* 服务提供者直连 + * 设置 `@ShenyuDubboClient` 注解中的 `url` 属性。 + * 修改 `Admin` 控制台修改元数据内的 `url` 属性。 + * 对所有请求有效。 +* 参数验证和自定义异常 + * 指定 `validation = "shenyuValidation"`。 + * 在接口中抛出 `ShenyuException` 时,异常信息会返回,需要注意的是显式抛出 `ShenyuException`。 + + ```java + @Service(validation = "shenyuValidation") + public class TestServiceImpl implements TestService { + + @Override + @ShenyuDubboClient(path = "/test", desc = "test method") + public String test(@Valid HelloServiceRequest name) throws ShenyuException { + if (true){ + throw new ShenyuException("Param binding error."); + } + return "Hello " + name.getName(); + } + } + ``` + + * 请求参数 + + ```java + public class HelloServiceRequest implements Serializable { + + private static final long serialVersionUID = -5968745817846710197L; + + @NotEmpty(message = "name cannot be empty") + private String name; + + @NotNull(message = "age cannot be null") + private Integer age; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Integer getAge() { + return age; + } + + public void setAge(Integer age) { + this.age = age; + } + } + ``` + + * 发送请求 + + ```json + { + "name": "" + } + ``` + + * 返回 + + ```json + { + "code": 500, + "message": "Internal Server Error", + "data": "name cannot be empty,age cannot be null" + } + ``` + + * 当按照要求传递请求参数时,会返回自定义异常的信息 + + ```json + { + "code": 500, + "message": "Internal Server Error", + "data": "Param binding error." + } + ``` + +## Http --> 网关 --> Dubbo Provider + +实际上就是把 `http` 请求,转成 `dubbo` 协议,内部使用 `dubbo 泛化`来进行调用。 +`dubbo` 服务在接入网关的时候,加上了 `@ShenyuDubboClient` 注解,并设置了 `path` 字段来指定请求路径。 +然后在`yml`中配置了 `contextPath`。 + +假如有一个这样的方法, `contextPath` 配置的是 `/dubbo`。 + +```java +@Override +@ShenyuDubboClient(path = "/insert", desc = "插入一条数据") +public DubboTest insert(final DubboTest dubboTest) { + return dubboTest; +} +``` + +那么请求的路径为:`http://localhost:9195/dubbo/insert`,`localhost:9195`是网关的地址,如果你更改了,这里也要改。 + +请求参数: `DubboTest` 是一个 `javabean` 对象,有 2 个字段,`id` 与 `name` ,那么我们通过 `body` 中传递这个对象的 `json` 数据就好。 + +``` +{"id": "1234", "name": "XIAO5y"} +``` + +如果接口中,没有参数,那么`body` 传值为: + +``` +{} +``` + +如果接口有很多个参数,请参考上面介绍过的多参数类型支持。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/proxy/grpc-proxy.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/proxy/grpc-proxy.md new file mode 100644 index 00000000000..defb448593c --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/proxy/grpc-proxy.md @@ -0,0 +1,194 @@ +--- +title: gRPC服务接入 +description: gRPC服务接入 +--- + +此篇文章是介绍 `gRPC` 服务接入到 `Apache ShenYu` 网关,`Apache ShenYu` 网关使用 `grpc` 插件来接入`gRPC`服务。 + +接入前,请正确启动 `shenyu-admin`,并开启`grpc`插件,在网关端和`grpc`服务端引入相关依赖。可以参考前面的 [gRPC快速开始](../quick-start/quick-start-grpc)。 + + +应用客户端接入的相关配置请参考:[客户端接入配置](../property-config/register-center-access.md)。 + +数据同步的相关配置请参考:[数据同步配置](../property-config/use-data-sync.md)。 + +## 在网关中引入 grpc 插件 + + +引入网关对`gRPC`的代理插件,在网关的 `pom.xml` 文件中增加如下依赖: + +```xml + + + org.apache.shenyu + shenyu-spring-boot-starter-plugin-grpc + ${project.version} + + +``` + +* 重启你的网关服务。 + +## gRPC服务接入网关 + +可以参考: [shenyu-examples-grpc](https://github.com/apache/shenyu/tree/master/shenyu-examples/shenyu-examples-grpc) + +1. 在由`gRPC`构建的微服务中,引入如下依赖: + +```xml + + org.apache.shenyu + shenyu-spring-boot-starter-client-grpc + ${shenyu.version} + + + guava + com.google.guava + + + +``` + +在 `shenyu-examples-grpc` 下执行以下命令生成 `java` 代码。 + +```shell +mvn protobuf:compile //编译消息对象 +mvn protobuf:compile-custom //依赖消息对象,生成接口服务 +``` + +2. 在 application.yaml 增加如下配置: + +```yaml +shenyu: + register: + registerType: http #zookeeper #etcd #nacos #consul + serverLists: http://localhost:9095 #localhost:2181 #http://localhost:2379 #localhost:8848 + props: + username: admin + password: 123456 + client: + grpc: + props: + contextPath: /grpc + appName: grpc + ipAndPort: 127.0.0.1:38080 + port: 38080 +``` + +3. 在`gRPC`服务接口实现类上加上 `@ShenyuGrpcClient` 注解。启动你的服务提供者,成功注册后,在后台管理系统进入`插件列表 -> rpc proxy -> grpc`,会看到自动注册的选择器和规则信息。 + +示例: + +```java + @Override + @ShenyuGrpcClient(path = "/echo", desc = "echo") + public void echo(EchoRequest request, StreamObserver responseObserver) { + System.out.println("Received: " + request.getMessage()); + EchoResponse.Builder response = EchoResponse.newBuilder() + .setMessage("ReceivedHELLO") + .addTraces(Trace.newBuilder().setHost(getHostname()).build()); + responseObserver.onNext(response.build()); + responseObserver.onCompleted(); + } + +``` + +## 用户请求 + +可以通过 `http` 的方式来请求你的`grpc`服务。`Apache ShenYu`网关需要有一个路由前缀,这个路由前缀就是你接入项目进行配置 `contextPath`。 + +如果你的`proto`文件定义如下: + +```protobuf +message EchoRequest { + string message = 1; +} +``` + +那么请求参数如下所示: + +```json +{ + "data": [ + { + "message": "hello grpc" + } + ] +} +``` + +当前是以 `json` 的格式传递参数,`key`的名称默认是`data`,你可以在 `GrpcConstants.JSON_DESCRIPTOR_PROTO_FIELD_NAME` 中进行重置;`value`的传入则根据你定义的 `proto` 文件。 + +`Apache ShenYu` 可以支持 `gRPC` 的流式调用,通过数组的形式传递多个参数。 + + +如果你的`proto`文件定义如下: + +```protobuf +message RequestData { + string text = 1; +} +``` + +对应的方法调用请求参数如下: + +- `UNARY` + +```json +{ + "data": [ + { + "text": "hello grpc" + } + ] +} +``` + +- `CLIENT_STREAMING` + +```json +{ + "data": [ + { + "text": "hello grpc" + }, + { + "text": "hello grpc" + }, + { + "text": "hello grpc" + } + ] +} +``` + +- `SERVER_STREAMING` + + +```json +{ + "data": [ + { + "text": "hello grpc" + } + ] +} +``` + +- `BIDI_STREAMING` + +```json +{ + "data": [ + { + "text": "hello grpc" + }, + { + "text": "hello grpc" + }, + { + "text": "hello grpc" + } + ] +} +``` diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/proxy/http-proxy.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/proxy/http-proxy.md new file mode 100644 index 00000000000..0d04b557140 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/proxy/http-proxy.md @@ -0,0 +1,260 @@ +--- +title: Http服务接入 +keywords: ["Http"] +description: Http服务接入 +--- + +本文档旨在帮助 `http` 服务接入到 `Apache ShenYu` 网关。`Apache ShenYu` 网关使用 `divide` 插件来处理 `http` 请求。 + +接入前,请正确启动 `shenyu-admin`,并开启`divide`插件,在网关端和`Http`服务端引入相关依赖。可以参考前面的 [Http快速开始](../../quick-start/quick-start-http)。 + +应用客户端接入的相关配置请参考:[客户端接入配置](../property-config/register-center-access.md)。 + +数据同步的相关配置请参考:[数据同步配置](../property-config/use-data-sync.md)。 + +## 在网关中引入 divide 插件 + +* 在网关的 `pom.xml` 文件中增加如下依赖: + + ```xml + + org.apache.shenyu + shenyu-spring-boot-starter-plugin-divide + ${project.version} + + + + org.apache.shenyu + shenyu-spring-boot-starter-plugin-httpclient + ${project.version} + + ``` + +## Http请求接入网关(springMvc 体系用户) + +* `SpringBoot` 用户 + + 可以参考:[shenyu-examples-http](https://github.com/apache/shenyu/tree/master/shenyu-examples/shenyu-examples-http) + + 1. 在你的`http`服务中的 `pom.xml`文件 新增如下依赖: + + ```xml + + org.apache.shenyu + shenyu-spring-boot-starter-client-springmvc + ${shenyu.version} + + ``` + + 2. 在 application.yaml 增加如下配置: + + ```yaml + shenyu: + register: + registerType: http #zookeeper #etcd #nacos #consul + serverLists: http://localhost:9095 #localhost:2181 #http://localhost:2379 #localhost:8848 + props: + username: admin + password: 123456 + client: + http: + props: + contextPath: /http + appName: http + # port: 8189 + ``` + +* `SpringMvc` 用户 + + 可以参考:[shenyu-examples-springmvc](https://github.com/apache/shenyu/tree/master/shenyu-examples/shenyu-examples-springmvc) + + 在你的`http`服务中的 `pom.xml`文件 新增如下依赖: + + ```xml + + org.apache.shenyu + shenyu-client-springmvc + ${shenyu.version} + + ``` + + 并在你的 `bean` 定义的 `xml` 文件中新增如下: + + ```xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ``` + + 在你的 `controller` 的接口上加上 `@ShenyuSpringMvcClient` 注解。 + + 你可以把注解加到 `Controller` 类上面,里面的`path`属性则为前缀,如果含有 `/**` 代表你的整个接口需要被网关代理。 + +示例一 + +下面表示的是 `/test/payment`,`/test/findByUserId` 都会被网关代理。 + +```java + @RestController + @RequestMapping("/test") + @ShenyuSpringMvcClient(path = "/test/**") + public class HttpTestController { + + @PostMapping("/payment") + public UserDTO post(@RequestBody final UserDTO userDTO) { + return userDTO; + } + + @GetMapping("/findByUserId") + public UserDTO findByUserId(@RequestParam("userId") final String userId) { + UserDTO userDTO = new UserDTO(); + userDTO.setUserId(userId); + userDTO.setUserName("hello world"); + return userDTO; + } + } +``` + +示例二 + +下面表示的是: `/order/save` 会被网关代理,而 `/order/findById` 则不会。 + + +```java + @RestController + @RequestMapping("/order") + @ShenyuSpringMvcClient(path = "/order") + public class OrderController { + + @PostMapping("/save") + @ShenyuSpringMvcClient(path = "/save") + public OrderDTO save(@RequestBody final OrderDTO orderDTO) { + orderDTO.setName("hello world save order"); + return orderDTO; + } + + @GetMapping("/findById") + public OrderDTO findById(@RequestParam("id") final String id) { + OrderDTO orderDTO = new OrderDTO(); + orderDTO.setId(id); + orderDTO.setName("hello world findById"); + return orderDTO; + } + } +``` + +示例三:这是一种简化的使用方式,只需要一个简单的注释即可使用元数据注册到网关. +特别说明:目前只支持`@RequestMapping、@GetMapping、@PostMapping、@DeleteMapping、@PutMapping`注解,并且只对`@XXXMapping`中的第一个路径有效 + +```java + @RestController + @RequestMapping("new/feature") + public class NewFeatureController { + + /** + * no support gateway access api. + * + * @return result + */ + @RequestMapping("/gateway/not") + public EntityResult noSupportGateway() { + return new EntityResult(200, "no support gateway access"); + } + + /** + * Do not use shenyu annotation path. used request mapping path. + * + * @return result + */ + @RequestMapping("/requst/mapping/path") + @ShenyuSpringCloudClient + public EntityResult requestMappingUrl() { + return new EntityResult(200, "Do not use shenyu annotation path. used request mapping path"); + } + + /** + * Do not use shenyu annotation path. used post mapping path. + * + * @return result + */ + @PostMapping("/post/mapping/path") + @ShenyuSpringCloudClient + public EntityResult postMappingUrl() { + return new EntityResult(200, "Do not use shenyu annotation path. used post mapping path"); + } + + /** + * Do not use shenyu annotation path. used post mapping path. + * + * @return result + */ + @GetMapping("/get/mapping/path") + @ShenyuSpringCloudClient + public EntityResult getMappingUrl() { + return new EntityResult(200, "Do not use shenyu annotation path. used get mapping path"); + } + } + +``` + + +* 启动你的项目,你的服务接口接入到了网关,进入`shenyu-admin`后台管理系统的`插件列表 -> http process -> divide`,看到自动创建的选择器和规则。 + +## Http请求接入网关(其他语言,非springMvc体系) + +* 首先在 `shenyu-admin` 找到 `divide` 插件,进行选择器,和规则的添加,进行流量的匹配筛选。 + +* 如果不懂怎么配置,请参考 [选择器和规则管理](../admin-usage/selector-and-rule)。 + +* 您也可以自定义开发属于你的 `http-client`,参考 [多语言 Http 客户端开发](../../developer/developer-shenyu-client)。 + +## 用户请求 + +当你的`Http`服务接入到`Apache ShenYu`网关后,请求方式没有很大的变动,小的改动有两点。 + +* 第一点,你之前请求的域名是你自己的服务,现在要换成网关的域名。 + +* 第二点,`Apache ShenYu` 网关需要有一个路由前缀,这个路由前缀就是你接入项目进行配置 `contextPath`,如果熟的话,可以在 `shenyu-admin` 中的`divide`插件进行自由更改。 + * 比如你有一个 `order` 服务 它有一个接口,请求路径 `http://localhost:8080/test/save`。 + + * 现在就需要换成:`http://localhost:9195/order/test/save`。 + + * 其中 `localhost:9195` 为网关的`ip`端口,默认端口是`9195` ,`/order` 是你接入网关配置的 `contextPath`。 + + * 其他参数,请求方式不变。 + +然后你就可以进行访问了,如此的方便与简单。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/proxy/motan-proxy.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/proxy/motan-proxy.md new file mode 100644 index 00000000000..b7545bc990a --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/proxy/motan-proxy.md @@ -0,0 +1,108 @@ +--- +title: Motan服务接入 +description: Motan服务接入 +--- + +此篇文介绍如何将 `Motan` 服务接入到 `Apache ShenYu` 网关,`Apache ShenYu` 网关使用 `motan` 插件来接入`Motan`服务。 + +接入前,请正确启动 `shenyu-admin`,并开启`motan`插件,在网关端和`motan`服务端引入相关依赖。可以参考前面的 [Motan快速开始](../quick-start/quick-start-motan) 。 + + +应用客户端接入的相关配置请参考:[客户端接入配置](../property-config/register-center-access.md)。 + +数据同步的相关配置请参考:[数据同步配置](../property-config/use-data-sync.md)。 + +## 在网关中引入 motan 插件 + + +引入网关对`Motan`的代理插件,在网关的 `pom.xml` 文件中增加如下依赖: + +```xml + + + org.apache.shenyu + shenyu-spring-boot-starter-plugin-motan + ${project.version} + + + com.weibo + motan-core + 1.1.9 + + + com.weibo + motan-registry-zookeeper + 1.1.9 + + + com.weibo + motan-transport-netty4 + 1.1.9 + + + com.weibo + motan-springsupport + 1.1.9 + +``` + +* 重启你的网关服务。 + +## Motan服务接入网关 + +可以参考: [shenyu-examples-motan](https://github.com/apache/shenyu/tree/master/shenyu-examples/shenyu-examples-motan) + +1. 在由`Motan`构建的微服务中,引入如下依赖: + +```xml + + org.apache.shenyu + shenyu-spring-boot-starter-client-motan + ${shenyu.version} + +``` + +2. 在 `application.yaml` 配置文件增加如下配置: + +```yaml +shenyu: + register: + registerType: http #zookeeper #etcd #nacos #consul + serverLists: http://localhost:9095 #localhost:2181 #http://localhost:2379 #localhost:8848 + props: + username: admin + password: 123456 + client: + motan: + props: + contextPath: /motan + ipAndPort: motan + appName: motan + port: 8081 + package-path: org.apache.shenyu.examples.motan.service + basicServiceConfig: + exportPort: 8002 +motan: + registry: + protocol: zookeeper + address: 127.0.0.1:2181 +``` + +3. 在`Motan`服务接口实现类的方法上加上注解`@ShenyuMotanClient`,启动你的服务提供者,成功注册后,在后台管理系统进入`插件列表 -> rpc proxy -> motan`,会看到自动注册的选择器和规则信息。 + +示例: + +```java +@MotanService(export = "demoMotan:8002") +public class MotanDemoServiceImpl implements MotanDemoService { + @Override + @ShenyuMotanClient(path = "/hello") + public String hello(String name) { + return "hello " + name; + } +} +``` + +## 用户请求 + +可以通过 `http` 的方式来请求你的`motan`服务。`Apache ShenYu`网关需要有一个路由前缀,这个路由前缀就是接入网关配置的 `contextPath`。比如: `http://localhost:9195/motan/hello` 。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/proxy/sofa-rpc-proxy.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/proxy/sofa-rpc-proxy.md new file mode 100644 index 00000000000..95f02bcc515 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/proxy/sofa-rpc-proxy.md @@ -0,0 +1,194 @@ +--- +title: Sofa服务接入 +keywords: ["Sofa"] +description: sofa 接入 Apache ShenYu 网关 +--- + +此篇文章是介绍 `sofa` 服务接入到 `Apache ShenYu` 网关,`Apache ShenYu` 网关使用 `sofa` 插件来接入`sofa`服务。 + +接入前,请正确启动 `shenyu-admin`,并开启`sofa`插件,在网关端和`sofa`服务端引入相关依赖。可以参考前面的 [Sofa快速开始](../quick-start/quick-start-sofa)。 + +关于插件使用可请参考:[Sofa插件](../../plugin-center/proxy/sofa-plugin.md) + +应用客户端接入的相关配置请参考:[客户端接入配置](../property-config/register-center-access.md)。 + +数据同步的相关配置请参考:[数据同步配置](../property-config/use-data-sync.md)。 + +## 在网关中引入 sofa 插件 + +> 当前版本,默认已经引入此依赖 + +1. 在网关的 `pom.xml` 文件中增加如下依赖: + + ```xml + + com.alipay.sofa + sofa-rpc-all + 5.7.6 + + + net.jcip + jcip-annotations + + + + + org.apache.curator + curator-client + 4.0.1 + + + org.apache.curator + curator-framework + 4.0.1 + + + org.apache.curator + curator-recipes + 4.0.1 + + + org.apache.shenyu + shenyu-spring-boot-starter-plugin-sofa + ${project.version} + + ``` + +2. 重启网关服务。 + +## sofa服务接入网关 + +可以参考示例:[shenyu-examples-sofa](https://github.com/apache/shenyu/tree/master/shenyu-examples/shenyu-examples-sofa) + +1. `springboot`构建,引入以下依赖: + + ```xml + + com.alipay.sofa + rpc-sofa-boot-starter + ${rpc-sofa-boot-starter.version} + + + org.apache.shenyu + shenyu-spring-boot-starter-client-sofa + ${shenyu.version} + + ``` + +2. 在 application.yml 中配置 + +```yaml +com: + alipay: + sofa: + rpc: + registry-address: zookeeper://127.0.0.1:2181 # consul # nacos + bolt-port: 8888 +shenyu: + register: + registerType: http #zookeeper #etcd #nacos #consul + serverLists: http://localhost:9095 #localhost:2181 #http://localhost:2379 #localhost:8848 + props: + username: admin + password: 123456 + client: + sofa: + props: + contextPath: /sofa + ipAndPort: sofa + appName: sofa + port: 8888 +``` + +3. 在 resources 目录下xml 文件中配置 sofa 服务暴露的服务接口 + +```xml + + + + + + + + + + +``` + +4. 在接口上增加`@ShenyuSofaClient`注解 + +```java +@ShenyuSofaClient("/demo") +@Service +public class SofaClientMultiParamServiceImpl implements SofaClientMultiParamService { + + @Override + @ShenyuSofaClient("/findByIdsAndName") + public SofaSimpleTypeBean findByIdsAndName(final List ids, final String name) { + return new SofaSimpleTypeBean(ids.toString(), "hello world shenyu sofa param findByIdsAndName :" + name); + } +} +``` + +5. 启动`sofa`服务,成功注册后 +- 进入后台管理系统的 `插件列表 -> Proxy -> Sofa`,会看到自动注册的选择器、规则信息。 +- 进入后台管理系统的 `基础配置-> 元数据管理`,搜索appName(通过)可以看到元数据,每一个`sofa`接口方法,都会对应一条元数据。 + + + +## sofa用户请求及参数说明 + +- 可以通过 `http` 的方式来请求网关,从而请求到你的 `sofa` 服务。 + - `Apache ShenYu` 网关需要有一个路由前缀,这个路由前缀就是接入网关配置的 `contextPath`。 + +> 比如你有一个 `order` 服务 它有一个接口,它的注册路径 `/order/test/save` +> +> 现在就是通过 `post` 方式请求网关:http://localhost:9195/order/test/save +> +> 其中 `localhost:9195` 为网关的 `ip` 端口,默认端口是 `9195` ,`/order` 是你`sofa`接入网关配置的 `contextPath` + + +* 参数传递: + + * 通过 `http`协议, `post` 方式访问网关,通过在`http body`中传入`json`类型参数。 + * 更多参数类型传递,可以参考 [shenyu-examples-sofa](https://github.com/apache/shenyu/tree/master/shenyu-examples/shenyu-examples-sofa) 中的接口定义,以及参数传递方式。 + +* 单个`java bean`参数类型 (默认) +* 自定义实现多参数支持: + * 在你搭建的网关项目中,新增一个类 `MySofaParamResolveService`,实现 `org.apache.shenyu.plugin.api.sofa.SofaParamResolveService`接口。 + + ```java + public interface SofaParamResolveService { + + /** + * Build parameter pair. + * this is Resolve http body to get sofa param. + * + * @param body the body + * @param parameterTypes the parameter types + * @return the pair + */ + Pair buildParameter(String body, String parameterTypes); + } + ``` + +* `body`为`http`中`body`传的`json`字符串。 + +* `parameterTypes`: 匹配到的方法参数类型列表,如果有多个,则使用`,`分割。 + +* `Pair`中,`left`为参数类型,`right`为参数值,这是`sofa`泛化调用的标准。 + +* 把你的类注册成`Spring`的`bean`,覆盖默认的实现。 + + ```java + @Bean + public SofaParamResolveService mySofaParamResolveService() { + return new MySofaParamResolveService(); + } + ``` + diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/proxy/spring-cloud-proxy.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/proxy/spring-cloud-proxy.md new file mode 100644 index 00000000000..5d988029e39 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/proxy/spring-cloud-proxy.md @@ -0,0 +1,305 @@ +--- +title: Spring Cloud服务接入 +keywords: ["Spring Cloud"] +description: SpringCloud接入ShenYu网关 +--- + +此篇文章是介绍 `springCloud` 服务接入到 `Apache ShenYu` 网关,`Apache ShenYu` 网关使用 `springCloud` 插件来接入`Spring Cloud`服务。 + +接入前,请正确启动 `shenyu-admin`,并开启`springCloud`插件,在网关端和`springCloud`服务端引入相关依赖。可以参考前面的 [Spring Cloud快速开始](../quick-start/quick-start-springcloud)。 + +应用客户端接入的相关配置请参考:[客户端接入配置](../property-config/register-center-access.md)。 + +数据同步的相关配置请参考:[数据同步配置](../property-config/use-data-sync.md)。 + +## 在网关中引入 springCloud 插件 + +* 在网关的 `pom.xml` 文件中引入如下依赖。 + +```xml + + + org.apache.shenyu + shenyu-spring-boot-starter-plugin-springcloud + ${project.version} + + + + org.apache.shenyu + shenyu-spring-boot-starter-plugin-httpclient + ${project.version} + + + + + org.springframework.cloud + spring-cloud-commons + 2.2.0.RELEASE + +``` + +* 如果你使用 `eureka` 作为 `springCloud`的注册中心 + + * 在网关的`pom.xml`文件中,新增如下依赖: + + ```xml + + org.springframework.cloud + spring-cloud-starter-netflix-eureka-client + 2.2.0.RELEASE + + ``` + +* 在网关的`yml`文件中,新增如下配置: + + ```yaml + eureka: + client: + serviceUrl: + defaultZone: http://localhost:8761/eureka/ # 你的eureka地址 + instance: + prefer-ip-address: true + ``` + +* 如果你使用 `nacos` 作为 `springCloud`的注册中心 + + * 在网关的`pom.xml`文件中,新增如下依赖: + + ```xml + + com.alibaba.cloud + spring-cloud-starter-alibaba-nacos-discovery + 2.1.0.RELEASE + + ``` + +* 在网关的`yml`文件中 新增如下配置: + + ```yaml + spring: + cloud: + nacos: + discovery: + server-addr: 127.0.0.1:8848 # 你的nacos地址 + ``` + +特别提示:请确保spring Cloud注册中心服务发现配置开启 + +* 配置方式 + +```yml +spring: + cloud: + discovery: + enabled: true +``` + +* 代码方式 + +```java +@SpringBootApplication +@EnableDiscoveryClient +public class ShenyuBootstrapApplication { + + /** + * Main Entrance. + * + * @param args startup arguments + */ + public static void main(final String[] args) { + SpringApplication.run(ShenyuBootstrapApplication.class, args); + } +} +``` + +* 重启你的网关服务。 + +## SpringCloud服务接入网关 + +可以参考:[shenyu-examples-springcloud](https://github.com/apache/shenyu/tree/master/shenyu-examples/shenyu-examples-springcloud) + + +* 在由`SpringCloud`构建的微服务中,引入如下依赖: + +```xml + + org.apache.shenyu + shenyu-spring-boot-starter-client-springcloud + ${shenyu.version} + +``` + + +* 在 `controller`接口上加上 `@ShenyuSpringCloudClient` 注解。 注解可以加到类或方法上面,`path`属性为前缀,如果含有 `/**` 代表你的整个接口需要被网关代理。 + +* 示例一: + 代表 `/test/payment`, `/test/findByUserId` 都会被网关代理。 + +```java + @RestController + @RequestMapping("/test") + @ShenyuSpringCloudClient(path = "/test/**") + public class HttpTestController { + + @PostMapping("/payment") + public UserDTO post(@RequestBody final UserDTO userDTO) { + return userDTO; + } + + @GetMapping("/findByUserId") + public UserDTO findByUserId(@RequestParam("userId") final String userId) { + UserDTO userDTO = new UserDTO(); + userDTO.setUserId(userId); + userDTO.setUserName("hello world"); + return userDTO; + } + } +``` + + +* 示例二: + 代表 `/order/save`,会被网关代理,而`/order/findById` 则不会。 + +```java + @RestController + @RequestMapping("/order") + @ShenyuSpringCloudClient(path = "/order") + public class OrderController { + + @PostMapping("/save") + @ShenyuSpringMvcClient(path = "/save") + public OrderDTO save(@RequestBody final OrderDTO orderDTO) { + orderDTO.setName("hello world save order"); + return orderDTO; + } + + @GetMapping("/findById") + public OrderDTO findById(@RequestParam("id") final String id) { + OrderDTO orderDTO = new OrderDTO(); + orderDTO.setId(id); + orderDTO.setName("hello world findById"); + return orderDTO; + } + } +``` + + +* 示例三: + `isFull`:`true` 代表整个服务都会被网关代理。 + +```yaml +shenyu: + register: + registerType: http #zookeeper #etcd #nacos #consul + serverLists: http://localhost:9095 #localhost:2181 #http://localhost:2379 #localhost:8848 + props: + username: admin + password: 123456 + client: + springCloud: + props: + contextPath: /springcloud + isFull: true +# port: 8884 +# registerType : 服务注册类型,请参考应用客户端接入文档 +# serverList: 服务列表,请参考应用客户端接入文档 +# contextPath: 为你的项目在shenyu网关的路由前缀。 比如/order ,/product 等等,网关会根据你的这个前缀来进行路由。 +# appName:你的应用名称,不配置的话,会默认取application 中的名称 +# isFull: 设置true 代表代理你的整个服务,false表示代理你其中某几个controller +``` + + ```java + @RestController + @RequestMapping("/order") + public class OrderController { + + @PostMapping("/save") + @ShenyuSpringMvcClient(path = "/save") + public OrderDTO save(@RequestBody final OrderDTO orderDTO) { + orderDTO.setName("hello world save order"); + return orderDTO; + } + + @GetMapping("/findById") + public OrderDTO findById(@RequestParam("id") final String id) { + OrderDTO orderDTO = new OrderDTO(); + orderDTO.setId(id); + orderDTO.setName("hello world findById"); + return orderDTO; + } + } +``` + + +* 示例四:这是一种简化的使用方式,只需要一个简单的注解,使用元数据注册到网关。 +特别说明:目前只支持`@RequestMapping、@GetMapping、@PostMapping、@DeleteMapping、@PutMapping`注解,并且只对`@XXXMapping`中的第一个路径有效。 + +```java + @RestController + @RequestMapping("new/feature") + public class NewFeatureController { + + /** + * no support gateway access api. + * + * @return result + */ + @RequestMapping("/gateway/not") + public EntityResult noSupportGateway() { + return new EntityResult(200, "no support gateway access"); + } + + /** + * Do not use shenyu annotation path. used request mapping path. + * + * @return result + */ + @RequestMapping("/requst/mapping/path") + @ShenyuSpringCloudClient + public EntityResult requestMappingUrl() { + return new EntityResult(200, "Do not use shenyu annotation path. used request mapping path"); + } + + /** + * Do not use shenyu annotation path. used post mapping path. + * + * @return result + */ + @PostMapping("/post/mapping/path") + @ShenyuSpringCloudClient + public EntityResult postMappingUrl() { + return new EntityResult(200, "Do not use shenyu annotation path. used post mapping path"); + } + + /** + * Do not use shenyu annotation path. used post mapping path. + * + * @return result + */ + @GetMapping("/get/mapping/path") + @ShenyuSpringCloudClient + public EntityResult getMappingUrl() { + return new EntityResult(200, "Do not use shenyu annotation path. used get mapping path"); + } + } + +``` + +* 启动你的服务成功注册后,进入后台管理系统的`插件列表 -> rpc proxy -> springCloud`,会看到自动注册的选择器和规则信息。 + + +## 用户请求 + +和之前的访问方式没有大的改变,需要注意的是: + +* 你之前请求的域名是你自己的服务,现在要换成网关的域名。 + +* 网关需要有一个路由前缀,这个路由前缀就是你接入项目进行配置 `contextPath`,可以在 `shenyu-admin` 中的 `springCloud`插件进行更改。 + +> 比如你有一个 `order` 服务 它有一个接口,请求路径 `http://localhost:8080/test/save` +> +> 现在就需要换成:`http://localhost:9195/order/test/save` +> +> 其中 `localhost:9195` 为网关的 `ip` 端口,默认端口是 `9195` ,`/order` 是你接入网关配置的 `contextPath` +> +> 其他参数,请求方式不变。然后你就可以进行访问了,如此的方便与简单。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/proxy/tars-proxy.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/proxy/tars-proxy.md new file mode 100644 index 00000000000..6a8a1bcd777 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/proxy/tars-proxy.md @@ -0,0 +1,96 @@ +--- +title: Tars服务接入 +description: Tars服务接入 +--- + +此篇文介绍如何将 `Tars` 服务接入到 `Apache ShenYu` 网关,`Apache ShenYu` 网关使用 `tars` 插件来接入`Tars`服务。 + +接入前,请正确启动 `shenyu-admin`,并开启`tars`插件,在网关端和`tars`服务端引入相关依赖。可以参考前面的 [Tars快速开始](../quick-start/quick-start-tars) 。 + + +应用客户端接入的相关配置请参考:[客户端接入配置](../property-config/register-center-access.md)。 + +数据同步的相关配置请参考:[数据同步配置](../property-config/use-data-sync.md)。 + +## 在网关中引入 tars 插件 + + +引入网关对`Tars`的代理插件,在网关的 `pom.xml` 文件中增加如下依赖: + +```xml + + + org.apache.shenyu + shenyu-spring-boot-starter-plugin-tars + ${project.version} + + + + com.tencent.tars + tars-client + 1.7.2 + + +``` + +* 重启你的网关服务。 + +## Tars服务接入网关 + +可以参考: [shenyu-examples-tars](https://github.com/apache/shenyu/tree/master/shenyu-examples/shenyu-examples-tars) + +1. 在由`Tars`构建的微服务中,引入如下依赖: + +```xml + + org.apache.shenyu + shenyu-spring-boot-starter-client-tars + ${shenyu.version} + +``` + +2. 在 `application.yaml` 配置文件增加如下配置: + +```yaml +shenyu: + register: + registerType: http #zookeeper #etcd #nacos #consul + serverLists: http://localhost:9095 #localhost:2181 #http://localhost:2379 #localhost:8848 + props: + username: admin + password: 123456 + client: + tars: + props: + contextPath: /tars + appName: tars + port: 21715 + host: 192.168.41.103 +``` + +3. 在`Tars`服务接口实现类上加上 `@ShenyuTarsService` 注解,在方法上加上注解`@ShenyuTarsClient`,启动你的服务提供者,成功注册后,在后台管理系统进入`插件列表 -> rpc proxy -> tars`,会看到自动注册的选择器和规则信息。 + +示例: + +```java + @TarsServant("HelloObj") + @ShenyuTarsService(serviceName = "ShenyuExampleServer.ShenyuExampleApp.HelloObj") + public class HelloServantImpl implements HelloServant { + @Override + @ShenyuTarsClient(path = "/hello", desc = "hello") + public String hello(int no, String name) { + return String.format("hello no=%s, name=%s, time=%s", no, name, System.currentTimeMillis()); + } + + @Override + @ShenyuTarsClient(path = "/helloInt", desc = "helloInt") + public int helloInt(int no, String name) { + return 1; + } + } + +``` + +## 用户请求 + +可以通过 `http` 的方式来请求你的`tars`服务。`Apache ShenYu`网关需要有一个路由前缀,这个路由前缀就是接入网关配置的 `contextPath`。比如: `http://localhost:9195/tars/hello` 。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/proxy/websocket-proxy.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/proxy/websocket-proxy.md new file mode 100644 index 00000000000..b0a547996ab --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/proxy/websocket-proxy.md @@ -0,0 +1,87 @@ +--- +title: Websocket服务接入 +description: Websocket服务接入 +--- +此篇文介绍如何将 `Websocket` 服务接入到 `Apache ShenYu` 网关,`Apache ShenYu` 网关使用 `Websocket` 插件来接入 `Websocket`服务。 + +接入前,请正确启动 `shenyu-admin`,并开启 `Websocket`插件,在网关端和 `Websocket`服务端引入相关依赖。可以参考前面的 [Websocket快速开始](../quick-start/quick-start-websocket) 。 + +应用客户端接入的相关配置请参考:[客户端接入配置](../property-config/register-center-access.md)。 + +数据同步的相关配置请参考:[数据同步配置](../property-config/use-data-sync.md)。 + +## 在网关中引入 Websocket 插件 + +引入网关对 `Websocket`的代理插件,在网关的 `pom.xml` 文件中增加如下依赖,默认已引入该依赖: + +```xml + + + org.apache.shenyu + shenyu-spring-boot-starter-plugin-websocket + ${project.version} + +``` + +* 重启你的网关服务。 + +## Websocket服务接入网关 + +> 参考示例: [shenyu-examples-websocket](https://github.com/apache/shenyu/tree/master/shenyu-examples/shenyu-examples-websocket),包含 `annotation websocket`、`spring native websocket`、`spring reactive websocket`三种实现方式的示例 + +1. 在由 `Websocket`构建的服务中,引入如下依赖: + +```xml + + org.apache.shenyu + shenyu-spring-boot-starter-client-websocket + ${shenyu.version} + +``` + +2. 在 `application.yaml` 配置文件增加如下配置: + +```yaml +shenyu: + register: + registerType: http + serverLists: http://localhost:9095 # shenyu-admin服务端口 + props: + username: admin + password: 123456 + client: + websocket: + props: + contextPath: /ws-annotation + appName: ws-annotation + port: 8001 # 需要和服务端口保持一致 +``` + +3. 在 `Websocket`服务接口实现类上加上 `@ShenyuSpringWebSocketClient` 注解,启动你的服务,成功注册后,在 `shenyu-admin`管理系统进入 `插件列表 -> Proxy -> Websocket`,会看到自动注册的选择器和规则信息。 + +示例: + +```java +@ShenyuSpringWebSocketClient("/myWs") +@ServerEndpoint("/myWs") +public class WsServerEndpoint { + @OnOpen + public void onOpen(final Session session) { + LOG.info("connect successful"); + } + + @OnClose + public void onClose(final Session session) { + LOG.info("connect closed"); + } + + @OnMessage + public String onMsg(final String text) { + return "server send message:" + text; + } +} +``` + +## 用户请求 + +需要通过 `ws` 协议来请求你的 `Websocket`服务。`Apache ShenYu`网关会配置一个路由前缀,这个路由前缀就是接入网关配置文件中的 `contextPath`。比如: `ws://localhost:9195/ws-annotation/myWs`,之后就可以正常建立连接发送和接收消息。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/sdk-usage/_category_.json b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/sdk-usage/_category_.json new file mode 100644 index 00000000000..f5623cb13fb --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/sdk-usage/_category_.json @@ -0,0 +1,4 @@ +{ + "label": "Shenyu-Sdk 接入", + "position": 3 +} diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/sdk-usage/shenyu-sdk-consul.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/sdk-usage/shenyu-sdk-consul.md new file mode 100644 index 00000000000..5ec4e99691a --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/sdk-usage/shenyu-sdk-consul.md @@ -0,0 +1,197 @@ +--- +title: 使用Consul接入 +keywords: ["Sdk 使用", "Consul"] +description: Sdk使用 +--- + +## 背景说明 + +Shenyu提供了Shenyu-Sdk方便让服务能够快速接入shenyu网关, 客户端服务只需要依赖该sdk, 并做些简单配置, 即可类似调用本地接口一样调用网关暴露的API。 + + + +客户端接入网关的注册中心支持(nacos、eureka、etcd、zookeeper、consul),下面为`shenyu-bootstrap`及`应用客户端`使用**Zookeeper**注册中心时的相关指引。 + +## 环境准备 + +需要参考 `运维部署` , 选择一种方式启动`shenyu-admin`及`shenyu-bootstrap`. + +## shenyu-bootstrap + +### 添加Maven依赖 + +在网关的`pom.xml`文件中引入如下依赖. + +```xml + + org.apache.shenyu + shenyu-spring-boot-starter-registry + ${project.version} + +``` + +### 配置文件调整 + +在网关的`yml`配置文件中添加如下配置. + +```yaml +shenyu: + register: + enabled: true + registerType: consul + serverLists: localhost + props: + delay: 1 + wait-time: 55 + instanceId: shenyu-gateway + hostName: localhost + tags: test1,test2 + preferAgentAddress: false + enableTagOverride: false + +# registerType: 服务注册类型,填写 consul +# serverLists: consul client agent地址(sidecar模式部署(单机或者集群),也可以是consul server agent的地址(只能连接一个consul server agent节点,如果是集群,那么会存在单点故障问题)) +# delay: 对Metadata的监控每次轮询的间隔时长,单位为秒,默认1秒 +# wait-time: 对Metadata的监控单次请求的等待时间(长轮询机制),单位为秒,默认55秒 +# instanceId: consul服务必填,consul需要通过instance-id找到具体服务 +# name 服务注册到consul时所在的组名 +# hostName: 为 consul 注册类型时,填写 注册服务实例的 地址, 该注册中心注册的服务实例地址,并不会用于客户端的调用,所以该配置可以不填,port,preferAgentAddress同理 +# port: 为 consul 注册类型时,填写 注册服务实例的 端口 +# tags: 对应consul配置中的tags配置 +# preferAgentAddress:使用consul客户端侧的agent对应的address作为注册服务实例的address,会覆盖hostName的手动配置 +# enableTagOverride:对应consul配置中的enableTagOverride配置 + +# 详细参考`用户指南>属性配置>客户端接入配置`文档 +``` + +## 应用客户端 + +### 添加Maven依赖 + +在应用客户端的`pom.xml`文件中引入如下依赖. + +- Shenyu-Sdk 核心包 + +```xml + + + org.apache.shenyu + shenyu-sdk-core + 2.5.1-SNAPSHOT + + + + org.apache.shenyu + shenyu-spring-boot-starter-sdk + 2.5.1-SNAPSHOT + + +``` + +- Shenyu-Sdk http实现包 + +> http客户端实现, 目前提供实现okhttp, httpclient. 其他客户端实现可继承`AbstractShenyuSdkClient`实现。 + +```xml + + + org.apache.shenyu + shenyu-sdk-httpclient + 2.5.1-SNAPSHOT + + + + +``` + +### 配置文件调整 + +在应用客户端的`yml`配置文件中添加如下配置. + +```yaml +shenyu: + sdk: + enabled: true + register-type: consul #zookeeper #local #etcd #nacos #consul + server-lists: localhost #localhost:2181 #http://localhost:9095 #http://localhost:2379 #localhost:8848 + props: + checkTtl: 5 + token: "" + waitTime: 30 + watchDelay: 5 + tags: "" + port: 8500 + retry: + enable: true + period: 100 + maxPeriod: 1000 + maxAttempts: 5 + scheme: http +# register-type : 服务注册类型,填写 consul +# server-lists: 为consul注册类型时,填写consul地址,多个地址用英文逗号分隔 +# checkTtl: TTL, 默认5秒 +# token: "" +# waitTime: 对Metadata的监控单次请求的等待时间(长轮询机制),单位为秒,默认55秒 +# watchDelay: 对Metadata的监控每次轮询的间隔时长,单位为秒,默认1秒 +# tags: 对应consul配置中的tags配置 +# port: consul 服务端口 +# retry 失败重试相关配置 +# retry.period: 重试等待时间 +# retry.maxPeriod: 最大重试等待时间 +# retry.maxAttempts: 最大重试次数 +# scheme: 请求协议头 +``` + +## 本地接口配置 + +1. 在项目启动类上标注`@EnableShenyuClients(basePackages = "org.apache.shenyu.examples.sdk.http.api")`, 其中`basePackages`中维护的是Shenyu-Sdk对应维护网关API接口的所在包位置. + +2. 创建interface并使用`@ShenyuClient(name = "xxx", contextId = "ShenyuSdkApiName")`注解标注, 其中`name`表示网关服务名.假如你需要定义多个bean来维护网关的API, 可以使用`contextId`作为对应的bean别名. + +3. 在定义接口中添加所要映射shenyu网关中的接口方法, 其中`@xxMapping`中的`value`对应值是网关中对应请求的路径。 + +**示例** + +项目启动类 + +```java +@SpringBootApplication +@EnableShenyuClients(basePackages = "org.apache.shenyu.examples.sdk.http.api") +public class ShenyuSdkHttpExampleApplication { + + /** + * main. + * + * @param args args + */ + public static void main(final String[] args) { + SpringApplication.run(ShenyuSdkHttpExampleApplication.class, args); + } +} +``` + +网关API接口 + +```java +@ShenyuClient(name = "shenyu-gateway", contextId = "ShenyuSdkApiName") +public interface ShenyuHttpClientApi { + + /** + * findById. + * test Get. + * + * @param id id + * @return SdkTestDto + */ + @GetMapping("/http/shenyu/client/findById") + SdkTestDto findById(@RequestParam("id") String id); +} +``` + +更多可参考示例工程 [shenyu-examples-sdk](https://github.com/apache/shenyu/tree/master/shenyu-examples/shenyu-examples-sdk) diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/sdk-usage/shenyu-sdk-etcd.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/sdk-usage/shenyu-sdk-etcd.md new file mode 100644 index 00000000000..1524029978a --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/sdk-usage/shenyu-sdk-etcd.md @@ -0,0 +1,183 @@ +--- +title: 使用Etcd接入 +keywords: ["Sdk 使用", "Etcd"] +description: Sdk使用 +--- + +## 背景说明 + +Shenyu提供了Shenyu-Sdk方便让服务能够快速接入shenyu网关, 客户端服务只需要依赖该sdk, 并做些简单配置, 即可类似调用本地接口一样调用网关暴露的API。 + + + +客户端接入网关的注册中心支持(nacos、eureka、etcd、zookeeper、consul),下面为`shenyu-bootstrap`及`应用客户端`使用**Zookeeper**注册中心时的相关指引。 + +## 环境准备 + +需要参考 `运维部署` , 选择一种方式启动`shenyu-admin`及`shenyu-bootstrap`. + +## shenyu-bootstrap + +### 添加Maven依赖 + +在网关的`pom.xml`文件中引入如下依赖. + +```xml + + org.apache.shenyu + shenyu-spring-boot-starter-registry + ${project.version} + +``` + +### 配置文件调整 + +在网关的`yml`配置文件中添加如下配置. + +```yaml +shenyu: + register: + enabled: true + registerType: etcd + serverLists: http://localhost:2379 + props: + contextPath: /http + appName: http + port: 8189 + isFull: false +# registerType : 服务注册类型,填写 etcd +# serverList: 为etcd注册类型时,填写etcd地址,多个地址用英文逗号分隔 +# port: 你本项目的启动端口,目前springmvc/tars/grpc需要进行填写 +# contextPath: 为你的这个mvc项目在shenyu网关的路由前缀, 比如/order ,/product 等等,网关会根据你的这个前缀来进行路由. +# appName:你的应用名称,不配置的话,会默认取 `spring.application.name` 的值 +# isFull: 设置true 代表代理你的整个服务,false表示代理你其中某几个controller;目前适用于springmvc/springcloud + +# 详细参考`用户指南>属性配置>客户端接入配置`文档 +``` + +## 应用客户端 + +### 添加Maven依赖 + +在应用客户端的`pom.xml`文件中引入如下依赖. + +- Shenyu-Sdk 核心包 + +```xml + + + org.apache.shenyu + shenyu-sdk-core + 2.5.1-SNAPSHOT + + + + org.apache.shenyu + shenyu-spring-boot-starter-sdk + 2.5.1-SNAPSHOT + + +``` + +- Shenyu-Sdk http实现包 + +> http客户端实现, 目前提供实现okhttp, httpclient. 其他客户端实现可继承`AbstractShenyuSdkClient`实现。 + +```xml + + + org.apache.shenyu + shenyu-sdk-httpclient + 2.5.1-SNAPSHOT + + + + +``` + +### 配置文件调整 + +在应用客户端的`yml`配置文件中添加如下配置. + +```yaml +shenyu: + sdk: + enabled: true + register-type: etcd + server-lists: http://localhost:2379 + props: + etcdTimeout: 3000 + etcdTTL: 5 + retry: + enable: true + period: 100 + maxPeriod: 1000 + maxAttempts: 5 + algorithm: roundRobin + scheme: http + +# register-type : 服务注册类型,填写 etcd +# server-lists: 为etcd注册类型时,填写etcd地址,多个地址用英文逗号分隔 +# etcdTimeout: 请求超时时间, 单位毫秒, 默认3000 +# etcdTTL: 租约TTL, 默认5秒 +# retry 失败重试相关配置 +# retry.period: 重试等待时间 +# retry.maxPeriod: 最大重试等待时间 +# retry.maxAttempts: 最大重试次数 +# algorithm: 负载均衡 +# scheme: 请求协议头 +``` + +## 本地接口配置 + +1. 在项目启动类上标注`@EnableShenyuClients(basePackages = "org.apache.shenyu.examples.sdk.http.api")`, 其中`basePackages`中维护的是Shenyu-Sdk对应维护网关API接口的所在包位置. + +2. 创建interface并使用`@ShenyuClient(name = "xxx", contextId = "ShenyuSdkApiName")`注解标注, 其中`name`表示网关服务名.假如你需要定义多个bean来维护网关的API, 可以使用`contextId`作为对应的bean别名. + +3. 在定义接口中添加所要映射shenyu网关中的接口方法, 其中`@xxMapping`中的`value`对应值是网关中对应请求的路径。 + +**示例** + +项目启动类 + +```java +@SpringBootApplication +@EnableShenyuClients(basePackages = "org.apache.shenyu.examples.sdk.http.api") +public class ShenyuSdkHttpExampleApplication { + + /** + * main. + * + * @param args args + */ + public static void main(final String[] args) { + SpringApplication.run(ShenyuSdkHttpExampleApplication.class, args); + } +} +``` + +网关API接口 + +```java +@ShenyuClient(name = "shenyu-gateway", contextId = "ShenyuSdkApiName") +public interface ShenyuHttpClientApi { + + /** + * findById. + * test Get. + * + * @param id id + * @return SdkTestDto + */ + @GetMapping("/http/shenyu/client/findById") + SdkTestDto findById(@RequestParam("id") String id); +} +``` + +更多可参考示例工程 [shenyu-examples-sdk](https://github.com/apache/shenyu/tree/master/shenyu-examples/shenyu-examples-sdk) diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/sdk-usage/shenyu-sdk-eureka.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/sdk-usage/shenyu-sdk-eureka.md new file mode 100644 index 00000000000..2ec9be6a699 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/sdk-usage/shenyu-sdk-eureka.md @@ -0,0 +1,180 @@ +--- +title: 使用Eureka接入 +keywords: ["Sdk 使用", "Eureka"] +description: Sdk使用 +--- + +## 背景说明 + +Shenyu提供了Shenyu-Sdk方便让服务能够快速接入shenyu网关, 客户端服务只需要依赖该sdk, 并做些简单配置, 即可类似调用本地接口一样调用网关暴露的API。 + + + +客户端接入网关时可使用注册中心做服务发现,支持的注册中心有`nacos、eureka、etcd、zookeeper、consul`, 下面为`shenyu-bootstrap`及`应用客户端`使用**eureka**为注册中心时的相关指引。 + +## 环境准备 + +需要参考 `运维部署` , 选择一种方式启动`shenyu-admin`及`shenyu-bootstrap`. + +## shenyu-bootstrap + +### 添加Maven依赖 + +在网关的`pom.xml`文件中引入如下依赖. + +```xml + + org.springframework.cloud + spring-cloud-starter-netflix-eureka-client + ${eureka-client.version} + + + org.springframework.cloud + spring-cloud-starter-loadbalancer + + + +``` + +### 配置文件调整 + +在网关的`yml`配置文件中添加如下配置. + +```yaml +spring: + cloud: + discovery: + enabled: true # 启用服务发现 + +eureka: + client: + enabled: true + serviceUrl: + defaultZone: http://localhost:8761/eureka/ # 此处填你的eureka注册中心地址 + instance: + prefer-ip-address: true +``` + +## 应用客户端 + +### 添加Maven依赖 + +在应用客户端的`pom.xml`文件中引入如下依赖. + +- Shenyu-Sdk 核心包 + +```xml + + + org.apache.shenyu + shenyu-sdk-core + 2.5.1-SNAPSHOT + + + + org.apache.shenyu + shenyu-spring-boot-starter-sdk + 2.5.1-SNAPSHOT + + +``` + +- Shenyu-Sdk http实现包 + +> http客户端实现, 目前提供实现okhttp, httpclient. 其他客户端实现可继承`AbstractShenyuSdkClient`实现。 + +```xml + + + org.apache.shenyu + shenyu-sdk-httpclient + 2.5.1-SNAPSHOT + + + + +``` + +### 配置文件调整 + +在应用客户端的`yml`配置文件中添加如下配置. + +```yaml +shenyu: + sdk: + enabled: true + register-type: eureka + server-lists: http://localhost:8761/eureka/ + props: + retry: + enable: true + period: 100 + maxPeriod: 1000 + maxAttempts: 5 + algorithm: roundRobin + scheme: http + +# registerType : 服务注册类型,填写 eureka +# serverList: 为eureka注册类型时,配置成你的eureka注册中心地址,集群环境请使用(,)分隔 +# retry 失败重试相关配置 +# retry.period: 重试等待时间 +# retry.maxPeriod: 最大重试等待时间 +# retry.maxAttempts: 最大重试次数 +# algorithm: 负载均衡 +# scheme: 请求协议头 +``` + + +## 本地接口配置 + +1. 在项目启动类上标注`@EnableShenyuClients(basePackages = "org.apache.shenyu.examples.sdk.http.api")`, 其中`basePackages`中维护的是Shenyu-Sdk对应维护网关API接口的所在包位置. + +2. 创建interface并使用`@ShenyuClient(name = "xxx", contextId = "ShenyuSdkApiName")`注解标注, 其中`name`表示网关服务名.假如你需要定义多个bean来维护网关的API, 可以使用`contextId`作为对应的bean别名. + +3. 在定义接口中添加所要映射shenyu网关中的接口方法, 其中`@xxMapping`中的`value`对应值是网关中对应请求的路径。 + +**示例** + +项目启动类 + +```java +@SpringBootApplication +@EnableShenyuClients(basePackages = "org.apache.shenyu.examples.sdk.http.api") +public class ShenyuSdkHttpExampleApplication { + + /** + * main. + * + * @param args args + */ + public static void main(final String[] args) { + SpringApplication.run(ShenyuSdkHttpExampleApplication.class, args); + } +} +``` + +网关API接口 + +```java +@ShenyuClient(name = "shenyu-bootstrap", contextId = "ShenyuSdkApiName") +public interface ShenyuHttpClientApi { + + /** + * findById. + * test Get. + * + * @param id id + * @return SdkTestDto + */ + @GetMapping("/http/shenyu/client/findById") + SdkTestDto findById(@RequestParam("id") String id); +} +``` + +更多可参考示例工程 [shenyu-examples-sdk](https://github.com/apache/shenyu/tree/master/shenyu-examples/shenyu-examples-sdk) diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/sdk-usage/shenyu-sdk-feign.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/sdk-usage/shenyu-sdk-feign.md new file mode 100644 index 00000000000..6c30599bbc5 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/sdk-usage/shenyu-sdk-feign.md @@ -0,0 +1,130 @@ +--- +title: 使用 Shenyu-SDK-Feign +keywords: ["Shenyu-Sdk 使用", "feign"] +description: Shenyu-Sdk-Feign 使用 +--- + +## Shenyu sdk-feign + +> 集成`openFeign`来实现声明式SDK调用网关API. +> 与`shenyu-sdk`一样, `shenyu-sdk-feign`是另外一个选项; +> 详情请看 : +> * 请参照: [shenyu-sdk-consul](../../user-guide/sdk-usage/shenyu-sdk-consul) +> * 请参照: [shenyu-sdk-etcd](../../user-guide/sdk-usage/shenyu-sdk-etcd) +> * 请参照: [shenyu-sdk-eureka](../../user-guide/sdk-usage/shenyu-sdk-eureka) +> * 请参照: [shenyu-sdk-nacos](../../user-guide/sdk-usage/shenyu-sdk-nacos) +> * 请参照: [shenyu-sdk-zookeeper](../../user-guide/sdk-usage/shenyu-sdk-zookeeper) + +### 添加Maven依赖 + +在客户端应用的`pom.xml`文件中引入如下依赖(与`FeignClient`兼容). + +```xml + + + org.springframework.cloud + spring-cloud-starter-openfeign + ${spring-cloud.version} + + + + org.apache.shenyu + shenyu-spring-boot-starter-sdk-feign + 2.6.1-SNAPSHOT + + +``` + + +### 配置文件 + +在客户端应用的`yml`配置文件中添加以下配置. + +```yaml +shenyu: + sdk: + enabled: true + register-type: consul + server-lists: localhost + props: + algorithm: roundRobin + scheme: http + +# 如果不使用`openFeign`和`springCloud-loadBalance`,则必须启用外部客户端选项。. +feign: + client: + httpclient: + enabled: true + +# registerType : 服务注册类型,填写 etcd +# serverList: 为etcd注册类型时,填写etcd地址,多个地址用英文逗号分隔 + +# algorithm: 负载均衡算法. +# scheme: 请求协议. + +``` + +## 本地接口配置 + +1. 在项目启动类上标注`@EnableShenyuClients(basePackages = "org.apache.shenyu.examples.sdk.feign.api")`, 其中`basePackages`中维护的是Shenyu-Sdk对应维护网关API接口的所在包位置. + +2. 创建interface并使用`@ShenyuClient(name = "xxx", contextId = "ShenyuSdkApiName")`注解标注, 其中`name`表示网关服务名.假如你需要定义多个bean来维护网关的API, 可以使用`contextId`作为对应的bean别名. + +3. 在定义接口中添加所要映射shenyu网关中的接口方法, 其中`@xxMapping`中的`value`对应值是网关中对应请求的路径。 + +**示例** + +项目启动类 + +```java +import org.apache.shenyu.sdk.feign.EnableShenyuClients; + +@SpringBootApplication +@EnableShenyuClients(basePackages = "org.apache.shenyu.examples.sdk.feign.api") +public class ShenyuSdkHttpExampleApplication { + + /** + * main. + * + * @param args args + */ + public static void main(final String[] args) { + SpringApplication.run(ShenyuSdkHttpExampleApplication.class, args); + } +} +``` + +网关API接口 + +```java +import org.apache.shenyu.sdk.feign.ShenyuClient; + +@ShenyuClient(name = "shenyu-gateway", contextId = "ShenyuSdkApiName", path = "/feign/shenyu/client") +public interface ShenyuFeignClientApi { + + /** + * findById. + * test Get. + * + * @param id id + * @return SdkTestDto + */ + @GetMapping("/findById") + SdkTestDto findById(@RequestParam("id") String id); + + /** + * annoTest. + * + * @param cookie cookie + * @param header header + * @param id id + * @param requestDto requestDto + * @return sdkTestDto + */ + @PostMapping("/{id}/anno") + SdkTestDto annoTest(@CookieValue("cookie") String cookie, @RequestHeader("header") String header, @PathVariable("id") String id, @RequestBody SdkTestDto requestDto); + +} +``` + +更多可参考示例工程 [shenyu-examples-sdk-feign](https://github.com/apache/shenyu/tree/master/shenyu-examples/shenyu-examples-sdk/shenyu-examples-sdk-feign) diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/sdk-usage/shenyu-sdk-nacos.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/sdk-usage/shenyu-sdk-nacos.md new file mode 100644 index 00000000000..0196717a074 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/sdk-usage/shenyu-sdk-nacos.md @@ -0,0 +1,181 @@ +--- +title: 使用Nacos接入 +keywords: ["Sdk 使用", "Nacos"] +description: Sdk使用 +--- + +## 背景说明 + +Shenyu提供了Shenyu-Sdk方便让服务能够快速接入shenyu网关, 客户端服务只需要依赖该sdk, 并做些简单配置, 即可类似调用本地接口一样调用网关暴露的API。 + + + +客户端接入网关的注册中心支持(nacos、eureka、etcd、zookeeper、consul),下面为`shenyu-bootstrap`及`应用客户端`使用**Nacos**注册中心时的相关指引。 + +## 环境准备 + +需要参考 `运维部署` , 选择一种方式启动`shenyu-admin`及`shenyu-bootstrap`. + +## shenyu-bootstrap + +### 添加Maven依赖 + +在网关的`pom.xml`文件中引入如下依赖. + +```xml + + org.apache.shenyu + shenyu-spring-boot-starter-registry + ${project.version} + +``` + +### 配置文件调整 + +在网关的`yml`配置文件中添加如下配置. + +```yaml +spring: + application: + name: shenyu-bootstrap + cloud: + discovery: + enabled: true + nacos: + discovery: + server-addr: 127.0.0.1:8848 # 此处填你的nacos服务地址 + enabled: true + namespace: ShenyuRegisterCenter # nacos命名空间 + # 如开启nacos鉴权需配置如下参数 + username: nacos # 鉴权用户名 + password: nacos # 鉴权密码 +``` + +## 应用客户端 + +### 添加Maven依赖 + +在应用客户端的`pom.xml`文件中引入如下依赖. + +- Shenyu-Sdk 核心包 + +```xml + + + org.apache.shenyu + shenyu-sdk-core + 2.5.1-SNAPSHOT + + + + org.apache.shenyu + shenyu-spring-boot-starter-sdk + 2.5.1-SNAPSHOT + + +``` + +- Shenyu-Sdk http实现包 + +> http客户端实现, 目前提供实现okhttp, httpclient. 其他客户端实现可继承`AbstractShenyuSdkClient`实现。 + +```xml + + + org.apache.shenyu + shenyu-sdk-httpclient + 2.5.1-SNAPSHOT + + + + +``` + +### 配置文件调整 + +在应用客户端的`yml`配置文件中添加如下配置. + +```yaml +shenyu: + sdk: + enabled: true + register-type: nacos + server-lists: localhost:2181 + props: + nacosNameSpace: ShenyuRegisterCenter + username: nacos + password: nacos + retry: + enable: true + period: 100 + maxPeriod: 1000 + maxAttempts: 5 + algorithm: roundRobin + scheme: http + +# registerType : 服务注册类型,填写 nacos +# serverList: 为nacos注册类型时,配置成你的nacos地址,集群环境请使用(,)分隔 +# nacosNameSpace: nacos命名空间ID +# username: nacos鉴权用户名 +# password: nacos鉴权密码 +# retry 失败重试相关配置 +# retry.period: 重试等待时间 +# retry.maxPeriod: 最大重试等待时间 +# retry.maxAttempts: 最大重试次数 +# algorithm: 负载均衡 +# scheme: 请求协议头 +``` + +## 本地接口配置 + +1. 在项目启动类上标注`@EnableShenyuClients(basePackages = "org.apache.shenyu.examples.sdk.http.api")`, 其中`basePackages`中维护的是Shenyu-Sdk对应维护网关API接口的所在包位置. + +2. 创建interface并使用`@ShenyuClient(name = "xxx", contextId = "ShenyuSdkApiName")`注解标注, 其中`name`表示网关服务名.假如你需要定义多个bean来维护网关的API, 可以使用`contextId`作为对应的bean别名. + +3. 在定义接口中添加所要映射shenyu网关中的接口方法, 其中`@xxMapping`中的`value`对应值是网关中对应请求的路径。 + +**示例** + +项目启动类 + +```java +@SpringBootApplication +@EnableShenyuClients(basePackages = "org.apache.shenyu.examples.sdk.http.api") +public class ShenyuSdkHttpExampleApplication { + + /** + * main. + * + * @param args args + */ + public static void main(final String[] args) { + SpringApplication.run(ShenyuSdkHttpExampleApplication.class, args); + } +} +``` + +网关API接口 + +```java +@ShenyuClient(name = "shenyu-bootstrap", contextId = "ShenyuSdkApiName") +public interface ShenyuHttpClientApi { + + /** + * findById. + * test Get. + * + * @param id id + * @return SdkTestDto + */ + @GetMapping("/http/shenyu/client/findById") + SdkTestDto findById(@RequestParam("id") String id); +} +``` + +更多可参考示例工程 [shenyu-examples-sdk](https://github.com/apache/shenyu/tree/master/shenyu-examples/shenyu-examples-sdk) diff --git a/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/sdk-usage/shenyu-sdk-zookeeper.md b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/sdk-usage/shenyu-sdk-zookeeper.md new file mode 100644 index 00000000000..90cef1da014 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/version-2.6.1/user-guide/sdk-usage/shenyu-sdk-zookeeper.md @@ -0,0 +1,180 @@ +--- +title: 使用Zookeeper接入 +keywords: ["Sdk 使用", "zookeeper"] +description: Sdk使用 +--- + +## 背景说明 + +Shenyu提供了Shenyu-Sdk方便让服务能够快速接入shenyu网关, 客户端服务只需要依赖该sdk, 并做些简单配置, 即可类似调用本地接口一样调用网关暴露的API。 + + + +客户端接入网关的注册中心支持(nacos、eureka、etcd、zookeeper、consul),下面为`shenyu-bootstrap`及`应用客户端`使用**Zookeeper**注册中心时的相关指引。 + +## 环境准备 + +需要参考 `运维部署` , 选择一种方式启动`shenyu-admin`及`shenyu-bootstrap`. + +## shenyu-bootstrap + +### 添加Maven依赖 + +在网关的`pom.xml`文件中引入如下依赖. + +```xml + + org.apache.shenyu + shenyu-spring-boot-starter-registry + ${project.version} + +``` + +### 配置文件调整 + +在网关的`yml`配置文件中添加如下配置. + +```yaml +shenyu: + register: + enabled: true + registerType: zookeeper + serverLists: localhost:2181 + props: + contextPath: /http + appName: http + port: 8189 + isFull: false +# registerType : 服务注册类型,填写 zookeeper +# serverList: 为zookeeper注册类型时,填写zookeeper地址,多个地址用英文逗号分隔 +# port: 你本项目的启动端口,目前springmvc/tars/grpc需要进行填写 +# contextPath: 为你的这个mvc项目在shenyu网关的路由前缀, 比如/order ,/product 等等,网关会根据你的这个前缀来进行路由. +# appName:你的应用名称,不配置的话,会默认取 `spring.application.name` 的值 +# isFull: 设置true 代表代理你的整个服务,false表示代理你其中某几个controller;目前适用于springmvc/springcloud + +# 详细参考`用户指南>属性配置>客户端接入配置`文档 +``` + +## 应用客户端 + +### 添加Maven依赖 + +在应用客户端的`pom.xml`文件中引入如下依赖. + +- Shenyu-Sdk 核心包 + +```xml + + + org.apache.shenyu + shenyu-sdk-core + 2.5.1-SNAPSHOT + + + + org.apache.shenyu + shenyu-spring-boot-starter-sdk + 2.5.1-SNAPSHOT + + +``` + +- Shenyu-Sdk http实现包 + +> http客户端实现, 目前提供实现okhttp, httpclient. 其他客户端实现可继承`AbstractShenyuSdkClient`实现。 + +```xml + + + org.apache.shenyu + shenyu-sdk-httpclient + 2.5.1-SNAPSHOT + + + + +``` + +### 配置文件调整 + +在应用客户端的`yml`配置文件中添加如下配置. + +```yaml +shenyu: + sdk: + enabled: true + register-type: zookeeper + server-lists: localhost:2181 + props: + retry: + enable: true + period: 100 + maxPeriod: 1000 + maxAttempts: 5 + algorithm: roundRobin + scheme: http + +# registerType : 服务注册类型,填写 zookeeper +# serverList: 为zookeeper注册类型时,填写zookeeper地址,多个地址用英文逗号分隔 +# retry 失败重试相关配置 +# retry.period: 重试等待时间 +# retry.maxPeriod: 最大重试等待时间 +# retry.maxAttempts: 最大重试次数 +# algorithm: 负载均衡 +# scheme: 请求协议头 +``` + + +## 本地接口配置 + +1. 在项目启动类上标注`@EnableShenyuClients(basePackages = "org.apache.shenyu.examples.sdk.http.api")`, 其中`basePackages`中维护的是Shenyu-Sdk对应维护网关API接口的所在包位置. + +2. 创建interface并使用`@ShenyuClient(name = "xxx", contextId = "ShenyuSdkApiName")`注解标注, 其中`name`表示网关服务名.假如你需要定义多个bean来维护网关的API, 可以使用`contextId`作为对应的bean别名. + +3. 在定义接口中添加所要映射shenyu网关中的接口方法, 其中`@xxMapping`中的`value`对应值是网关中对应请求的路径。 + +**示例** + +项目启动类 + +```java +@SpringBootApplication +@EnableShenyuClients(basePackages = "org.apache.shenyu.examples.sdk.http.api") +public class ShenyuSdkHttpExampleApplication { + + /** + * main. + * + * @param args args + */ + public static void main(final String[] args) { + SpringApplication.run(ShenyuSdkHttpExampleApplication.class, args); + } +} +``` + +网关API接口 + +```java +@ShenyuClient(name = "shenyu-gateway", contextId = "ShenyuSdkApiName") +public interface ShenyuHttpClientApi { + + /** + * findById. + * test Get. + * + * @param id id + * @return SdkTestDto + */ + @GetMapping("/http/shenyu/client/findById") + SdkTestDto findById(@RequestParam("id") String id); +} +``` + +更多可参考示例工程 [shenyu-examples-sdk](https://github.com/apache/shenyu/tree/master/shenyu-examples/shenyu-examples-sdk) diff --git a/src/components/DownloadCompoent.tsx b/src/components/DownloadCompoent.tsx index 695695c1c23..df23211970b 100644 --- a/src/components/DownloadCompoent.tsx +++ b/src/components/DownloadCompoent.tsx @@ -7,6 +7,14 @@ const data = [ { title: translate({ message: 'Source Codes' }), versions: [ + { + versionTitle: '2.6.1', + targets: { + 'zip': 'https://www.apache.org/dyn/closer.lua/shenyu/2.6.1/apache-shenyu-2.6.1-src.zip', + 'asc': 'https://downloads.apache.org/shenyu/2.6.1/apache-shenyu-2.6.1-src.zip.asc', + 'sha512': 'https://downloads.apache.org/shenyu/2.6.1/apache-shenyu-2.6.1-src.zip.sha512', + } + }, { versionTitle: '2.6.0', targets: { @@ -52,6 +60,14 @@ const data = [ { title: translate({ message: 'ShenYu-Admin Binary Distribution' }), versions: [ + { + versionTitle: '2.6.1', + targets: { + 'tar': 'https://www.apache.org/dyn/closer.lua/shenyu/2.6.1/apache-shenyu-2.6.1-admin-bin.tar.gz', + 'asc': 'https://downloads.apache.org/shenyu/2.6.1/apache-shenyu-2.6.1-admin-bin.tar.gz.asc', + 'sha512': 'https://downloads.apache.org/shenyu/2.6.1/apache-shenyu-2.6.1-admin-bin.tar.gz.sha512', + } + }, { versionTitle: '2.6.0', targets: { @@ -97,6 +113,14 @@ const data = [ { title: translate({ message: 'ShenYu-Bootstrap Binary Distribution' }), versions: [ + { + versionTitle: '2.6.1', + targets: { + 'tar': 'https://www.apache.org/dyn/closer.lua/shenyu/2.6.1/apache-shenyu-2.6.1-bootstrap-bin.tar.gz', + 'asc': 'https://downloads.apache.org/shenyu/2.6.1/apache-shenyu-2.6.1-bootstrap-bin.tar.gz.asc', + 'sha512': 'https://downloads.apache.org/shenyu/2.6.1/apache-shenyu-2.6.1-bootstrap-bin.tar.gz.sha512', + } + }, { versionTitle: '2.6.0', targets: { diff --git a/src/data/docsInfo.js b/src/data/docsInfo.js index 91f0ab84e66..4dc79c60969 100644 --- a/src/data/docsInfo.js +++ b/src/data/docsInfo.js @@ -10,7 +10,9 @@ export default [ nextVersion: "/docs/next/index", versionsList: [ { next: "/docs/next/index" }, - { "2.5.1": "/docs/index" }, + { "2.6.1": "/docs/2.6.1/index" }, + { "2.6.0": "/docs/2.6.0/index" }, + { "2.5.1": "/docs/2.5.1/index" }, { "2.5.0": "/docs/2.5.0/index" }, { "2.4.3": "/docs/2.4.3/index" }, { "2.4.2": "/docs/2.4.2/index" }, diff --git a/src/data/event.js b/src/data/event.js index 2c66ae3d435..7f52ddb02a3 100644 --- a/src/data/event.js +++ b/src/data/event.js @@ -2,6 +2,12 @@ import React from "react"; import Translate from "@docusaurus/Translate"; export default [ + { + title: Release Apache Shenyu 2.6.1, + description: + "New Features \n 1. Add dubbo annotation analysis for shenyu ingress controller \n 2. Support alert notice \n 3. Add nacos, etcd, eureka as discovery service \n ......", + src: "2.6.1-release", + }, { title: Release Apache ShenYu WASM 1.0.0, description: diff --git a/versioned_docs/version-2.6.1/benchmark-test/_category_.json b/versioned_docs/version-2.6.1/benchmark-test/_category_.json new file mode 100644 index 00000000000..566577bd399 --- /dev/null +++ b/versioned_docs/version-2.6.1/benchmark-test/_category_.json @@ -0,0 +1,4 @@ +{ + "label": "Benchmark Test", + "position": 8 +} diff --git a/versioned_docs/version-2.6.1/benchmark-test/benchmark-test.md b/versioned_docs/version-2.6.1/benchmark-test/benchmark-test.md new file mode 100644 index 00000000000..e66d1ef0973 --- /dev/null +++ b/versioned_docs/version-2.6.1/benchmark-test/benchmark-test.md @@ -0,0 +1,300 @@ +--- +sidebar_position: 8 +title: Benchmark Test Report +keywords: ["test", "benchmark-test"] +description: ShenYu Benchmark Test Report +--- + +## Hardware + +### Back-end Mock Service Server: + +- CPU: 4 cores and 8 threads Intel Cascade Lake @ 3.0GHz +- RAM: 16G + +### Gateway node server: + +- CPU: 4 cores and 8 threads Intel Cascade Lake @ 3.0GHz +- RAM: 16G + +The test tool takes up few resources and is installed on the gateway node server. + +## ShenYu Version + +- ShenYu Admin: 2.6.0 +- ShenYu Bootstrap: 2.6.0 + +## Test Tool + +wrk-4.2.0 + +## Test Case Description + +### Instruction + +- Use the Mock service to simulate an interface with an average response time of 20ms and about 2k response messages +- Each test lasts 3 minutes +- JDK version: OpenJdk-1.8.0 +- The HTTP request side is tested with `NettyClient` and `WebClient` respectively +- Log level is set to `WARN` +- Apache ShenYu Bootstrap deploy mode: standalone +- Apache ShenYu Admin deploy in `Back-end Mock Service Server` + +### JVM Configuration + +``` +-Xmx 4g +-Xms 4g +-Xmn 1g +-Xss 512k +-XX: +DisableExplicitGC +-XX: LargePageSizeInBytes=128m +``` + +### Public Configuration + +* application.yml + +```yml +matchCache: + selector: + selectorEnabled: true + initialCapacity: 10000 # initial capacity in cache + maximumSize: 10000 # max size in cache + rule: + initialCapacity: 10000 # initial capacity in cache + maximumSize: 65536 # max size in cache +trie: + enabled: true + childrenSize: 10000 + pathVariableSize: 1000 + pathRuleCacheSize: 1000 + matchMode: antPathMatch +``` + +```yml +netty: + http: + # set to false, user can custom the netty tcp server config. + webServerFactoryEnabled: true + selectCount: 1 + workerCount: 8 + accessLog: false + serverSocketChannel: + soRcvBuf: 87380 + soBackLog: 128 + soReuseAddr: false + connectTimeoutMillis: 10000 + writeBufferHighWaterMark: 65536 + writeBufferLowWaterMark: 32768 + writeSpinCount: 16 + autoRead: false + allocType: "pooled" + messageSizeEstimator: 8 + singleEventExecutorPerGroup: true + socketChannel: + soKeepAlive: false + soReuseAddr: false + soLinger: -1 + tcpNoDelay: true + soRcvBuf: 87380 + soSndBuf: 16384 + ipTos: 0 + allowHalfClosure: false + connectTimeoutMillis: 10000 + writeBufferHighWaterMark: 65536 + writeBufferLowWaterMark: 32768 + writeSpinCount: 16 + autoRead: false + allocType: "pooled" + messageSizeEstimator: 8 + singleEventExecutorPerGroup: true +``` + +```yaml + file: + enabled: false + maxSize : 10 +``` + +```yaml + cross: + enabled: false +``` + +```yaml +logging: + level: + root: warn + org.springframework.boot: warn + org.apache.ibatis: warn + org.apache.shenyu.bonuspoint: warn + org.apache.shenyu.lottery: warn + org.apache.shenyu: warn +``` + +* logback.xml + +```xml + + + + + +``` + +### WebClient Configuration + +```yml +httpclient: + strategy: webClient # netty + connectTimeout: 45000 # 45000 + responseTimeout: 3000 # 3000 + readerIdleTime: 3000 # 3000 + writerIdleTime: 3000 # 3000 + allIdleTime: 3000 # 3000 + readTimeout: 3000 # 3000 + writeTimeout: 3000 # 3000 + wiretap: false # false + keepAlive: false # false + maxInMemorySize: 1 # 1 + pool: + type: ELASTIC # ELASTIC + name: proxy # proxy + maxConnections: 16 # 16 + acquireTimeout: 45000 # 45000 + maxIdleTime: 3000 # 3000 +``` + +### Netty Client Configuration + +```yml +httpclient: + strategy: netty # netty + connectTimeout: 45000 # 45000 + responseTimeout: 3000 # 3000 + readerIdleTime: 3000 # 3000 + writerIdleTime: 3000 # 3000 + allIdleTime: 3000 # 3000 + readTimeout: 3000 # 3000 + writeTimeout: 3000 # 3000 + wiretap: false # false + keepAlive: false # false + maxInMemorySize: 1 # 1 + pool: + type: ELASTIC # ELASTIC + name: proxy # proxy + maxConnections: 16 # 16 + acquireTimeout: 45000 # 45000 + maxIdleTime: 3000 # 3000 +``` + +## Benchmark Test Results + +* Direct Access to Back-end Test Result + +| **QPS** | **50% latency (ms)** | **75% latency (ms)** | **90% latency (ms)** | **99% latency (ms)** | **平均响应时间(ms)** | **最大响应时间(ms)** | +|:---------------:|:----------------------:|:----------------------:|:----------------------:|:----------------------:|:----------------:|:----------------:| +| 28998.20 | 19.81 | 23.78 | 28.26 | 41.24 | 20.92 | 402.90 | + +* netty + +| currency | QPS | 50% latency (ms) | 75% latency (ms) | 90% latency (ms) | 99% latency (ms) | 平均响应时间(ms) | 最大响应时间(ms) | +|:-------------:|:----------:|:------------------:|:------------------:|:------------------:|:------------------:|:------------:|:------------:| +| 600 currency | 20472.95 | 19.37 | 25.36 | 32.89 | 69.92 | 22.09 | 1043.33 | +| 800 currency | 20703.55 | 23.57 | 31.32 | 40.11 | 77.28 | 26.11 | 576.47 | +| 1000 currency | 20979.91 | 29.21 | 37.86 | 47.23 | 80.91 | 31.20 | 860.55 | +| 1200 currency | 21129.88 | 32.45 | 42.40 | 52.68 | 96.10 | 35.06 | 1070 | + +* webClient + +| currency | QPS | 50% latency (ms) | 75% latency (ms) | 90% latency (ms) | 99% latency (ms) | 平均响应时间(ms) | 最大响应时间(ms) | +|:--------:|:----------:|:------------------:|:------------------:|:------------------:|:------------------:|:------------:|:------------:| +| 600 currency | 18640.47 | 15.77 | 24.77 | 38.26 | 80.31 | 20.32 | 852.06 | +| 800 currency | 18723.44 | 18.12 | 28.69 | 44.96 | 95.3 | 23.52 | 765.26 | +| 1000 currency | 18928.99 | 19.99 | 31.42 | 49.09 | 108.84 | 25.93 | 1040 | +| 1200 currency | 18965.37 | 22.10 | 34.62 | 54.48 | 122.31 | 28.66 | 1075 | + +### Direct Access to Back-end Test Result + +#### Test Result + +| **QPS** | **50% latency (ms)** | **75% latency (ms)** | **90% latency (ms)** | **99% latency (ms)** | **Avg response time (ms)** | **Max response time (ms)** | +|:---------------:|:----------------------:|:----------------------:|:----------------------:|:----------------------:|:----------------:|:----------------:| +| 28998.20 | 19.81 | 23.78 | 28.26 | 41.24 | 20.92 | 402.90 | + +#### Screenshot of Test Result + + + +### Access to Back-end Services via NettyClient Test Result + +##### Test Result + +| currency | **QPS** | **50% latency (ms)** | **75% latency (ms)** | **90% latency (ms)** | **99% latency (ms)** | **Avg response time (ms)** | **Max response time (ms)** | +|:-----------:|:--------:|:--------------------:|:--------------------:|:--------------------:|:--------------------:|:--------------:|:--------------:| +| 600 concurrency | 20472.95 | 19.37 | 25.36 | 32.89 | 69.92 | 22.09 | 1043.33 | +| 800 concurrency | 20703.55 | 23.57 | 31.32 | 40.11 | 77.28 | 26.11 | 576.47 | +| 1000 concurrency | 20979.91 | 29.21 | 37.86 | 47.23 | 80.91 | 31.20 | 860.55 | +| 1200 concurrency | 21129.88 | 32.45 | 42.40 | 52.68 | 96.10 | 35.06 | 1070 | + +#### Screenshot of Test Result + +##### 600 concurrency + + + + + +##### 800 concurrency + + + + + +##### 1000 concurrency + + + + + +##### 1200 concurrency + + + + + +### Access to Back-end Services via WebClient Test Result + +#### Test Result + +| currency | **QPS** | **50% latency (ms)** | **75% latency (ms)** | **90% latency (ms)** | **99% latency (ms)** | **Avg response time (ms)** | **Max response time (ms)** | +|:-----------:|:--------:|:--------------------:|:--------------------:|:--------------------:|:--------------------:|:--------------:|:--------------:| +| 600 concurrency | 18640.47 | 15.77 | 24.77 | 38.26 | 80.31 | 20.32 | 852.06 | +| 800 concurrency | 18723.44 | 18.12 | 28.69 | 44.96 | 95.3 | 23.52 | 765.26 | +| 1000 concurrency | 18928.99 | 19.99 | 31.42 | 49.09 | 108.84 | 25.93 | 1040 | +| 1200 concurrency | 18965.37 | 22.10 | 34.62 | 54.48 | 122.31 | 28.66 | 1075 | + +#### Screenshot of Test Result + +##### 600 concurrency + + + + + +##### 800 concurrency + + + + +##### 1000 concurrency + + + + +##### 1200 concurrency + + + + diff --git a/versioned_docs/version-2.6.1/deployment/_category_.json b/versioned_docs/version-2.6.1/deployment/_category_.json new file mode 100644 index 00000000000..534be1dfb6d --- /dev/null +++ b/versioned_docs/version-2.6.1/deployment/_category_.json @@ -0,0 +1,4 @@ +{ + "label": "Deployment", + "position": 3 +} diff --git a/versioned_docs/version-2.6.1/deployment/deployment-before.md b/versioned_docs/version-2.6.1/deployment/deployment-before.md new file mode 100644 index 00000000000..298283ebf36 --- /dev/null +++ b/versioned_docs/version-2.6.1/deployment/deployment-before.md @@ -0,0 +1,56 @@ +--- +sidebar_position: 0 +title: Deployment Prerequisites +keywords: ["Deployment Prerequisites"] +description: Deployment Prerequisites +--- + +This article describes some of the prerequisites you need to prepare before deploying the Apache ShenYu gateway. + +## Database Initialize + +Before deploying the `Shenyu-admin` project, initialize the database it uses (databases currently support: Mysql, PostgreSql, Oracle), which used the script files are stored in db directory [project root directory](https://github.com/apache/shenyu/tree/master/db), The following describes the initial steps for each database. + +### Mysql + +In [the mysql initialization scripts directory](https://github.com/apache/shenyu/tree/master/db/init/mysql) found in the initialization script `schema.sql`, Use the client connection tool to connect to your Mysql service and execute, so you get a database named `shenyu`, which can later be used as the database for the `Shenyu-admin` project. + +* sql script: https://github.com/apache/shenyu/tree/master/db/init/mysql + +* driver: + + * maven repository: https://repo1.maven.org/maven2/mysql/mysql-connector-java/8.0.30/ + * homepage: https://www.mysql.com/products/connector/ + +### PostgreSql + +In [the pg initialization scripts directory](https://github.com/apache/shenyu/tree/master/db/init/pg) found in the initialization script `create-database.sql`、 `create-table.sql`, and use the client connection tool to connect to your PostgreSql service. so you get a database named `shenyu`, which can later be used as a database for the `Shenyu-admin` project. + +* sql script: https://github.com/apache/shenyu/tree/master/db/init/pg + +* driver: + + * maven repository: https://mvnrepository.com/artifact/org.postgresql/postgresql/42.5.0 + * homepage: https://jdbc.postgresql.org/download/ + +### Oracle + +In [the oracle initialization scripts directory](https://github.com/apache/shenyu/blob/master/db/init/oracle) found in the initialization script `schema.sql`, Use the client connection tool to connect to your Oracle service to create a database, execute the `schema.sql` script on this database, and initialize the `Shenyu-admin` database. After can be [project configuration file](https://github.com/apache/shenyu/blob/master/shenyu-admin/src/main/resources/application-oracle.yml) to adjust your Oracle environment configuration. + +* sql script: https://github.com/apache/shenyu/blob/master/db/init/oracle + +* driver: + + * maven repository: https://mvnrepository.com/artifact/com.oracle.database.jdbc/ojdbc8/19.3.0.0 + * homepage: https://www.oracle.com/database/technologies/appdev/jdbc-downloads.html + +### OpenGauss + +In [the openGuass initialization scripts directory](https://github.com/apache/shenyu/blob/master/db/init/og) found in the initialization script `create-table.sql`, Use the client connection tool to connect to your openGauss service to create a database, execute the `create-table.sql` script on this database, and initialize the `Shenyu-admin` database. After can be [project configuration file](https://github.com/apache/shenyu/blob/master/shenyu-admin/src/main/resources/application-og.yml) to adjust your openGauss environment configuration. + +* sql script: https://github.com/apache/shenyu/blob/master/db/init/og + +* driver: + + * maven repository: https://mvnrepository.com/artifact/org.opengauss/opengauss-jdbc/5.0.0-og + * homepage: https://gitee.com/opengauss/openGauss-connector-jdbc diff --git a/versioned_docs/version-2.6.1/deployment/deployment-cluster.md b/versioned_docs/version-2.6.1/deployment/deployment-cluster.md new file mode 100644 index 00000000000..a24277f8c16 --- /dev/null +++ b/versioned_docs/version-2.6.1/deployment/deployment-cluster.md @@ -0,0 +1,246 @@ +--- +sidebar_position: 7 +title: Cluster Deployment +keywords: ["Gateway Cluster Environment", "Cluster Environment"] +description: Cluster Deployment +--- + +> Before you read this document, you need to complete some preparations before deploying Shenyu according to the [Deployment Prerequisites document](./deployment-before.md). + +This article introduces how to deploy the `Shenyu` gateway in cluster environment. + +> In this part, you can see [ShenYu Binary Packages Deployment](./deployment-package.md) before deploying. + +### Environmental Preparation + +* Two or more Gateway Boostrap servers, these servers must install JDK1.8+. +* A server for Gateway Admin, this server must install mysql/pgsql/h2 and JDK1.8+. +* A server for nginx. + +### Start Apache ShenYu Admin + +* download and unzip [apache-shenyu-${current.version}-admin-bin.tar.gz](https://archive.apache.org/dist/incubator/shenyu/2.5.1/apache-shenyu-2.5.1-admin-bin.tar.gz) in your Gateway Admin server. + +* config your database, go to the `/conf` directory, and modify `spring.profiles.active` of the configuration in `application.yaml` to `mysql`, `pg` or `h2`. + +* config your way of synchronization, go to the `/conf` directory, and modify `shenyu.sync` of configuration in `application.yaml` to `websocket`, `http`, `zookeeper`, `etcd`, `consul` or `nacos`. + +* start Apache ShenYu Admin in `bin` directory. + +``` +> windows: start.bat + +> linux: ./start.sh +``` + +### Start Apache ShenYu Boostrap + +* download and unzip [apache-shenyu-${current.version}-bootstrap-bin.tar.gz](https://archive.apache.org/dist/incubator/shenyu/2.5.1/apache-shenyu-2.5.1-bootstrap-bin.tar.gz) in your Gateway Boostrap server. + +* config your synchronization, go to the `/conf` directory, and modify `shenyu.sync` of configuration in `application.yaml` to `websocket`, `http`, `zookeeper`, `etcd`, `consul` or `nacos`, this configuaration must remain the same of `ShenyYu Admin`. + +* repeat above-mentioned operations in each `ShenYu Bootstrap` server. + +* start Apache ShenYu Bootstrap in `bin` directory. + +``` +> windwos : start.bat + +> linux : ./start.sh +``` + +> After completing these operations, you will deploy `ShenYu Boostrap` Cluster. +> +> For example. you will deploy `ShenYu Bootstrap` in `10.1.1.1` and `10.1.1.2` and deploy nginx in `10.1.1.3`. + +### Start Nginx + +* download and install `nginx`. + +* modify `upstream` and `server` of configuration in `nginx.conf`. + +```nginx +upstream shenyu_gateway_cluster { + ip_hash; + server 10.1.1.1:9195 max_fails=3 fail_timeout=10s weight=50; + server 10.1.1.2:9195 max_fails=3 fail_timeout=10s weight=50; +} + +server { + listen 9195; + location / { + proxy_pass http://shenyu_gateway_cluster; + proxy_set_header HOST $host; + proxy_read_timeout 10s; + proxy_connect_timeout 10s; + } +} +``` + +* start nginx. + +``` +> windows: ./nginx.exe + +> linux: /usr/local/nginx/sbin/nginx +``` + +* verify nginx, looking at your `ShenYu Bootstrap` log or `Nginx` log, Where will the verification request go. + +Apache ShenYu Nginx Module + +--- + +This module provided SDK to watch available ShenYu instance list as upstream nodes by Service Register Center for OpenResty. +1. [ETCD](#greeting-etcd) (Supported) +2. [Nacos](#greeting-nacos) (Supported) +3. [Zookeeper](#greeting-zookeeper) (Supported) +4. Consul (TODO) + +In the cluster mode, Apache ShenYu supports the deployment of multiple ShenYu instances, which may have new instances joining or leaving at any time. +Hence, Apache ShenYu introduces Service Discovery modules to help client to detect the available instances. +Currently, Apache ShenYu Bootstrap already supports Apache Zookeeper, Nacos, Etcd, and consul. Client or LoadBalancer can get the available ShenYu instances by those Service register center. + +## Getting Started + +- Prerequisite: +1. Luarocks +2. OpenResty + +### Build from source + +The first, clone the source from GitHub. + +``` +git clone https://github.com/apache/shenyu-nginx +``` + +Then, build from source and install. + +``` +cd shenyu-nginx +luarocks make rockspec/shenyu-nginx-main-0.rockspec +``` + +### Greeting ETCD + +Modify the Nginx configure, create and initialize the ShenYu Register to connect to the target register center. +The module will fetch the all of ShenYu instances which are registered to Etcd in the same cluster. +It works like Etcd client to watch(based on long polling) ShenYu instance lists. + +Here is an example for Etcd. + +``` +init_worker_by_lua_block { + local register = require("shenyu.register.etcd") + register.init({ + balancer_type = "chash", + etcd_base_url = "http://127.0.0.1:2379", + }) +} +``` + +1. `balancer_type` specify the balancer. It has supported `chash` and `round robin`. +2. `etcd_base_url` specify the Etcd server.(Currently, authentication is not supported.) + +Add an `upstream block` for ShenYu and enable to update upstream servers dynamically. This case will synchronize the ShenYu instance list with register center. +And then pick one up for handling the request. + +``` +upstream shenyu { + server 0.0.0.1; -- bad + + balancer_by_lua_block { + require("shenyu.register.etcd").pick_and_set_peer() + } +} +``` + +Finally, restart OpenResty. + +``` +openresty -s reload +``` + +Here is a completed [example](https://github.com/apache/shenyu-nginx/blob/main/example/etcd/nginx.conf) working with ETCD. + +### Greeting Nacos + +Modify the Nginx configure, create and initialize the ShenYu Register to connect to target register center. Here is an example for Nacos. + +``` +init_worker_by_lua_block { + local register = require("shenyu.register.nacos") + register.init({ + shenyu_storage = ngx.shared.shenyu_storage, + balancer_type = "chash", + nacos_base_url = "http://127.0.0.1:8848", + username = "nacos", + password = "naocs", + }) +} +``` + +1. `balancer_type` specify the balancer. It has supported `chash` and `round robin`. +2. `nacos_base_url` specify the Nacos server address. +3. `username` specify the username to log in Nacos. (it is only required when Nacos auth enable) +4. `password` specify the password to log in Nacos. + +Modify the `upstream` to enable to update upstream servers dynamically. This case will synchronize the ShenYu instance list with register center. +And then pick one up for handling the request. + +``` +upstream shenyu { + server 0.0.0.1; -- bad + + balancer_by_lua_block { + require("shenyu.register.nacos").pick_and_set_peer() + } +} +``` + +Finally, restart OpenResty. + +``` +openresty -s reload +``` + +Here is a completed [example](https://github.com/apache/shenyu-nginx/blob/main/example/nacos/nginx.conf) working with Nacos. + +## Greeting Zookeeper + +Modify the Nginx configure, create and initialize the ShenYu register to connect to target register center. +Listen for changes to the node via the zookeeper watch event. Here is an example of the zookeeper configuration. + +``` +init_worker_by_lua_block { + local register = require("shenyu.register.zookeeper") + register.init({ + servers = {"127.0.0.1:2181","127.0.0.1:2182"}, + shenyu_storage = ngx.shared.shenyu_storage, + balancer_type = "roundrobin" + }); + } +``` + +1. `servers` zookeeper cluster address. +2. ``balancer_type`` specify the balancer. It has supported `chash` and `round robin`. + +Modify the upstream to enable to update upstream servers dynamically. This case will synchronize the ShenYu instance list with register center. And then pick one up for handling the request. + +``` + upstream shenyu { + server 0.0.0.1; + balancer_by_lua_block { + require("shenyu.register.zookeeper").pick_and_set_peer() + } + } +``` + +Finally, restart OpenResty. + +``` +openresty -s reload +``` + +Here is a completed [example](https://github.com/apache/shenyu-nginx/blob/main/example/zookeeper/nginx.conf) working with Zookeeper. diff --git a/versioned_docs/version-2.6.1/deployment/deployment-custom.md b/versioned_docs/version-2.6.1/deployment/deployment-custom.md new file mode 100644 index 00000000000..4ea65337cd6 --- /dev/null +++ b/versioned_docs/version-2.6.1/deployment/deployment-custom.md @@ -0,0 +1,66 @@ +--- +sidebar_position: 6 +title: Custom Deployment +keywords: ["Custom"] +description: Custom Deployment +--- + +This article describes how to build your own gateway based on `Apache ShenYu`. + +> Before you read this document, you need to complete some preparations before deploying Shenyu according to the [Deployment Prerequisites document](./deployment-before.md). + +### Start Apache ShenYu Admin + +* docker reference docker deployment Apache ShenYu Admin + +* liunx/windows reference binary packages deployment Apache ShenYu Admin + +### Build your own gateway (recommended) + +* first create an empty `springboot` project, you can refer to `shenyu-bootstrap`, or you can create it on [spring official website](https://spring.io/quickstart). + +* introduce the following `jar` package: + +```xml + + + org.springframework.boot + spring-boot-starter-webflux + 2.2.2.RELEASE + + + org.springframework.boot + spring-boot-starter-actuator + 2.2.2.RELEASE + + + org.apache.shenyu + shenyu-spring-boot-starter-gateway + ${current.version} + + + org.apache.shenyu + shenyu-spring-boot-starter-sync-data-websocket + ${current.version} + + +``` + +among them, `${project.version}` please use the current latest version. + +* add the following configuration to your `application.yaml` file: + +```yaml +spring: + main: + allow-bean-definition-overriding: true +management: + health: + defaults: + enabled: false +shenyu: + sync: + websocket: + urls: ws://localhost:9095/websocket //set to your shenyu-admin address + allowOrigin: ws://localhost:9195 +``` diff --git a/versioned_docs/version-2.6.1/deployment/deployment-docker-compose.md b/versioned_docs/version-2.6.1/deployment/deployment-docker-compose.md new file mode 100644 index 00000000000..36514a54e98 --- /dev/null +++ b/versioned_docs/version-2.6.1/deployment/deployment-docker-compose.md @@ -0,0 +1,39 @@ +--- +sidebar_position: 3 +title: Docker-compose Deployment +keywords: ["docker-compose", "Deployment"] +description: Docker-compose Deployment +--- + +This article introduces the use of `docker-compose` to deploy the `Apache ShenYu` gateway. + +> Before you read this document, you need to complete some preparations before deploying Shenyu according to the [Deployment Prerequisites document](./deployment-before.md). + +### Download shell script + +```shell +curl -O https://raw.githubusercontent.com/apache/shenyu/master/shenyu-dist/shenyu-docker-compose-dist/src/main/resources/install.sh +``` + +### execute script + +This script will download the required configuration files and mysql-connector, and can be executed repeatedly if the download fails. + +```shell +sh ./install.sh #The latest configuration is pulled by default. If you need to deploy the released version, you can add a parameter to indicate the version number, such as: v2.4.2 or latest +``` + +### Initialize the `shenyu-admin` database + +Refer to the [database initialization documentation](./deployment-before.md#database-initialize) to initialize the database. + +### Modify the configuration file + +Modify the configuration file downloaded by the script to set up configurations such as `JDBC`. + +### Execute docker-compose + +```shell +cd shenyu-${VERSION} +docker-compose -f ./shenyu-${VERSION}/docker-compose.yaml up -d +``` diff --git a/versioned_docs/version-2.6.1/deployment/deployment-docker.md b/versioned_docs/version-2.6.1/deployment/deployment-docker.md new file mode 100644 index 00000000000..2eb8261f6c2 --- /dev/null +++ b/versioned_docs/version-2.6.1/deployment/deployment-docker.md @@ -0,0 +1,113 @@ +--- +sidebar_position: 3 +title: Docker Deployment +keywords: ["docker", "Deployment"] +description: Docker Deployment +--- + +This article introduces the use of `docker` to deploy the `Apache ShenYu` gateway. + +> Before you read this document, you need to complete some preparations before deploying Shenyu according to the [Deployment Prerequisites document](./deployment-before.md). + +### Create Docker Network + +``` +docker network create shenyu +``` + +### Start Apache ShenYu Admin + +``` +docker pull apache/shenyu-admin:${current.version} +``` + +> After version 2.5.1, when `docker run`, we can customize JVM startup parameters by adding `-e ADMIN_JVM="xxxx"` + +* use `h2` to store data: + +``` +docker run -d -p 9095:9095 --name shenyu-admin --net shenyu apache/shenyu-admin:${current.version} +``` + +* use `MySQL` to store data, follow the [guide document](./deployment-before.md#mysql) to initialize the database, copy [mysql-connector.jar](https://repo1.maven.org/maven2/mysql/mysql-connector-java/8.0.29/mysql-connector-java-8.0.29.jar) to `/$(your_work_dir)/ext-lib`: + +``` +docker run --name shenyu-admin -v /${your_work_dir}/ext-lib:/opt/shenyu-admin/ext-lib -e "SPRING_PROFILES_ACTIVE=mysql" -e "spring.datasource.url=jdbc:mysql://${your_ip_port}/shenyu?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai&zeroDateTimeBehavior=convertToNull" -e "spring.datasource.username=${your_username}" -e "spring.datasource.password=${your_password}" -d -p 9095:9095 --net shenyu apache/shenyu-admin:${current.version} +``` + +another way is to put the `application.yml`、`application-mysql.yml` configuration in ${your_work_dir}/conf from [Configure address](https://github.com/apache/shenyu/blob/master/shenyu-admin/src/main/resources/) , modify the configuration `spring.profiles.active = mysql` in `application.yml`, and then execute the following statement: + +``` +docker run --name shenyu-admin -v ${your_work_dir}/conf:/opt/shenyu-admin/conf -v /${your_work_dir}/ext-lib:/opt/shenyu-admin/ext-lib -d -p 9095:9095 --net shenyu apache/shenyu-admin:${current.version} +``` + +* use `PostgreSql` to store data, follow the [guide document](./deployment-before.md#postgresql) to initialize the database, execute the following statement: + +``` +docker run --name shenyu-admin -e "SPRING_PROFILES_ACTIVE=pg" -e "spring.datasource.url=jdbc:postgresql://${your_ip_port}/shenyu?useUnicode=true&characterEncoding=utf-8&useSSL=false" -e "spring.datasource.username=${your_username}" -e "spring.datasource.password=${your_password}" -d -p 9095:9095 --net shenyu apache/shenyu-admin:${current.version} +``` + +another way is to put the `application.yml`、`application-pg.yml` configuration in ${your_work_dir}/conf, modify the configuration `spring.profiles.active = pg` in `application.yml`,and then execute the following statement: + +``` +docker run --name shenyu-admin -v ${your_work_dir}/conf:/opt/shenyu-admin/conf -d -p 9095:9095 --net shenyu apache/shenyu-admin:${current.version} +``` + +* use `Oracle` to store data, follow the [guide document](./deployment-before.md#oracle) to initialize the database, execute the following statement: + +``` +docker run --name shenyu-admin -e "SPRING_PROFILES_ACTIVE=oracle" -e "spring.datasource.url=jdbc:oracle:thin:@localhost:1521/shenyu" -e "spring.datasource.username=${your_username}" -e "spring.datasource.password=${your_password}" -d -p 9095:9095 --net shenyu apache/shenyu-admin:${current.version} +``` + +another way is to put the `application.yml`、`application-oracle.yml` configuration in ${your_work_dir}/conf, modify the configuration `spring.profiles.active = oracle` in `application.yml`, and then execute the following statement: + +``` +docker run --name shenyu-admin -v ${your_work_dir}/conf:/opt/shenyu-admin/conf -d -p 9095:9095 --net shenyu apache/shenyu-admin:${current.version} +``` + +* use `OpenGauss` to store data, follow the [guide document](./deployment-before.md#opengauss) to initialize the database, execute the following statement: + +``` +docker run --name shenyu-admin -e "SPRING_PROFILES_ACTIVE=og" -e "spring.datasource.url=jdbc:opengauss://localhost:5432/shenyu" -e "spring.datasource.username=${your_username}" -e "spring.datasource.password=${your_password}" -d -p 9095:9095 --net shenyu apache/shenyu-admin:${current.version} +``` + +another way is to put the `application.yml`、`application-og.yml` configuration in ${your_work_dir}/conf, modify the configuration `spring.profiles.active = og` in `application.yml`, and then execute the following statement: + +``` +docker run --name shenyu-admin -v ${your_work_dir}/conf:/opt/shenyu-admin/conf -d -p 9095:9095 --net shenyu apache/shenyu-admin:${current.version} +``` + +### Start Apache ShenYu Bootstrap + +> After version 2.5.1, when `docker run`, we can customize JVM startup parameters by adding `-e BOOT_JVM="xxxx"` + +First, pull the docker image + +```shell +docker pull apache/shenyu-bootstrap:${current.version} +``` + +If you don't need to modify the configuration, just use the command below to run the application + +```shell +docker run -d \ + -p 9195:9195 \ + --name shenyu-bootstrap \ + --net shenyu \ + --env SHENYU_SYNC_WEBSOCKET_URLS=ws://shenyu-admin:9095/websocket \ + apache/shenyu-bootstrap:${current.version} +``` + +> `SHENYU_SYNC_WEBSOCKET_URLS` indicates the websocket address that shenyu-bootstrap used to communicate with shenyu-admin + +If you need to modify the configuration, copy the configuration from the Github directory where the bootstrap [configuration file](https://github.com/apache/shenyu/tree/master/shenyu-bootstrap/src/main/resources) is located, then recorded it as `$BOOTSTRAP_CONF`. After your modification, execute the command below to run the application + +```shell +docker run -d \ + -p 9195:9195 \ + -v $BOOTSTRAP_CONF:/opt/shenyu-bootstrap/conf \ + --name shenyu-bootstrap \ + --net shenyu \ + --env SHENYU_SYNC_WEBSOCKET_URLS=ws://shenyu-admin:9095/websocket \ + apache/shenyu-bootstrap:${current.version} +``` diff --git a/versioned_docs/version-2.6.1/deployment/deployment-helm.md b/versioned_docs/version-2.6.1/deployment/deployment-helm.md new file mode 100644 index 00000000000..5b70a294056 --- /dev/null +++ b/versioned_docs/version-2.6.1/deployment/deployment-helm.md @@ -0,0 +1,10 @@ +--- +sidebar_position: 5 +title: Helm Deployment +keywords: ["Helm"] +description: Helm Deployment +--- + +This article introduces the use of `helm` to deploy the `Apache ShenYu` gateway. + +Please refer to [Helm Deployment](https://shenyu.apache.org/helm/index/) for details. diff --git a/versioned_docs/version-2.6.1/deployment/deployment-k8s.md b/versioned_docs/version-2.6.1/deployment/deployment-k8s.md new file mode 100644 index 00000000000..2470e1c710f --- /dev/null +++ b/versioned_docs/version-2.6.1/deployment/deployment-k8s.md @@ -0,0 +1,863 @@ +--- +sidebar_position: 4 +title: K8s Deployment +keywords: ["k8s"] +description: K8s Deployment +--- + +> Before you read this document, you need to complete some preparations before deploying Shenyu according to the [Deployment Prerequisites document](./deployment-before.md). + +This article introduces the use of `K8s` to deploy the `Apache ShenYu` gateway. + +> Catalog +> +> Example 1: Using h2 as a database +> +> 1. create Namespace and ConfigMap +> 2. deploying shenyu-admin +> 3. deploy shenyu-bootstrap +> +> Example 2: Use MySQL as the database +> +> Similar to the h2 process, there are two points to note +> +> 1. you need to load [mysql-connector.jar](https://repo1.maven.org/maven2/mysql/mysql-connector-java/8.0.18/mysql-connector-java-8.0.18.jar), the download command is executed when the container is started +> 2. you need to specify an external MySQL database configuration +> +> The process is as follows. +> +> 1. create Namespace and ConfigMap +> 2. deploy shenyu-admin +> 3. deploy shenyu-bootstrap + + +## Example 1: Using h2 as a database + +### 1. Create Namespace and ConfigMap + +- create shenyu-ns.yaml + +```yaml +apiVersion: v1 +kind: Namespace +metadata: + name: shenyu + labels: + name: shenyu +--- +apiVersion: v1 +kind: ConfigMap +metadata: + name: shenyu-cm + namespace: shenyu +data: + shenyu-admin-application.yml: | + server: + port: 9095 + address: 0.0.0.0 + spring: + profiles: + active: h2 + thymeleaf: + cache: true + encoding: utf-8 + enabled: true + prefix: classpath:/static/ + suffix: .html + mvc: + pathmatch: + matching-strategy: ant_path_matcher + mybatis: + config-location: classpath:/mybatis/mybatis-config.xml + mapper-locations: classpath:/mappers/*.xml + shenyu: + register: + registerType: http #http #zookeeper #etcd #nacos #consul + serverLists: #localhost:2181 #http://localhost:2379 #localhost:8848 + props: + sessionTimeout: 5000 + connectionTimeout: 2000 + checked: true + zombieCheckTimes: 5 + scheduledTime: 10 + nacosNameSpace: ShenyuRegisterCenter + sync: + websocket: + enabled: true + messageMaxSize: 10240 + allowOrigins: ws://shenyu-admin-svc.shenyu.svc.cluster.local:9095;ws://shenyu-bootstrap-svc.shenyu.svc.cluster.local:9195; + ldap: + enabled: false + url: ldap://xxxx:xxx + bind-dn: cn=xxx,dc=xxx,dc=xxx + password: xxxx + base-dn: ou=xxx,dc=xxx,dc=xxx + object-class: person + login-field: cn + jwt: + expired-seconds: 86400000 + shiro: + white-list: + - / + - /favicon.* + - /static/** + - /index** + - /platform/login + - /websocket + - /error + - /actuator/health + - /swagger-ui.html + - /webjars/** + - /swagger-resources/** + - /v2/api-docs + - /csrf + swagger: + enable: true + apidoc: + gatewayUrl: http://127.0.0.1:9195 + envProps: + - envLabel: Test environment + addressLabel: Request Address + addressUrl: http://127.0.0.1:9195 + - envLabel: Prod environment + addressLabel: Request Address + addressUrl: http://127.0.0.1:9195 + logging: + level: + root: info + org.springframework.boot: info + org.apache.ibatis: info + org.apache.shenyu.bonuspoint: info + org.apache.shenyu.lottery: info + org.apache.shenyu: info + shenyu-admin-application-h2.yml: | + shenyu: + database: + dialect: h2 + init_script: "sql-script/h2/schema.sql" + init_enable: true + spring: + datasource: + url: jdbc:h2:mem:~/shenyu;DB_CLOSE_DELAY=-1;MODE=MySQL; + username: sa + password: sa + driver-class-name: org.h2.Driver + shenyu-bootstrap-application.yml: | + server: + port: 9195 + address: 0.0.0.0 + spring: + main: + allow-bean-definition-overriding: true + allow-circular-references: true + application: + name: shenyu-bootstrap + codec: + max-in-memory-size: 2MB + cloud: + discovery: + enabled: false + nacos: + discovery: + server-addr: 127.0.0.1:8848 # Spring Cloud Alibaba Dubbo use this. + enabled: false + namespace: ShenyuRegisterCenter + eureka: + client: + enabled: false + serviceUrl: + defaultZone: http://localhost:8761/eureka/ + instance: + prefer-ip-address: true + management: + health: + defaults: + enabled: false + shenyu: + matchCache: + selector: + selectorEnabled: false + initialCapacity: 10000 # initial capacity in cache + maximumSize: 10000 # max size in cache + rule: + initialCapacity: 10000 # initial capacity in cache + maximumSize: 10000 # max size in cache + trie: + childrenSize: 10000 + pathVariableSize: 1000 + pathRuleCacheSize: 1000 + matchMode: antPathMatch + netty: + http: + # set to false, user can custom the netty tcp server config. + webServerFactoryEnabled: true + selectCount: 1 + workerCount: 4 + accessLog: false + serverSocketChannel: + soRcvBuf: 87380 + soBackLog: 128 + soReuseAddr: false + connectTimeoutMillis: 10000 + writeBufferHighWaterMark: 65536 + writeBufferLowWaterMark: 32768 + writeSpinCount: 16 + autoRead: false + allocType: "pooled" + messageSizeEstimator: 8 + singleEventExecutorPerGroup: true + socketChannel: + soKeepAlive: false + soReuseAddr: false + soLinger: -1 + tcpNoDelay: true + soRcvBuf: 87380 + soSndBuf: 16384 + ipTos: 0 + allowHalfClosure: false + connectTimeoutMillis: 10000 + writeBufferHighWaterMark: 65536 + writeBufferLowWaterMark: 32768 + writeSpinCount: 16 + autoRead: false + allocType: "pooled" + messageSizeEstimator: 8 + singleEventExecutorPerGroup: true + instance: + enabled: false + registerType: zookeeper #etcd #consul + serverLists: localhost:2181 #http://localhost:2379 #localhost:8848 + props: + cross: + enabled: true + allowedHeaders: + allowedMethods: "*" + allowedAnyOrigin: true # the same of Access-Control-Allow-Origin: "*" + allowedExpose: "" + maxAge: "18000" + allowCredentials: true + switchConfig: + local: true + file: + enabled: true + maxSize : 10 + sync: + websocket: + urls: ws://shenyu-admin-svc.shenyu.svc.cluster.local:9095/websocket + allowOrigin: ws://shenyu-bootstrap-svc.shenyu.svc.cluster.local:9195 + exclude: + enabled: false + paths: + - /favicon.ico + fallback: + enabled: false + paths: + - /fallback/hystrix + - /fallback/resilience4j + health: + enabled: false + paths: + - /actuator/health + - /health_check + extPlugin: + path: + enabled: true + threads: 1 + scheduleTime: 300 + scheduleDelay: 30 + scheduler: + enabled: false + type: fixed + threads: 16 + upstreamCheck: + enabled: false + timeout: 3000 + healthyThreshold: 1 + unhealthyThreshold: 1 + interval: 5000 + printEnabled: true + printInterval: 60000 + ribbon: + serverListRefreshInterval: 10000 + metrics: + enabled: false + name : prometheus + host: 127.0.0.1 + port: 8090 + jmxConfig: + props: + jvm_enabled: true + local: + enabled: false + sha512Key: "BA3253876AED6BC22D4A6FF53D8406C6AD864195ED144AB5C87621B6C233B548BAEAE6956DF346EC8C17F5EA10F35EE3CBC514797ED7DDD3145464E2A0BAB413" + logging: + level: + root: info + org.springframework.boot: info + org.apache.ibatis: info + org.apache.shenyu.bonuspoint: info + org.apache.shenyu.lottery: info + org.apache.shenyu: info + +``` + +- execute `kubectl apply -f shenyu-ns.yaml` + +### 2. Create shenyu-admin + +- create shenyu-admin.yaml + +```yaml +# Example of using the nodeport type to expose ports +apiVersion: v1 +kind: Service +metadata: + namespace: shenyu + name: shenyu-admin-svc +spec: + selector: + app: shenyu-admin + type: NodePort + ports: + - protocol: TCP + port: 9095 + targetPort: 9095 + nodePort: 31095 +--- +# shenyu-admin +apiVersion: apps/v1 +kind: Deployment +metadata: + namespace: shenyu + name: shenyu-admin +spec: + selector: + matchLabels: + app: shenyu-admin + replicas: 1 + template: + metadata: + labels: + app: shenyu-admin + spec: + volumes: + - name: shenyu-admin-application + configMap: + name: shenyu-cm + items: + - key: shenyu-admin-application.yml + path: shenyu-admin-application.yml + - name: shenyu-admin-application-h2 + configMap: + name: shenyu-cm + items: + - key: shenyu-admin-application-h2.yml + path: shenyu-admin-application-h2.yml + containers: + - name: shenyu-admin + image: apache/shenyu-admin:latest + imagePullPolicy: Always + ports: + - containerPort: 9095 + env: + - name: 'TZ' + value: 'Asia/Beijing' + volumeMounts: + - name: shenyu-admin-application + mountPath: /opt/shenyu-admin/conf/application.yml + subPath: shenyu-admin-application.yml + - name: shenyu-admin-application-h2 + mountPath: /opt/shenyu-admin/conf/application-h2.yml + subPath: shenyu-admin-application-h2.yml +``` + +- execute`kubectl apply -f shenyu-admin.yaml` + +### 3. Create shenyu-bootstrap + +- create shenyu-bootstrap.yaml + +```yaml +# Example of using the nodeport type to expose ports +apiVersion: v1 +kind: Service +metadata: + namespace: shenyu + name: shenyu-bootstrap-svc +spec: + selector: + app: shenyu-bootstrap + type: NodePort + ports: + - protocol: TCP + port: 9195 + targetPort: 9195 + nodePort: 31195 +--- +# shenyu-bootstrap +apiVersion: apps/v1 +kind: Deployment +metadata: + namespace: shenyu + name: shenyu-bootstrap +spec: + selector: + matchLabels: + app: shenyu-bootstrap + replicas: 1 + template: + metadata: + labels: + app: shenyu-bootstrap + spec: + volumes: + - name: shenyu-bootstrap-application + configMap: + name: shenyu-cm + items: + - key: shenyu-bootstrap-application.yml + path: shenyu-bootstrap-application.yml + containers: + - name: shenyu-bootstrap + image: apache/shenyu-bootstrap:latest + ports: + - containerPort: 9195 + env: + - name: TZ + value: Asia/Beijing + volumeMounts: + - name: shenyu-bootstrap-application + mountPath: /opt/shenyu-bootstrap/conf/application.yml + subPath: shenyu-bootstrap-application.yml +``` + +- execute `kubectl apply -f shenyu-bootstrap.yaml` + + +## Example 2: Use MySQL as the database + +### 1. Create Namespace and ConfigMap + +- create shenyu-ns.yaml + +```yaml +apiVersion: v1 +kind: Namespace +metadata: + name: shenyu + labels: + name: shenyu +--- +apiVersion: v1 +kind: ConfigMap +metadata: + name: shenyu-cm + namespace: shenyu +data: + shenyu-admin-application.yml: | + server: + port: 9095 + address: 0.0.0.0 + spring: + profiles: + active: mysql + thymeleaf: + cache: true + encoding: utf-8 + enabled: true + prefix: classpath:/static/ + suffix: .html + mvc: + pathmatch: + matching-strategy: ant_path_matcher + mybatis: + config-location: classpath:/mybatis/mybatis-config.xml + mapper-locations: classpath:/mappers/*.xml + shenyu: + register: + registerType: http #http #zookeeper #etcd #nacos #consul + serverLists: #localhost:2181 #http://localhost:2379 #localhost:8848 + props: + sessionTimeout: 5000 + connectionTimeout: 2000 + checked: true + zombieCheckTimes: 5 + scheduledTime: 10 + nacosNameSpace: ShenyuRegisterCenter + sync: + websocket: + enabled: true + messageMaxSize: 10240 + allowOrigins: ws://shenyu-admin-svc.shenyu.svc.cluster.local:9095;ws://shenyu-bootstrap-svc.shenyu.svc.cluster.local:9195; + ldap: + enabled: false + url: ldap://xxxx:xxx + bind-dn: cn=xxx,dc=xxx,dc=xxx + password: xxxx + base-dn: ou=xxx,dc=xxx,dc=xxx + object-class: person + login-field: cn + jwt: + expired-seconds: 86400000 + shiro: + white-list: + - / + - /favicon.* + - /static/** + - /index** + - /platform/login + - /websocket + - /error + - /actuator/health + - /swagger-ui.html + - /webjars/** + - /swagger-resources/** + - /v2/api-docs + - /csrf + swagger: + enable: true + apidoc: + gatewayUrl: http://127.0.0.1:9195 + envProps: + - envLabel: Test environment + addressLabel: Request Address + addressUrl: http://127.0.0.1:9195 + - envLabel: Prod environment + addressLabel: Request Address + addressUrl: http://127.0.0.1:9195 + logging: + level: + root: info + org.springframework.boot: info + org.apache.ibatis: info + org.apache.shenyu.bonuspoint: info + org.apache.shenyu.lottery: info + org.apache.shenyu: info + shenyu-admin-application-mysql.yml: | + shenyu: + database: + dialect: mysql + init_script: "sql-script/mysql/schema.sql" + init_enable: true + spring: + datasource: + url: jdbc:mysql://{your_mysql_ip}:{your_mysql_port}/shenyu?useUnicode=true&characterEncoding=utf-8&useSSL=false + username: {your_mysql_user} + password: {your_mysql_password} + driver-class-name: com.mysql.jdbc.Driver + shenyu-bootstrap-application.yml: | + server: + port: 9195 + address: 0.0.0.0 + spring: + main: + allow-bean-definition-overriding: true + allow-circular-references: true + application: + name: shenyu-bootstrap + codec: + max-in-memory-size: 2MB + cloud: + discovery: + enabled: false + nacos: + discovery: + server-addr: 127.0.0.1:8848 # Spring Cloud Alibaba Dubbo use this. + enabled: false + namespace: ShenyuRegisterCenter + eureka: + client: + enabled: false + serviceUrl: + defaultZone: http://localhost:8761/eureka/ + instance: + prefer-ip-address: true + management: + health: + defaults: + enabled: false + shenyu: + matchCache: + selector: + selectorEnabled: false + initialCapacity: 10000 # initial capacity in cache + maximumSize: 10000 # max size in cache + rule: + initialCapacity: 10000 # initial capacity in cache + maximumSize: 10000 # max size in cache + trie: + childrenSize: 10000 + pathVariableSize: 1000 + pathRuleCacheSize: 1000 + matchMode: antPathMatch + netty: + http: + # set to false, user can custom the netty tcp server config. + webServerFactoryEnabled: true + selectCount: 1 + workerCount: 4 + accessLog: false + serverSocketChannel: + soRcvBuf: 87380 + soBackLog: 128 + soReuseAddr: false + connectTimeoutMillis: 10000 + writeBufferHighWaterMark: 65536 + writeBufferLowWaterMark: 32768 + writeSpinCount: 16 + autoRead: false + allocType: "pooled" + messageSizeEstimator: 8 + singleEventExecutorPerGroup: true + socketChannel: + soKeepAlive: false + soReuseAddr: false + soLinger: -1 + tcpNoDelay: true + soRcvBuf: 87380 + soSndBuf: 16384 + ipTos: 0 + allowHalfClosure: false + connectTimeoutMillis: 10000 + writeBufferHighWaterMark: 65536 + writeBufferLowWaterMark: 32768 + writeSpinCount: 16 + autoRead: false + allocType: "pooled" + messageSizeEstimator: 8 + singleEventExecutorPerGroup: true + instance: + enabled: false + registerType: zookeeper #etcd #consul + serverLists: localhost:2181 #http://localhost:2379 #localhost:8848 + props: + cross: + enabled: true + allowedHeaders: + allowedMethods: "*" + allowedAnyOrigin: true # the same of Access-Control-Allow-Origin: "*" + allowedExpose: "" + maxAge: "18000" + allowCredentials: true + switchConfig: + local: true + file: + enabled: true + maxSize : 10 + sync: + websocket: + urls: ws://shenyu-admin-svc.shenyu.svc.cluster.local:9095/websocket + allowOrigin: ws://shenyu-bootstrap-svc.shenyu.svc.cluster.local:9195 + exclude: + enabled: false + paths: + - /favicon.ico + fallback: + enabled: false + paths: + - /fallback/hystrix + - /fallback/resilience4j + health: + enabled: false + paths: + - /actuator/health + - /health_check + extPlugin: + path: + enabled: true + threads: 1 + scheduleTime: 300 + scheduleDelay: 30 + scheduler: + enabled: false + type: fixed + threads: 16 + upstreamCheck: + enabled: false + timeout: 3000 + healthyThreshold: 1 + unhealthyThreshold: 1 + interval: 5000 + printEnabled: true + printInterval: 60000 + ribbon: + serverListRefreshInterval: 10000 + metrics: + enabled: false + name : prometheus + host: 127.0.0.1 + port: 8090 + jmxConfig: + props: + jvm_enabled: true + local: + enabled: false + sha512Key: "BA3253876AED6BC22D4A6FF53D8406C6AD864195ED144AB5C87621B6C233B548BAEAE6956DF346EC8C17F5EA10F35EE3CBC514797ED7DDD3145464E2A0BAB413" + logging: + level: + root: info + org.springframework.boot: info + org.apache.ibatis: info + org.apache.shenyu.bonuspoint: info + org.apache.shenyu.lottery: info + org.apache.shenyu: info +``` + +- execute `kubectl apply -f shenyu-ns.yaml` + +### 2. Create shenyu-admin + +- create shenyu-admin.yaml + +```yaml +# Example of using the nodeport type to expose ports +apiVersion: v1 +kind: Service +metadata: + namespace: shenyu + name: shenyu-admin-svc +spec: + selector: + app: shenyu-admin + type: NodePort + ports: + - protocol: TCP + port: 9095 + targetPort: 9095 + nodePort: 31095 +--- +# shenyu-admin +apiVersion: apps/v1 +kind: Deployment +metadata: + namespace: shenyu + name: shenyu-admin +spec: + selector: + matchLabels: + app: shenyu-admin + replicas: 1 + template: + metadata: + labels: + app: shenyu-admin + spec: + volumes: + - name: shenyu-admin-application + configMap: + name: shenyu-cm + items: + - key: shenyu-admin-application.yml + path: shenyu-admin-application.yml + - name: shenyu-admin-application-mysql + configMap: + name: shenyu-cm + items: + - key: shenyu-admin-application-mysql.yml + path: shenyu-admin-application-mysql.yml + - name: mysql-connector-volume + emptyDir: {} + initContainers: + - name: download-mysql-jar + image: busybox:1.35.0 + command: [ "sh","-c"] + args: ["wget https://repo1.maven.org/maven2/mysql/mysql-connector-java/8.0.23/mysql-connector-java-8.0.23.jar; + wget https://repo1.maven.org/maven2/mysql/mysql-connector-java/8.0.23/mysql-connector-java-8.0.23.jar.md5; + if [ $(md5sum mysql-connector-java-8.0.23.jar | cut -d ' ' -f1) = $(cat mysql-connector-java-8.0.23.jar.md5) ]; + then echo success; + else echo failed; + exit 1; + fi; + mv /mysql-connector-java-8.0.23.jar /opt/shenyu-admin/ext-lib/mysql-connector-java.jar" ] + volumeMounts: + - name: mysql-connector-volume + mountPath: /opt/shenyu-admin/ext-lib + containers: + - name: shenyu-admin + image: apache/shenyu-admin:latest + imagePullPolicy: Always + ports: + - containerPort: 9095 + env: + - name: 'TZ' + value: 'Asia/Beijing' + - name: SPRING_PROFILES_ACTIVE + value: mysql + volumeMounts: + - name: shenyu-admin-application + mountPath: /opt/shenyu-admin/conf/application.yml + subPath: shenyu-admin-application.yml + - name: shenyu-admin-application-mysql + mountPath: /opt/shenyu-admin/conf/application-mysql.yml + subPath: shenyu-admin-application-mysql.yml + - name: mysql-connector-volume + mountPath: /opt/shenyu-admin/ext-lib +``` + +- execute`kubectl apply -f shenyu-admin.yaml` + +### 3. Create shenyu-bootstrap + +- create shenyu-bootstrap.yaml + +```yaml +# Example of using the nodeport type to expose ports +apiVersion: v1 +kind: Service +metadata: + namespace: shenyu + name: shenyu-bootstrap-svc +spec: + selector: + app: shenyu-bootstrap + type: NodePort + ports: + - protocol: TCP + port: 9195 + targetPort: 9195 + nodePort: 31195 +--- +# shenyu-bootstrap +apiVersion: apps/v1 +kind: Deployment +metadata: + namespace: shenyu + name: shenyu-bootstrap +spec: + selector: + matchLabels: + app: shenyu-bootstrap + replicas: 1 + template: + metadata: + labels: + app: shenyu-bootstrap + spec: + volumes: + - name: shenyu-bootstrap-application + configMap: + name: shenyu-cm + items: + - key: shenyu-bootstrap-application.yml + path: shenyu-bootstrap-application.yml + containers: + - name: shenyu-bootstrap + image: apache/shenyu-bootstrap:latest + ports: + - containerPort: 9195 + env: + - name: TZ + value: Asia/Beijing + volumeMounts: + - name: shenyu-bootstrap-application + mountPath: /opt/shenyu-bootstrap/conf/application.yml + subPath: shenyu-bootstrap-application.yml +``` + +- execute `kubectl apply -f shenyu-bootstrap.yaml` + +## Test Access + +**Access Address**:http://{K8S_CLUSTER_IP}:31095/ + +**Account/password**:admin/123456 diff --git a/versioned_docs/version-2.6.1/deployment/deployment-local.md b/versioned_docs/version-2.6.1/deployment/deployment-local.md new file mode 100644 index 00000000000..6009dd8fa78 --- /dev/null +++ b/versioned_docs/version-2.6.1/deployment/deployment-local.md @@ -0,0 +1,52 @@ +--- +sidebar_position: 1 +title: Local Deployment +keywords: ["Deployment"] +description: Local Deployment +--- + +This article introduces how to start the `Apache ShenYu` gateway in the local environment. + +> Before you read this document, you need to complete some preparations before deploying Shenyu according to the [Deployment Prerequisites document](./deployment-before.md). + +### Environmental preparation + +* Install JDK1.8+ locally +* Install Git locally +* Install Maven locally +* Choose a development tool, such as IDEA + +### Download the compiled code + +* Download + +``` +git clone https://github.com/apache/shenyu.git +cd shenyu +mvn clean install '-Dmaven.javadoc.skip=true' '-B' '-Drat.skip=true' '-Djacoco.skip=true' '-DskipITs' '-DskipTests' +``` + +* use the development tool to start `org.apache.shenyu.admin.ShenyuAdminBootstrap`,Visit http://localhost:9095, the default username and password are: `admin` and `123456` respectively. + + * If you use `h2` for storage, set the variable `--spring.profiles.active = h2` and start the server. + + * If you use `MySQL` for storage, follow the [guide document](./deployment-before.md#mysql) to initialize the database and modify the `JDBC` configuration in `application-mysql.yml`, set the variable `--spring.profiles.active = mysql` and start the server. + + * If you use `PostgreSql` for storage, follow the [guide document](./deployment-before.md#postgresql) to initialize the database and modify the `JDBC` configuration in `application-pg.yml`, set the variable `--spring.profiles.active = pg` and start the server. + + * If you use `Oracle` for storage, follow the [guide document](./deployment-before.md#oracle) to initialize the database and modify the `JDBC` configuration in `application-oracle.yml`, set the variable `--spring.profiles.active = oracle`. + + * If you use `OpenGuass` for storage, follow the [guide document](./deployment-before.md#opengauss) to initialize the database and modify the `JDBC` configuration in `application-og.yml`, set the variable `--spring.profiles.active = og`. + +* use the development tool to start `org.apache.shenyu.bootstrap.ShenyuBootstrapApplication`. + + + + + + + + + + + diff --git a/versioned_docs/version-2.6.1/deployment/deployment-package.md b/versioned_docs/version-2.6.1/deployment/deployment-package.md new file mode 100644 index 00000000000..a1992ffcc31 --- /dev/null +++ b/versioned_docs/version-2.6.1/deployment/deployment-package.md @@ -0,0 +1,81 @@ +--- +sidebar_position: 2 +title: Binary Packages Deployment +keywords: ["Deployment"] +description: Binary Packages Deployment +--- + +This article introduces the deployment of the `Apache ShenYu` gateway using the binary packages. + +> Before you read this document, you need to complete some preparations before deploying Shenyu according to the [Deployment Prerequisites document](./deployment-before.md). + +### Start Apache ShenYu Admin + +* download [apache-shenyu-${current.version}-admin-bin.tar.gz](https://archive.apache.org/dist/shenyu/2.6.0/apache-shenyu-2.6.0-admin-bin.tar.gz) + +* unzip `apache-shenyu-${current.version}-admin-bin.tar.gz`。 go to the `bin` directory. + +> After version 2.5.1, `start.sh` started to support custom JVM startup parameters through the environment variable `ADMIN_JVM`. + +* use `h2` to store data: + +``` +> windows: start.bat + +> linux: ./start.sh +``` + +* use `MySQL` to store data, follow the [guide document](./deployment-before.md#mysql) to initialize the database, copy [mysql-connector.jar](https://repo1.maven.org/maven2/mysql/mysql-connector-java/8.0.18/mysql-connector-java-8.0.18.jar) to /$(your_work_dir)/ext-lib, go to the `/conf` directory, and modify the `JDBC` configuration in `application-mysql.yml`. + +* Modify `spring.profiles.active` in `conf/application.yml` to `mysql` + +``` +> windows: start.bat + +> linux: ./start.sh +``` + +* use `PostgreSql` to store data, follow the [guide document](./deployment-before.md#postgresql) to initialize the database, go to the `/conf` directory, and modify the `JDBC` configuration in `application-pg.yml`. + +* Modify `spring.profiles.active` in `conf/application.yml` to `pg` + +``` +> windows: start.bat + +> linux: ./start.sh --spring.profiles.active = pg +``` + +* use `Oracle` to store data, follow the [guide document](./deployment-before.md#oracle) to initialize the database, go to the `/conf` directory, and modify the `JDBC` configuration in `application-oracle.yml`. + +* Modify `spring.profiles.active` in `conf/application.yml` to `oracle` + +``` +> windows: start.bat + +> linux: ./start.sh +``` + +* use `OpenGauss` to store data, follow the [guide document](./deployment-before.md#opengauss) to initialize the database, go to the `/conf` directory, and modify the `JDBC` configuration in `application-og.yml`. + +* Modify `spring.profiles.active` in `conf/application.yml` to `og` + +``` +> windows: start.bat + +> linux: ./start.sh +``` + +### Start Apache ShenYu Bootstrap + +* download [apache-shenyu-${current.version}-bootstrap-bin.tar.gz](https://archive.apache.org/dist/shenyu/2.6.0/apache-shenyu-2.6.0-bootstrap-bin.tar.gz) + +* unzip `apache-shenyu-${current.version}-bootstrap-bin.tar.gz`。 go to the `bin` directory. + +> After version 2.5.1, `start.sh` started to support custom JVM startup parameters through the environment variable `BOOT_JVM`. + +``` +> windwos : start.bat + +> linux : ./start.sh +``` + diff --git a/versioned_docs/version-2.6.1/deployment/deployment-quick.md b/versioned_docs/version-2.6.1/deployment/deployment-quick.md new file mode 100644 index 00000000000..81a5a267a29 --- /dev/null +++ b/versioned_docs/version-2.6.1/deployment/deployment-quick.md @@ -0,0 +1,109 @@ +--- +sidebar_position: 1 +title: Local Quick Deployment +keywords: ["Deployment"] +description: Local Quick Deployment +--- + +This article introduces how to quickly start the `Apache ShenYu` gateway in the standalone environment. + +> Before you read this document, you need to complete some preparations before deploying Shenyu according to the [Deployment Prerequisites document](./deployment-before.md). + +### Environmental preparation + +* Install JDK1.8+ locally + +### Start Apache ShenYu Bootstrap + +* download [apache-shenyu-${current.version}-bootstrap-bin.tar.gz](https://archive.apache.org/dist/shenyu/2.6.0/apache-shenyu-2.6.0-bootstrap-bin.tar.gz) + +* unzip `apache-shenyu-${current.version}-bootstrap-bin.tar.gz`。 go to the `bin` directory. + +``` +> windwos : start.bat + +> linux : ./start.sh +``` + +### Selector and rule configuration + +please refer to [Developer Local Model](../developer/local-model#add-selector-and-rules) add the selector and rule. + +example: + +* your service address is`http://127.0.0.1:8080/helloworld` and the response like follow: + +```json +{ + "name" : "Shenyu", + "data" : "hello world" +} +``` + +* use the follow data to add selector and rule + +### by postman + +> Add `localKey: 123456` to Headers. If you need to customize the localKey, you can use the sha512 tool to generate the key based on plaintext and update the `shenyu.local.sha512Key` property. +> +> `POST` method,address`http://localhost:9195/shenyu/plugin/selectorAndRules`, body use `raw json` content: + +``` +Headers + +localKey: 123456 +``` + +```json +{ + "pluginName": "divide", + "selectorHandler": "[{\"upstreamUrl\":\"127.0.0.1:8080\"}]", + "conditionDataList": [{ + "paramType": "uri", + "operator": "match", + "paramValue": "/**" + }], + "ruleDataList": [{ + "ruleHandler": "{\"loadBalance\":\"random\"}", + "conditionDataList": [{ + "paramType": "uri", + "operator": "match", + "paramValue": "/**" + }] + }] +} +``` + +### by curl + +```bash +curl --location --request POST 'http://localhost:9195/shenyu/plugin/selectorAndRules' \ +--header 'Content-Type: application/json' \ +--header 'localKey: 123456' \ +--data-raw '{ + "pluginName": "divide", + "selectorHandler": "[{\"upstreamUrl\":\"127.0.0.1:8080\"}]", + "conditionDataList": [{ + "paramType": "uri", + "operator": "match", + "paramValue": "/**" + }], + "ruleDataList": [{ + "ruleHandler": "{\"loadBalance\":\"random\"}", + "conditionDataList": [{ + "paramType": "uri", + "operator": "match", + "paramValue": "/**" + }] + }] +}' +``` + +* open `http://localhost:9195/helloworld`: + +```json +{ + "name" : "Shenyu", + "data" : "hello world" +} +``` diff --git a/versioned_docs/version-2.6.1/design/_category_.json b/versioned_docs/version-2.6.1/design/_category_.json new file mode 100644 index 00000000000..727286eafa2 --- /dev/null +++ b/versioned_docs/version-2.6.1/design/_category_.json @@ -0,0 +1,4 @@ +{ + "label": "Design", + "position": 2 +} diff --git a/versioned_docs/version-2.6.1/design/data-sync.md b/versioned_docs/version-2.6.1/design/data-sync.md new file mode 100644 index 00000000000..e1256f7c52f --- /dev/null +++ b/versioned_docs/version-2.6.1/design/data-sync.md @@ -0,0 +1,121 @@ +--- +sidebar_position: 2 +title: Data Sync Design +keywords: ["Apache ShenYu"] +description: Data Synchronization Design +--- + +This document explains the principle of data synchronization. Data synchronization refers to the strategy used to synchronize data to ShenYu gateway after shenyu-admin background operation data. ShenYu gateway currently supports ZooKeeper, WebSocket, HTTP Long Polling, Nacos, Etcd and Consul for data synchronization. + +See [Data Synchronization Configuration](../user-guide/property-config/use-data-sync.md) for configuration information about data synchronization. + + + + + +## Preface {#preface} + +Gateway is the entrance of request and it is a very important part in micro service architecture, therefore the importance of gateway high availability is self-evident. When we use gateway, we have to change configuration such as flow rule, route rule for satisfying business requirement. Therefore, the dynamic configuration of the gateway is an important factor to ensure the high availability of the gateway. + +In the actual use of Apache ShenYu Gateway, users also feedback some problems: + +* Apache ShenYu depends on ZooKeeper, how to use Etcd, Consul, Nacos and other registry center? + +* Apache ShenYu depends on Redis and InfluxDB, and do not use limiting plugins or monitoring plugins. Why need these? + +* Why not use configuration center for configuration synchronization? + +* Why can't updates be configured dynamically? + +* Every time you want to query the database, Redis is a better way. + +According to the feedback of users, we have also partially reconstructed ShenYu. The current data synchronization features are as follows: + + +* All configuration is cached in ShenYu gateway memory, each request uses local cache, which is very fast. + +* Users can modify any data in the background of shenyu-admin, and immediately synchronize to the gateway memory. + +* Support ShenYu plugin, selector, rule data, metadata, signature data and other data synchronization. + +* All plugin selectors and rules are configured dynamically and take effect immediately, no service restart required. + +* Data synchronization mode supports Zookeeper, HTTP long polling, Websocket, Nacos, Etcd and Consul. + + +## Principle Analysis {#principle-analysis} + +The following figure shows the process of data synchronization of ShenYu. ShenYu Gateway will synchronize configuration data from configuration service at startup, and support push-pull mode to get configuration change information, and then update local cache. The administrator can change the user permissions, rules, plugins and traffic configuration in the admin system(shenyu-admin), and synchronize the change information to ShenYu Gateway through the push-pull mode. Whether the mode is push or pull depends on the synchronization mode used. + + + + +In the original version, the configuration service relied on the Zookeeper implementation to manage the back-end push of changes to the gateway. Now, WebSocket, HTTP long polling, ZooKeeper, Nacos, Etcd, and Consul can now be supported by specifying the corresponding synchronization policy by setting `shenyu.sync.${strategy}` in the configuration file. The default WeboSocket synchronization policy can be used to achieve second level data synchronization. However, it is important to note that Apache ShenYu Gateway and shenyu-admin must use the same synchronization policy. + + + +As showing picture below,`shenyu-admin` will issue a configuration change notification through `EventPublisher` after users change configuration,`EventDispatcher` will handle this modification and send configuration to corresponding event handler according to configured synchronization strategy. + +- If it is a `websocket` synchronization strategy,it will push modified data to `shenyu-web`,and corresponding `WebsocketDataHandler` handler will handle `shenyu-admin` data push at the gateway layer +- If it is a `zookeeper` synchronization strategy,it will push modified data to `zookeeper`,and the `ZookeeperSyncCache` will monitor the data changes of `zookeeper` and process them +- If it is a `http` synchronization strategy,`shenyu-web` proactively initiates long polling requests,90 seconds timeout by default,if there is no modified data in `shenyu-admin`,http request will be blocked,if there is a data change, it will respond to the changed data information,if there is no data change after 60 seconds,then respond with empty data,gateway continue to make http request after getting response,this kind of request will repeat. + + + +### Zookeeper Synchronization {#zookeeper-synchronization} + +The zookeeper-based synchronization principle is very simple,it mainly depends on `zookeeper` watch mechanism,`shenyu-web` will monitor the configured node,when `shenyu-admin` starts,all the data will be written to `zookeeper`,it will incrementally update the nodes of `zookeeper` when data changes,at the same time, `shenyu-web` will monitor the node for configuration information, and update the local cache once the information changes + +![Zookeeper Node Design](https://yu199195.github.io/images/soul/soul-zookeeper.png) + +`Apache ShenYu` writes the configuration information to the zookeeper node,and it is meticulously designed. If you want to learn more about the code implementation, refer to the source code `ZookeeperSyncDataService`. + +### WebSocket Synchronization {#websocket-synchronization} + +The mechanism of `websocket` and `zookeeper` is similar,when the gateway and the `shenyu-admin` establish a `websocket` connection,`shenyu-admin` will push all data at once,it will automatically push incremental data to `shenyu-web` through `websocket` when configured data changes + +When we use websocket synchronization,pay attention to reconnect after disconnection,which also called keep heartbeat.`Apache ShenYu` uses `java-websocket` ,a third-party library,to connect to `websocket`. If you want to learn more about the code implementation, refer to the source code `WebsocketSyncDataService`. + +### Http Long Polling {#http-long-polling} + +The mechanism of zookeeper and websocket data synchronization is relatively simple,but http synchronization will be relatively complicated.ShenYu borrows the design ideas of `Apollo` and `Nacos` and realizes `http` long polling data synchronization using their advantages.Note that this is not traditional ajax long polling. + + + +http long polling mechanism as above,shenyu-web gateway requests shenyu-admin configuration services,timeout is 90 seconds,it means gateway layer request configuration service will wait at most 90 seconds,this is convenient for shenyu-admin configuration service to respond modified data in time,and therefore we realize near real-time push. + +After the http request reaches shenyu-admin, it does not respond immediately,but uses the asynchronous mechanism of Servlet3.0 to asynchronously respond to the data.First of all,put long polling request task `LongPollingClient` into `BlocingQueue`,and then start scheduling task,execute after 60 seconds,this aims to remove the long polling request from the queue after 60 seconds,even there is no configured data change.Because even if there is no configuration change,gateway also need to know,otherwise it will wait,and there is a 90 seconds timeout when the gateway requests configuration services. + + +If the administrator changes the configuration data during this period,the long polling requests in the queue will be removed one by one, and respond which group’s data has changed(we distribute plugins, rules, flow configuration , user configuration data into different groups).After gateway receives response,it only knows which Group has changed its configuration,it need to request again to get group configuration data.Someone may ask,why don't you write out the changed data directly?We also discussed this issue deeply during development, because the http long polling mechanism can only guarantee quasi real-time,if gateway layer does not handle it in time,or administrator updates configuration frequently,we probably missed some configuration change push.For security, we only inform that a certain Group information has changed. + + +When `shenyu-web` gateway layer receives the http response information,pull modified information(if exists),and then request `shenyu-admin` configuration service again,this will repeatedly execute. If you want to learn more about the code implementation, refer to the source code `HttpSyncDataService`. + +### Nacos Synchronization {#nacos-synchronization} + + +The synchronization principle of Nacos is basically similar to that of ZooKeeper, and it mainly depends on the configuration management of Nacos. The path of each configuration node is similar to that of ZooKeeper. + +ShenYu gateway will monitor the configured node. At startup, if there is no configuration node in Nacos, it will write the synchronous full amount of data into Nacos. When the sequential data send changes, it will update the configuration node in Nacos in full amount. The local cache is updated. + +If you want to learn more about the code implementation, please refer to the source code `NacosSyncDataService` and the official documentation for [Nacos](https://nacos.io/zh-cn/docs/sdk.html) . + +### Etcd Synchronization {#etcd-synchronization} + +Etcd data synchronization principle is similar to Zookeeper, mainly relying on Etcd's watch mechanism, and each configuration node path is the same as that of Zookeeper. + +The native API for Etcd is a bit more complicated to use, so it's somewhat encapsulated. + +ShenYu gateway will listen to the configured node. When startup, if there is no configuration node in Etcd, it will write the synchronous full amount of data into Etcd. When the sequential data send changes, it will update the configuration node in Etcd incrementally. + +If you want to learn more about the code implementation, refer to the source `EtcdSyncDataService`. + +### Consul Synchronization {#consul-synchronization} + + +Consul data synchronization principle is that the gateway regularly polls Consul's configuration center to get the configuration version number for local comparison. + +ShenYu gateway will poll the configured nodes regularly, and the default interval is 1s. When startup, if there is no configuration node in Consul, write the synchronous full amount of data into Consul, then incrementally update the configuration node in Consul when the subsequent data is sent to change. At the same time, Apache ShenYu Gateway will regularly polls the node of configuration information and pull the configuration version number for comparison with the local one. The local cache is updated when the version number is changed. + +If you want to learn more about the code implementation, refer to the source `ConsulsyncDataService`. diff --git a/versioned_docs/version-2.6.1/design/database-design.md b/versioned_docs/version-2.6.1/design/database-design.md new file mode 100644 index 00000000000..5e03ce634fa --- /dev/null +++ b/versioned_docs/version-2.6.1/design/database-design.md @@ -0,0 +1,95 @@ +--- +sidebar_position: 1 +title: Admin Database Design +keywords: ["db"] +description: ShenYu Admin Database Design +--- + +Apache Shenyu Admin is the management system of the gateway, which can manage all plugins, selectors and rules visually, set users, roles and resources. + +## Plugin, Selector And Rule {#plugin-selector-and-rule} + +* Plugin: ShenYu uses the plugin design idea to realize the hot plug of the plugin, which is easy to expand. Built-in rich plugins, including RPC proxy, circuit breaker and current limiting, authority and certification, monitoring, and more. +* Selector: Each plugin can set multiple selectors to carry out preliminary filtering of traffic. +* Rule: Multiple rules can be set per selector for more fine-grained control of flow. + +* The Database Table UML Diagram: + +![](/img/shenyu/db/shenyu-db.png) + +* Detailed design: + + * One plugin corresponds to multiple selectors,one selector corresponds to multiple rules. + + * One selector corresponds to multiple match conditions,one rule corresponds to multiple match conditions. + + * Each rule handles differently in corresponding plugin according to field handler,field handler is a kind of data of JSON string type.You can view detail during the use of shenyu-admin. + +## Resource Permission {#resource-permission} + +* The resource are the menus and buttons in the shenyu-admin console. + +* Resource Permission use database to store user name,role,resource data and relationship. + +* The Resource Permission Table UML Diagram: +![](/img/shenyu/db/shenyu-permission-db.png) + +* Detailed design: + - one user corresponds to multiple role,one role corresponds to multiple resources. + +## Data Permission {#data-permission} + +* Data Permission use database to store the relationship between users, selectors and rules. + +* The Data Permission Table UML Diagram: +![data permission uml](/img/shenyu/db/data_permission.png) + + +* Detailed design: + * The most important table is `data_permission`, where a user corresponds to multiple data permissions. + * The field `data_type` distinguishes between different types of data, which corresponds to the following: 0 -> selector, 1 -> rule. + * The field `data_id` holds the primary key id of the corresponding type. + +## Meta Data {#meta-data} + +* Metadata is used for generic invoke by gateway. +* For each interface method, there is one piece of metadata. +* The Database Table UML Diagram: + + + + +* Detailed design: + * `path`: When the gateway is requested, a piece of data will be matched according to `path`, and then the subsequent process will be carried out. + + * `rpc_ext`: Used to hold extended information for the RPC proxy.。 + +## Dictionary Management {#dictionary-management} + +* Dictionary management is used to maintain and manage public data dictionaries. +* The Database Table UML Diagram: + + + +## API Documentation {#API-documentation} + +* The API document tables used to maintain and manage API documents. +* The API document (such as json, md, html, etc.) of common specifications (such as OpenApi3.0 and yapi) can be imported into `shenyu-admin` and finally stored in the API document tables. +* API documents of other common specifications can be generated through the API document tables. +* The Database Table UML Diagram: + + + +* Detailed design: + * A tag can have multiple child tags, the level of tags is unlimited, the lowest leaf node is API. + * Interfaces with the same path but supporting multiple http methods, they are counted as multiple APIs. + * An API has multiple request parameters and response fields. + * A parameter/field has its own type (model), and each type have multiple fields. + * A field has its own type, which corresponds to multiple values. + * A value can be used as either a request example value, or a response example value (for example, 200 indicates OK, and 400 indicates illegal parameters). + * The `query`, `header` and `body`, all of them are `json` stored in `mock_request_record`,but `body` does not support special types such as file。 + * The `ext` of the `tag` table stores the full amount of json data of its parent tag (including the parent tag of the parent tag, and so on). + * The `ext` of the `api` table may store the IP list and the service name of `SpringCloud`. + * The `type` of the `parameter` table mainly includes `requestUrlParam`, `requestHeader`, `requestBody`, `requestPathVariable`, `responseHeader`, and `responseBody`; If the returned type is a special type (such as file), do not associate `model_id`. + * The `ext` of the `field` table stores generic type in json format (convenient for subsequent expansion), such as `{"genericTypes": [model_id1, model_id2]}`; `model_id` indicates which type has this field, `self_model_id` indicates which type of this field. + * The `is_example` of `detail` table indicates whether a value is a request sample value, true is a request sample value, and false is a response value. diff --git a/versioned_docs/version-2.6.1/design/flow-control.md b/versioned_docs/version-2.6.1/design/flow-control.md new file mode 100644 index 00000000000..9f33519b2be --- /dev/null +++ b/versioned_docs/version-2.6.1/design/flow-control.md @@ -0,0 +1,36 @@ +--- +title: Flow Control Design +keywords: ["flow-control"] +description: ShenYu Flow Control Design +--- + +ShenYu gateway realizes flow control through plugins, selectors and rules. For related data structure, please refer to the previous [Apache ShenYu Admin Database Design](./database-design) . + + +### Plugin + +In Apache ShenYu Admin System, each plugin uses Handle (JSON format) fields to represent different processing, and the plugin processing is used to manage and edit the custom processing fields in the JSON. + +The main purpose of this feature is to enable plugins to handle templated configurations. + +### Selector And Rule + +Selector and rule are the most soul of Apache ShenYu Gateway. Master it and you can manage any traffic. + +A plugin has multiple selectors, and one selector corresponds to multiple rules. The selector is the first level filter of traffic, and the rule is the final filter. For a plugin, we want to meet the traffic criteria based on our configuration before the plugin will be executed. Selectors and rules are designed to allow traffic to perform what we want under certain conditions. The rules need to be understood first. + +The execution logic of plugin, selector and rule is as follows. When the traffic enters into ShenYu gateway, it will first judge whether there is a corresponding plugin and whether the plugin is turned on. Then determine whether the traffic matches the selector of the plugin. It then determines whether the traffic matches the rules of the selector. If the request traffic meets the matching criteria, the plugin will be executed. Otherwise, the plugin will not be executed. Process the next one. ShenYu gateway is so through layers of screening to complete the flow control. + + + + +### Traffic filtering + + + +Traffic filtering is the soul of the selector and the rule, corresponding to the matching conditions in the selector and the rule. According to different traffic filtering rules, we can deal with various complex scenes. Traffic filtering can fetch data from Http requests such as `Header`, `URI`, `Query`, `Cookie`, etc. + +You can then use `Match`, `=`, `SpEL`, `Regex`, `Groovy`, `Exclude`, etc, to Match the desired data. Multi-group matching Adds matching policies that can use And/Or. + + +please refer to [Selector And Rule Config](../user-guide/admin-usage/selector-and-rule) for details. diff --git a/versioned_docs/version-2.6.1/design/register-center-design.md b/versioned_docs/version-2.6.1/design/register-center-design.md new file mode 100644 index 00000000000..7640e99aa50 --- /dev/null +++ b/versioned_docs/version-2.6.1/design/register-center-design.md @@ -0,0 +1,61 @@ +--- +title: Client Registry Design +keywords: ["Client Access"] +description: Application Client Access +--- + +> *Notice* +> After ShenYu version 2.6.1, the ShenYu register just support http type, and the middleware register type has been removed. +> So, please use the http register type to register your service. +> ShenYu Register Center isn't microservice register center, it just register metadata, selector data, rule data to shenyu-admin, and then shenyu-admin will sync data to shenyu-gateway. + + +Application client access means to access your microservice to ShenYu gateway, currently supports HTTP, Dubbo, Spring Cloud, gRPC, Motan, Sofa, Tars and other protocols access. + +Refer to the client access configuration in the user documentation for [Application Client Access Config](../user-guide/property-config/register-center-access.md) . + + + + +## Design principle + +#### Client + +![](/img/shenyu/register/client.png) + +Declare the registry client type, such as HTTP, in your microservice configuration. Use SPI to load and initialize the corresponding registry client when the application starts, implement the post-processor interface associated with the Spring Bean, get the service interface information to register in it, and place the obtained information into Disruptor. + +The Registry client reads data from the Disruptor and registers the interface information with shenyu-admin, where the Disruptor decouples data from operations for scaling. + +#### Server + +![](/img/shenyu/register/server.png) + +Declare the registry server type, such as HTTP in the Shenyu-Admin configuration. When shenyu-admin is started, it will read the configuration type, load and initialize the corresponding registry server, and when the registry server receives the interface information registered by shenyu-client, it will put it into Disruptor, which will trigger the registration processing logic to update the interface information and publish a synchronous event. + +Disruptor provides data and operations decoupling for expansion. If there are too many registration requests, resulting in abnormal registration, there is also a data buffer role. + +## Http Registry + +The principle of HTTP service registration is relatively simple. After Shenyu-Client is started, the relevant service registration interface of Shenyu-Admin will be called to upload data for registration. + +After receiving the request, shenyu-admin will update the data and publish the data synchronization event to synchronize the interface information to ShenYu Gateway. + +## SPI + +| *SPI Name* | *Description* | +| -------------------------------- | --------------------------- | +| ShenyuClientRegisterRepository | ShenYu client register SPI | + +| *Implementation Class* | *Description* | +| -------------------------------- | --------------------------- | +| HttpClientRegisterRepository | Http client register repository | + + +| *SPI Name* | *Description* | +| -------------------------------- | ----------------------------- | +| ShenyuServerRegisterRepository | ShenYu server register SPI | + +| *Implementation Class* | *Description* | +| -------------------------------- | ----------------------------- | +| ShenyuHttpRegistryController | Http server repository | diff --git a/versioned_docs/version-2.6.1/design/spi-design.md b/versioned_docs/version-2.6.1/design/spi-design.md new file mode 100644 index 00000000000..4aee4218411 --- /dev/null +++ b/versioned_docs/version-2.6.1/design/spi-design.md @@ -0,0 +1,49 @@ +--- +title: SPI Design +keywords: ["spi design"] +description: spi-design +--- + + +SPI, called Service Provider Interface, is a built-in JDK Service that provides discovery function and a dynamic replacement discovery mechanism. + + +[shenyu-spi](https://github.com/apache/shenyu/tree/master/shenyu-spi) is a custom SPI extension implementation for Apache Shenyu gateway. The design and implementation principles refer to [SPI Extension Implementations](https://dubbo.apache.org/en/docs/v2.7/dev/impls/) . + + +### Registry Center + +`Consul`, `Etcd`, `Http`, `Nacos` and `Zookeeper` are supported. The expansion of the registry including client and server, interface respectively `ShenyuServerRegisterRepository` and `ShenyuClientRegisterRepository`. + +### Metrics Center + +Responsible for service monitoring, loading concrete implementation through `SPI`, currently support `Prometheus`, service interface is `MetricsService`. + + + +### Load Balance + +Select one of the service providers to call. Currently, the supported algorithms are `Has`, `Random`, and `RoundRobin`, and the extended interface is `LoadBalance`. + +### RateLimiter + + +In the `RateLimiter` plugin, which stream limiting algorithm to use, currently supporting `Concurren`, `LeakyBucke`, `SlidingWindow` and `TokenBucket`, the extension interface is `RateLimiterAlgorithm`. + + +### Match Strategy + +Which matching method to use when adding selectors And rules, currently supports `And`, `Or`, And the extension interface is `MatchStrategy`. + + +### Parameter Data + + +Currently, `URI`,`RequestMethod`, `Query`, `Post`, `IP`, `Host`, `Cookie`, and `Header` are supported. The extended interface is `ParameterData`. + + +### Predicate Judge + +Which conditional policy to use when adding selectors and rules currently supports `Match`, `Contains`,`Equals`, `Groovy`, `Regex`, `SpEL`, `TimerAfter`, `TimerBefore` and `Exclude`. The extension interface is `PredicateJudge`. + + diff --git a/versioned_docs/version-2.6.1/design/wasm-plugin-design.md b/versioned_docs/version-2.6.1/design/wasm-plugin-design.md new file mode 100644 index 00000000000..60f9eff0dc3 --- /dev/null +++ b/versioned_docs/version-2.6.1/design/wasm-plugin-design.md @@ -0,0 +1,25 @@ +--- +title: WASM plugin design +keywords: ["WASM"] +description: Apache ShenYu WASM plugin design +--- + +`Apache ShenYu` is a Java native API Gateway for service proxy, protocol conversion and API governance. Currently, ShenYu has good scalability in the Java language. However, ShenYu's support for multiple languages is still relatively weak. + +`WASM`(WebAssembly) bytecode is designed to be encoded in a size- and load-time-efficient binary format. WebAssembly aims to leverage the common hardware features available on various platforms to execute in browsers at machine code speed. + +`WASI`(WebAssembly System Interface) allows WASM to run in non browser environments such as Linux. + +The goal of `WASMPlugin` is to be able to run WASM bytecode. Other languages, as long as their code can be compiled into WASM bytecode (such as Rust/golang/C++), can be used to write ShenYu plugins. + +## Develop Phase + + + +## Prepare Phase + + + +## Runtime Phase + + diff --git a/versioned_docs/version-2.6.1/developer/_category_.json b/versioned_docs/version-2.6.1/developer/_category_.json new file mode 100644 index 00000000000..0dd2e4019ee --- /dev/null +++ b/versioned_docs/version-2.6.1/developer/_category_.json @@ -0,0 +1,4 @@ +{ + "label": "Developer", + "position": 7 +} diff --git a/versioned_docs/version-2.6.1/developer/custom-filter.md b/versioned_docs/version-2.6.1/developer/custom-filter.md new file mode 100644 index 00000000000..211d3bc2de5 --- /dev/null +++ b/versioned_docs/version-2.6.1/developer/custom-filter.md @@ -0,0 +1,109 @@ +--- +title: Custom Filter +keywords: ["Custom Filter"] +description: custom filter +--- + +## Description + +* This doc shows a demo for how to extend `org.springframework.web.server.WebFliter`. + +## CORS Support + +* `org.apache.shenyu.web.filter.CrossFilter` is designed for `WebFilter` implementation. + + ```java + public class CrossFilter implements WebFilter { + + private static final String ALLOWED_HEADERS = "x-requested-with, authorization, Content-Type, Authorization, credential, X-XSRF-TOKEN,token,username,client"; + + private static final String ALLOWED_METHODS = "*"; + + private static final String ALLOWED_ORIGIN = "*"; + + private static final String ALLOWED_EXPOSE = "*"; + + private static final String MAX_AGE = "18000"; + + @Override + @SuppressWarnings("all") + public Mono filter(final ServerWebExchange exchange, final WebFilterChain chain) { + ServerHttpRequest request = exchange.getRequest(); + if (CorsUtils.isCorsRequest(request)) { + ServerHttpResponse response = exchange.getResponse(); + HttpHeaders headers = response.getHeaders(); + headers.add("Access-Control-Allow-Origin", ALLOWED_ORIGIN); + headers.add("Access-Control-Allow-Methods", ALLOWED_METHODS); + headers.add("Access-Control-Max-Age", MAX_AGE); + headers.add("Access-Control-Allow-Headers", ALLOWED_HEADERS); + headers.add("Access-Control-Expose-Headers", ALLOWED_EXPOSE); + headers.add("Access-Control-Allow-Credentials", "true"); + if (request.getMethod() == HttpMethod.OPTIONS) { + response.setStatusCode(HttpStatus.OK); + return Mono.empty(); + } + } + return chain.filter(exchange); + } + } + ``` + +* Registering `CrossFilter` as a `Spring Bean`. + +## Filtering Spring Boot health check + +* You can control the order by applying `@Order` to the implementation class . + +```java +@Component +@Order(-99) +public final class HealthFilter implements WebFilter { + + private static final String[] FILTER_TAG = {"/actuator/health", "/health_check"}; + + @Override + public Mono filter(@Nullable final ServerWebExchange exchange, @Nullable final WebFilterChain chain) { + ServerHttpRequest request = Objects.requireNonNull(exchange).getRequest(); + String urlPath = request.getURI().getPath(); + for (String check : FILTER_TAG) { + if (check.equals(urlPath)) { + String result = JsonUtils.toJson(new Health.Builder().up().build()); + DataBuffer dataBuffer = exchange.getResponse().bufferFactory().wrap(result.getBytes()); + return exchange.getResponse().writeWith(Mono.just(dataBuffer)); + } + } + return Objects.requireNonNull(chain).filter(exchange); + } +} + +``` + +## Extending `org.apache.shenyu.web.filter.AbstractWebFilter` + +* Add a new class and inherit from `org.apache.shenyu.web.filter.AbstractWebFilter`. +* Implement abstract methods of parent class. + +```java + /** + * this is Template Method ,children Implement your own filtering logic. + * + * @param exchange the current server exchange + * @param chain provides a way to delegate to the next filter + * @return {@code Mono} result:TRUE (is pass),and flow next filter;FALSE (is not pass) execute doDenyResponse(ServerWebExchange exchange) + */ + protected abstract Mono doFilter(ServerWebExchange exchange, WebFilterChain chain); + + /** + * this is Template Method ,children Implement your own And response client. + * + * @param exchange the current server exchange. + * @return {@code Mono} response msg. + */ + protected abstract Mono doDenyResponse(ServerWebExchange exchange); +``` + +* if method `doFilter` returns `Mono`, this filter is passing, While rejecting, it will call method `doDenyResponse` and sending infos in response body to frontend. + + + + diff --git a/versioned_docs/version-2.6.1/developer/custom-jwt-covert-algorithm.md b/versioned_docs/version-2.6.1/developer/custom-jwt-covert-algorithm.md new file mode 100644 index 00000000000..b51343ed3b5 --- /dev/null +++ b/versioned_docs/version-2.6.1/developer/custom-jwt-covert-algorithm.md @@ -0,0 +1,92 @@ +--- +title: Custom Jwt convert Algorithm +keywords: ["Custom Jwt Convert"] +description: Custom Jwt convert Algorithm +--- + + + +## Description + +* Users can customize the convert algorithm of `Jwt-plugin` to achieve convert. + + + +## Extension + + The default implementation is `org.apache.shenyu.plugin.jwt.strategy.DefaultJwtConvertStrategy`. The SPI mechanism is adopted for extension, and the steps are as follows: + +1. Implements interface `org.apache.shenyu.plugin.jwt.strategy.JwtConvertStrategy` + + ```java + /** + * Represents a conversion strategy that convert jwt to some attributes of + * serverWebExchange, especially attributes of the request header. + */ + @SPI + public interface JwtConvertStrategy { + + /** + * HandleJson needs to be parsed into jwtRuleHandle in order to + * specify how to convert jwt. + * + * @param handleJson handleJson from rule + * @return jwtRuleHandle + */ + JwtRuleHandle parseHandleJson(String handleJson); + + /** + * Converts jwt to some attributes of serverWebExchange based on jwtRuleHandle. + * + * @param jwtRuleHandle jwtRuleHandle + * @param exchange exchange + * @param jwtBody jwtBody + * @return serverWebExchange + */ + ServerWebExchange convert(JwtRuleHandle jwtRuleHandle, ServerWebExchange exchange, Map jwtBody); + + } + ``` + + ```java + + @Join + public class CustomJwtConvertStrategy implements JwtConvertStrategy { + + @Override + public CustomJwtRuleHandle parseHandleJson(final String handleJson) { + + return GsonUtils.getInstance().fromJson(handleJson, CustomJwtRuleHandle.class); + } + + @Override + public ServerWebExchange convert(final JwtRuleHandle jwtRuleHandle, final ServerWebExchange exchange, final Map jwtBody) { + final CustomJwtRuleHandle customJwtRuleHandle = (CustomJwtRuleHandle) jwtRuleHandle; + String customConvert = customJwtRuleHandle.getCustomConvert(); + ServerHttpRequest modifiedRequest = + exchange.getRequest().mutate().header("custom", customConvert).build(); + + return exchange.mutate().request(modifiedRequest).build(); + } + } + ``` + +2. Configures SPI + + ```tex + custom=org.apache.shenyu.plugin.jwt.strategy.CustomJwtConvertStrategy + ``` + + + +The project would use different conversion strategies based on the`handleType` parameter of `JwtRuleHandle` . For example, for the following `JwtRuleHandle`,the project would use our above `CustomJwtConvertStrategy` . (Note: ` handleType ` is `default` or nonexistent, the project would use default `DefaultJwtConvertStrategy`) + +```json +{ + "handleType":"custom", + "customConvert":"customConvert" +} +``` + +The case code is available for viewing in `org.apache.shenyu.plugin.jwt.strategy.CustomJwtConvertStrategy` + diff --git a/versioned_docs/version-2.6.1/developer/custom-parsing-ip-and-host.md b/versioned_docs/version-2.6.1/developer/custom-parsing-ip-and-host.md new file mode 100644 index 00000000000..a974f75343e --- /dev/null +++ b/versioned_docs/version-2.6.1/developer/custom-parsing-ip-and-host.md @@ -0,0 +1,51 @@ +--- +title: Fetching Correct IP Address And Host +keywords: ["Apache ShenYu"] +description: Fetching correct IP address and host +--- + +## Description + +* This doc demonstrates how to get correct IP address and host when `Apache ShenYu` serves behind `nginx` reverse proxy. +* After fetched real `IP` and `host`, you can match them with plugins and selectors. + +## Default Implementation + +* The embedded implementation in `Apache ShenYu` is :`org.apache.shenyu.web.forward.ForwardedRemoteAddressResolver`. + +* You need to config `X-Forwarded-For` in `nginx` first to get correct `IP address` and `host`. + + +## Implement through a Plugin + +* Declare a new class named `CustomRemoteAddressResolver` and implements `org.apache.shenyu.plugin.api.RemoteAddressResolver`. + +```java +public interface RemoteAddressResolver { + + /** + * Resolve inet socket address. + * + * @param exchange the exchange + * @return the inet socket address + */ + default InetSocketAddress resolve(ServerWebExchange exchange) { + return exchange.getRequest().getRemoteAddress(); + } + +} +``` + +* Register defined class as a `Spring Bean`. + +```java + @Bean + public SignService customRemoteAddressResolver() { + return new CustomRemoteAddressResolver(); + } +``` + + + + + diff --git a/versioned_docs/version-2.6.1/developer/custom-plugin.md b/versioned_docs/version-2.6.1/developer/custom-plugin.md new file mode 100644 index 00000000000..a863107e6a6 --- /dev/null +++ b/versioned_docs/version-2.6.1/developer/custom-plugin.md @@ -0,0 +1,318 @@ +--- +title: Custom Plugin +keywords: ["Custom Plugin"] +description: plugins +--- + +## Description + +* Plugins are core executors of `Apache ShenYu` gateway. Every plugin handles matched requests when enabled. +* There are two kinds of plugins in the `Apache ShenYu` gateway. + * The first type is a chain with single responsibility, and can not custom filtering of traffic. + * The other one can do its own chain of responsibility for matched traffic. +* You could reference from [shenyu-plugin](https://github.com/apache/shenyu/tree/master/shenyu-plugin) module and develop plugins by yourself. Please fire pull requests of your wonderful plugins without hesitate. + +## Single Responsibility Plugins + +* Add following dependency: + +```xml + + org.apache.shenyu + shenyu-plugin-api + ${project.version} + +``` + +* Declare a new class named `MyShenyuPlugin` and implements `org.apache.shenyu.plugin.api.ShenyuPlugin` + +```java +public interface ShenyuPlugin { + + /** + * Process the Web request and (optionally) delegate to the next + * {@code WebFilter} through the given {@link ShenyuPluginChain}. + * + * @param exchange the current server exchange + * @param chain provides a way to delegate to the next filter + * @return {@code Mono} to indicate when request processing is complete + */ + Mono execute(ServerWebExchange exchange, ShenyuPluginChain chain); + + /** + * return plugin order . + * This attribute To determine the plugin execution order in the same type plugin. + * + * @return int order + */ + int getOrder(); + + /** + * acquire plugin name. + * this is plugin name define you must offer the right name. + * if you impl AbstractShenyuPlugin this attribute not use. + * + * @return plugin name. + */ + default String named() { + return ""; + } + + /** + * plugin is execute. + * if return true this plugin can not execute. + * + * @param exchange the current server exchange + * @return default false. + */ + default Boolean skip(ServerWebExchange exchange) { + return false; + } +} + +``` + +Detailed instruction of interface methods: + +* `execute()` core method, you can do any task here freely. +* `getOrder()` get the order of current plugin. +* `named()` acquire the name of specific plugin that uses the `Camel Case`, eg: `dubbo`, `springCloud` . +* `skip()` determines whether this plugin should be skipped under certain conditions. +* Register plugin in `Spring` as a `Bean`, or simply apply `@Component` in implementation class. + +```java + @Bean + public ShenyuPlugin myShenyuPlugin() { + return new MyShenyuPlugin(); + } +``` + + +## Matching Traffic Processing Plugin + +* Introduce the following dependency: + +```xml + + org.apache.shenyu + shenyu-plugin-base + ${project.version} + +``` + +* Add a new class `CustomPlugin`, inherit from `org.apache.shenyu.plugin.base.AbstractShenyuPlugin` + +* examples down below: + +```java +/** + * This is your custom plugin. + * He is running in after before plugin, implement your own functionality. + * extends AbstractShenyuPlugin so you must user shenyu-admin And add related plug-in development. + * + * @author xiaoyu(Myth) + */ +public class CustomPlugin extends AbstractShenyuPlugin { + + /** + * return plugin order . + * The same plugin he executes in the same order. + * + * @return int + */ + @Override + public int getOrder() { + return 0; + } + + /** + * acquire plugin name. + * return you custom plugin name. + * It must be the same name as the plug-in you added in the admin background. + * + * @return plugin name. + */ + @Override + public String named() { + return "shenYu"; + } + + /** + * plugin is execute. + * Do I need to skip. + * if you need skip return true. + * + * @param exchange the current server exchange + * @return default false. + */ + @Override + public Boolean skip(final ServerWebExchange exchange) { + return false; + } + + /** + * this is Template Method child has Implement your own logic. + * + * @param exchange exchange the current server exchange + * @param chain chain the current chain + * @param selector selector + * @param rule rule + * @return {@code Mono} to indicate when request handling is complete + */ + @Override + protected abstract Mono doExecute(ServerWebExchange exchange, ShenyuPluginChain chain, SelectorData selector, RuleData rule) { + LOGGER.debug(".......... function plugin start.............."); + /* + * Processing after your selector matches the rule. + * rule.getHandle() is you Customize the json string to be processed. + * for this example. + * Convert your custom json string pass to an entity class. + */ + final String ruleHandle = rule.getHandle(); + + final Test test = GsonUtils.getInstance().fromJson(ruleHandle, Test.class); + + /* + * Then do your own business processing. + * The last execution chain.execute(exchange). + * Let it continue on the chain until the end. + */ + System.out.println(test.toString()); + return chain.execute(exchange); + } +} + +``` + +* Detailed explanation: + + * Plugins will match the selector rule for customized plugins inherit from this abstract class. + + * Firstly define a new plugin in `shenyu-admin` –> BasicConfig –> Plugin, please mind that your plugin name should match the `named()` method overridden in your class. + + * Re-login `shenyu-admin`, the plugin you added now showing on plugin-list page, you can choose selectors for matching. + + * There is a field named `handler` in rules, it is customized json string to be processed. You can process data after acquiring a ruleHandle (`final String ruleHandle = rule.getHandle();`) in `doExecute()` method. + +* Register plugin in `Spring` as a `Bean`, or simply apply `@Component` in implementation class. + +```java + @Bean + public ShenyuPlugin customPlugin() { + return new CustomPlugin(); + } +``` + +## Subscribe your plugin data and do customized jobs + +* Declare a new class named `PluginDataHandler` and implements `org.apache.shenyu.plugin.base.handler.PluginDataHandler` + +```java +public interface PluginDataHandler { + + /** + * Handler plugin. + * + * @param pluginData the plugin data + */ + default void handlerPlugin(PluginData pluginData) { + } + + /** + * Remove plugin. + * + * @param pluginData the plugin data + */ + default void removePlugin(PluginData pluginData) { + } + + /** + * Handler selector. + * + * @param selectorData the selector data + */ + default void handlerSelector(SelectorData selectorData) { + } + + /** + * Remove selector. + * + * @param selectorData the selector data + */ + default void removeSelector(SelectorData selectorData) { + } + + /** + * Handler rule. + * + * @param ruleData the rule data + */ + default void handlerRule(RuleData ruleData) { + } + + /** + * Remove rule. + * + * @param ruleData the rule data + */ + default void removeRule(RuleData ruleData) { + } + + /** + * Plugin named string. + * + * @return the string + */ + String pluginNamed(); + +} +``` + +* Ensure `pluginNamed()` is same as the plugin name you defined. +* Register defined class as a `Spring Bean`, or simply apply `@Component` in implementation class. + +```java +@Bean +public PluginDataHandler pluginDataHandler() { + return new PluginDataHandler(); +} +``` + +## Dynamic loading + +* When using this feature, the above extensions `ShenyuPlugin`, `PluginDataHandler`, do not need to be `spring bean`. You just need to build the jar package of the extension project. + +* Config in Yaml: + +```yaml +shenyu: + extPlugin: + path: //Load the extension plugin jar package path + enabled: true //Whether to turn on + threads: 1 //Number of loading plug-in threads + scheduleTime: 300 //Cycle time (in seconds) + scheduleDelay: 30 //How long the shenyu gateway is delayed to load after it starts (in seconds) +``` + +#### Plugin loading path details + +* This path is for the directory where the extended plugin jar package is stored。 + +* Used `-Dplugin-ext=xxxx`, Also used `shenyu.extPlugin.path` in yaml,If neither is configured, the `ext-lib` directory in the apache shenyu gateway boot path will be loaded by default. + +* Priority :`-Dplugin-ext=xxxx` > `shenyu.extPlugin.path` > `ext-lib(default)` + + +## Plugin jar upload + +* To use this feature, you will need to package the `ShenyuPlugin` extension as a custom ShenyuPlugin Jar +* Configure it in ShenyuAdmin + * use `ShenyuAdmin - BasicConfig - Plugin` add plugin in `pluginJar` click upload button +* Custom ShenyuPlugin can be started by loading third-party jars into the `-cp` directory if it depends on other third-party packages in shenyu-bootstrap + +Tips: + +The Upload jar package plugin supports hot loading +If you need to modify the jar online. You can make a new jar. And raise the version number, for example '1.0.1' to '1.0.2' + + diff --git a/versioned_docs/version-2.6.1/developer/custom-result.md b/versioned_docs/version-2.6.1/developer/custom-result.md new file mode 100644 index 00000000000..8c8320e227e --- /dev/null +++ b/versioned_docs/version-2.6.1/developer/custom-result.md @@ -0,0 +1,115 @@ +--- +title: Custom Response +keywords: ["Custom Response"] +description: customising response structure +--- + +## Description + +* This doc offers examples for customising response structure in `Apache ShenYu` gateway. +* The response body structure in gateways should be unified, it is recommended for specify yours. + + +## Default Implementation + +* The default implementation class is `org.apache.shenyu.plugin.api.result.DefaultShenyuResult`. +* Following is the response structure: + +```java +public class ShenyuDefaultEntity implements Serializable { + + private static final long serialVersionUID = -2792556188993845048L; + + private Integer code; + + private String message; + + private Object data; + +} +``` + +* The returned `json` as follows: + +```json +{ + "code": -100, //response code, + "message": "Your parameter error, please check the relevant documentation!", //hint messages + "data": null // business data +} +``` + +## Extensions + +* Declare a new class named `CustomShenyuResult` and implements `org.apache.shenyu.plugin.api.result.ShenyuResult` + +```java +/** + * The interface shenyu result. + */ +public interface ShenyuResult { + + /** + * The response result. + * + * @param exchange the exchange + * @param formatted the formatted object + * @return the result object + */ + default Object result(ServerWebExchange exchange, Object formatted) { + return formatted; + } + + /** + * format the origin, default is json format. + * + * @param exchange the exchange + * @param origin the origin + * @return format origin + */ + default Object format(ServerWebExchange exchange, Object origin) { + // basic data + if (ObjectTypeUtils.isBasicType(origin)) { + return origin; + } + // error result or rpc origin result. + return JsonUtils.toJson(origin); + } + + /** + * the response context type, default is application/json. + * + * @param exchange the exchange + * @param formatted the formatted data that is origin data or byte[] convert string + * @return the context type + */ + default MediaType contentType(ServerWebExchange exchange, Object formatted) { + return MediaType.APPLICATION_JSON; + } + + /** + * Error t. + * + * @param code the code + * @param message the message + * @param object the object + * @return the t + */ + T error(int code, String message, Object object); +} +``` + +> Processing sequence: `format`->`contextType`->`result`. The `format` method performs data formatting. If the data is a basic type and returns itself, other types are converted to `JSON`, and the parameter `origin` is the original data. Formatting can be performed according to the situation. `contextType`, if it is a basic type, use `text/plain`, the default is `application/json`, the parameter `formatted` is the data processed by the `format` method, and can be combined with the return result of `format` for data type Define processing. The parameter `formatted` of `result` is the data processed by the `format` method, which returns to itself by default, and can be combined with the return result of `format` for custom processing of the data type. + +* `T` is a generic parameter for your response data. +* Register defined class as a `Spring Bean`. + +```java +@Bean +public ShenyuResult customShenyuResult() { + return new CustomShenyuResult(); +} +``` + + + diff --git a/versioned_docs/version-2.6.1/developer/custom-sign-algorithm.md b/versioned_docs/version-2.6.1/developer/custom-sign-algorithm.md new file mode 100644 index 00000000000..db231ad5c4e --- /dev/null +++ b/versioned_docs/version-2.6.1/developer/custom-sign-algorithm.md @@ -0,0 +1,58 @@ +--- +title: Custom Sign Algorithm +keywords: ["Custom Sign"] +description: specify sign plugins for examination +--- + +## Description + +* Users can customize the signature authentication algorithm to achieve verification. + +## Extension + +* The default implementation is `org.apache.shenyu.plugin.sign.service.ComposableSignService`. + + ```java + @Bean + @ConditionalOnMissingBean(value = SignService.class, search = SearchStrategy.ALL) + public SignService signService() { + return new ComposableSignService(new DefaultExtractor(), new DefaultSignProvider()); + } + ``` + + + +* Declare a new class named `CustomSignService` and implements `org.apache.shenyu.plugin.plugin.sign.service`. + +```java +public interface SignService { + + /** + * Gets verifyResult. + * @param exchange exchange + * @param requestBody requestBody + * @return result + */ + VerifyResult signatureVerify(ServerWebExchange exchange, String requestBody); + + /** + * Gets verifyResult. + * @param exchange exchange + * @return result + */ + VerifyResult signatureVerify(ServerWebExchange exchange); +} + + +``` + +* When returning is `isSuccess()` of VerifyResult, the sign verification passes. If there's false, the `getReason()` of VerifyResult will be return to the frontend to show. +* Register defined class as a Spring Bean. + +```java + @Bean + public SignService customSignService() { + return new CustomSignService(); + } +``` + diff --git a/versioned_docs/version-2.6.1/developer/developer-shenyu-client.md b/versioned_docs/version-2.6.1/developer/developer-shenyu-client.md new file mode 100644 index 00000000000..44346cb1152 --- /dev/null +++ b/versioned_docs/version-2.6.1/developer/developer-shenyu-client.md @@ -0,0 +1,185 @@ +--- +title: A multilingual HTTP client +keywords: ["Http Client"] +description: A multilingual HTTP client +--- + +## Description + +* This document focuses on how to access gateways for `HTTP` services in other languages. +* To access the gateway, you need to get the token first, and then you can call the registration service or metadata interface according to your needs. + + + +## Get token + +- **Request Method** + + `GET` + +- **Request Path** + - `http://{shenyu-admin}/platform/login` + - Where `shenyu-admin` is the `ip + port` of the `admin` backend management system. + + +- **Request Params** + + - `query` parameter, the account password is the username and password of the admin service. + + | Field | Type | Required | Desc | + | -------- | ------ | --------- | --------------------- | + | userName | String | Yes | shenyu admin account | + | password | String | Yes | shenyu admin password | + +- **Return Data** + + | Field | | Type | Desc | + | ------- | ----------- | ------- | ----------------------------- | + | code | | Integer | Return code | + | message | | String | Return message | + | data | | Object | Return data | + | | id | Integer | user id | + | | userName | String | account | + | | role | Integer | role id | + | | enabled | Boolean | status | + | | dateCreated | String | create time | + | | dateUpdated | String | update time | + | | token | String | token | + | | expiredTime | Long | timeout time, in milliseconds | + + **Example** + + ```json + { + "code": 200, + "message": "login dashboard user success", + "data": { + "id": "1", + "userName": "admin", + "role": 1, + "enabled": true, + "dateCreated": "2022-09-07 22:08:23", + "dateUpdated": "2022-09-07 22:08:23", + "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyTmFtZSI6ImFkbWluIiwiZXhwIjoxNjYyNjQ2MzU5fQ.WBXBgCcGsnnC00pRbDOtqCVoAaZr8MKH6WE6kY-NGaI", + "expiredTime": 86400000 + } + } + ``` + + + +## Registration Services + +- **Request Method** + + `POST` + +- **Request Path** + - `http://{shenyu-admin}/shenyu-client/register-uri` + - Where `shenyu-admin` is the `ip + port` of the `admin` backend management system. + + +* **Request Params** + + - `Header` + + - `contentType: application/json` + + - `X-Access-Token: {token}`,token is the token obtained by `Get token`. + + - `Body`,`json` format + + | Field | Type | Required | Desc | + | ----------- | ------- |--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| ------------------------------------------------------------ | + | protocol | String | Yes | protocol type | + | appName | String | Yes | app name | + | contextPath | String | Yes | service path | + | rpcType | String | Yes | rpc type, supported type reference [RpcTypeEnum](https://github.com/apache/shenyu/blob/master/shenyu-common/src/main/java/org/apache/shenyu/common/enums/RpcTypeEnum.java) | + | host | String | Yes | service IP | + | port | Integer | Yes | service port | + | eventType | String | Yes | event type, supported types reference [EventType](https://github.com/apache/shenyu/blob/master/shenyu-register-center/shenyu-register-common/src/main/java/org/apache/shenyu/register/common/enums/EventType.java) | + + **Example** + + ```json + { + "protocol": "http", + "appName": "app", + "contextPath": "/test", + "rpcType": "http", + "host": "127.0.0.1", + "port": "8080", + "eventType": "REGISTER" + } + ``` + +- **Return Data** + + A successful registration returns `success`. + +## Registration Metadata + +- **Request Method** + + `POST` + +- **Request Path** + + - `http://{shenyu-admin}/shenyu-client/register-metadata` + - Where `shenyu-admin` is the `ip + port` of the `admin` backend management system. + +- **Request Params** + + - `Header` + + - `contentType: application/json` + + - `X-Access-Token: {token}`,token is the token obtained by `Get token`. + + - `Body`,`json` format. + + | Field | Type | Required | Desc | + | ---------------- | ------- |----------------------------------------------------------------------------------------------------------------------------------------------------------------------------| ------------------------------------------------------------ | + | appName | String | Yes | app name | + | contextPath | String | Yes | service path | + | path | String | Yes | path | + | pathDesc | String | Yes | path description | + | rpcType | String | Yes | rpc type, supported type reference [RpcTypeEnum](https://github.com/apache/shenyu/blob/master/shenyu-common/src/main/java/org/apache/shenyu/common/enums/RpcTypeEnum.java) | + | serviceName | String | Yes | service name | + | methodName | String | Yes | method name | + | ruleName | String | Yes | rule name | + | parameterTypes | String | Yes | parameter Type | + | rpcExt | String | Yes | rpc expansion parameters | + | enabled | Boolean | No | status | + | host | String | Yes | service IP | + | port | Integer | Yes | service port | + | pluginNames | List | No | plugin name list | + | registerMetaData | Boolean | No | whether to register metadata | + + **examples** + + ```json + { + "appName": "app", + "contextPath": "/", + "path": "/test", + "rpcType": "http", + "serviceName": "test service", + "parameterTypes": "java.lang.String", + "pathDesc": "test path", + "methodName": "test method", + "ruleName": "test rule", + "rpcExt": "{\"loadbalance\":\"hash\",\"retries\":3,\"timeout\":-1}", + "enabled": true, + "host": "127.0.0.1", + "port": 8080, + "pluginNames": [], + "registerMetaData": true + } + ``` + +- **Return Data** + + A successful registration returns `success`. + + diff --git a/versioned_docs/version-2.6.1/developer/file-and-image.md b/versioned_docs/version-2.6.1/developer/file-and-image.md new file mode 100644 index 00000000000..123599f1e94 --- /dev/null +++ b/versioned_docs/version-2.6.1/developer/file-and-image.md @@ -0,0 +1,19 @@ +--- +title: File Upload And Download +keywords: ["File"] +description: file upload and download +--- + +## description + +* This doc gives a brief description for upload and download files using `Apache ShenYu`. + +## File Upload + +* The default file size limit is `10M`. +* For custom limitation, use`--file.size` with an integer variable. e.g.`--file.size = 30` +* Upload your files just as way you did before + +## File Download + +* `Apache ShenYu` supports download files in stream. There is no need to change anything. diff --git a/versioned_docs/version-2.6.1/developer/integration-test.md b/versioned_docs/version-2.6.1/developer/integration-test.md new file mode 100644 index 00000000000..13ccf2cf3b2 --- /dev/null +++ b/versioned_docs/version-2.6.1/developer/integration-test.md @@ -0,0 +1,38 @@ +--- +title: Run Integration Test Locally +description: Run Integration Test Locally +tags: ["integration test"] +--- + +### Preparation + +1. Clone the code of [Apache ShenYu](https://github.com/apache/shenyu). +2. Install and start docker. + +### Start integration test locally + +1. Build with Maven + +```shell +./mvnw -B clean install -Prelease,docker -Dmaven.javadoc.skip=true -Dmaven.test.skip=true +``` + +2. Build integrated tests + +```shell +./mvnw -B clean install -Pit -DskipTests -f ./shenyu-integrated-test/pom.xml +``` + +3. Start docker compose + +```shell +docker-compose -f ./shenyu-integrated-test/${{ matrix.case }}/docker-compose.yml up -d +``` + +> You need to replace `${{ matrix.case }}` with the exact directory, such as `shenyu-integrated-test-http`. + +4. Run test + +```shell +./mvnw test -Pit -f ./shenyu-integrated-test/${{ matrix.case }}/pom.xml +``` diff --git a/versioned_docs/version-2.6.1/developer/local-model.md b/versioned_docs/version-2.6.1/developer/local-model.md new file mode 100644 index 00000000000..2b313a193dd --- /dev/null +++ b/versioned_docs/version-2.6.1/developer/local-model.md @@ -0,0 +1,552 @@ +--- +title: Local Model +keywords: ["Local Model"] +description: Local Model +--- + +## Description + +* Standalone environment, then use the local `API` to update the apache shenyu gateway data.the yaml config: + +```yaml +shenyu: + local: + enabled: true + sha512Key: 123456 +``` + +* Common result: + +``` +success +``` + +* Common preFix: `localhost:9095/shenyu` + +* Common Header: `localKey: 123456` + +## Plugin + +### saveOrUpdate + +save or update plugin data + +##### Request Method + +POST + +##### Path + +/plugin/saveOrUpdate + +##### Request Parameters + +|Name|Type|Required|Default|Description| +|---|---|---|---|---| +|**PluginData**|[PluginData](#PluginData)|True| |Plugin data object (pass Json object inside Body)| + +#####
PluginData
+ +|Name|Type|Required|Default|Description| +|---|---|---|---|---| +|**id**|String|False| |plugin id| +|**name**|String|True| |plugin name| +|**config**|String|False| |plugin configuration (Json format)| +|**role**|String|False| |plugin role | +|**enabled**|Boolean|False| |whether to turn on| + +##### Example + +POST body + +``` +{"id":3,"name":"divide","enabled":"true"} + +``` + +### CleanAll + +Clear all data (plugins, selectors, rules) + +##### Request Method + +GET + +##### Path + +/cleanAll + +### Clean Plugin + +Clear plugin data(selector, rule) + +##### Request Method + +GET + +##### Path + +/cleanPlugin?name = xxxx + +##### RequestParam + +|Name|Type|Required|Default|Description| +|---|---|---|---|---| +|**name**|String|true| |plugin name | + +### Delete plugin + +Remove plugin data (not included, the selectors and rules data) + +##### Request Method + +GET + +##### Path + +/plugin/delete?name = xxxx + +##### RequestParam + +|Name|Type|Required|Default|Description| +|---|---|---|---|---| +|**name**|String|true| |plugin name | + +### Delete All Plugin + +Remove all plugin data (not included, the selectors and rules data) + +##### Request Method + +GET + +##### Path + +/plugin/deleteAll + +### Find plugin by name + +Find plugin by name + +##### Request Method + +GET + +##### Path + +/plugin/findByName?name=xxxx + +##### RequestParam + +|Name|Type|Required|Default|Description| +|---|---|---|---|---| +|**name**|String|true| |plugin name | + +### Save or Update Selector + +Save or Update Selector + +##### Request Method + +POST + +##### Path + +/plugin/selector/saveOrUpdate + +##### RequestParam + +|Name|Type|Required|Default|Description| +|---|---|---|---|---| +|**SelectorData**|[SelectorData](#SelectorData)|True| |Selector object (pass Json object inside Body)| + +#####
SelectorData
+ +|Name|Type|Required|Default|Description| +|---|---|---|---|---| +|**id**|String|False| |selector id| +|**pluginName**|String|True| |plugin name| +|**name**|String|False| |Selector name (default is plugin:selector+random number if not filled)| +|**matchMode**|Integer|False| |Matching mode (0:and;1:or), not filled with the default generation And mode| +|**type**|Integer|False| |Traffic type(0: full traffic; 1: custom traffic) do not fill in the default generation of full traffic| +|**sort**|Integer|False| |Sort by, not filled by default generate 10| +|**enabled**|Boolean|False| |Whether to turn on, not fill in the default generation true| +|**logged**|Boolean|False| |Whether or not to print the log, do not fill in the default generated into false| +|**handle**|String|False| |Selector handler (Json objects, depending on each plug-in, different objects are passed)| +|**conditionList**|[Condition](#Condition)|False| |Conditional collection, custom traffic needs to be passed, full traffic does not need to be passed (Json List object)| + +#####
Condition
+ +|Name|Type|Required|Default|Description| +|---|---|---|---|---| +|**paramType**|String|True| |param type(post,uri,query,host,header,cookie,req_method,domain)| +|**operator**|String|True| |operator (match,=,regex,>,<,contains,SpEL,Groovy,TimeBefore,TimeAfter)| +|**paramName**|String|False| |param mame(The uri parameter type can be passed without)| +|**paramValue**|Integer|False| |param value| + + +##### Example + +POST body + +``` +{ + "pluginName": "divide", + "type": 1, + "handle": "[{\"upstreamUrl\":\"127.0.0.1:8089\"}]", + "conditionDataList": [{ + "paramType": "uri", + "operator": "match", + "paramName": null, + "paramValue": "/**" + }] +} + +``` + +##### Result + +Is selector id + +``` +xxxxx +``` + +### Add Selector And Rules + +Add a selector with multiple rules + +##### Request Method + +POST + +##### Path + +/plugin/selectorAndRules + +##### RequestParam + +|Name|Type|Required|Default|Description| +|---|---|---|---|---| +|**SelectorRulesData**|[SelectorRulesData](#SelectorRulesData)|True| |Selector rule object (Body inside pass Json object)| + +#####
SelectorRulesData
+ +|Name|Type|Required|Default|Description| +|---|---|---|---|---| +|**pluginName**|String|True| |plugin name| +|**selectorName**|String|False| |Selector name (if not filled in, it is generated by default plugin:selector+random number)| +|**matchMode**|Integer|False| |Matching mode (0:and;1:or), not filled with the default generation And mode| +|**selectorHandler**|String|False| |Selector handler (Json objects, depending on each plug-in, different objects are passed)| +|**conditionList**|[ConditionData](#ConditionData)|True| |Selector condition collection (Json List object)| +|**ruleDataList**|[RuleLocalData](#RuleLocalData)|True| |Rule condition collection (Json List object)| + +#####
RuleLocalData
+ +|Name|Type|Required|Default|Description| +|---|---|---|---|---| +|**ruleName**|String|False| |rule name| +|**ruleHandler**|String|True| |Rule handler (different plugins pass different values))| +|**matchMode**|Integer|False| |Matching pattern (0:and;1:or)| +|**conditionList**|[ConditionData](#ConditionData)|True| |Rule condition collection (Json List object)| + +#####
ConditionData
+ +|Name|Type|Required|Default|Description| +|---|---|---|---|---| +|**paramType**|String|True| |param type(post,uri,query,host,header,cookie,req_method,domain)| +|**operator**|String|True| |operator (match,=,regex,>,<,contains,SpEL,Groovy,TimeBefore,TimeAfter)| +|**paramName**|String|False| |param mame(The uri parameter type can be passed without)| +|**paramValue**|Integer|False| |param value| + +##### Example + +POST body + +``` +{ + "pluginName": "divide", + "selectorHandler": "[{\"upstreamUrl\":\"127.0.0.1:8089\"}]", + "conditionDataList": [{ + "paramType": "uri", + "operator": "match", + "paramValue": "/http/**" + }], + "ruleDataList": [{ + "ruleHandler": "{\"loadBalance\":\"random\"}", + "conditionDataList": [{ + "paramType": "uri", + "operator": "=", + "paramValue": "/http/test/payment" + }] + }, { + "ruleHandler": "{\"loadBalance\":\"random\"}", + "conditionDataList": [{ + "paramType": "uri", + "operator": "=", + "paramValue": "/http/order/save" + }] + }] +} + +``` + +### Delete Selector + +Delete selectors based on selector id and plugin name + +##### Request Method + +GET + +##### Path + +/plugin/selector/delete?pluginName=xxxx&&id=xxxx + +##### RequestParam + +|Name|Type|Required|Default|Description| +|---|---|---|---|---| +|**pluginName**|String|true| |plugin name | +|**id**|String|true| |selector id | + +### Find All Selector + +Get all selectors by plugin name + +##### Request Method + +GET + +##### Path + +/plugin/selector/findList?pluginName=xxxx + +##### RequestParam + +|Name|Type|Required|Default|Description| +|---|---|---|---|---| +|**pluginName**|String|true| |plugin name | + +### Save or Update Rule Data + +Save or Update Rule Data + +##### Request Method + +POST + +##### Path + +/plugin/rule/saveOrUpdate + +##### RequestParam + +|Name|Type|Required|Default|Description| +|---|---|---|---|---| +|**RuleData**|[RuleData](#RuleData)|True| |Rule object (pass Json object inside Body)| + +#####
RuleData
+ +|Name|Type|Required|Default|Description| +|---|---|---|---|---| +|**id**|String|False| |rule id| +|**pluginName**|String|True| |plugin name| +|**name**|String|False| |Rule name (default generation if not filled plugin:rule+random number)| +|**selectorId**|String|True| |Selector id| +|**matchMode**|Integer|False| |Matching mode (0:and;1:or), not filled with the default generation And mode| +|**sort**|Integer|False| |Sort by , not filled by default generate 10| +|**enabled**|Boolean|False| |Whether to turn on, not fill in the default generation true| +|**logged**|Boolean|False| |Whether or not to print the log, do not fill in the default generated into false| +|**handle**|String|False| |Rule handler (Json objects, depending on each plug-in, different objects are passed)| +|**conditionList**|[ConditionData](#ConditionData)|False| |Conditional collections (Json List objects)| + +#####
conditionList
+ +|Name|Type|Required|Default|Description| +|---|---|---|---|---| +|**paramType**|String|True| |param type(post,uri,query,host,header,cookie,req_method,domain)| +|**operator**|String|True| |operator (match,=,regex,>,<,contains,SpEL,Groovy,TimeBefore,TimeAfter)| +|**paramName**|String|False| |param mame(The uri parameter type can be passed without)| +|**paramValue**|Integer|False| |param value| + +##### Example + +POST body + +``` +{ + "pluginName": "divide", + "selectorId": 123456, + "handle": "{\"loadBalance\":\"random\"}", + "conditionDataList": [{ + "paramType": "uri", + "operator": "=", + "paramValue": "/test" + }] +} + +``` + +##### Result + +Is rule id + +``` +xxxxx +``` + +### Delete rule data + +Delete rules based on selector id and rule id + +##### Request Method + +GET + +##### Path + +/plugin/rule/delete?selectorId=xxxx&&id=xxxx + +##### RequestParam + +|Name|Type|Required|Default|Description| +|---|---|---|---|---| +|**selectorId**|String|true| |selector ID | +|**id**|String|true| |rule ID | + +### Find Rule data List + +Get all rules by selector ID + +##### Request Method + +GET + +##### Path + +/plugin/rule/findList?selectorId=xxxx + +##### RequestParam + +|Name|Type|Required|Default|Description| +|---|---|---|---|---| +|**selectorId**|String|true| |selector id | + +## Meta data + +### Save Or Update + +Save Or Update Meta data + +##### Request Method + +POST + +##### Path + +/meta/saveOrUpdate + +##### RequestParam + +|Name|Type|Required|Default|Description| +|---|---|---|---|---| +|**MetaData**|[MetaData](#MetaData)|True| |Metadata object (pass Json object inside Body)| + +#####
MetaData
+ +|Name|Type|Required|Default|Description| +|---|---|---|---|---| +|**id**|String|False| |ID| +|**appName**|String|True| |app name| +|**contextPath**|String|True| |contextPath| +|**path**|String|True| |path| +|**rpcType**|String|True| |rpc type(dubbo,sofa,tars,springCloud,motan,grpc)| +|**serviceName**|String|True| |service name| +|**methodName**|String|True| |method name| +|**parameterTypes**|String|True| |parameter types| +|**rpcExt**|String|False| |rpc extension parameters (json objects)| +|**enabled**|Boolean|False| |Whether to turn on| + +### Delete + +Delete Meta data + +##### Request Method + +GET + +##### Path + +/meta/delete?rpcType=xxxx&&path=xxx + +##### RequestParam + +|Name|Type|Required|Default|Description| +|---|---|---|---|---| +|**rpcType**|String|true| |rpc type(dubbo,sofa,tars,springCloud,motan,grpc) | +|**path**|String|true| |path | + +## App Sign Data + +### Save Or Update + +Save Or Update App Sign Data + +##### Request Method + +POST + +##### Path + +/auth/saveOrUpdate + +##### RequestParam + +|Name|Type|Required|Default|Description| +|---|---|---|---|---| +|**AppAuthData**|[AppAuthData](#AppAuthData)|True| |Signature object (Json object passed inside the Body)| + +#####
AppAuthData
+ +|Name|Type|Required|Default|Description| +|---|---|---|---|---| +|**appKey**|String|True| |app key| +|**appSecret**|String|True| |app secret| +|**enabled**|Boolean|False| |Whether to turn on| +|**open**|Boolean|False| |is open| +|**paramDataList**|[AuthParamData](#AuthParamData)|false| |Parameter set, open is true when you need to pass (Json list object)| +|**AuthPathData**|[AuthPathData](#AuthPathData)|false| |Path collection, open is true when you need to pass (Json list object)| + +#####
AuthParamData
+ +|Name|Type|Required|Default|Description| +|---|---|---|---|---| +|**appName**|String|True| |app name| +|**appParam**|String|True| |app param| + +#####
AuthPathData
+ +|Name|Type|Required|Default|Description| +|---|---|---|---|---| +|**appName**|String|True| |app name| +|**path**|String|True| |path| +|**enabled**|Boolean|False| |Whether to turn on| + +### Delete + +Delete App Sign Data + +##### Request Method + +GET + +##### Path + +/auth/delete?appKey=xxxx + +##### RequestParam + +|Name|Type|Required|Default|Description| +|---|---|---|---|---| +|**appKey**|String|true| |app key | diff --git a/versioned_docs/version-2.6.1/developer/notice-alert.md b/versioned_docs/version-2.6.1/developer/notice-alert.md new file mode 100644 index 00000000000..500b8ed7ec5 --- /dev/null +++ b/versioned_docs/version-2.6.1/developer/notice-alert.md @@ -0,0 +1,83 @@ +--- +title: Alarm Notice +keywords: ["alarm"] +description: Alarm message dispatch and notice +--- + +## Description + +* This doc gives a brief description for send alarm notice message using `Apache ShenYu API`. + +## Enable Alert in ShenYu Gateway + +* Config the gateway `application.yml` + +```yaml +shenyu: + alert: + enabled: true + # the shenyu admin servers, if admin cluster, config like 127.0.0.1:9095,192.3.4.2:9095 + admins: localhost:9095 +``` + +## Send Alarm Message + +* We can send custom alarm message in plugin using `AlarmSender.alarm()` + +Refer below: + +```java +public class ParamMappingPlugin extends AbstractShenyuPlugin { + + @Override + public Mono doExecute(final ServerWebExchange exchange, final ShenyuPluginChain chain, final SelectorData selector, final RuleData rule) { + ParamMappingRuleHandle paramMappingRuleHandle = ParamMappingPluginDataHandler.CACHED_HANDLE.get().obtainHandle(CacheKeyUtils.INST.getKey(rule)); + + if(some condition) { + Map labels = new HashMap<>(8); + labels.put("plugin", "http-redirect"); + labels.put("component", "http"); + AlarmSender.alarmHighEmergency("alarm-title", "alarm-content", labels); + AlarmSender.alarmMediumCritical("alarm-title", "alarm-content", labels); + AlarmSender.alarmLowWarning("alarm-title", "alarm-content", labels); + AlarmSender.alarm((byte) 0, "alarm-title", "alarm-content"); + } + + HttpHeaders headers = exchange.getRequest().getHeaders(); + MediaType contentType = headers.getContentType(); + return match(contentType).apply(exchange, chain, paramMappingRuleHandle); + } +} +``` + +## Dispatch Alarm Notice + +* In the previous step, we send custom alarm message in plugin. +* Now we configure how these messages are sent to whom(tom,lili...) by which type(email,DingDing...) +* Config this in ShenYu Admin Dashboard. + +![alarm-config](/img/shenyu/alert/alarm-config.png) + +Have fun! + +## Attention + +1. If you use the email notice, you should config your email send server in ShenYu Admin `application.yml` + +```yaml +spring: + mail: + # Attention: this is mail server address. + host: smtp.qq.com + username: shenyu@apache.com + # Attention: this is not email account password, this requires an email authorization code + password: your-password + port: 465 + default-encoding: UTF-8 + properties: + mail: + smtp: + socketFactoryClass: javax.net.ssl.SSLSocketFactory + ssl: + enable: true +``` diff --git a/versioned_docs/version-2.6.1/developer/shenyu-optimize.md b/versioned_docs/version-2.6.1/developer/shenyu-optimize.md new file mode 100644 index 00000000000..0c35a713ef6 --- /dev/null +++ b/versioned_docs/version-2.6.1/developer/shenyu-optimize.md @@ -0,0 +1,44 @@ +--- +title: ShenYu Optimize +keywords: ["Optimize"] +description: performance optimization for Apache ShenYu +--- + +## Description + +* This doc shows how to do performance optimization for Apache ShenYu. + +## Time Consumption + +* Apache ShenYu is JVM driven and processing time for a single request is nearly between `1-3` ms. + +## Netty Optimization + +* `spring-webflux` is one of dependencies of ShenYu, and it uses Netty in lower layer. +* The demo down below demonstrates tuning ShenYu by customizing params in Netty. + +```java +@Bean + public NettyReactiveWebServerFactory nettyReactiveWebServerFactory() { + NettyReactiveWebServerFactory webServerFactory = new NettyReactiveWebServerFactory(); + webServerFactory.addServerCustomizers(new EventLoopNettyCustomizer()); + return webServerFactory; + } + +private static class EventLoopNettyCustomizer implements NettyServerCustomizer { + + @Override + public HttpServer apply(final HttpServer httpServer) { + return httpServer + .tcpConfiguration(tcpServer -> tcpServer + .runOn(LoopResources.create("shenyu-netty", 1, DEFAULT_IO_WORKER_COUNT, true), false) + .selectorOption(ChannelOption.SO_REUSEADDR, true) + .selectorOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) + .option(ChannelOption.TCP_NODELAY, true) + .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)); + } +} +``` + +* The `shenyu-bootstrap` module offers this class, you may modify it when benchmarking your app if necessary. +* You can get references of business thread model from [thread model](./thread-model) diff --git a/versioned_docs/version-2.6.1/developer/spi/_category_.json b/versioned_docs/version-2.6.1/developer/spi/_category_.json new file mode 100644 index 00000000000..149cee92bf3 --- /dev/null +++ b/versioned_docs/version-2.6.1/developer/spi/_category_.json @@ -0,0 +1,4 @@ +{ + "label": "SPI", + "position": 1 +} diff --git a/versioned_docs/version-2.6.1/developer/spi/custom-load-balance.md b/versioned_docs/version-2.6.1/developer/spi/custom-load-balance.md new file mode 100644 index 00000000000..f4ea3ecb2b8 --- /dev/null +++ b/versioned_docs/version-2.6.1/developer/spi/custom-load-balance.md @@ -0,0 +1,65 @@ +--- +title: Custom Load Balancer +keywords: ["LoadBalance"] +description: Custom Load Balance +--- + +* This paper describes how to customize the extension of `org.apache.shenyu.loadbalancer.spi.LoadBalancer`. + +* Create a new project and introduce the following dependencies: + +```xml + + + org.apache.shenyu + shenyu-plugin-base + ${project.version} + + +``` + +* Create a new class `CustomLoadBalancer`, extends `org.apache.shenyu.loadbalancer.spi.AbstractLoadBalancer`. + +```java +public class CustomLoadBalancer extends AbstractLoadBalancer { + + @Override + public Upstream doSelect(final List upstreamList, final String ip) { + // custom load balancer + } +} +``` + +* In the project's META-INF/services directory, create key-value as following in `org.apache.shenyu.loadbalancer.spi.LoadBalancer` file. + +```shell title="script" +${spi name}=${custom class path} +``` + +`${spi name}` represents the name of `spi` and `${custom class path}` represents the fully qualified name of the class. Such as: + +```shell title="script" +custom=xxx.xxx.xxx.CustomLoadBalancer +``` + +* Package the project and copy it to the `lib` or `ext-lib` directory of the gateway (bootstrap-bin). + +* In the `Apache ShenYu` gateway management system --> BasicConfig --> Dictionary, find the dictionary code as `LOAD_BALANCE`, add a new piece of data, pay attention to the dictionary name: `${spi name}`. + + + +> DictionaryType: `loadBalance`; +> +> DictionaryCode: `LOAD_BALANCE`; +> +> DictionaryName: `${spi name}`, input your custom spi name; +> +> DictionaryValue: When used, the value of the drop-down box, do not repeat with the existing; +> +> DictionaryDescribe: desc your custom match strategy; +> +> Sort: to sort; + +* When adding selectors or rules, you can use custom MatchType: + + diff --git a/versioned_docs/version-2.6.1/developer/spi/custom-match-mode.md b/versioned_docs/version-2.6.1/developer/spi/custom-match-mode.md new file mode 100644 index 00000000000..3539e3e54ff --- /dev/null +++ b/versioned_docs/version-2.6.1/developer/spi/custom-match-mode.md @@ -0,0 +1,72 @@ +--- +title: Custom Match Mode +keywords: ["MatchStrategy"] +description: custom match mode +--- + + +* This paper describes how to customize the extension of `org.apache.shenyu.plugin.base.condition.strategy.MatchStrategy`. + +* Create a new project and introduce the following dependencies: + +```xml + + + org.apache.shenyu + shenyu-plugin-base + ${project.version} + + +``` + +* Create a new class `CustomMatchStrategy`, extends `org.apache.shenyu.plugin.base.condition.strategy.AbstractMatchStrategy`, implements `org.apache.shenyu.plugin.base.condition.strategy.MatchStrategy`, add annotation `org.apache.shenyu.spi.Join`. + +```java +/** + * This is custom match strategy. + */ +@Join +public class CustomMatchStrategy extends AbstractMatchStrategy implements MatchStrategy { + + @Override + public Boolean match(final List conditionDataList, final ServerWebExchange exchange) { + // custom match strategy + } +} +``` + +* In the project's META-INF/services directory, create `org.apache.shenyu.plugin.base.condition.strategy.MatchStrategy` file. + +```shell title="script" +${spi name} = ${custom class path} +``` + +`${spi name}` represents the name of `spi` and `${custom class path}` represents the fully qualified name of the class. Such as: + +```shell title="script" +custom = xxx.xxx.xxx.CustomMatchStrategy +``` + +* Package the project and copy it to the `lib` or `ext-lib` directory of the gateway (bootstrap-bin). + +* In the `Apache ShenYu` gateway management system --> BasicConfig --> Dictionary, find the dictionary code as `MATCH_MODE`, add a new piece of data, pay attention to the dictionary name: `${spi name}`. + + + +> DictionaryType: `matchMode`; +> +> DictionaryCode: `MATCH_MODE`; +> +> DictionaryName: `${spi name}`, input your custom spi name; +> +> DictionaryValue: When used, the value of the drop-down box, do not repeat with the existing; +> +> DictionaryDescribe: desc your custom match strategy; +> +> Sort: to sort; +> +> Status: open or close. + +* When adding selectors or rules, you can use custom MatchType: + + diff --git a/versioned_docs/version-2.6.1/developer/spi/custom-metrics-monitor.md b/versioned_docs/version-2.6.1/developer/spi/custom-metrics-monitor.md new file mode 100644 index 00000000000..c8bf88e78c4 --- /dev/null +++ b/versioned_docs/version-2.6.1/developer/spi/custom-metrics-monitor.md @@ -0,0 +1,63 @@ +--- +title: Custom Metrics Monitor +keywords: ["MetricsMonitor"] +description: custom Metrics Monitor +--- + + +## Explanation + +* Before custom development, please customize and build the gateway environment first, please refer to: [custom deployment](../deployment-custom) + +* This article describes how to customize the extension of `org.apache.shenyu.plugin.metrics.spi.MetricsService`. + +## Extension + +* Create a new project and introduce the following dependencies: + +```xml + + + org.apache.shenyu + shenyu-plugin-base + ${project.version} + + +``` + +* Create a new class `${you class}`,implements `org.apache.shenyu.plugin.metrics.spi.MetricsService` + +``` +public class ${you class} implements MetricsService { + + /** + * Start metrics tracker. + * + * @param metricsConfig metrics config + * @param metricsRegister the metrics register + */ + public void start(MetricsConfig metricsConfig, MetricsRegister metricsRegister){ + //your code + } + + /** + * Stop metrics tracker. + */ + public void stop() { + //your code + } +} +``` + +* In the project `resources` directory,Create a new `META-INF/shenyu` directory, and the new file name is : `org.apache.shenyu.plugin.metrics.spi.MetricsService`. +add `${you spi name}` = `${you class path}`: + +``` +${you spi name} = ${you class path} +``` + +* Package the project and copy it to the `lib` or `ext-lib` directory of the gateway (bootstrap-bin). + +* In the `Admin` service ---> BasicConfig ---> Plugin , Find the `Monitor` plugin, edit config, pay attention to the `metricsName` name: `${you spi name}`. + + diff --git a/versioned_docs/version-2.6.1/developer/spi/custom-mock-generator.md b/versioned_docs/version-2.6.1/developer/spi/custom-mock-generator.md new file mode 100644 index 00000000000..618fb42b5ea --- /dev/null +++ b/versioned_docs/version-2.6.1/developer/spi/custom-mock-generator.md @@ -0,0 +1,77 @@ +--- +title: Custom Mock Data Generator +keywords: ["Mock"] +description: custom mock data generator +--- +## Explanation + +1. This article describes how to make custom extensions to `org.apache.shenyu.plugin.mock.generator.Generator`. +2. The mock data generation expression needs to satisfy the format of `${name|param1|param2|...}` + +## Extension + +* Create a new project and introduce the following dependencies: + +```xml + + + org.apache.shenyu + shenyu-plugin-mock + ${project.version} + + +``` + +* Create a new class `CustomerGenerator`,implements `org.apache.shenyu.plugin.mock.generator.Generator`。 + +```java +@Join +public class CustomGenerator implements Generator { + @Override + public String getName() { + // The name of the generator, i.e. the content before the first | of the expression + } + + @Override + public String generate() { + // Implement the logic of data generation + } + + @Override + public int getParamSize() { + // The number of required parameters of the expression + } + + @Override + public void initParam(List params, String rule) { + // params is the contents except the name after the expression is split according to | + // rule is the content of the original expression , if there is a custom parameter processing logic, you can use this parameter + } + + @Override + public boolean match(String rule) { + // Check if the current expression is valid + } + + @Override + public String[] getPrefixAndSuffix() { + // Return the prefix and suffix added after the generated content, please return a string array with two elements + // 0th element is the prefix, 1st element is the suffix + } +} +``` + +* In the project `resources` directory,Create a new `META-INF/shenyu` directory, and the new file name is : `org.apache.shenyu.plugin.mock.generator.Generator`. + add `${you spi name}` = `${you class path}`: + +```shell title="script" +${spi name}=${custom class path} +``` + +`${spi name}` represents the name of `spi`, `${spi name }` needs to be consistent with the definition of the getName() method in the Generator implementation class, `${custom class path}` represents the fully qualified name of the class. for example: + +```shell title="script" +custom=xxx.xxx.xxx.CustomGenerator +``` + +* Package the project and copy it to the `lib` or `ext-lib` directory of the gateway (bootstrap-bin). diff --git a/versioned_docs/version-2.6.1/developer/spi/custom-parameter-data.md b/versioned_docs/version-2.6.1/developer/spi/custom-parameter-data.md new file mode 100644 index 00000000000..bff80ece761 --- /dev/null +++ b/versioned_docs/version-2.6.1/developer/spi/custom-parameter-data.md @@ -0,0 +1,71 @@ +--- +title: Custom Parameter Data +keywords: ["ParameterData"] +description: Custom Parameter Data +--- + +This paper describes how to customize the extension of `org.apache.shenyu.plugin.base.condition.data.ParameterData`. + +* Create a new project and introduce the following dependencies: + +```xml + + + org.apache.shenyu + shenyu-plugin-base + ${project.version} + + +``` + +* Create a new class `CustomParameterData`, implements `org.apache.shenyu.plugin.base.condition.data.ParameterData`, add annotation `org.apache.shenyu.spi.Join`. + +```java +/** + * This is custom parameter data. + */ +@Join +public class CustomParameterData implements ParameterData { + + @Override + public String builder(final String paramName, final ServerWebExchange exchange) { + // custom parameter data + } +} +``` + +* In the project's META-INF/services directory, create `org.apache.shenyu.plugin.base.condition.data.ParameterData` file, add key-value as following: + +```shell title="script" +${spi name} = ${custom class path} +``` + +`${spi name}` represents the name of `spi` and `${custom class path}` represents the fully qualified name of the class. Such as: + +```shell title="script" +custom=xxx.xxx.xxx.CustomParameterData +``` + +* Package the project and copy it to the `lib` or `ext-lib` directory of the gateway (bootstrap-bin). + +* In the `Apache ShenYu` gateway management system --> BasicConfig --> Dictionary, find the dictionary code as `PARAM_TYPE`, add a new piece of data, pay attention to the dictionary name: `${spi name}`. + + + +> DictionaryType: `paramType`; +> +> DictionaryCode: `PARAM_TYPE`; +> +> DictionaryName: `${spi name}`, input your custom spi name; +> +> DictionaryValue: When used, the value of the drop-down box, do not repeat with the existing; +> +> DictionaryDescribe: desc your custom match strategy; +> +> Sort: to sort; +> +> Status: open or close. + +* When adding selectors or rules, you can use custom parameter data: + + diff --git a/versioned_docs/version-2.6.1/developer/spi/custom-predicate-judge.md b/versioned_docs/version-2.6.1/developer/spi/custom-predicate-judge.md new file mode 100644 index 00000000000..6b1640d5b89 --- /dev/null +++ b/versioned_docs/version-2.6.1/developer/spi/custom-predicate-judge.md @@ -0,0 +1,121 @@ +--- +title: Custom Predicate Judge +keywords: ["PredicateJudge"] +description: Custom Predicate Judge +--- + +## Introduction + +* This paper describes how to customize the extension of `org.apache.shenyu.plugin.base.condition.judge.PredicateJudge`. +* The conditional predicate is the bridge between data and rules in the selector and serves to filter out requests that match the conditions. +* There are already seven conditional predicates including match, =, regex, contains, TimeBefore, TimeAfter, exclude. +* Please refer to [judge](https://github.com/apache/shenyu/tree/master/shenyu-plugin/shenyu-plugin-base/src/main/java/org/apache/shenyu/plugin/base/condition/judge) module, add your own conditional predicates, or submit `pr` to the official website if you have a good common plugin. + +## Extension + +* Create a new project and introduce the following dependencies: + +```xml + + + org.apache.shenyu + shenyu-plugin-base + ${project.version} + + +``` + +* Create a new class `CustomPredicateJudge`, implements `org.apache.shenyu.plugin.base.condition.judge.PredicateJudge`, add annotation `org.apache.shenyu.spi.Join`. + +```java +/** + * custom predicate judge. + */ +@Join +public class CustomPredicateJudge implements PredicateJudge { + + @Override + public Boolean judge(final ConditionData conditionData, final String realData) { + // Custom Predicate Judge + } +} + +``` + +* In the project's META-INF/services directory, create `org.apache.shenyu.plugin.base.condition.judge.PredicateJudge` file, add key-value as following: + +```shell title="script" +${spi name} = ${custom class path} +``` + +`${spi name}` represents the name of `spi` and `${custom class path}` represents the fully qualified name of the class. Such as: + +```shell title="script" +custom=xxx.xxx.xxx.CustomPredicateJudge +``` + +* Package the project and copy it to the `lib` or `ext-lib` directory of the gateway (bootstrap-bin). + +* In the `Apache ShenYu` gateway management system --> BasicConfig --> Dictionary, find the dictionary code as `OPERATOR`, add a new piece of data, pay attention to the dictionary name: `${spi name}`. + + + +> DictionaryType: `operator`; +> +> DictionaryCode: `OPERATOR`; +> +> DictionaryName: `${spi name}`, input your custom spi name; +> +> DictionaryValue: When used, the value of the drop-down box, do not repeat with the existing; +> +> DictionaryDescribe: desc your custom match strategy; +> +> Sort: to sort; +> +> Status: open or close. + +* When adding selectors or rules, you can use custom predicate judge: + + + +## Example + +* Add `GroovyPredicateJudge` and `SpELPredicateJudge` extension. + +```java +/** + * Groovy predicate judge. + */ +@Join +public class GroovyPredicateJudge implements PredicateJudge { + + @Override + public Boolean judge(final ConditionData conditionData, final String realData) { + return (Boolean) Eval.me(conditionData.getParamName(), realData, conditionData.getParamValue()); + } +} +``` + +```java +/** + * SpEL predicate judge. + */ +@Join +public class SpELPredicateJudge implements PredicateJudge { + + private static final ExpressionParser EXPRESSION_PARSER = new SpelExpressionParser(); + + @Override + public Boolean judge(final ConditionData conditionData, final String realData) { + Expression expression = EXPRESSION_PARSER.parseExpression(conditionData.getParamValue().replace('#' + conditionData.getParamName(), realData)); + return expression.getValue(Boolean.class); + } +} +``` + +* Update `org.apache.shenyu.plugin.base.condition.judge.PredicateJudge`: + +```shell title="script" +Groovy=xxx.xxx.xxx.GroovyPredicateJudge +SpEL=xxx.xxx.xxx.SpELPredicateJudge +``` diff --git a/versioned_docs/version-2.6.1/developer/spi/custom-rate-limiter.md b/versioned_docs/version-2.6.1/developer/spi/custom-rate-limiter.md new file mode 100644 index 00000000000..4d2bebdbc65 --- /dev/null +++ b/versioned_docs/version-2.6.1/developer/spi/custom-rate-limiter.md @@ -0,0 +1,104 @@ +--- +title: Custom Rate Limiter +keywords: ["RateLimiter"] +description: Custom Rate Limiter +--- + +## Explanation + +* Before custom development, please customize and build the gateway environment first, please refer to: [custom deployment](../deployment-custom). + +* This article describes how to customize the extension of `org.apache.shenyu.plugin.ratelimiter.algorithm.RateLimiterAlgorithm` . + +## Extension + +* Create a new project and introduce the following dependencies: + +```xml + + + org.apache.shenyu + shenyu-plugin-base + ${project.version} + + +``` + +* Create a new class `${you class}`, implements `org.apache.shenyu.plugin.ratelimiter.algorithm.RateLimiterAlgorithm` + +```java +public class ${you class} implements RateLimiterAlgorithm { + + /** + * Gets script. + * + * @return the script + */ + public RedisScript getScript() { + //coding and return + } + + /** + * Gets keys. + * + * @param id the id + * @return the keys + */ + public List getKeys(String id) { + //coding and return + } + + /** + * Callback string. + * + * @param script the script + * @param keys the keys + * @param scriptArgs the script args + */ + public void callback(final RedisScript script, final List keys, final List scriptArgs) { + //coding and return + } +} +``` + +* In the project `resources` directory,Create a new `META-INF/shenyu` directory, and the new file name is : `org.apache.shenyu.plugin.ratelimiter.algorithm.RateLimiterAlgorithm`. +add `${you spi name}` = `${you class path}`: + +``` +${you spi name} = ${you class path} +``` + +* Package the project and copy it to the `lib` or `ext-lib` directory of the gateway (bootstrap-bin). + +* In the `Admin` service ---> BasicConfig ---> Dictionary , Find the dictionary code as `ALGORITHM_*`, add a new piece of data, pay attention to the dictionary name: `${you spi name}`. + + + +* Or execute the following custom `SQL` statement: + +```sql +INSERT IGNORE INTO `shenyu_dict` ( + `id`, + `type`, + `dict_code`, + `dict_name`, + `dict_value`, + `desc`, + `sort`, + `enabled`, + `date_created`, + `date_updated` + ) +VALUES ( + 'you id', + 'matchMode', + 'MATCH_MODE', + 'you spi name', + 'you value', + 'you spi name', + 0, + 1, + '2021-08-30 19:29:10', + '2021-08-30 20:15:23' + ); +``` diff --git a/versioned_docs/version-2.6.1/developer/thread-model.md b/versioned_docs/version-2.6.1/developer/thread-model.md new file mode 100644 index 00000000000..cee61af2ec3 --- /dev/null +++ b/versioned_docs/version-2.6.1/developer/thread-model.md @@ -0,0 +1,30 @@ +--- +title: Thread Model +keywords: ["Thread"] +description: thread model +--- + +## Description + +* This article gives an introduction to thread models in ShenYu and usage in various scenarios. + +## IO And Work Thread + +* `spring-webflux` is one of dependencies of ShenYu, and it uses Netty thread model in lower layer. + +## Business Thread + +* Use scheduling thread to execute by default. +* A fixed thread pool manages business threads, the number of threads is count in this formula: cpu * 2 + 1. + + +## Type Switching + +* `reactor.core.scheduler.Schedulers`. +* `-Dshenyu.scheduler.type=fixed` is a default config. If set to other value, a flexible thread pool will take place it.`Schedulers.elastic()`. +* `-Dshenyu.work.threads = xx` is for configuring number of threads, the default value calculates in following formula `cpu * 2 + 1` with a minimum of 16 threads. + + + + + diff --git a/versioned_docs/version-2.6.1/index.md b/versioned_docs/version-2.6.1/index.md new file mode 100644 index 00000000000..6ed8b63106b --- /dev/null +++ b/versioned_docs/version-2.6.1/index.md @@ -0,0 +1,179 @@ +--- +sidebar_position: 1 +title: Overview +keywords: ["Apache shenyu"] +description: This is an asynchronous, high-performance, cross-language, responsive API gateway. +aliases: "/shenyu/docs/Home" +--- + +# Architecture + + ![](/img/architecture/shenyu-architecture-3d.png) + +# What is the Apache ShenYu? + +This is an asynchronous, high-performance, cross-language, responsive API gateway. + +# Why named Apache ShenYu + +ShenYu (神禹) is the honorific name of Chinese ancient monarch Xia Yu (also known in later times as Da Yu), who left behind the touching story of the three times he crossed the Yellow River for the benefit of the people and successfully managed the flooding of the river. He is known as one of the three greatest kings of ancient China, along with Yao and Shun. + +* Firstly, the name ShenYu is to promote the traditional virtues of our Chinese civilisation. +* Secondly, the most important thing about the gateway is the governance of the traffic. +* Finally, the community will do things in a fair, just, open and meritocratic way, paying tribute to ShenYu while also conforming to the Apache Way. + +--- + +# Features + +* Proxy: Support for Apache® Dubbo™, Spring Cloud, gRPC, Motan, SOFA, TARS, WebSocket, MQTT +* Security: Sign, OAuth 2.0, JSON Web Tokens, WAF plugin +* API governance: Request, response, parameter mapping, Hystrix, RateLimiter plugin +* Observability: Tracing, metrics, logging plugin +* Dashboard: Dynamic traffic control, visual backend for user menu permissions +* Extensions: Plugin hot-swapping, dynamic loading +* Cluster: NGINX, Docker, Kubernetes +* Language: provides .NET, Python, Go, Java client for API register + +--- + +# Mind map + + ![](/img/shenyu/activite/shenyu-xmind.png) + + --- + +# Quick Start (docker) + +### Run Apache ShenYu Admin + +``` +docker pull apache/shenyu-admin +docker network create shenyu +docker run -d -p 9095:9095 --net shenyu apache/shenyu-admin +``` + +Default account: **admin** + +Default password: **123456** + +### Run Apache ShenYu Bootstrap + +``` +docker pull apache/shenyu-bootstrap +docker run -d -p 9195:9195 -e "shenyu.local.enabled=true" --net shenyu apache/shenyu-bootstrap +``` + +### Set router + +* Real requests :, + +```json +{ + "name" : "Shenyu", + "data" : "hello world" +} +``` + +* Set routing rules (Standalone) + +Add `localKey: 123456` to Headers. If you need to customize the localKey, you can use the sha512 tool to generate the key based on plaintext and update the `shenyu.local.sha512Key` property. + +``` +curl --location --request POST 'http://localhost:9195/shenyu/plugin/selectorAndRules' \ +--header 'Content-Type: application/json' \ +--header 'localKey: 123456' \ +--data-raw '{ + "pluginName": "divide", + "selectorHandler": "[{\"upstreamUrl\":\"127.0.0.1:8080\"}]", + "conditionDataList": [{ + "paramType": "uri", + "operator": "match", + "paramValue": "/**" + }], + "ruleDataList": [{ + "ruleHandler": "{\"loadBalance\":\"random\"}", + "conditionDataList": [{ + "paramType": "uri", + "operator": "match", + "paramValue": "/**" + }] + }] +}' +``` + +* Proxy request : + +```json +{ + "name" : "Shenyu", + "data" : "hello world" +} +``` + +--- + +# Plugin + + Whenever a request comes in, Apache ShenYu will execute it by all enabled plugins through the chain of responsibility. + + As the heart of Apache ShenYu, plugins are extensible and hot-pluggable. + + Different plugins do different things. + + Of course, users can also customize plugins to meet their own needs. + + If you want to customize, see [custom-plugin](https://shenyu.apache.org/docs/developer/custom-plugin/) . + +--- + +# Selector & Rule + + According to your HTTP request headers, selectors and rules are used to route your requests. + + Selector is your first route, It is coarser grained, for example, at the module level. + + Rule is your second route and what do you think your request should do. For example a method level in a module. + + The selector and the rule match only once, and the match is returned. So the coarsest granularity should be sorted last. + +--- + +# Data Caching & Data Sync + + Since all data have been cached using ConcurrentHashMap in the JVM, it's very fast. + + Apache ShenYu dynamically updates the cache by listening to the ZooKeeper node (or WebSocket push, HTTP long polling) when the user changes configuration information in the background management. + + ![](/img/shenyu/dataSync/shenyu-config-processor-en.png) + + ![](/img/shenyu/dataSync/config-strategy-processor-en.png) + +--- + +# Prerequisite + +* JDK 1.8+ + +--- + +# Stargazers over time + + + +--- + +# Contributor and Support + +* [How to Contribute](https://shenyu.apache.org/community/contributor-guide) +* [Mailing Lists](mailto:dev@shenyu.apache.org) + +--- + +# Known Users + +In order of registration, More access companies are welcome to register at [https://github.com/apache/shenyu/issues/68](https://github.com/apache/shenyu/issues/68) (For open source users only) . + +All Users : [Known Users](https://shenyu.apache.org/community/user-registration) + +--- diff --git a/versioned_docs/version-2.6.1/plugin-center/_category_.json b/versioned_docs/version-2.6.1/plugin-center/_category_.json new file mode 100644 index 00000000000..5831affdd38 --- /dev/null +++ b/versioned_docs/version-2.6.1/plugin-center/_category_.json @@ -0,0 +1,4 @@ +{ + "label": "Plugin Center", + "position": 6 +} diff --git a/versioned_docs/version-2.6.1/plugin-center/cache/_category_.json b/versioned_docs/version-2.6.1/plugin-center/cache/_category_.json new file mode 100644 index 00000000000..8768a0fab5a --- /dev/null +++ b/versioned_docs/version-2.6.1/plugin-center/cache/_category_.json @@ -0,0 +1,4 @@ +{ + "label": "Cache", + "position": 7 +} diff --git a/versioned_docs/version-2.6.1/plugin-center/cache/cache-plugin.md b/versioned_docs/version-2.6.1/plugin-center/cache/cache-plugin.md new file mode 100644 index 00000000000..10675c44589 --- /dev/null +++ b/versioned_docs/version-2.6.1/plugin-center/cache/cache-plugin.md @@ -0,0 +1,152 @@ +--- +title: Cache Plugin +keywords: ["Cache"] +description: Cache Plugin +--- + +# 1. Overview + +## 1.1 Plugin Name + +* Cache Plugin + +## 1.2 Appropriate Scenario + +* Situation where data is not updated frequently and a large number of calls are required. + +* For Situation where data consistency is not required. + +## 1.3 Plugin functionality + +* The `Cache` plugin is able to cache the results of the target service, allowing the user to configure the expiration + time of the cached results. + +## 1.4 Plugin code + +* Core Module `shenyu-plugin-cache-handler`. +* Core Module `shenyu-plugin-cache-redis`. +* Core Module `shenyu-plugin-cache-memory`. + +* Core Class `org.apache.shenyu.plugin.cache.CachePlugin` +* Core Class `org.apache.shenyu.plugin.cache.redis.RedisCache` +* Core Class `org.apache.shenyu.plugin.cache.memory.MemoryCache` + +## 1.5 Added Since Which shenyu version + +* Since 2.4.3 + +# 2. How to use plugin + +## 2.1 Plugin-use procedure chart + +![](/img/shenyu/plugin/plugin_use_en.jpg) + +## 2.2 Import pom + +* Import cache plugin dependency in `ShenYu Bootstrap`. + +```xml + + + org.apache.shenyu + shenyu-spring-boot-starter-plugin-cache + ${project.version} + + +``` + +## 2.3 Enable plugin + +- In shenyu-admin --> BasicConfig --> Plugin --> `cache` set Status enabled. + +## 2.4 Config plugin + +### 2.4.1 Plugin Config + +![](/img/shenyu/plugin/cache/cache-plugin-config-en.png) + +* `cacheType`: Cache currently supports two modes of caching data. + +* memory:local memory mode + +* redis:redis mode + +The current default is `local memory mode`, the results of the target service are stored in the local memory, if the +gateway is deployed by way of cluster, it is not recommended to use `local memory mode`, it is recommended to +use `redis mode`, the data of the target service are cached in redis. + +If you are using `local memory mode`, you only need to select memory in cacheType, no other configuration is needed. + +If you are using `redis mode`, select redis in cacheType, and the parameters are as follows + +* `database`: which database the cache results are stored in, the default is index database 0. + +* `master`: default is master. + +* `mode`: the working mode of redis, the default is single-point mode: `standalone`, in addition to cluster + mode: `cluster`, sentinel mode: `sentinel`. + +* `url`: configure the IP and port of the redis database, configured by colon connection, example: `192.168.1.1:6379`. + +* `password`: the password of the redis database, if not, you can not configure. + +* `maxldle`: the maximum free connections in the connection pool + +* `minldle`: minimum idle connections in the connection pool + +* `maxActive`: the maximum number of connections in the connection pool + +* `maxWait`: the maximum blocking wait time for the connection pool (use negative values to indicate no limit) default -1 + +### 2.4.2 Selector Config + +* Selectors and rules, please refer to: [Selector And Rule Config](../../user-guide/admin-usage/selector-and-rule) . + +### 2.4.3 Rule Config + +![](/img/shenyu/plugin/cache/cache-plugin-rule-en.png) + +* Only matching requests will be cached by the Cache plugin for the results of the target service. + +`timeoutSecods`: the value is the target service result data cache time, the default is 60, in `seconds`. + +Notice: The current version of the Cache plugin uses the url as a unique key to identify the same request. + +## 2.5 Examples + +### 2.5.1 Use redis cache request result + +#### 2.5.1.1 Plugin Config + +![](/img/shenyu/plugin/cache/cache-plugin-config-example-en.png) + +select redis cache type, config redis database, url, mode, password + +#### 2.5.1.2 Selector Config + +![](/img/shenyu/plugin/cache/cache-plugin-selector-en.png) + +#### 2.5.1.3 Rule Config + +![](/img/shenyu/plugin/cache/cache-plugin-rule-en.png) + +#### 2.5.1.4 Send Request + +* send http request to cache result. + +```http title="request" +### shengyu getway proxy orderSave +GET http://localhost:9195/http/order/findById?id=123 +Accept: application/json +Content-Type: application/json +``` + +#### 2.5.1.5 Check Result + +![](/img/shenyu/plugin/cache/cache-result.jpg) + +![](/img/shenyu/plugin/cache/cache-result-check.png) + +# 3. How to disable plugin + +- In `shenyu-admin` --> BasicConfig --> Plugin --> `cache` set Status disable. diff --git a/versioned_docs/version-2.6.1/plugin-center/common/_category_.json b/versioned_docs/version-2.6.1/plugin-center/common/_category_.json new file mode 100644 index 00000000000..88b377b2c49 --- /dev/null +++ b/versioned_docs/version-2.6.1/plugin-center/common/_category_.json @@ -0,0 +1,4 @@ +{ + "label": "Common", + "position": 6 +} diff --git a/versioned_docs/version-2.6.1/plugin-center/common/general-context-plugin.md b/versioned_docs/version-2.6.1/plugin-center/common/general-context-plugin.md new file mode 100644 index 00000000000..b8d6453151a --- /dev/null +++ b/versioned_docs/version-2.6.1/plugin-center/common/general-context-plugin.md @@ -0,0 +1,36 @@ +--- +title: GeneralContext Plugin +keywords: ["generalContext"] +description: generalContext plugin +--- + +## Description + +* When making invokes to the target service, Apache ShenYu gateway also allows users to use the `generalContext` plugin to pass the service context parameters by reading the header in this request. + +## Plugin Setting + +* In `shenyu-admin` --> BasicConfig --> Plugin --> `generalContext`, set to enable. +* If the user don't use, please disable the plugin in the background. + + + +* Introduce `generalContext` support in the pox.xml file of the gateway. + +```xml + + + org.apache.shenyu + shenyu-spring-boot-starter-plugin-general-context + ${project.version} + + +``` + +* Selectors and rules, please refer to: [Selector And Rule Config](../../user-guide/admin-usage/selector-and-rule). +* Only those matched requests can print the information about this request. + +## Situation + +* The parameters in the request header need to be passed to the proxy server. +* Need to replace a key in the request header and pass it to the proxy server. diff --git a/versioned_docs/version-2.6.1/plugin-center/fault-tolerance/_category_.json b/versioned_docs/version-2.6.1/plugin-center/fault-tolerance/_category_.json new file mode 100644 index 00000000000..b02214033d8 --- /dev/null +++ b/versioned_docs/version-2.6.1/plugin-center/fault-tolerance/_category_.json @@ -0,0 +1,4 @@ +{ + "label": "Fault Tolerance", + "position": 3 +} diff --git a/versioned_docs/version-2.6.1/plugin-center/fault-tolerance/hystrix-plugin.md b/versioned_docs/version-2.6.1/plugin-center/fault-tolerance/hystrix-plugin.md new file mode 100644 index 00000000000..7e740e802c8 --- /dev/null +++ b/versioned_docs/version-2.6.1/plugin-center/fault-tolerance/hystrix-plugin.md @@ -0,0 +1,144 @@ +--- +title: Hystrix Plugin +keywords: ["Hystrix"] +description: hystrix plugin +--- + +# 1. Overview + +## 1.1 Plugin Name + +* Hystrix Plugin + +## 1.2 Appropriate Scenario + +* The backend service is unstable, use hystrix for protection + +## 1.3 Plugin functionality + +* Fusing the flow +* Protect the application behind ShenYu Gateway +* Isolation mode supports `thread` and `semaphore`. + +## 1.4 Plugin code + +* Core Module: `shenyu-plugin-hystrix` + +* Core Class: `org.apache.shenyu.plugin.hystrix.HystrixPlugin` + +## 1.5 Added Since Which shenyu version + +* Since ShenYu 2.4.0 + +# 2. How to use plugin + +## 2.1 Plugin-use procedure chart + +![](/img/shenyu/plugin/plugin_use_en.jpg) + +## 2.2 Import pom + +* Add `hystrix` dependency in the `pom.xml` file of the gateway. + +```xml + + + org.apache.shenyu + shenyu-spring-boot-starter-plugin-hystrix + ${project.version} + + +``` + +## 2.3 Enable plugin + +* In `shenyu-admin`--> BasicConfig --> Plugin --> `hystrix` set to enable. + +## 2.4 Config plugin + +### 2.4.1 Plugin Config + +* No Config, but you should open hystrix plugin. + +### 2.4.2 Selector Config + +It is used to filter traffic for the first time and does not require handle fields. + +For more information on selectors and rules configuration, see [Selector And Rule Config](../../user-guide/admin-usage/selector-and-rule) , only some of the fields are covered here. + +![](/img/shenyu/plugin/hystrix/selector_en.png) + +### 2.4.3 Rule Config + +* For the final filtering of traffic, there is a rule handler logic, isolation mode supports `thread` and `semaphore`. + +![](/img/shenyu/plugin/hystrix/rule_en.png) + +* Hystrix handler details: + + * `MinimumRequests`: the minimum number of requests required to trigger a circuit breaker. + + * `ErrorThresholdPercentage`: percentage of exception occurring during that time. + + * `Timeout`(ms): execution timeout. + + * `MaxConcurrentRequests`: max concurrent requests. + + * `Sleep`(ms): The recovery time after the circuit breaker. + + * `GroupKey`: It is generally set to: `contextPath`. + + * `CallBackUrl`: default url `/fallback/hystrix`. + + * `CommandKey`: generally, it is set to a specific path interface. + +## 2.5 Examples + +### 2.5.1 use hystrix protect application + +#### 2.5.1.1 Preparation + +- Start ShenYu Admin +- Start ShenYu Bootstrap +- Start a backend service + +#### 2.5.1.2 Selector Config + +![](/img/shenyu/plugin/hystrix/selector_en.png) + +#### 2.5.1.3 Rule Config + +* The rules in the pictures below are test examples, actual environment depends on the specific situation. + +![](/img/shenyu/plugin/hystrix/hystrix-example-rule-en.png) + +* test example + +```java +@RestController +@RequestMapping("/test") +@ShenyuSpringMvcClient("/test/**") +public class HttpTestController { + @PostMapping("/testHystrix") + public ResultBean ok() { + Random random = new Random(); + int num = random.nextInt(100); + if (num > 20) { + throw new RuntimeException(); + } + return new ResultBean(200, "ok", null); + } +} +``` + +#### 2.5.1.4 Send Request With `Apache Jmeter` + +![](/img/shenyu/plugin/hystrix/hystrix-send-request.png) + +#### 2.5.1.5 Check Result + +![](/img/shenyu/plugin/hystrix/hystrix-result.png) + +# 3. How to disable plugin + +- In `shenyu-admin` --> BasicConfig --> Plugin --> `hystrix` set Status disable. diff --git a/versioned_docs/version-2.6.1/plugin-center/fault-tolerance/rate-limiter-plugin.md b/versioned_docs/version-2.6.1/plugin-center/fault-tolerance/rate-limiter-plugin.md new file mode 100644 index 00000000000..0f1c2a7794b --- /dev/null +++ b/versioned_docs/version-2.6.1/plugin-center/fault-tolerance/rate-limiter-plugin.md @@ -0,0 +1,193 @@ +--- +title: RateLimiter Plugin +keywords: ["rateLimiter"] +description: rateLimiter plugin +--- + +# 1. Overview + +## 1.1 Plugin Name + +* RateLimiter Plugin + +## 1.2 Appropriate Scenario + +* traffic control in gateway cluster environment +* rate limiting according to specific rules +* You can set to the interface level, or the parameter level. How to use it depends on your traffic configuration. + +## 1.3 Plugin functionality + +* use redis to control gateway traffic + +## 1.4 Plugin code + +* Core Module `shenyu-plugin-ratelimiter`. + +* Core Class `org.apache.shenyu.plugin.ratelimiter.RateLimiterPlugin` +* Core Class `org.apache.shenyu.plugin.ratelimiter.executor.RedisRateLimiter` + +## 1.5 Added Since Which shenyu version + +* Since ShenYu 2.4.0 + +## 1.6 Technical Solution + +### 1.6.1 Using redis token bucket algorithm to limit traffic. + +- The system generates the token at a constant rate, and then puts the token into the token bucket. +- The token bucket's capacity. When the bucket is full, the token put into it will be discarded. +- Each time requests come, you need to obtain a token from the token bucket. If there are tokens, the service will be provided; if there are no tokens, the service will be rejected. + +* Flow Diagram: + ![](/img/shenyu/plugin/ratelimiter/tokenbucket.png) + + +### 1.6.2 Using redis leaky bucket algorithm to limit traffic. + +- water (request) go to the leaky bucket first. The leaky bucket goes out at a fixed speed. When the flow speed is too fast, it will overflow directly (reject service) + +* Flow Diagram: + ![](/img/shenyu/plugin/ratelimiter/leakybucket.png) + + +### 1.6.3 Using redis sliding time window algorithm to limit traffic. + +- The sliding time window maintains the count value of unit time. Whenever a requests pass, the count value will be increased by 1. When the count value exceeds the preset threshold, other requests in unit time will be rejected. If the unit time has ended, clear the counter to zero and start the next round counting. + +* Flow Diagram: + ![](/img/shenyu/plugin/ratelimiter/sldingwindow.png) + +# 2. How to use plugin + +## 2.1 Plugin-use procedure + +![](/img/shenyu/plugin/plugin_use_en.jpg) + +## 2.2 Import pom + +* Add `rateLimiter` dependency in `pom.xml` file of the gateway. + +```xml + + + org.apache.shenyu + shenyu-spring-boot-starter-plugin-ratelimiter + ${project.version} + + +``` + +## 2.3 Enable plugin + +* In `shenyu-admin`--> BasicConfig --> Plugin --> `rateLimiter` set to enable. + +## 2.4 Config plugin + +### 2.4.1 Plugin Config + +![](/img/shenyu/plugin/ratelimiter/ratelimiter-plugin-en.png) + +* `mode`: the working mode of redis, the default is single-point mode: `standalone`, in addition to cluster + mode: `cluster`, sentinel mode: `sentinel`. + +* `master`: default is master. + +* `url`: configure the IP and port of the redis database, configured by colon connection, example: `192.168.1.1:6379`. + +* `password`: the password of the redis database, if not, you can not configure. + +### 2.4.2 Selector Config + +* Selectors and rules, please refer to: [Selector And Rule Config](../../user-guide/admin-usage/selector-and-rule) + +### 2.4.3 Rule Config + +![](/img/shenyu/plugin/ratelimiter/ratelimiter-plugin-rule-en.png) + +* TokenBucket/Concurrent + + * `algorithmName`: `tokenBucket`/`concurrent`. + + * `replenishRate`: It is how many requests you allow users to execute per second, while not discarding any requests. This is the filling rate of token bucket. + + * `burstCapacity`: it is the maximum number of requests that users are allowed to execute in one second. This is token bucket can save the number of token. + + * `keyResolverName`: `whole` indicates that the traffic is limited by gateway per second, and `remoteAddress` indicates that the traffic is limited by IP per second. + +* LeakyBucket + + * `algorithmName`: `leakyBucket`. + + * `replenishRate`: The rate at which requests are executed per unit time, and the rate at which water droplets leak out of the leaky bucket. + + * `burstCapacity`: The maximum number of requests that users are allowed to execute in one second. This is the amount of water in the bucket. + + * `keyResolverName`: `whole` indicates that the traffic is limited by gateway per second, and `remoteAddress` indicates that the traffic is limited by IP per second. + +* SlidingWindow + + * `algorithmName`: `slidingWindow`. + + * `replenishRate`: The rate of requests per unit time, used to calculate the size of the time window. + + * `burstCapacity`: The maximum number of requests in the time window (per unit time). + + * `keyResolverName`: `whole` indicates that the traffic is limited by gateway per second, and `remoteAddress` indicates that the traffic is limited by IP per second. + +## 2.5 Examples + +### 2.5.1 Limit traffic with `RateLimiter` plugin in gateway cluster environment + +#### 2.5.1.1 Preparation + +- Start ShenYu Admin on `10.10.10.10:9095` +- Start two ShenYu Bootstrap on `10.10.10.20:9195` and `10.10.10.30:9195`, and config data sync center on `10.10.10.10:9095` +- config nginx, for example: + +```nginx +upstream shenyu_gateway_cluster { + ip_hash; + server 10.1.1.1:9195 max_fails=3 fail_timeout=10s weight=50; + server 10.1.1.2:9195 max_fails=3 fail_timeout=10s weight=50; +} + +server { + location / { + proxy_pass http://shenyu_gateway_cluster; + proxy_set_header HOST $host; + proxy_read_timeout 10s; + proxy_connect_timeout 10s; + } +} +``` + +#### 2.5.1.2 Plugin/Selector/Rule Configuration + +- config redis configuration with ratelimiter plugin + +- config selector + +- config rule + +![](/img/shenyu/plugin/ratelimiter/rule-example-en.png) + +replenishRate is 3, burstCapacity is 10 + +#### 2.5.1.3 Send Request to `Ngin`x by `Apache Jmeter` + +* jmeter thread group configuration + +![](/img/shenyu/plugin/ratelimiter/jmeter-thread-group.png) + +* jmeter http request configuration + +![](/img/shenyu/plugin/ratelimiter/jmeter-http-request.png) + +#### 2.5.1.4 Check Result + +![](/img/shenyu/plugin/ratelimiter/jmeter-result.png) + +# 3. How to disable plugin + +- In `shenyu-admin` --> BasicConfig --> Plugin --> `rateLimiter` set Status disable. diff --git a/versioned_docs/version-2.6.1/plugin-center/fault-tolerance/resilience4j-plugin.md b/versioned_docs/version-2.6.1/plugin-center/fault-tolerance/resilience4j-plugin.md new file mode 100644 index 00000000000..f58c00b30c4 --- /dev/null +++ b/versioned_docs/version-2.6.1/plugin-center/fault-tolerance/resilience4j-plugin.md @@ -0,0 +1,81 @@ +--- +title: Resilience4j Plugin +keywords: ["Resilience4j"] +description: resilience4j plugin +--- + +## Description + +* `Resilience4j` is one of the options that supports flow control and circuit breaking. +* `Resilience4j` supports flow control and circuit breaking functions for gateway. + +## Plugin Setting + +Select a mode to start shenyu-admin. For details, see deployment. For example, with [Local Deployment](../../deployment/deployment-local) starts the `Apache ShenYu` background management system. + +* In BasicConfig --> Plugin --> resilience4j, set to enable. +* If the user don't use, please disable the plugin in the background. + + + + + +## Add resilience4j plugin dependency + +* Add `resilience4j` dependency in the `pom.xml` file of the gateway. + +```xml + + + org.apache.shenyu + shenyu-spring-boot-starter-plugin-resilience4j + ${project.version} + + +``` + +## Resilience4j Config + +For more information on selectors and rules configuration, see [Selector And Rule Config](../../user-guide/admin-usage/selector-and-rule) , only some of the fields are covered here. + +#### Selector Config + +It is used to filter traffic for the first time and does not require handle fields. + + + + +#### Rule Config + +For the final filtering of traffic, there is a rule handler logic. + + + +* Resilience4j Processing Details + + * `limitForPeriod` :Configures the number of permissions available during one limit refresh period,default value:`50`. + + * `limitRefreshPeriod` :Configures the period of a limit refresh. After each period the rate limiter sets its permissions count back to the limitForPeriod value,default value:`500`. + + * `timeoutDurationRate` :Configures wait time(ms) a thread waits for a permission,default value:`5000`. + + * `circuitEnable` :Configures circuitBreaker enable, `0`:OFF ,`1`:ON ,default value:`0`. + + * `failureRateThreshold` :Configures the failure rate threshold in percentage,When the failure rate is equal or greater than the threshold the CircuitBreaker transitions to open and starts short-circuiting calls,default value:`50`. + + * `fallbackUri` :Configures the fallback uri. + + * `minimumNumberOfCalls` :Configures the minimum number of calls which are required (per sliding window period) before the CircuitBreaker can calculate the error rate or slow call rate,default value:`100`. + + * `bufferSizeInHalfOpen`:Configures the number of permitted calls when the CircuitBreaker is half open,default value:`10`. + + * `slidingWindowSize` :Configures the size of the sliding window which is used to record the outcome of calls when the CircuitBreaker is closed,default value:`100`. + + * `slidingWindowType` :Configures the type of the sliding window which is used to record the outcome of calls when the CircuitBreaker is closed, + Sliding window can either be `0`:count-based or `1`:time-based.,default value:`0`. + + * `timeoutDuration` :Configures request CircuitBreaker timeout(ms),default value:`30000`. + + * `waitIntervalInOpen` :Configures the circuitBreaker time(ms) of duration,default value:`10`. + + * `automaticTransitionFromOpenToHalfOpenEnabled` :Configures automatically transition from open state to half open state,`true`:ON, `false`:OFF, default value:`false`. diff --git a/versioned_docs/version-2.6.1/plugin-center/fault-tolerance/sentinel-plugin.md b/versioned_docs/version-2.6.1/plugin-center/fault-tolerance/sentinel-plugin.md new file mode 100644 index 00000000000..9c7919098ba --- /dev/null +++ b/versioned_docs/version-2.6.1/plugin-center/fault-tolerance/sentinel-plugin.md @@ -0,0 +1,215 @@ +--- +title: Sentinel Plugin +keywords: ["Sentinel"] +description: sentinel plugin +--- + +# 1. Overview + +## 1.1 Plugin Name + +* Sentinel Plugin + +## 1.2 Appropriate Scenario + +* `Sentinel` is one of the options that supports flow control and circuit breaking. +* `Sentinel` supports flow control and circuit breaking functions for gateway. + +## 1.3 Plugin functionality + +* flow control +* request circuit breaker and service degrade + +## 1.4 Plugin code + +* Core Module `shenyu-plugin-sentinel`. + +* Core Class `org.apache.shenyu.plugin.sentinel.SentinelPlugin` + +## 1.5 Added Since Which shenyu version + +* Since 2.4.0 + +# 2. How to use plugin + +## 2.1 Plugin-use procedure chart + +![](/img/shenyu/plugin/plugin_use_en.jpg) + +## 2.2 Import pom + +* Add `sentinel` dependency in the `pom.xml` file of the gateway(shenyu-bootstrap). + +```xml + + + org.apache.shenyu + shenyu-spring-boot-starter-plugin-sentinel + ${project.version} + + +``` + +## 2.3 Enable plugin + +* In `shenyu-admin`--> BasicConfig --> Plugin --> `sentinel` set to enable. + +## 2.4 Config plugin + +### 2.4.1 Plugin configuration + +### 2.4.2 Selector configuration + +It is used to filter traffic for the first time and does not require `handle` fields. + + + +### 2.4.3 Rule configuration + +For the final filtering of traffic, there is a rule handler logic. + + + +| field | default value | field type | desc | +|-----------------------------------------------------|--------------------|------------|----------------------------------------------------------------------------------------------------------------------------| +| degradeRuleCount | | Doule | degrade threshold | +| degradeRuleEnable | 1(enabled) | Integer | whether enable circuit breaking function of `sentinel` | +| degradeRuleGrade | 0(slow call ratio) | Integer | circuit breaker strategy, support RT of seconds level/ Error Ratio of seconds level/ Error Count of minutes level strategy | +| degradeRuleMinRequestAmount | 5 | Integer | circuit breaker min request amount | +| degradeRuleSlowRatioThreshold | 1.0d | Double | slow ratio threshold of degrading | +| degradeRuleStatIntervals | 1 | Integer | status intervals of degrade | +| degradeRuleTimeWindow | | Integer | time of degrading(unit: second) | +| flowRuleControlBehavior | 0(direact reject) | Integer | effect(reject directly/ queue/ slow start up), it do not support flow control by invocation relation. | + | flowRuleControlBehavior-direct rejection by default | | | | +| flowRuleControlBehavior-warm up | | | | +| flowRuleControlBehavior-constant speed queuing | | | | +| flowRuleControlBehavior-preheating uniformly queued | | | | +| flowRuleMaxQueueingTimeMs | 500ms | Integer | Maximum queuing time (valid in "preheating uniformly queued", "constant speed queuing" mode) | +| flowRuleWarmUpPeriodSec | 10 | Integer | Cold start warm-up time (seconds) (valid in "preheating uniformly queued" "warm up" mode) | +| flowRuleCount | | Integer | sentinel flow control count | +| flowRuleEnable | 1(enabled) | Integer | whether enable sentinel flow control function. | +| flowRuleGrade | 1(QPS) | Integer | type of current limit threshold(QPS or Thread Count)。 | +| fallbackUri | | String | degraded uri after circuit breaking. | + +## 2.5 Examples + +### 2.5.1 Using sentinel for flow control + +#### 2.5.1.1 Plugin configuration + +For more information on selectors and rules configuration, see [Selector And Rule Config](../../user-guide/admin-usage/selector-and-rule) , only some of the fields are covered here. + +* In `shenyu-admin`--> BasicConfig --> Plugin --> `sentinel` set to enable. + +#### 2.5.1.2 Selector configuration + +![](/img/shenyu/plugin/sentinel/example-selector-en.png) + +#### 2.5.1.3 Rule configuration + +![](/img/shenyu/plugin/sentinel/example-rule-en.png) + +just use qps flow control strategy, and qps is 10, reject strategy is directly reject. + +the code is as follows: + +```java +@RestController +@RequestMapping("/order") +@ShenyuSpringMvcClient("/order") +public class OrderController { + + /** + * Save order dto. + * + * @param orderDTO the order dto + * @return the order dto + */ + @PostMapping("/save") + @ShenyuSpringMvcClient("/save") + public OrderDTO save(@RequestBody final OrderDTO orderDTO) { + orderDTO.setName("hello world save order"); + return orderDTO; + } +} +``` + +#### 2.5.1.4 request by `Apache Jmeter` + +* Jmeter thead group config + +![](/img/shenyu/plugin/sentinel/sentinel-flow-control-config.png) + +* Jmeter http request config + +![](/img/shenyu/plugin/sentinel/sentinel-flow-control-http.png) + +#### 2.5.1.5 Check result + +![](/img/shenyu/plugin/sentinel/sentinel-flow-control.png) + +### 2.5.2 Using sentinel for request circuit breaker + +#### 2.5.2.1 Plugin configuration + +* In `shenyu-admin`--> BasicConfig --> Plugin --> `sentinel` set to enable. + +#### 2.5.2.2 Selector configuration + +![](/img/shenyu/plugin/sentinel/example-selector-en.png) + +#### 2.5.2.3 Rule configuration + +![](/img/shenyu/plugin/sentinel/example-circuitbreaker-rule.png) + +when degrade strategy is `exception number`, `degradeRuleSlowRatioThreshold` is not effective. When the minimum number of requests per unit of time is 5, and the request happens exception great than 3, it will trigger the circuit breaker. + +when degrade strategy is `slow call ratio`, `degradeRuleSlowRatioThreshold` is effective, `degradeRuleCount` means RT(e.g. 200). + +the code is as follows: + +```java +@RestController +@RequestMapping("/order") +@ShenyuSpringMvcClient("/order") +public class OrderController { + + /** + * Save order dto. + * + * @param orderDTO the order dto + * @return the order dto + */ + @PostMapping("/save") + @ShenyuSpringMvcClient("/save") + public OrderDTO save(@RequestBody final OrderDTO orderDTO) { + + Random random = new Random(); + int num = random.nextInt(100); + if (num > 40) { + throw new RuntimeException("num great than 20"); + } + orderDTO.setName("hello world save order"); + return orderDTO; + } + +} +``` + +#### 2.5.2.4 request by `Apache Jmeter` + +* Jmeter thead group config + +![](/img/shenyu/plugin/sentinel/sentinel-flow-control-config.png) + +* Jmeter http request config + +![](/img/shenyu/plugin/sentinel/sentinel-flow-control-http.png) + +#### 2.5.2.5 Check result + +![](/img/shenyu/plugin/sentinel/example-circuitbreaker.png) + +# 3. How to disable plugin + +- In `shenyu-admin` --> BasicConfig --> Plugin --> `sentinel` set Status disable. diff --git a/versioned_docs/version-2.6.1/plugin-center/http-process/_category_.json b/versioned_docs/version-2.6.1/plugin-center/http-process/_category_.json new file mode 100644 index 00000000000..77ac2bace2f --- /dev/null +++ b/versioned_docs/version-2.6.1/plugin-center/http-process/_category_.json @@ -0,0 +1,4 @@ +{ + "label": "Http Process", + "position": 1 +} diff --git a/versioned_docs/version-2.6.1/plugin-center/http-process/contextpath-plugin.md b/versioned_docs/version-2.6.1/plugin-center/http-process/contextpath-plugin.md new file mode 100644 index 00000000000..8a05fe6c1fb --- /dev/null +++ b/versioned_docs/version-2.6.1/plugin-center/http-process/contextpath-plugin.md @@ -0,0 +1,127 @@ +--- +title: ContextPath Plugin +keywords: ["contextPath"] +description: contextPath plugin +--- + +# 1. Overview + +## 1.1 Plugin Name + +* ContextPath Plugin + +## 1.2 Appropriate Scenario + +* Different services can do traffic governance of services by setting different context paths. + +## 1.3 Plugin functionality + +* Set the context path for service. +* When the interface is called, the plug-in uniformly prefixes the interface address of the service. + +## 1.4 Plugin Code + +* Core module ```shenyu-plugin-context-path``` +* Core class ```org.apache.shenyu.plugin.context.path.ContextPathPlugin``` + +## 1.5 Added since which shenyu version + +* 2.3.0 + +# 2. How to use plugin + +## 2.1 Plugin-use procedure chart + +![](/img/shenyu/plugin/context-path/procedure-en.png) + +## 2.2 Import pom + +- import maven config in shenyu-bootstrap project's `pom.xml` file. + +```xml + + org.apache.shenyu + shenyu-spring-boot-starter-gateway + ${project.version} + +``` + +## 2.3 Enable plugin + +- In `shenyu-admin` --> BasicConfig --> Plugin --> `contextPath` set Status enable. + +![](/img/shenyu/plugin/context-path/enable-en.png) + +## 2.4 Config plugin + +- Set client project's contextPath. + +![](/img/shenyu/plugin/context-path/client-project-config.png) + +- Selector and rule config, please refer: [Selector and rule config](../../user-guide/admin-usage/selector-and-rule). +- shenyu-admin contextPath plugin config, config contextPath and addPrefix, contextPath defines the value of contextPath, +- and addPrefix defines the prefix that needs to be automatically added when the interface is called. + +![](/img/shenyu/plugin/context-path/plugin-config-en.png) + +## 2.5 Examples + +### 2.5.1 Example set service context path + +#### 2.5.1.1 Refer [Local Deployment](https://shenyu.apache.org/docs/deployment/deployment-local/) to start admin and bootstrap. + +#### 2.5.1.2 Refer 2.2 to import pom and restart bootstrap. + +#### 2.5.1.3 Refer 2.3 to enable plugin. + +#### 2.5.1.4 Client project config contextPath. + +Client project can directly use [shenyu-examples-http](https://github.com/apache/shenyu/tree/master/shenyu-examples/shenyu-examples-http), and config contextPath in application.yml. + +![](/img/shenyu/plugin/context-path/client-project-config.png) + +- After the configuration is completed, and start client project, you can see that there is an additional context selector and rule configuration in shenyu-admin. + +![](/img/shenyu/plugin/context-path/context-path-selector-and-rule-en.png) + +#### 2.5.1.5 Call Interface + +![](/img/shenyu/plugin/context-path/invoke-interface.png) + +### 2.5.2 Example add prefix + +#### 2.5.2.1 Refer [Local Deployment](https://shenyu.apache.org/docs/deployment/deployment-local/) to start admin and bootstrap. + +#### 2.5.2.2 Refer 2.2 to import pom and restart bootstrap. + +#### 2.5.2.3 Refer 2.3 to enable plugin. + +#### 2.5.2.4 Client project config contextPath. + +For client project we can directly use [shenyu-examples-http](https://github.com/apache/shenyu/tree/master/shenyu-examples/shenyu-examples-http), and config contextPath in application.yml. + +![](/img/shenyu/plugin/context-path/client-project-config.png) + +- After the configuration is completed, start client project, you can see that there is an additional context selector and rule configuration in shenyu-admin. + +![](/img/shenyu/plugin/context-path/context-path-selector-and-rule-en.png) + +#### 2.5.2.5 Config addPrefix + +![](/img/shenyu/plugin/context-path/add-prefix-en.png) + +#### 2.5.2.6 Modify the value of uri in the selector and condition configuration to delete the addPrefix part. + +Since this example uses the service of the http protocol, we need to modify the divide plugin. + +![](/img/shenyu/plugin/context-path/remove-add-prefix-en.png) + +#### 2.5.2.5 Call Interface + +![](/img/shenyu/plugin/context-path/invoke-interface-add-prefix.png) + +# 3. How to disable plugin + +- In `shenyu-admin` --> BasicConfig --> Plugin --> `contextPath` set Status disable. + +![](/img/shenyu/plugin/context-path/disable-en.png) diff --git a/versioned_docs/version-2.6.1/plugin-center/http-process/modifyresponse-plugin.md b/versioned_docs/version-2.6.1/plugin-center/http-process/modifyresponse-plugin.md new file mode 100644 index 00000000000..06dd2d0bdf5 --- /dev/null +++ b/versioned_docs/version-2.6.1/plugin-center/http-process/modifyresponse-plugin.md @@ -0,0 +1,146 @@ +--- +title: ModifyResponse Plugin +keywords: ["modifyResponse"] +description: modifyResponse plugin +--- + +# 1. Overview + +## 1.1 Plugin Name + +* ModifyResponse Plugin + +## 1.2 Appropriate Scenario + +* This plugin is used for modifying HTTP response status code, response headers or response body parameters. + +## 1.3 Plugin functionality + +* Reset HTTP response status code +* Add, set, replace or remove HTTP response headers. +* Add, replace or remove HTTP response body(JSON) parameters. + +## 1.4 Plugin Code + +* Core module ```shenyu-plugin-modify-response``` +* Core class ```org.apache.shenyu.plugin.modify.response.ModifyResponsePlugin``` + +## 1.5 Added since which shenyu version + +* 2.4.0 + +# 2. How to use plugin + +## 2.1 Plugin-use procedure chart + +![](/img/shenyu/plugin/modify-response/procedure-en.png) + +## 2.2 Import pom + +- import maven config in shenyu-bootstrap project's `pom.xml` file. + +```xml + + org.apache.shenyu + shenyu-spring-boot-starter-gateway + ${project.version} + +``` + +## 2.3 Enable plugin + +- In `shenyu-admin` --> BasicConfig --> Plugin --> `modifyResponse` set Status enable. +- +![](/img/shenyu/plugin/modify-response/enable-en.png) + +## 2.4 Config plugin + +* Selector and rule config, please refer: [Selector and rule config](../../user-guide/admin-usage/selector-and-rule). +* In `shenyu-admin` --> `PluginList` --> `HttpProcess` --> `modifyResponse`, add selector config first,then add rule config: + * Add selector config + ![](/img/shenyu/plugin/modify-response/plugin-selector-config-en.png) + * Add rule config + ![](/img/shenyu/plugin/modify-response/plugin-rule-config-en.png) + +## 2.5 Examples + +Here is an example of client project [shenyu-examples-http](https://github.com/apache/shenyu/tree/master/shenyu-examples/shenyu-examples-http). + +### 2.5.1 Example reset HTTP response status code + +#### 2.5.1.1 Refer [Local Deployment](https://shenyu.apache.org/docs/deployment/deployment-local/) to start admin and bootstrap. + +#### 2.5.1.2 Refer 2.2 to import pom and restart bootstrap. + +#### 2.5.1.3 Refer 2.3 to enable plugin. + +#### 2.5.1.4 Refer 2.4 to add plugin config. + +Add plugin config: + +![](/img/shenyu/plugin/modify-response/status-code-rule-config-en.png) + +#### 2.5.1.5 Call Interface + +![](/img/shenyu/plugin/modify-response//status-code-invoke-interface.png) + +### 2.5.2 Example modify HTTP response headers + +#### 2.5.2.1 Refer [Local Deployment](https://shenyu.apache.org/docs/deployment/deployment-local/) to start admin and bootstrap. + +#### 2.5.2.2 Refer 2.2 to import pom and restart bootstrap. + +#### 2.5.2.3 Refer 2.3 to enable plugin. + +#### 2.5.2.4 Refer 2.4 to add plugin config. + +Add plugin config: + +![](/img/shenyu/plugin/modify-response/header-rule-config-en.png) + +#### 2.5.2.5 Call Interface + +![](/img/shenyu/plugin/modify-response/header-invoke-interface.png) + +### 2.5.3 Example modify HTTP response body + +#### 2.5.3.1 Refer [Local Deployment](https://shenyu.apache.org/docs/deployment/deployment-local/) to start admin and bootstrap. + +#### 2.5.3.2 Refer 2.2 to import pom and restart bootstrap. + +#### 2.5.3.3 Refer 2.3 to enable plugin. + +#### 2.5.3.4 Refer 2.4 to add plugin config. + +Add plugin config: + +![](/img/shenyu/plugin/modify-response/body-rule-config-en.png) + +#### 2.5.3.5 Call Interface + +![](/img/shenyu/plugin/modify-response/body-invoke-interface.png) + +## 3. How to disable plugin + +- In `shenyu-admin` --> BasicConfig --> Plugin --> `modifyResponse` set Status disable. + +![](/img/shenyu/plugin/modify-response/disable-en.png) + +## 4. rule parameter list + +for modifying status code: + +* `statusCode`: reset response status code + +for modifying response headers: + +* `addHeaders`: add response headers, `k-v` format +* `setHeaders`: set response headers, `k-v` format +* `replaceHeaderKeys`: replace response headers,`key` is matching to the header key that should be replacing, value is target value after replacing +* `removeHeaderKeys`: remove response headers,`key` is matching to the header key that should be removing + +for modifying response body: + +* `addBodyKeys`: add response body parameters +* `replaceBodyKeys`: replace response body parameters,`key` is matching to the body(JSON) key that should be replacing, value is target value after replacing +* `removeBodyKeys`: remove response body parameters,`key` is matching to the body(JSON) key that should be removing diff --git a/versioned_docs/version-2.6.1/plugin-center/http-process/parammapping-plugin.md b/versioned_docs/version-2.6.1/plugin-center/http-process/parammapping-plugin.md new file mode 100644 index 00000000000..caa04ab2722 --- /dev/null +++ b/versioned_docs/version-2.6.1/plugin-center/http-process/parammapping-plugin.md @@ -0,0 +1,109 @@ +--- +title: ParamMapping Plugin +keywords: ["paramMapping-plugin"] +description: paramMapping-plugin +--- + +# 1. Overview + +## 1.1 Plugin Name + +* ParamMapping Plugin + +## 1.2 Appropriate Scenario + +* Add/remove/replace certain fixed parameters to the request + +## 1.3 Plugin functionality + +* `paramMapping` is used to edit your request parameters. + +## 1.4 Plugin code + +* Core Module `shenyu-plugin-param-mapping` + +* Core Class `org.apache.shenyu.plugin.param.mapping.ParamMappingPlugin` + +## 1.5 Added Since Which shenyu version + +* Since ShenYu 2.4.0 + +# 2. How to use plugin + +## 2.1 Plugin-use procedure chart + +![](/img/shenyu/plugin/plugin_use_en.jpg) + +## 2.2 Import pom + +* Introduce `paramMapping` dependency in the pom.xml file of the gateway. + +```xml + + + org.apache.shenyu + shenyu-spring-boot-starter-plugin-param-mapping + ${project.version} + + +``` + +## 2.3 Enable plugin + +- In `shenyu-admin` --> BasicConfig --> Plugin --> `paramMapping` set Status enabled. + +## 2.4 Config plugin + +### 2.4.1 Plugin Config + +* you should open this plugin when using. + +### 2.4.2 Selector Config + +* Selectors and rules, please refer to:[Selector And Rule Config](../../user-guide/admin-usage/selector-and-rule)。 + +* Only those matched requests can be modified your request body. + +### 2.4.3 Rule Config + +![](/img/shenyu/plugin/param-mapping/param-mapping.png) +* param details: + * `addParameterKeys`: add a new `key-value` on body + * `replaceParameterKeys`: replace request body's `key` ,`key` is the value to be replaced,`value` is the value after replacement + * `removeParameterKeys`: remove a body `key` + +* param_mapping modify the request body is achieved through `JSONPath` , `$.` represents the root directory. + +## 2.5 Examples + +### 2.5.1 Add parameters in request + +#### 2.5.1.1 Config Plugin + +* you should open the plugin when using. + +#### 2.5.1.2 Selector Config + +#### 2.5.1.3 Rule Config + +![](/img/shenyu/plugin/param-mapping/param-mapping.png) + +use the configuration,unopened the plugin,request body is: + +```json +{"id":3,"data":{"value":"18","age":"36"}} +``` + +#### 2.5.1.4 Check Result + +open the plugin,the final request body is + +```json +{"name":"shenyu","userId":3,"data":{"age":"36"}} +``` + +add a new key-value `name:shenyu`,replace the key `id` to `userId`, remove the key `data.value` . + +# 3. How to disable plugin + +- In `shenyu-admin` --> BasicConfig --> Plugin --> `paramMapping` set Status disable. diff --git a/versioned_docs/version-2.6.1/plugin-center/http-process/redirect-plugin.md b/versioned_docs/version-2.6.1/plugin-center/http-process/redirect-plugin.md new file mode 100644 index 00000000000..3e61f08f813 --- /dev/null +++ b/versioned_docs/version-2.6.1/plugin-center/http-process/redirect-plugin.md @@ -0,0 +1,94 @@ +--- +title: Redirect Plugin +keywords: ["redirect"] +description: redirect plugin +--- + +# 1. Overview + +## 1.1 Plugin Name + + - Redirect Plugin + +## 1.2 Appropriate Scenario + + - As the name suggests, the `redirect` plugin is to re-forward and redirect `uri`. + +## 1.3 Plugin functionality + + - When the Apache ShenYu gateway makes proxy calls to the target service, it also allows users to use the `redirect` plugin to redirect requests. + +## 1.4 Plugin code + + Core module ```shenyu-plugin-context-redirect``` + Core class ```org.apache.shenyu.plugin.redirect.RedirectPlugin``` + +## 1.5 Added Since Which shenyu version + + before 2.2.0 . + +# 2. How to use plugin + +## 2.1 Plugin-use procedure chart + + + +## 2.2 Import pom + + - import maven config in shenyu-bootstrap project's `pom.xml` file. + + ```xml + + + org.apache.shenyu + shenyu-spring-boot-starter-plugin-redirect + ${project.version} + + + ``` + +## 2.3 Enable plugin + + - In `shenyu-admin` --> BasicConfig --> Plugin --> `Redirect` set Status enable. + + + +## 2.4 Config plugin + + - Selector and rule config, please refer: [Selector and rule config](../../user-guide/admin-usage/selector-and-rule). + - In `shenyu-admin` --> `PluginList` --> `HttpProcess` --> `Redirect`, add selector config first,then add rule config: + - Add selector config + + + - Add rule config + + + +## 2.5 Examples + +### 2.5.1 Redirect + + - When we configure a custom path in `Rule`, it should be a reachable service path. + - When the request is matched, the `ShenYu Gateway` will perform the `308` service jump according to the customized path. + 1. Refer [Local Deployment](https://shenyu.apache.org/docs/deployment/deployment-local/) to start admin and bootstrap. + 2. Refer 2.2 to import pom and restart bootstrap. + 3. Refer 2.3 to enable plugin. + 4. Refer 2.4 and [Selector and rule config](../../user-guide/admin-usage/selector-and-rule). + 5. Invoke interface: [demo](http://localhost:9195/http) + - Invoke the interface declared by selectors and rules will redirect to the specified path. + - In this demo, it will jump to [ShenYu official website](https://shenyu.apache.org) + + + +### 2.5.2 Gateway's own interface forwarding + + - When the matching rules are met, the service will use the `DispatcherHandler` internal interface for forwarding. + - To implement the gateway's own interface forwarding, we need to use `/` as the prefix in the configuration path. The specific configuration is as shown in the figure below. + + + +# 3. How to disable plugin + +- In `shenyu-admin` --> BasicConfig --> Plugin --> `Redirect` set Status disable. + + diff --git a/versioned_docs/version-2.6.1/plugin-center/http-process/request-plugin.md b/versioned_docs/version-2.6.1/plugin-center/http-process/request-plugin.md new file mode 100644 index 00000000000..b3757c51204 --- /dev/null +++ b/versioned_docs/version-2.6.1/plugin-center/http-process/request-plugin.md @@ -0,0 +1,91 @@ +--- +title: Request Plugin +keywords: ["request"] +description: request plugin +--- + +# 1. Overview + +## 1.1 Plugin Name + +* Request Plugin + +## 1.2 Appropriate Scenario + +* The request plugin is able to make customized changes to the request parameters of `uri`. + +## 1.3 Plugin functionality + +* The `Apache ShenYu` gateway allows users to use the `request` plugin to add, modify, and remove request headers to request parameters, request headers, and `Cookie` when proxying a target service. + +## 1.4 Plugin code + +* Core Module `shenyu-plugin-request` + +* Core Class `org.apache.shenyu.plugin.request.RequestPlugin` + +## 1.5 Added Since Which shenyu version + +* Since ShenYu 2.4.0 + +# 2. How to use plugin + +## 2.1 Plugin-use procedure chart + + + +## 2.2 Import pom + +- Import maven config in shenyu-bootstrap project's `pom.xml` file, which is already added by default. + +```xml + + org.apache.shenyu + shenyu-spring-boot-starter-plugin-request + ${project.version} + +``` + +## 2.3 Enable plugin + +- In `shenyu-admin` --> BasicConfig --> Plugin --> `request` set Status enabled. + + > If there is an option to configure a `ruleHandlePageType` on the page here, you can configure any string, e.g. `custom`, which has no effect on the request, and will be removed in later versions. + + + + +## 2.4 Config plugin + +- selectors and rules, only requests that match are forwarded and redirected, see the [Selector And Rule Config](../../user-guide/admin-usage/selector-and-rule) +- `shenyu-admin` Plugin --> `HttpProcess` --> `Request`. Add the selector first, then add the rule: +- Add the selector: + + + +- Add the rule + + + +## 2.5 Examples + +### 2.5.1 Adding request parameters + +- When we configure a custom path in `Rules`, it should be a reachable service path. +- When a request is matched, based on the customized path, the `Apache ShenYu` gateway performs a service hop. + +1. Refer to [Local Deployment](https://shenyu.apache.org/docs/deployment/deployment-local)启动 admin 和网关 +2. Refer to 2.2 importing pom and restarting the gateway. +3. Refer to 2.3 enabling Plugin +4. Start the project [shenyu-examples-http](https://github.com/apache/shenyu/tree/master/shenyu-examples/shenyu-examples-http) +5. Refer to 2.4 and [Selector And Rule Config](../../user-guide/admin-usage/selector-and-rule), configuring plugin rules. +6. Call interface:[http-test-api.http](https://github.com/apache/shenyu/blob/master/shenyu-examples/shenyu-examples-http/src/main/http/http-test-api.http) +- Calling the interface declared by the selector and rule will see the request parameters configured in the request plugin. + + + +# 3. How to disable plugin + +- In `shenyu-admin` --> BasicConfig --> Plugin --> `request` set Status disable. +- + diff --git a/versioned_docs/version-2.6.1/plugin-center/http-process/rewrite-plugin.md b/versioned_docs/version-2.6.1/plugin-center/http-process/rewrite-plugin.md new file mode 100644 index 00000000000..adc096f0299 --- /dev/null +++ b/versioned_docs/version-2.6.1/plugin-center/http-process/rewrite-plugin.md @@ -0,0 +1,103 @@ +--- +title: Rewrite Plugin +keywords: ["rewrite"] +description: rewrite plugin +--- + +# 1. Overview + +## 1.1 Plugin Name + +* Rewrite Plugin + +## 1.2 Appropriate Scenario + +* The request uri can be different from the target service by rewriting the path. + +## 1.3 Plugin functionality + +* This plugin is used to rewrite the request uri. + +## 1.4 Plugin code + +* Core Module `shenyu-plugin-rewrite` + +* Core Class `org.apache.shenyu.plugin.rewrite.RewritePlugin` + +## 1.5 Added Since Which shenyu version + +* Since ShenYu 2.4.0 + +# 2. How to use plugin + +## 2.1 Plugin-use procedure chart + +![](/img/shenyu/plugin/rewrite/rewrite_use_en.png) + +## 2.2 Import pom + +- Import maven config in shenyu-bootstrap project's `pom.xml` file.. + +```xml + + org.apache.shenyu + shenyu-spring-boot-starter-plugin-rewrite + ${project.version} + +``` + +## 2.3 Enable plugin + +- In `shenyu-admin` --> BasicConfig --> Plugin --> `rewrite` set Status enabled. +![](/img/shenyu/plugin/rewrite/rewrite_open_en.png) + +## 2.4 Config plugin + +### 2.4.1 Plugin Config + +* Enable the plugin before using. +* Disable the plugin if don't use. + +### 2.4.2 Selector Config + +* Please refer to: [Selector And Rule Config](../../user-guide/admin-usage/selector-and-rule). + +### 2.4.3 Rule Config + +![](/img/shenyu/plugin/rewrite/rewrite_rule_config.png) + +* Param details: + * `regex`: The regular expression that matches the part of uri to be rewrited. + * `replace`: The content of replacement. + +## 2.5 Examples + +### 2.5.1 Example for rewriting uri + +#### 2.5.1.1 Run the shenyu-examples-http project + +* Use [shenyu-examples-http](https://github.com/apache/shenyu/tree/master/shenyu-examples/shenyu-examples-http), please refer to [Run the shenyu-examples-http project](../../quick-start/quick-start-http#run-the-shenyu-examples-http-project) + +#### 2.5.1.1 Plugin Config + +* Refer to [2.4.1](#241-plugin-config) to configure plugin. + +#### 2.5.1.2 Selector Config + +* Refer to [2.4.2](#242-selector-config) to configure selector + +#### 2.5.1.3 Rule Config + +![](/img/shenyu/plugin/rewrite/rewrite_example_rule.png) + +The request `/http/hello` would be rewritten to `/hi` + +#### 2.5.1.4 Check Result + +Use some tool (such as Postman) to make a request: + +![](/img/shenyu/plugin/rewrite/rewrite_example_result.png) + +# 3. How to disable plugin + +- In `shenyu-admin` --> BasicConfig --> Plugin --> `rewrite` set Status disable. diff --git a/versioned_docs/version-2.6.1/plugin-center/mock/_category_.json b/versioned_docs/version-2.6.1/plugin-center/mock/_category_.json new file mode 100644 index 00000000000..e4f13a148a9 --- /dev/null +++ b/versioned_docs/version-2.6.1/plugin-center/mock/_category_.json @@ -0,0 +1,4 @@ +{ + "label": "Mock", + "position": 8 +} diff --git a/versioned_docs/version-2.6.1/plugin-center/mock/mock-plugin.md b/versioned_docs/version-2.6.1/plugin-center/mock/mock-plugin.md new file mode 100644 index 00000000000..9c1c55ef7c0 --- /dev/null +++ b/versioned_docs/version-2.6.1/plugin-center/mock/mock-plugin.md @@ -0,0 +1,178 @@ +--- +title: Mock Plugin +keywords: ["mock"] +description: mock plugin +--- + +# 1. Overview + +## 1.1 Plugin Name + +* Mock Plugin + +## 1.2 Appropriate Scenario + +* Specify the status code and response body for the request to facilitate testing. + +## 1.3 Plugin functionality + +* Set the status code and body of the request. +* Support configuration `${}` placeholder to automatically generate data. + +* **Note:** In order to support a more flexible data generation method, the mock plug-in supports users to use SpEL expressions to generate mock data. Using SpEL expressions may lead to the risk of executing malicious scripts or applying destructive programs. We recommend that you be extra careful when using them, use them in a safe environment as much as possible, such as an intranet environment, and follow security best practices. + +## 1.4 Plugin Code + +* Core module ```shenyu-plugin-mock``` +* Core class ```org.apache.shenyu.plugin.mock.MockPlugin``` + +## 1.5 Added since which shenyu version + +* 2.5.0 + +# 2. How to use plugin + +## 2.1 Import pom + +- import maven config in shenyu-bootstrap project's `pom.xml` file. + +```xml + + org.apache.shenyu + shenyu-spring-boot-starter-plugin-mock + ${project.version} + +``` + +## 2.2 Enable plugin + +- In `shenyu-admin` --> BasicConfig --> Plugin --> `mock` set Status enable. + +![](/img/shenyu/plugin/mock/enable-mock-plugin-en.png) + +## 2.3 Config plugin + +- Selector and rule config, please refer: [Selector and rule config](../../user-guide/admin-usage/selector-and-rule). +- shenyu-admin mock plugin configuration, supports configuring httpStatusCode and responseContent + - httpStatusCode:the status code of the request. + - responseContent:the response body of the request,support configuring `${}` placeholders to generate random data. + +![](/img/shenyu/plugin/mock/mock-rule-configuration-en.png) + +## 2.4 `${}` supported syntax + +**~~`${int|min-max}`~~** +- **Description:** Generate random integers from `min` to `max`, inclusive of `min` and `max`. +- **Example:** `${int|10-20}` + +**~~`${double|min-max|format}`~~** +- **Description:** Generate random floating point numbers from `min` to `max`, formatted according to `format`. +- **Example:** `${double|10-20}` , `${double|10-20.5|%.2f}` + +**~~`${email}`~~** +- **Description:** Generate random email addresses. + +**~~`${phone}`~~** +- **Description:** Generate random 13-digit mobile number. + +**~~`${zh|min-max}`~~** +- **Description:** Generate random Chinese strings of length `min` to `max`. +- **Example:** `${zh|10-20}` + +**~~`${en|min-max}`~~** +- **Description:** Generate random English strings of length `min` to `max`. +- **Example:** `${en|10-20}` + +**~~`${bool}`~~** +- **Description:** Generate a random `boolean` value i.e. `true` or `false`. + +**~~`${list|[arg1,arg2...]}`~~** +- **Description:** Randomly returns any value in a list as a string. +- **Example:** `${list|[gril,boy]}` will return `boy` or `girl` + +**~~`${current|format}`~~** +- **Description:** Returns the current time and uses `format` to format, `format` can be default, the default is `YYYY-MM-dd HH:mm:ss`. +- **Example:** `${current}`,`${current|YYYY-MM-dd}` + +**~~`${array|item|length}`~~** +- **Description:** According to the `item` format definition, an array of length `length` can be generated. All the above data generation rules can be nested in `item`, and the result will be automatically added with `[]`. +- **Example:** `${array|{"name":"test"}|3}` result is `[{"name":"test"},{"name":"test"},{"name":"test"}]`,`${array|{"age":${int|18-65}}|3}`. + +**${expression|expression}** + +`Spel` expressions are currently supported with built-in functions and arguments, which fully replace the old ${} syntax + +- **`${expression|#int(min,max)}`** + + - **Description:** Generate random integers from `min` to `max`, inclusive of `min` and `max`. + + - **Example:** `${expression|#int(1,2)}` + +- **`${expression|#double(min,max)}`** + + - **Description:** Generate random floating point numbers from `min` to `max`, formatted according to `format`. + - **Example:**`${expression|#double(10.5,12.0)}`,`${expression|#double(10.5,12.0,'¥%.2f')}` + +- **`${expression|#email()}`** + + - **Description:** Generate random email addresses. + +- **`${expression|#phone()}`** + + - **Description:** Generate random 13-digit mobile number. + +- **`${expression|zh(min,max)}`** + + - **Description:** Generate random Chinese strings of length `min` to `max`. + - **Example:** `${expression|#zh(1,10)}` + +- **`${expression|#bool()}`** + + - **Description:** Generate a random `boolean` value i.e. `true` or `false`. + +- **`${expression|#oneOf(arg1,arg2...)}`** + + - **Description:** Randomly returns any value in a list. + - **Example:** `${expression|#oneOf('shenyu','number',1)}` will return `'shenyu'` or `'number'`or`1` + +- **`${expression|current()}`** + + + **Description:** Returns the current time and uses `format` to format, `format` can be default, the default is `YYYY-MM-dd HH:mm:ss`. + + **Example:** `${expression|#current()}`,`${expression|#current('YYYY-MM-dd')}` + +- **`${expression|#array(item,length)}`** + + - **Description:** According to the `item` format definition, an array of length `length` can be generated. + + - **Example:** `expression|#array('shenyu',3)` would generate `["shenyu","shenyu","shenyu"]`. + + You can use it nested like`${expression|#array(#bool(),2)}`or`${expression|#array(#array('shenyu',2),2)}` + +- **`${expression|#req}`** + + - **Description:** Req is built-in request parameters ,which can generate response data based on request content + - **Example:**`${expression|#req.method}`、`${expression|#req.queries['query_name']}`、`${req.queries.query_name}`、`${expression|#req.uri}`。`jsonPath` is used when the request body is json . For example ,when the request body is `{"name":"shenyu"}`,`${expression|#req.json.name}`would return "shenyu" ++ **`${expression|spel}`** + + + **Description**:Use Spel expressions directly to generate data + + **Example**:`${expression|T(java.time.LocalDate).now()}`、`${expression|1==1}` + +It is recommended to use the new '${}' syntax. The old syntax may be removed at an later date. + +Function replaceable table: + +| old | new | +| :------------------------- | :---------------------------------- | +| ${int\|min-max} | ${expression\|#int(min,max)} | +| ${double\|min-max\|format} | ${expression\|#double(min,max)} | +| ${email} | ${expression\|#email()} | +| ${phone} | ${expression\|#phone()} | +| ${zh\|min-max} | ${expression\|#zh(min,max)} | +| ${en\|min-max} | ${expression\|#en(min,max)} | +| ${list\|[arg1,arg2...]} | ${expression\|#oneOf(arg1,agr2...)} | +| ${current\|format} | ${expression\|#current(format)} | +| ${bool} | ${expression\|#bool()} | +| ${array\|item\|length} | ${expression#array(item,length)} | + +**You do not need to use add `""` on both sides of `${}`, the generated content will be prefixed and suffixed according to the definition of generator** + diff --git a/versioned_docs/version-2.6.1/plugin-center/observability/_category_.json b/versioned_docs/version-2.6.1/plugin-center/observability/_category_.json new file mode 100644 index 00000000000..5a1e175c459 --- /dev/null +++ b/versioned_docs/version-2.6.1/plugin-center/observability/_category_.json @@ -0,0 +1,4 @@ +{ + "label": "Observability", + "position": 5 +} diff --git a/versioned_docs/version-2.6.1/plugin-center/observability/logging-aliyun-sls.md b/versioned_docs/version-2.6.1/plugin-center/observability/logging-aliyun-sls.md new file mode 100644 index 00000000000..a4f8de782e0 --- /dev/null +++ b/versioned_docs/version-2.6.1/plugin-center/observability/logging-aliyun-sls.md @@ -0,0 +1,139 @@ +--- +title: Logging-Aliyun-Sls Plugin +keywords: ["logging"] +description: logging plugin +--- + +# 1. Overview + +## 1.1 Plugin Name + +* Logging-AliyunSls Plugin + +## 1.2 Appropriate Scenario + +* collect http request information to aliyun sls, analysis request information by aliyun sls platform. + +## 1.3 Plugin functionality + +* The gateway receives requests from the client, forwards them to the server, and returns the server results to the client. The gateway can record the details of each request, +* the plugin records access logs and sends to aliyun sls platform. + +## 1.4 Plugin code + +* Core Module `shenyu-plugin-logging-aliyun-sls` + +* Core Class `org.apache.shenyu.plugin.aliyun.sls.LoggingAliYunSlsPlugin` +* Core Class `org.apache.shenyu.plugin.aliyun.sls.client.AliyunSlsLogCollectClient` + +## 1.5 Added Since Which shenyu version + +ShenYu 2.5.0 + +# 2. How to use plugin + +## 2.1 Plugin-use procedure chart + +![](/img/shenyu/plugin/plugin_use_en.jpg) + +## 2.2 Import pom + +- import maven config in shenyu-bootstrap project's `pom.xml` file. + +```xml + + + org.apache.shenyu + shenyu-spring-boot-starter-plugin-logging-aliyun-sls + ${project.version} + + +``` + +## 2.3 Enable plugin + +- In `shenyu-admin` --> BasicConfig --> Plugin --> `loggingAliyunSls` set Status enable. + +## 2.4 Config plugin + +### 2.4.1 Plugin configuration + +![](/img/shenyu/plugin/logging/logging-aliyun-sls/plugin-config-en.jpg) + +| config-item | type | description | remarks | +| :-------------- | :------ | :----------------------------------------------------------- | :----------------- | +| accessId | String | accessId | must | +| accesskey | String | accesskey | must | +| host | String | host name, example:cn-guangzhou.log.aliyuncs.com | must | +| projectName | String | log project name | optional, default shenyu | +| logStoreName | String | log store name | optional, default shenyu-logstore | +| topic | String | aliyun sls log topic | optional, default shenyu-topic | +| ttlInDay | Integer | ttl times in one day | optional, default 3 | +| shardCount | Integer | aliyun sls log shard count | optional, default 10 | +| sendThreadCount | Integer | send log to aliyun sls thread number | optional, default 1 | +| ioThreadCount | Integer | io thread count | optional, default 1 | +| sampleRate | String | sample consume rate | optional, default 1 | +| maxRequestBody | Integer | max request body | optional, default 524288 | +| maxResponseBody | Integer | max response body | optional, default 524288 | +| bufferQueueSize | Integer | consume log queue size | optional, default 50000 | + + +### 2.4.2 Configuration Selectors and Rules + +* Selector and rule Config. Please refer: [Selector and rule config](../../user-guide/admin-usage/selector-and-rule.md). + +## 2.5 Logging Info + +collect request info as follows + +| Field Name | Meaning | Description | Remarks | +|:----------------------|:-------------------------------------------------------------------------------------------------------------------------------------------------------------------:|:------------------------------|:----| +| clientIp | Client IP | | | +| timeLocal | Request time string, format: yyyy-MM-dd HH:mm:ss.SSS | | | +| method | request method (different rpc type is not the same, http class for: get, post wait, rpc class for the interface name) | | | +| requestHeader | Request header (json format) | | | +| responseHeader | Response header (json format) | | | +| queryParams | Request query parameters | | | +| requestBody | Request Body (body of binary type will not be captured) | | | +| requestUri | Request uri | | | +| responseBody | Response body | | | +| responseContentLength | Response body size | | | +| rpcType | rpc type | | | +| status | response status | | | +| upstreamIp | Upstream (program providing the service) IP | | | +| upstreamResponseTime | Time taken by the upstream (program providing the service) to respond to the request (ms ms) | | | +| userAgent | Requested user agent | | | +| host | The requested host | | | +| module | Requested modules | | | +| path | The requested path | | | +| traceId | Requested Link Tracking ID | Need to access link tracking plugins, such as skywalking,zipkin | | + +## 2.6 Examples + +### 2.6.1 Collect Http Log by aliyun sls platform + +#### 2.6.1.1 Plugin Configuration + +* Open the plugin and configure aliyun-sls, configure it as follows. + +![](/img/shenyu/plugin/logging/logging-aliyun-sls/plugin-config-en.jpg) + +#### 2.6.1.2 Selector Configuration + +![](/img/shenyu/plugin/logging/logging-aliyun-sls/aliyun-sls-log-selector-en.png) + +#### 2.6.1.3 Rule Configuration + +![](/img/shenyu/plugin/logging/logging-aliyun-sls/aliyun-sls-log-rule-en.png) + +#### 2.6.1.4 Send Request + +![](/img/shenyu/plugin/logging/logging-aliyun-sls/call-service.png) + +#### 2.6.1.5 Aliyun sls Platform Display + +![](/img/shenyu/plugin/logging/logging-aliyun-sls/aliyun-sls-log.jpg) + +# 3. How to disable plugin + +- In `shenyu-admin` --> BasicConfig --> Plugin --> `loggingAliyunSls` set Status disable. diff --git a/versioned_docs/version-2.6.1/plugin-center/observability/logging-elasticsearch.md b/versioned_docs/version-2.6.1/plugin-center/observability/logging-elasticsearch.md new file mode 100644 index 00000000000..8354a5b7006 --- /dev/null +++ b/versioned_docs/version-2.6.1/plugin-center/observability/logging-elasticsearch.md @@ -0,0 +1,183 @@ +--- +title: Logging-ElasticSearch Plugin +keywords: ["Logging", "ElasticSearch"] +description: Logging-ElasticSearch Plugin +--- +# 1. Overview + +## 1.1 Plugin Name + +* Logging-ElasticSearch Plugin + +## 1.2 Appropriate Scenario + +* collect http request info to elasticsearch, query or display request info by another application(kibana). + +## 1.3 Plugin functionality + +>`Apache ShenYu` The gateway receives requests from the client, forwards them to the server, and returns the server results to the client. The gateway can record the details of each request, +>The list includes: request time, request parameters, request path, response result, response status code, time consumption, upstream IP, exception information waiting. +>Shenyu gateway can record access logs through logging-elasticsearch-plugin and send access logs to elasticsearch database. + +## 1.4 Plugin code + +* Core Module `shenyu-plugin-logging-elasticsearch` + +* Core Class `org.apache.shenyu.plugin.logging.elasticsearch.LoggingElasticSearchPlugin` +* Core Class `org.apache.shenyu.plugin.logging.elasticsearch.client.ElasticSearchLogCollectClient` + +## 1.5 Added Since Which shenyu version + +* Since 2.5.0 + +## 1.6 Technical Solutions + +* Architecture Diagram + +![](/img/shenyu/plugin/logging/logging-elasticsearch/logging-elasticsearch-arch.png) + +# 2. How to use plugin + +## 2.1 Plugin-use procedure chart + +![](/img/shenyu/plugin/plugin_use_en.jpg) + +## 2.2 Import pom + +* Add the dependency of logging-elasticsearch to the Shenyu-bootstrap-module 's `pom.xml` file. + +```xml + + + org.apache.shenyu + shenyu-spring-boot-starter-plugin-logging-elasticsearch + ${project.version} + + +``` + +## 2.3 Enable plugin + +* In `shenyu-admin` --> Basic Configuration --> Plugin Management --> `loggingElasticSearch`, configure the ElasticSearch parameter and set it to on. + +## 2.4 Config plugin + +### 2.4.1 Open the plugin and configure elasticsearch, configure it as follows. + +![](/img/shenyu/plugin/logging/logging-elasticsearch/logging-elasticsearch-config-en.png) + +- The individual configuration items are described as follows: + +| config-item | type | description | remarks | +|:----------------| :------ | :----------------------------------------------------------- | :---------------------------------- | +| host | String | host name | must | +| port | String | port num | must | +| sampleRate | String | Sampling rate, range 0~1, 0: off, 0.01: acquisition 1%, 1: acquisition 100% | Optional, default 1, all collection | +| compressAlg | String | Compression algorithm, no compression by default, currently supports LZ4 compression | Optional, no compression by default | +| maxResponseBody | Ingeter | Maximum response size, above the threshold no response will be collected | Optional, default 512KB | +| maxRequestBody | Ingeter | Maximum request body size, above the threshold no request body will be collected | Optional, default 512KB | +Except for host, port, all others are optional, in most cases only these 3 items need to be configured. + +### 2.4.2 Configuring Selectors and Rulers + +For detailed configuration of selectors and rules, please refer to: [Selector and rule management](../../user-guide/admin-usage/selector-and-rule)。 +In addition sometimes a large gateway cluster corresponds to multiple applications (business), different applications (business) corresponds to different topics, related to isolation, +then you can configure different topics (optional) and sampling rate (optional) by selector, the meaning of the configuration items as shown in the table above. +The operation is shown below: + +![](/img/shenyu/plugin/logging/logging-elasticsearch/logging-elasticsearch-option.png) + +## 2.5 Logging information + +The fields of the captured access log are as follows. + +| Field Name | Meaning | Description | Remarks | +| :-------------------- | :----------------------------------------------------------: | :----------------------------------------------------------- | :------ | +| clientIp | Client IP | | | +| timeLocal | Request time string, format: yyyy-MM-dd HH:mm:ss.SSS | | | +| method | request method (different rpc type is not the same, http class for: get, post wait, rpc class for the interface name) | | | +| requestHeader | Request header (json format) | | | +| responseHeader | Response header (json format) | | | +| queryParams | Request query parameters | | | +| requestBody | Request Body (body of binary type will not be captured) | | | +| requestUri | Request uri | | | +| responseBody | Response body | | | +| responseContentLength | Response body size | | | +| rpcType | rpc type | | | +| status | response status | | | +| upstreamIp | Upstream (program providing the service) IP | | | +| upstreamResponseTime | Time taken by the upstream (program providing the service) to respond to the request (ms ms) | | | +| userAgent | Requested user agent | | | +| host | The requested host | | | +| module | Requested modules | | | +| path | The requested path | | | +| traceId | Requested Link Tracking ID | Need to access link tracking plugins, such as skywalking,zipkin | | + + +## 2.6 Examples + +### 2.6.1 Collect Http Log by ElasticSearch + +#### 2.6.1.1 Install ElasticSearch + +Users need to deploy the `ElasticSearch` service to collect + +##### 2.6.1.1.1 Installing ElasticSearch under Windows Environment + +- To [download address](https://www.elastic.co/downloads/elasticsearch) Select Windows version to download +- After downloading the installation package, unzip it, enter the `bin` directory, and double-click to execute `elasticsearch.bat` to start +- The default startup port is `9200`. Access`http://localhost:9200`, verify success + +![](/img/shenyu/plugin/logging/logging-elasticsearch/elasticsearch-success.png) + +##### 2.6.1.1.2 Installing ElasticSearch in MacOS environment + +- To [download address](https://www.elastic.co/downloads/elasticsearch) Select Windows version to download +- After downloading the installation package, unzip it, enter the `bin` directory and execute the startup command on the terminal: `./elasticsearch` +- The default startup port is `9200`. Access `http://localhost:9200`, verify success + +![](/img/shenyu/plugin/logging/logging-elasticsearch/elasticsearch-success.png) + +#### 2.6.1.2 Install Kibana + +##### 2.6.1.2.1 Installing Kibana under Windows Environment + +- To [download address](https://www.elastic.co/cn/downloads/kibana) Select Windows version to download +- After downloading the installation package, unzip it, enter the `bin` directory, and double-click to execute `kibana.bat` to start +- The default startup port is `5601`. Access `http://localhost:5601`, verify success + +![](/img/shenyu/plugin/logging/logging-elasticsearch/kibana-success.png) + +##### 2.6.1.2.2 Installing Kibana in MacOS environment + +- To [download address](https://www.elastic.co/cn/downloads/kibana) Select Windows version to download +- After downloading the installation package, unzip it, enter the `bin` directory and execute the startup command on the terminal: `./kibana` +- The default startup port is `5601`. Access `http://localhost:5601`, verify success + +![](/img/shenyu/plugin/logging/logging-elasticsearch/kibana-success.png) + +#### 2.6.1.3 Plugin Configuration + +![](/img/shenyu/plugin/logging/logging-elasticsearch/logging-elasticsearch-config-en.png) + +#### 2.6.1.4 Selector and Rule Configuration + +* For detailed configuration of selectors and rules, please refer to:[Selector and rule management](../../user-guide/admin-usage/selector-and-rule)。 + +#### 2.6.1.5 Using postman to initiate a request + +![](/img/shenyu/plugin/logging/logging-elasticsearch/postman-request.png) + +#### 2.6.1.6 Querying data using kibana + +![](/img/shenyu/plugin/logging/logging-elasticsearch/index.png) + +- The first time you use the plug-in, you will automatically create a `shenyu-access-logging` index + +![](/img/shenyu/plugin/logging/logging-elasticsearch/data.png) + +- Using ES query statement, the requested log information can be queried + +# 3. How to disable plugin + +- In `shenyu-admin` --> BasicConfig --> Plugin --> `LoggingElasticSearch` set Status disable. diff --git a/versioned_docs/version-2.6.1/plugin-center/observability/logging-huawei-lts.md b/versioned_docs/version-2.6.1/plugin-center/observability/logging-huawei-lts.md new file mode 100644 index 00000000000..48a59f66173 --- /dev/null +++ b/versioned_docs/version-2.6.1/plugin-center/observability/logging-huawei-lts.md @@ -0,0 +1,172 @@ +--- +title: Logging-Huawei-Lts Plugin +keywords: ["Logging"] +description: logging plugin + +--- + +# 1. Overview + +## 1.1 Plugin Name + +* Logging-HuaweiLts Plugin + +## 1.2 Appropriate Scenario + +* collect http request information to huawei lts, analysis request information by huawei lts platform. + +## 1.3 Plugin functionality + +- The gateway receives requests from the client, forwards them to the server, and returns the server results to the client. The gateway can record the details of each request, + +* the plugin records access logs and sends to huawei lts platform. + +## 1.4 Plugin code + +* Core Module `shenyu-plugin-logging-huawei-lts` + +* Core Class `org.apache.shenyu.plugin.huawei.lts.LoggingHuaweiLtsPlugin` +* Core Class `org.apache.shenyu.plugin.huawei.lts.client.HuaweiLtsLogCollectClient` + +## 1.5 Added Since Which shenyu version + +ShenYu 2.6.0 + +# 2. How to use plugin + +## 2.1 Plugin-use procedure chart + +![](/img/shenyu/plugin/plugin_use_en.jpg) + +- ## 2.2 Import pom + + - import maven config in shenyu-bootstrap project's `pom.xml` file. + +```xml + + + org.apache.shenyu + shenyu-spring-boot-starter-plugin-logging-huawei-lts + ${project.version} + + +``` + +## 2.3 Enable plugin + +- In `shenyu-admin` --> BasicConfig --> Plugin --> `loggingHuaweiLts` set Status enable. + +## 2.4 Config plugin + +### 2.4.1 Plugin configuration + +### ![](/img/shenyu/plugin/logging/logging-huawei-lts/plugin-config-en.png) + +| config-item | description | type | remarks | +| ------------------------- | ------------------------------------------------------------ | ------- | -------- | +| projectId | The project ID of the HUAWEI CLOUD account(project id) | String | must | +| accessKeyId | AK of the HUAWEI CLOUD account | String | must | +| accessKeySecret | SK of HUAWEI CLOUD account | String | must | +| regionName | Regions of Cloud Log Service | String | must | +| logGroupId | The log group ID of the LTS | String | must | +| logStreamId | The log stream ID of the LTS | String | must | +| totalSizeInBytes | The upper limit of the log size that can be cached by a single producer instance | int | optional | +| maxBlockMs | If the producer has insufficient free space, the caller's maximum block time on the send method, in milliseconds. The default is 60 seconds (60000 milliseconds), and 0 seconds is recommended. When the maxBlockMs value >= 0, it will block until the set time. If the blocking time is reached, the memory cannot be obtained, that is, an error will be reported and the log will be discarded. When the value of maxBlockMs=-1, it will be blocked until the sending is successful, and the log will not be discarded | long | optional | +| ioThreadCount | The thread pool size for executing log sending tasks | int | optional | +| batchSizeThresholdInBytes | When the cached log size in a ProducerBatch is greater than or equal to batchSizeThresholdInBytes, the batch will be sent | int | optional | +| batchCountThreshold | When the number of cached logs in a ProducerBatch is greater than or equal to batchCountThreshold, the batch will be sent | int | optional | +| lingerMs | The lingering time of a ProducerBatch from creation until it is sendable | int | optional | +| retries | If a ProducerBatch fails to send for the first time, the number of times it can be retried is recommended to be 3 times. If retries is less than or equal to 0, the ProducerBatch will directly enter the failure queue after the first sending failure | int | optional | +| baseRetryBackoffMs | The backoff time for the first retry | long | optional | +| maxRetryBackoffMs | Maximum backoff time for retries | long | optional | +| giveUpExtraLongSingleLog | For logs exceeding 1M, the data larger than 1M will be discarded after splitting | boolean | optional | +| enableLocalTest | 是否开启跨云上报日志 | boolean | optional | + +- get `regionName` + +![](/img/shenyu/plugin/logging/logging-huawei-lts/huawei-lts-regionName.png) + +| **区域名称** | **RegionName** | +| ------------ | -------------- | +| 华北-北京二 | cn-north-2 | +| 华北-北京四 | cn-north-4 | +| 华北-北京一 | cn-north-1 | +| 华东-上海二 | cn-east-2 | +| 华东-上海一 | cn-east-3 | +| 华南-广州 | cn-south-1 | +| 华南-深圳 | cn-south-2 | +| 西南-贵阳一 | cn-southwest-2 | + +- get `projectId` + +![](/img/shenyu/plugin/logging/logging-huawei-lts/huawei-lts-projectId.png) + +- get `accessKeyId` and `accessKeySecret` + +![](/img/shenyu/plugin/logging/logging-huawei-lts/huawei-lts-access.png) + +- get `logGroupId` and `logStreamId` + +![](/img/shenyu/plugin/logging/logging-huawei-lts/huawei-lts-logGroupId.png) + +![](/img/shenyu/plugin/logging/logging-huawei-lts/huawei-lts-logStreamId.png) + +### 2.4.2 Configuration Selectors and Rules + +* Selector and rule Config. Please refer: [Selector and rule config](../../user-guide/admin-usage/selector-and-rule.md). + +## 2.5 Logging Info + +collect request info as follows + +| Field Name | Meaning | Description | Remarks | +| :-------------------- | :----------------------------------------------------------: | :----------------------------------------------------------- | :------ | +| clientIp | Client IP | | | +| timeLocal | Request time string, format: yyyy-MM-dd HH:mm:ss.SSS | | | +| method | request method (different rpc type is not the same, http class for: get, post wait, rpc class for the interface name) | | | +| requestHeader | Request header (json format) | | | +| responseHeader | Response header (json format) | | | +| queryParams | Request query parameters | | | +| requestBody | Request Body (body of binary type will not be captured) | | | +| requestUri | Request uri | | | +| responseBody | Response body | | | +| responseContentLength | Response body size | | | +| rpcType | rpc type | | | +| status | response status | | | +| upstreamIp | Upstream (program providing the service) IP | | | +| upstreamResponseTime | Time taken by the upstream (program providing the service) to respond to the request (ms ms) | | | +| userAgent | Requested user agent | | | +| host | The requested host | | | +| module | Requested modules | | | +| path | The requested path | | | +| traceId | Requested Link Tracking ID | Need to access link tracking plugins, such as skywalking,zipkin | | + +## 2.6 Examples + +### 2.6.1 Collect Http Log by tencent cls platform + +#### 2.6.1.1 Plugin Configuration + +* Open the plugin and configure huawei lts, configure it as follows. + +![](/img/shenyu/plugin/logging/logging-huawei-lts/plugin-config-en.png) + +#### 2.6.1.2 Selector Configuration + +![](/img/shenyu/plugin/logging/logging-huawei-lts/huawei-lts-log-selector-en.png) + +#### 2.6.1.3 Rule Configuration + +![](/img/shenyu/plugin/logging/logging-huawei-lts/huawei-lts-log-rule-en.png) + +#### 2.6.1.4 Send Request + +![](/img/shenyu/plugin/logging/logging-huawei-lts/call-service.png) + +#### 2.6.1.5 Huawei lts Platform Display + +![](/img/shenyu/plugin/logging/logging-huawei-lts/huawei-lts-log.png) + +# 3. How to disable plugin + +- In `shenyu-admin` --> BasicConfig --> Plugin -->`loggingHuaweiLts`set Status disable. diff --git a/versioned_docs/version-2.6.1/plugin-center/observability/logging-kafka.md b/versioned_docs/version-2.6.1/plugin-center/observability/logging-kafka.md new file mode 100644 index 00000000000..feb312c7e61 --- /dev/null +++ b/versioned_docs/version-2.6.1/plugin-center/observability/logging-kafka.md @@ -0,0 +1,162 @@ +--- +title: Logging-Kafka Plugin +keywords: ["Logging", "kafka"] +description: Logging-Kafka Plugin +--- + +# 1. Overview + +## 1.1 Plugin Name + +* Logging-Kafka Plugin + +## 1.2 Appropriate Scenario + +* collect http request log to Kafka, consume Kafka message to another application and analysis. + +## 1.3 Plugin functionality + +>`Apache ShenYu` The gateway receives requests from the client, forwards them to the server, and returns the server results to the client. The gateway can record the details of each request, +> The list includes: request time, request parameters, request path, response result, response status code, time consumption, upstream IP, exception information waiting. +> The Logging-Kafka plugin is a plugin that records access logs and sends them to the Kafka cluster. + +## 1.4 Plugin code + +* Core Module `shenyu-plugin-logging-kafka`. + +* Core Class `org.apache.shenyu.plugin.logging.kafka.LoggingKafkaPlugin` +* Core Claas `org.apache.shenyu.plugin.logging.kafka.client.KafkaLogCollectClient` + +## 1.5 Added Since Which shenyu version + +* Since ShenYu 2.5.0 + +## 1.6 Technical Solutions + +* Architecture Diagram + +![](/img/shenyu/plugin/logging/logging-kafka/logging-kafka-arch.jpg) + +* Full asynchronous collection and delivery of `Logging` inside the `Apache ShenYu` gateway + +* Logging platform by consuming the logs in the `Kafka` cluster for repository, and then using `Grafana`, `Kibana` or other visualization platform to display + + +# 2. How to use plugin + +## 2.1 Plugin-use procedure chart + +![](/img/shenyu/plugin/logging/logging-console/loggingConsole-use-en.png) + +## 2.2 Import pom + +* Add the `Logging-Kafka` dependency to the gateway's `pom.xml` file. + +```xml + + + org.apache.shenyu + shenyu-spring-boot-starter-plugin-logging-kafka + ${project.version} + + +``` + +## 2.3 Enable plugin + +* In `shenyu-admin` --> Basic Configuration --> Plugin Management --> `loggingKafka`, configure the kafka parameter and set it to on. + +## 2.4 Config plugin + +### 2.4.1 Open the plugin and configure kafka, configure it as follows. + +![](/img/shenyu/plugin/logging/logging-config-en.png) + +* The individual configuration items are described as follows: + +| | | | | +|:----------------------------------|:---------------------|:----------------------------------|:------------| +| config-item | type | description | remarks | +| topic | String | Message Queue Topics | must | +| namesrvAddr | String | Message queue nameserver address | must | +| sampleRate | String | Sampling rate, range 0~1, 0: off, 0.01: acquisition 1%, 1: acquisition 100% | Optional, default 1, all collection | +| compressAlg | String | Compression algorithm, no compression by default, currently supports LZ4 compression | Optional, no compression by default | +| maxResponseBody | Ingeter | Maximum response size, above the threshold no response will be collected | Optional, default 512KB | +| maxRequestBody | Ingeter | Maximum request body size, above the threshold no request body will be collected | Optional, default 512KB | +Except for topic, namesrvAddr, all others are optional, in most cases only these 3 items need to be configured. The default group id is "shenyu-access-logging" + +### 2.4.2 Configuring Selectors and Rulers + +* For detailed configuration of selectors and rules, please refer to: [Selector and rule management](../../user-guide/admin-usage/selector-and-rule)。 + +In addition, sometimes a large gateway cluster corresponds to multiple applications (business), different applications (business) corresponds to different topics, related to isolation, +then you can configure different topics (optional) and sampling rate (optional) by selector, the meaning of the configuration items as shown in the table above. +The operation is shown below: +![](/img/shenyu/plugin/logging/logging-config.png) + +## 2.5 Logging Info + +collect request info as follows + +| Field Name | Meaning | Description | Remarks | +|:----------------------|:-------------------------------------------------------------------------------------------------------------------------------------------------------------------:|:------------------------------|:----| +| clientIp | Client IP | | | +| timeLocal | Request time string, format: yyyy-MM-dd HH:mm:ss.SSS | | | +| method | request method (different rpc type is not the same, http class for: get, post wait, rpc class for the interface name) | | | +| requestHeader | Request header (json format) | | | +| responseHeader | Response header (json format) | | | +| queryParams | Request query parameters | | | +| requestBody | Request Body (body of binary type will not be captured) | | | +| requestUri | Request uri | | | +| responseBody | Response body | | | +| responseContentLength | Response body size | | | +| rpcType | rpc type | | | +| status | response status | | | +| upstreamIp | Upstream (program providing the service) IP | | | +| upstreamResponseTime | Time taken by the upstream (program providing the service) to respond to the request (ms ms) | | | +| userAgent | Requested user agent | | | +| host | The requested host | | | +| module | Requested modules | | | +| path | The requested path | | | +| traceId | Requested Link Tracking ID | Need to access link tracking plugins, such as skywalking,zipkin | | + + +## 2.6 Examples + +### 2.6.1 Collect Http Log by Kafka + +#### 2.6.1.1 Plugin Configuration + +Open the plugin and configure kafka, configure it as follows. + +![](/img/shenyu/plugin/logging/logging-kafka/logging-config-cn.png) + +#### 2.6.1.2 Selector Configuration + +For detailed configuration of selectors and rules, please refer to: [Selector and rule management](../../user-guide/admin-usage/selector-and-rule)。 + +In addition, sometimes a large gateway cluster corresponds to multiple applications (business), different applications (business) corresponds to different topics, related to isolation, +then you can configure different topics (optional) and sampling rate (optional) by selector, the meaning of the configuration items as shown in the table above. +The operation is shown below: +![](/img/shenyu/plugin/logging/logging-kafka/logging-option-topic.png) + +#### 2.6.1.3 Rule Configuration + +![](/img/shenyu/plugin/logging/logging-kafka/log-rule-en.png) + +#### 2.6.1.4 Request Service + +![](/img/shenyu/plugin/logging/logging-rocketmq/call-service.png) + +#### 2.6.1.5 Consumption and display of Logging + +As each logging platform has differences, such as storage available clickhouse, ElasticSearch, etc., visualization has self-developed or open source Grafana, Kibana, etc.. +Logging-Kafka plugin uses Kafka to decouple production and consumption, while outputting logs in json format, +consumption and visualization require users to choose different technology stacks to achieve their own situation.= + +# 3. How to disable plugin + +- In `shenyu-admin` --> BasicConfig --> Plugin --> `loggingKafka` set Status disable. + + + diff --git a/versioned_docs/version-2.6.1/plugin-center/observability/logging-plugin.md b/versioned_docs/version-2.6.1/plugin-center/observability/logging-plugin.md new file mode 100644 index 00000000000..3bf717aecff --- /dev/null +++ b/versioned_docs/version-2.6.1/plugin-center/observability/logging-plugin.md @@ -0,0 +1,117 @@ +--- +title: Logging Plugin +keywords: ["logging"] +description: logging plugin +--- + +# 1. Overview + +## 1.1 Plugin Name + +* Logging-Console Plugin + +## 1.2 Appropriate Scenario + +* Users may want to view the information about request(including request headers, request parameters, response headers, response body...etc) where in the side of gateway when debugging during development or troubleshooting problems online. + +## 1.3 Plugin functionality + +* Collect http request url, header, request body, response and response body by logback or log4j, the log file will be saved locally. + +## 1.4 Plugin code + +* Core Module `shenyu-pluign-logging-console`. + +* Core Class `org.apache.shenyu.plugin.logging.console.LoggingConsolePlugin` + +## 1.5 Added Since Which shenyu version + +* Since ShenYu 2.4.0 + +# 2. How to use plugin + +## 2.1 Plugin-use procedure chart + +![](/img/shenyu/plugin/logging/logging-console/loggingConsole-use-en.png) + +## 2.2 Import pom + +- import maven config in shenyu-bootstrap project's `pom.xml` file. + +```xml + + org.apache.shenyu + shenyu-spring-boot-starter-plugin-logging-console + ${project.version} + +``` + +## 2.3 Enable plugin + +- In shenyu-admin --> BasicConfig --> Plugin --> loggingConsole set Status enable. + +## 2.4 Config plugin + +* Selector and rule Config. Please refer: [Selector and rule config](../../user-guide/admin-usage/selector-and-rule.md). + +## 2.5 Examples + +## 2.5.1 Collect all http request log + +> you must open loggingConsole plugin before you use loggingConsole plugin. + +### 2.5.1.1 Selector Configuration + +![](/img/shenyu/plugin/logging/logging-console/log-selector-en.jpg) + +### 2.5.1.2 Rule Configuration + +![](/img/shenyu/plugin/logging/logging-console/log-rule-en.jpg) + +### 2.5.1.3 Call Http Service + +![](/img/shenyu/plugin/logging/logging-console/call-service.png) + +### 2.5.1.4 Check Result + +if the request arrived successfully, you will see request information as follow. + +``` +Request Uri: http://localhost:9195/test/payment +Request Method: POST + +[Request Headers Start] +Content-Type: application/json +Content-Length: 46 +Host: localhost:9195 +Connection: Keep-Alive +User-Agent: Apache-HttpClient/4.5.13 (Java/11.0.11) +Cookie: JSESSIONID=CD325CE813F61BB37783A1D0835959DD +Accept-Encoding: gzip,deflate +[Request Headers End] + +[Request Body Start] +{ + "userId": "11", + "userName": "xiaoming" +} +[Request Body End] + +Response Code: 200 OK + +[Response Headers Start] +transfer-encoding: chunked +Content-Length: 37 +Content-Type: application/json +[Response Headers End] + +[Response Body Start] +{"userId":"11","userName":"xiaoming"} +[Response Body End] +``` + +# 3. How to disable plugin + +- In `shenyu-admin` --> BasicConfig --> Plugin --> `loggingConsole` set Status disable. + +![](/img/shenyu/plugin/logging/logging-console/unenable-log-plugin-en.jpg) diff --git a/versioned_docs/version-2.6.1/plugin-center/observability/logging-pulsar.md b/versioned_docs/version-2.6.1/plugin-center/observability/logging-pulsar.md new file mode 100644 index 00000000000..4f69a946a5f --- /dev/null +++ b/versioned_docs/version-2.6.1/plugin-center/observability/logging-pulsar.md @@ -0,0 +1,162 @@ +--- +title: Logging-Pulsar Plugin +keywords: ["Logging", "pulsar"] +description: Logging-Pulsar Plugin +--- + +# 1. Overview + +## 1.1 Plugin Name + +* Logging-Pulsar Plugin + +## 1.2 Appropriate Scenario + +* collect http request log to Pulsar, consume Pulsar message to another application and analysis. + +## 1.3 Plugin functionality + +>`Apache ShenYu` The gateway receives requests from the client, forwards them to the server, and returns the server results to the client. The gateway can record the details of each request, +> The list includes: request time, request parameters, request path, response result, response status code, time consumption, upstream IP, exception information waiting. +> The Logging-Pulsar plugin is a plugin that records access logs and sends them to the Pulsar cluster. + +## 1.4 Plugin code + +* Core Module `shenyu-plugin-logging-pulsar`. + +* Core Class `org.apache.shenyu.plugin.logging.pulsar.LoggingPulsarPlugin` +* Core Claas `org.apache.shenyu.plugin.logging.pulsar.client.PulsarLogCollectClient` + +## 1.5 Added Since Which shenyu version + +* Since ShenYu 2.5.1 + +## 1.6 Technical Solutions + +* Architecture Diagram + +![](/img/shenyu/plugin/logging/logging-pulsar/logging-pulsar-arch.jpg) + +* Full asynchronous collection and delivery of `Logging` inside the `Apache ShenYu` gateway + +* Logging platform by consuming the logs in the `Pulsar` cluster for repository, and then using `Grafana`, `Kibana` or other visualization platform to display + + +# 2. How to use plugin + +## 2.1 Plugin-use procedure chart + +![](/img/shenyu/plugin/logging/logging-console/loggingConsole-use-en.png) + +## 2.2 Import pom + +* Add the `Logging-Pulsar` dependency to the gateway's `pom.xml` file. + +```xml + + + org.apache.shenyu + shenyu-spring-boot-starter-plugin-logging-pulsar + ${project.version} + + +``` + +## 2.3 Enable plugin + +* In `shenyu-admin` --> Basic Configuration --> Plugin Management --> `loggingPulsar`, configure the pulsar parameter and set it to on. + +## 2.4 Config plugin + +### 2.4.1 Open the plugin and configure pulsar, configure it as follows. + +![](/img/shenyu/plugin/logging/logging-pulsar/logging-pulsar-config.jpg) + +* The individual configuration items are described as follows: + +| | | | | +|:----------------------------------|:---------------------|:----------------------------------|:------------| +| config-item | type | description | remarks | +| topic | String | Message Queue Topics | must | +| serviceUrl | String | Message queue service address | must | +| sampleRate | String | Sampling rate, range 0~1, 0: off, 0.01: acquisition 1%, 1: acquisition 100% | Optional, default 1, all collection | +| compressAlg | String | Compression algorithm, no compression by default, currently supports LZ4 compression | Optional, no compression by default | +| maxResponseBody | Ingeter | Maximum response size, above the threshold no response will be collected | Optional, default 512KB | +| maxRequestBody | Ingeter | Maximum request body size, above the threshold no request body will be collected | Optional, default 512KB | +Except for topic, serviceUrl, all others are optional, in most cases only these 3 items need to be configured. The default group id is "shenyu-access-logging" + +### 2.4.2 Configuring Selectors and Rulers + +* For detailed configuration of selectors and rules, please refer to: [Selector and rule management](../../user-guide/admin-usage/selector-and-rule)。 + +In addition, sometimes a large gateway cluster corresponds to multiple applications (business), different applications (business) corresponds to different topics, related to isolation, +then you can configure different topics (optional) and sampling rate (optional) by selector, the meaning of the configuration items as shown in the table above. +The operation is shown below: +![](/img/shenyu/plugin/logging/logging-config.png) + +## 2.5 Logging Info + +collect request info as follows + +| Field Name | Meaning | Description | Remarks | +|:----------------------|:-------------------------------------------------------------------------------------------------------------------------------------------------------------------:|:------------------------------|:----| +| clientIp | Client IP | | | +| timeLocal | Request time string, format: yyyy-MM-dd HH:mm:ss.SSS | | | +| method | request method (different rpc type is not the same, http class for: get, post wait, rpc class for the interface name) | | | +| requestHeader | Request header (json format) | | | +| responseHeader | Response header (json format) | | | +| queryParams | Request query parameters | | | +| requestBody | Request Body (body of binary type will not be captured) | | | +| requestUri | Request uri | | | +| responseBody | Response body | | | +| responseContentLength | Response body size | | | +| rpcType | rpc type | | | +| status | response status | | | +| upstreamIp | Upstream (program providing the service) IP | | | +| upstreamResponseTime | Time taken by the upstream (program providing the service) to respond to the request (ms ms) | | | +| userAgent | Requested user agent | | | +| host | The requested host | | | +| module | Requested modules | | | +| path | The requested path | | | +| traceId | Requested Link Tracking ID | Need to access link tracking plugins, such as skywalking,zipkin | | + + +## 2.6 Examples + +### 2.6.1 Collect Http Log by Pulsar + +#### 2.6.1.1 Plugin Configuration + +Open the plugin and configure pulsar, configure it as follows. + +![](/img/shenyu/plugin/logging/logging-pulsar/logging-pulsar-config.jpg) + +#### 2.6.1.2 Selector Configuration + +For detailed configuration of selectors and rules, please refer to: [Selector and rule management](../../user-guide/admin-usage/selector-and-rule)。 + +In addition, sometimes a large gateway cluster corresponds to multiple applications (business), different applications (business) corresponds to different topics, related to isolation, +then you can configure different topics (optional) and samplingf rate (optional) by selector, the meaning of the configuration items as shown in the table above. +The operation is shown below: +![](/img/shenyu/plugin/logging/logging-pulsar/logging-option-topic.jpg) + +#### 2.6.1.3 Rule Configuration + +![](/img/shenyu/plugin/logging/logging-pulsar/log-rule.jpg) + +#### 2.6.1.4 Request Service + +![](/img/shenyu/plugin/logging/logging-rocketmq/call-service.png) + +#### 2.6.1.5 Consumption and display of Logging + +As each logging platform has differences, such as storage available clickhouse, ElasticSearch, etc., visualization has self-developed or open source Grafana, Kibana, etc.. +Logging-Pulsar plugin uses Pulsar to decouple production and consumption, while outputting logs in json format, +consumption and visualization require users to choose different technology stacks to achieve their own situation.= + +# 3. How to disable plugin + +- In `shenyu-admin` --> BasicConfig --> Plugin --> `loggingPulsar` set Status disable. + + + diff --git a/versioned_docs/version-2.6.1/plugin-center/observability/logging-rocketmq.md b/versioned_docs/version-2.6.1/plugin-center/observability/logging-rocketmq.md new file mode 100644 index 00000000000..d59c340d7a4 --- /dev/null +++ b/versioned_docs/version-2.6.1/plugin-center/observability/logging-rocketmq.md @@ -0,0 +1,173 @@ +--- +title: Logging-RocketMQ Plugin +keywords: ["Logging", "RocketMQ"] +description: Logging-RocketMQ Plugin +--- + +# 1. Overview + +## 1.1 Plugin Name + +* Logging-RocketMQ Plugin + +## 1.2 Appropriate Scenario + +* collect http request log to rocketmq, consume rocketmq message to another application and analysis. + +## 1.3 Plugin functionality + +>`Apache ShenYu` The gateway receives requests from the client, forwards them to the server, and returns the server results to the client. The gateway can record the details of each request, +> The list includes: request time, request parameters, request path, response result, response status code, time consumption, upstream IP, exception information waiting. +> The Logging-RocketMQ plugin is a plugin that records access logs and sends them to the RocketMQ cluster. + +## 1.4 Plugin code + +* Core Module `shenyu-plugin-logging-rocketmq`. + +* Core Class `org.apache.shenyu.plugin.logging.rocketmq.LoggingRocketMQPlugin` +* Core Claas `org.apache.shenyu.plugin.logging.rocketmq.client.RocketMQLogCollectClient` + +## 1.5 Added Since Which shenyu version + +* Since ShenYu 2.5.0 + +## 1.6 Technical Solutions + +* Architecture Diagram + +![](/img/shenyu/plugin/logging/shenyu-agent-logging-arch.png) + +* Full asynchronous collection and delivery of `Logging` inside the `Apache ShenYu` gateway + +* Logging platform by consuming the logs in the `RocketMQ` cluster for repository, and then using `Grafana`, `Kibana` or other visualization platform to display + + +# 2. How to use plugin + +## 2.1 Plugin-use procedure chart + +![](/img/shenyu/plugin/plugin_use_en.jpg) + +## 2.2 Import pom + +* Add the `Logging-RocketMQ` dependency to the gateway's `pom.xml` file. + +```xml + + + org.apache.shenyu + shenyu-spring-boot-starter-plugin-logging-rocketmq + ${project.version} + + +``` + +## 2.3 Enable plugin + +* In `shenyu-admin` --> Basic Configuration --> Plugin Management --> `loggingRocketMQ`, configure the rocketMQ parameter and set it to on. + +## 2.4 Config plugin + +### 2.4.1 Open the plugin and configure rocketmq, configure it as follows. + +![](/img/shenyu/plugin/logging/logging-config-en.png) + +* The individual configuration items are described as follows: + +| | | | | +|:----------------------------------|:---------------------|:----------------------------------|:------------| +| config-item | type | description | remarks | +| topic | String | Message Queue Topics | must | +| namesrvAddr | String | Message queue nameserver address | must | +| producerGroup | String | Log Message Producer Group | must | +| sampleRate | String | Sampling rate, range 0~1, 0: off, 0.01: acquisition 1%, 1: acquisition 100% | Optional, default 1, all collection | +| compressAlg | String | Compression algorithm, no compression by default, currently supports LZ4 compression | Optional, no compression by default | +| maxResponseBody | Ingeter | Maximum response size, above the threshold no response will be collected | Optional, default 512KB | +| maxRequestBody | Ingeter | Maximum request body size, above the threshold no request body will be collected | Optional, default 512KB | +Except for topic, namesrvAddr, producerGroup, all others are optional, in most cases only these 3 items need to be configured. + +### 2.4.2 Configuring Selectors and Rulers + +* For detailed configuration of selectors and rules, please refer to: [Selector and rule management](../../user-guide/admin-usage/selector-and-rule)。 + +In addition, sometimes a large gateway cluster corresponds to multiple applications (business), different applications (business) corresponds to different topics, related to isolation, +then you can configure different topics (optional) and sampling rate (optional) by selector, the meaning of the configuration items as shown in the table above. +The operation is shown below: +![](/img/shenyu/plugin/logging/logging-option-topic-en.png) + +## 2.5 Logging Info + +collect request info as follows + +| Field Name | Meaning | Description | Remarks | +|:----------------------|:-------------------------------------------------------------------------------------------------------------------------------------------------------------------:|:------------------------------|:----| +| clientIp | Client IP | | | +| timeLocal | Request time string, format: yyyy-MM-dd HH:mm:ss.SSS | | | +| method | request method (different rpc type is not the same, http class for: get, post wait, rpc class for the interface name) | | | +| requestHeader | Request header (json format) | | | +| responseHeader | Response header (json format) | | | +| queryParams | Request query parameters | | | +| requestBody | Request Body (body of binary type will not be captured) | | | +| requestUri | Request uri | | | +| responseBody | Response body | | | +| responseContentLength | Response body size | | | +| rpcType | rpc type | | | +| status | response status | | | +| upstreamIp | Upstream (program providing the service) IP | | | +| upstreamResponseTime | Time taken by the upstream (program providing the service) to respond to the request (ms ms) | | | +| userAgent | Requested user agent | | | +| host | The requested host | | | +| module | Requested modules | | | +| path | The requested path | | | +| traceId | Requested Link Tracking ID | Need to access link tracking plugins, such as skywalking,zipkin | | + + +## 2.6 Examples + +### 2.6.1 Collect Http Log by RocketMQ + +#### 2.6.1.1 Plugin Configuration + +Open the plugin and configure rocketmq, configure it as follows. + +![](/img/shenyu/plugin/logging/logging-config-en.png) + +#### 2.6.1.2 Selector Configuration + +For detailed configuration of selectors and rules, please refer to: [Selector and rule management](../../user-guide/admin-usage/selector-and-rule)。 + +In addition, sometimes a large gateway cluster corresponds to multiple applications (business), different applications (business) corresponds to different topics, related to isolation, +then you can configure different topics (optional) and sampling rate (optional) by selector, the meaning of the configuration items as shown in the table above. +The operation is shown below: +![](/img/shenyu/plugin/logging/logging-option-topic-en.png) + +#### 2.6.1.3 Rule Configuration + +![](/img/shenyu/plugin/logging/logging-rocketmq/log-rule-en.jpg) + +#### 2.6.1.4 Request Service + +![](/img/shenyu/plugin/logging/logging-rocketmq/call-service.png) + +#### 2.6.1.5 Consumption and display of Logging + +As each logging platform has differences, such as storage available clickhouse, ElasticSearch, etc., visualization has self-developed or open source Grafana, Kibana, etc.. +Logging-RocketMQ plugin uses RocketMQ to decouple production and consumption, while outputting logs in json format, +consumption and visualization require users to choose different technology stacks to achieve their own situation. + + +#### 2.6.1.6 Panel Display + +Users can choose to visualize the implementation according to their own situation. +The following shows the effect of `Grafana`: +[Grafana Sandbox Experience](https://play.grafana.org) + +![](/img/shenyu/plugin/logging/grafana-loki-gateway.png) + +# 3. How to disable plugin + +- In `shenyu-admin` --> BasicConfig --> Plugin --> `loggingRocketMQ` set Status disable. + +![](/img/shenyu/plugin/logging/logging-rocketmq/logging-rocket-disabled-en.jpg) + + diff --git a/versioned_docs/version-2.6.1/plugin-center/observability/logging-tencent-cls.md b/versioned_docs/version-2.6.1/plugin-center/observability/logging-tencent-cls.md new file mode 100644 index 00000000000..9ab9890d474 --- /dev/null +++ b/versioned_docs/version-2.6.1/plugin-center/observability/logging-tencent-cls.md @@ -0,0 +1,143 @@ +--- +title: Logging-Tencent-Cls Plugin +keywords: ["Logging"] +description: logging plugin +--- + +# 1. Overview + +## 1.1 Plugin Name + +* Logging-TencentCls Plugin + +## 1.2 Appropriate Scenario + +* collect http request information to tencent cls, analysis request information by tencent cls platform. + +## 1.3 Plugin functionality + +* The gateway receives requests from the client, forwards them to the server, and returns the server results to the client. The gateway can record the details of each request, +* the plugin records access logs and sends to tencent cls platform. + +## 1.4 Plugin code + +* Core Module `shenyu-plugin-logging-tencent-cls` + +* Core Class `org.apache.shenyu.plugin.tencent.cls.LoggingTencentClsPlugin` +* Core Class `org.apache.shenyu.plugin.tencent.cls.client.TencentClsLogCollectClient` + +## 1.5 Added Since Which shenyu version + +ShenYu 2.5.1 + +# 2. How to use plugin + +## 2.1 Plugin-use procedure chart + +![](/img/shenyu/plugin/plugin_use_en.jpg) + +## 2.2 Import pom + +- import maven config in shenyu-bootstrap project's `pom.xml` file. + +```xml + + + org.apache.shenyu + shenyu-spring-boot-starter-plugin-logging-tencent-cls + ${project.version} + + +``` + +## 2.3 Enable plugin + +- In `shenyu-admin` --> BasicConfig --> Plugin --> `loggingTencentCls` set Status enable. + +## 2.4 Config plugin + +### 2.4.1 Plugin configuration + +![](/img/shenyu/plugin/logging/logging-tencent-cls/plugin-config-en.jpg) + +| config-item | type | remarks | description | +|:--------------------|:--------|:-------------------------------------|:---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| secretId | String | must | secretId | +| secretKey | String | must | secretKey | +| endpoint | String | must | host name, example:ap-guangzhou.cls.tencentcs.com | +| topic | String | optional, default shenyu-topic | topic | +| sendThreadCount | String | optional, default 1 | Number of core threads for log consumption callback | +| TotalSizeInBytes | Integer | optional, default 104857600 | The maximum log size that the instance can cache | +| MaxSendThreadCount | Integer | optional, default 50 | The maximum number of "goroutines" that the client can concurrently | +| MaxBlockSec | Integer | optional, default 60000 ms | The maximum amount of time the caller can block on the send method if the client is running out of free space.
If the required space cannot be satisfied after this time,
the send method will throw a TimeoutException. Set this value to a negative number if you want the send method to block until the required space is met | +| MaxBatchSize | Integer | optional, default 512 * 1024 (512KB) | When the cached log size in a Batch is greater than or equal to batchSizeThresholdInBytes, the batch will be sent, and the maximum size can be set to 5MB | +| MaxBatchCount | Integer | optional, default 4096 | When the number of logs cached in a batch is greater than or equal to batchCountThreshold, the batch will be sent and the maximum can be set to 40960 | +| LingerMs | Integer | optional, default 2000 ms | The duration of the batch from the creation to the time it can be sent, the minimum can be set to 100 milliseconds | +| Retries | Integer | optional, default 10 | If a Batch fails to be sent for the first time, the number of times it can be retried, if the retries is less than or equal to 0, the ProducerBatch will directly enter the failure queue after the first failure of sending | +| MaxReservedAttempts | Integer | optional, default 11 | Each batch that is attempted to be sent corresponds to an Attemp. This parameter is used to control the number of attempts returned to the user. By default, only the latest 11 attempts are retained. A larger parameter allows you to trace more information, but also consumes more memory | +| BaseRetryBackoffMs | Integer | optional, default 100 ms | Backoff time for the first retry The client samples the exponential backoff algorithm, and the planned waiting time for the Nth retry is baseRetryBackoffMs * 2^(N-1 | +| MaxRetryBackoffMs | Integer | optional, default 50 s | Maximum backoff time for retries | + +- get `topic` + +![](/img/shenyu/plugin/logging/logging-tencent-cls/tencent-topic.png) + +### 2.4.2 Configuration Selectors and Rules + +* Selector and rule Config. Please refer: [Selector and rule config](../../user-guide/admin-usage/selector-and-rule.md). + +## 2.5 Logging Info + +collect request info as follows + +| Field Name | Meaning | Description | Remarks | +|:----------------------|:---------------------------------------------------------------------------------------------------------------------:|:----------------------------------------------------------------|:--------| +| clientIp | Client IP | | | +| timeLocal | Request time string, format: yyyy-MM-dd HH:mm:ss.SSS | | | +| method | request method (different rpc type is not the same, http class for: get, post wait, rpc class for the interface name) | | | +| requestHeader | Request header (json format) | | | +| responseHeader | Response header (json format) | | | +| queryParams | Request query parameters | | | +| requestBody | Request Body (body of binary type will not be captured) | | | +| requestUri | Request uri | | | +| responseBody | Response body | | | +| responseContentLength | Response body size | | | +| rpcType | rpc type | | | +| status | response status | | | +| upstreamIp | Upstream (program providing the service) IP | | | +| upstreamResponseTime | Time taken by the upstream (program providing the service) to respond to the request (ms ms) | | | +| userAgent | Requested user agent | | | +| host | The requested host | | | +| module | Requested modules | | | +| path | The requested path | | | +| traceId | Requested Link Tracking ID | Need to access link tracking plugins, such as skywalking,zipkin | | + +## 2.6 Examples + +### 2.6.1 Collect Http Log by tencent cls platform + +#### 2.6.1.1 Plugin Configuration + +* Open the plugin and configure tencent-cls, configure it as follows. + +![](/img/shenyu/plugin/logging/logging-tencent-cls/plugin-config-en.jpg) + +#### 2.6.1.2 Selector Configuration + +![](/img/shenyu/plugin/logging/logging-tencent-cls/tencent-cls-log-selector-en.png) + +#### 2.6.1.3 Rule Configuration + +![](/img/shenyu/plugin/logging/logging-tencent-cls/tencent-cls-log-rule-en.png) + +#### 2.6.1.4 Send Request + +![](/img/shenyu/plugin/logging/logging-tencent-cls/call-service.png) + +#### 2.6.1.5 Tencent cls Platform Display + +![](/img/shenyu/plugin/logging/logging-tencent-cls/tencent-cls-log.jpg) + +# 3. How to disable plugin + +- In `shenyu-admin` --> BasicConfig --> Plugin --> `loggingTencentCls` set Status disable. diff --git a/versioned_docs/version-2.6.1/plugin-center/observability/metrics-plugin.md b/versioned_docs/version-2.6.1/plugin-center/observability/metrics-plugin.md new file mode 100644 index 00000000000..131a2344e8a --- /dev/null +++ b/versioned_docs/version-2.6.1/plugin-center/observability/metrics-plugin.md @@ -0,0 +1,245 @@ +--- +title: Metrics Plugin +keywords: ["Metrics"] +description: Metrics plugin +--- + +## Description + +* Metrics plugin is used to monitor its own running status(JVM-related) by gateway, include request response delay, QPS, TPS, and other related metrics. + +## Technical Solutions + +* Flow Diagram + ![](/img/shenyu/plugin/monitor/shenyu-metrics.png) +* Make even tracking in ShenYu Gateway by asynchronous or synchronous mode. + +* The `prometheus` server pulls metrics' through http request, and then displays it by `Grafana`. + +## Plugin Setting + +* Introduce `metrics` dependency in the pom.xml file of the gateway. + +```xml + + + org.apache.shenyu + shenyu-spring-boot-starter-plugin-metrics + ${project.version} + + +``` + +* modify this config in shenyu gateway yaml + +```yml +shenyu: + metrics: + enabled: false #false is close, true is open + name : prometheus + host: 127.0.0.1 + port: 8090 + jmxConfig: + props: + jvm_enabled: true #enable jvm monitoring +``` + +## Metrics Detail + +* All JVM,thread,memory,and other related information will be made event tracking,you can add a JVM module in the Grafana' panel, and it will be fully displayed, please refer to: https://github.com/prometheus/jmx_exporter + +* There are also the following custom `metrics` + +### shenyu gateway custom metrics + +| Name |type |labels | description | +|:----------------------------------- |:--------------------- |:------------- |:-------------------- | +|shenyu_request_total |Counter | none |collecting all requests of Apache ShenYu Gateway | +|shenyu_request_throw_total |Counter | none |collecting all exception requests of Apache ShenYu Gateway | +|shenyu_request_type_total |Counter | path,type |collecting all matched requests of monitor| +|shenyu_execute_latency_millis |histogram | none | ShenYu gateway execute time interval | + + +### jmx metrics + +| name | type | labals | help | +|:-------------------------------:|:-------:|:------:|:--------------------------------------------------------------:| +| jmx_config_reload_success_total | counter | | Number of times configuration have successfully been reloaded. | +| jmx_config_reload_failure_total | counter | | Number of times configuration have failed to be reloaded. | +| jmx_scrape_duration_seconds | gauge | | Time this JMX scrape took, in seconds. | +| jmx_scrape_error | gauge | | Non-zero if this scrape failed. | +| jmx_scrape_cached_beans | gauge | | Number of beans with their matching rule cached | +| jmx_scrape_duration_seconds | gauge | | Time this JMX scrape took, in seconds. | +| jmx_scrape_error | gauge | | Non-zero if this scrape failed. | +| jmx_scrape_cached_beans | gauge | | Number of beans with their matching rule cached | + +### jvm metrics + +#### StandardExports + +| name | type | labels | help | +|:-----------------------------:|:-------:|:------:|:------------------------------------------------------:| +| process_cpu_seconds_total | counter | | Total user and system CPU time spent in seconds. | +| process_start_time_seconds | gauge | | Start time of the process since unix epoch in seconds. | +| process_open_fds | gauge | | Number of open file descriptors. | +| process_max_fds | gauge | | Maximum number of open file descriptors. | +| process_virtual_memory_bytes | gauge | | Virtual memory size in bytes. | +| process_resident_memory_bytes | gauge | | Resident memory size in bytes. | + +#### MemoryPoolsExports + +| name | type | labels | help | +|:------------------------------------------:|:-----:|:----------------------:|:-----------------------------------------------------------------:| +| jvm_memory_objects_pending_finalization | gauge | {area="heap\|nonheap"} | The number of objects waiting in the finalizer queue. | +| jvm_memory_bytes_used | gauge | {area="heap\|nonheap"} | Used bytes of a given JVM memory area. | +| jvm_memory_bytes_committed | gauge | {area="heap\|nonheap"} | Committed (bytes) of a given JVM memory area. | +| jvm_memory_bytes_max | gauge | {area="heap\|nonheap"} | Max (bytes) of a given JVM memory area. | +| jvm_memory_bytes_init | gauge | {area="heap\|nonheap"} | Initial bytes of a given JVM memory area. | +| jvm_memory_pool_bytes_used | gauge | {pool} | Used bytes of a given JVM memory pool. | +| jvm_memory_pool_bytes_committed | gauge | {pool} | Committed bytes of a given JVM memory pool. | +| jvm_memory_pool_bytes_max | gauge | {pool} | Max bytes of a given JVM memory pool. | +| jvm_memory_pool_bytes_init | gauge | {pool} | Initial bytes of a given JVM memory pool. | +| jvm_memory_pool_collection_used_bytes | gauge | {pool} | Used bytes after last collection of a given JVM memory pool. | +| jvm_memory_pool_collection_committed_bytes | gauge | {pool} | Committed after last collection bytes of a given JVM memory pool. | +| jvm_memory_pool_collection_max_bytes | gauge | {pool} | Max bytes after last collection of a given JVM memory pool. | +| jvm_memory_pool_collection_init_bytes | gauge | {pool} | Initial after last collection bytes of a given JVM memory pool. | + +#### MemoryAllocationExports + +| name | type | labels | help | +|:-------------------------------------:|:-------:|:------:|:------------------------------------------------------------------------------------------:| +| jvm_memory_pool_allocated_bytes_total | counter | {pool} | Total bytes allocated in a given JVM memory pool. Only updated after GC, not continuously. | +| | | | | +| | | | | + +#### BufferPoolsExports + +| name | type | labels | help | +|:------------------------------:|:-----:|:------:|:------------------------------------------:| +| jvm_buffer_pool_used_bytes | gauge | {pool} | Used bytes of a given JVM buffer pool. | +| jvm_buffer_pool_capacity_bytes | gauge | {pool} | Bytes capacity of a given JVM buffer pool. | +| jvm_buffer_pool_used_buffers | gauge | {pool} | Used buffers of a given JVM buffer pool. | + +#### GarbageCollectorExports + +| name | type | labels | help | +|:-------------------------:|:-------:|:------:|:-------------------------------------------------------:| +| jvm_gc_collection_seconds | summary | {gc} | Time spent in a given JVM garbage collector in seconds. | + +#### ThreadExports + +| name | type | labels | help | +|:------------------------------:|:-------:|:-------:|:------------------------------------------------------------------------------------------------------:| +| jvm_threads_current | gauge | | Current thread count of a JVM | +| jvm_threads_daemon | gauge | | Daemon thread count of a JVM | +| jvm_threads_peak | gauge | | Peak thread count of a JVM | +| jvm_threads_started_total | counter | | Started thread count of a JVM | +| jvm_threads_deadlocked | gauge | | Cycles of JVM-threads that are in deadlock waiting to acquire object monitors or ownable synchronizers | +| jvm_threads_deadlocked_monitor | gauge | | Cycles of JVM-threads that are in deadlock waiting to acquire object monitors | +| jvm_threads_state | gauge | {state} | Current count of threads by state | + +#### ClassLoadingExports + +| name | type | labels | help | +|:--------------------------:|:-------:|:------:|:---------------------------------------------------------------------------------------:| +| jvm_classes_loaded | gauge | | The number of classes that are currently loaded in the JVM | +| jvm_classes_loaded_total | counter | | The total number of classes that have been loaded since the JVM has started execution | +| jvm_classes_unloaded_total | counter | | The total number of classes that have been unloaded since the JVM has started execution | + +#### VersionInfoExports + +| name | type | labels | help | +|:----:|:----:|:---------------------------------------------------------------------------------:|:---------------:| +| jvm | info | {version(java.runtime.version),vendor(java.vm.vendor),runtime(java.runtime.name)} | VM version info | + + +## Collect metrics + +Users need to install `Prometheus` service to collect + +### Install Prometheus in windows + +* Choose the corresponding environment [download address](https://prometheus.io/download/) to install +* Modify configuration file: `prometheus.yml` + + ```yaml + scrape_configs: + - job_name: 'Apache ShenYu' + # metrics_path defaults to '/metrics' + # scheme defaults to 'http'. + static_configs: + - targets: ['localhost:8090'] # metrics of apache shenyu are exposed on port 8090 by default + ``` + +* After the configuration is completed, you can directly double-click `prometheus.exe` in the window to start. The default boot port is `9090`,check `status`->`Targets` . Success can be verified at http://localhost:9090/ + +![](/img/shenyu/monitor/request-metric-6.png) + +### Install Prometheus in the macOS + +* Install prometheus with brew,After installation `prometheus` is in the `Cellar` folder under `homebrew`。 + +``` +brew install prometheus +``` + +* Execute the following command in the location of the prometheus.yml file to start prometheus。 + +``` +prometheus --config.file=prometheus.yml & +``` + +Visit `http://localhost:9090/` to verify that it starts normally。 + + +## Panel Display + +It is recommended to use `Grafana`, Users can customize the query to personalize the display panel. + +Here's how to install and deploy `Grafana` + +### Install Grafana in windows + +* Install Grafana + +[download](https://dl.grafana.com/oss/release/grafana-7.4.2.windows-amd64.zip) Unzip it and enter the `bin` directory and `double-click` `grafana-server.exe` to run it. Go to http://localhost:3000/?orgId=1 `admin/admin` to verify the success + +### Install Grafana in macOS + +* Install grafana using brew. + +``` +brew install grafana +``` + +* Start grafana as a service + +``` +brew services start grafana +``` + +Visit `http://localhost:3000/` to verify that it starts normally. + +### View monitoring data with Grafana + +* Configure the data source, select prometheus, note that the data source name is prometheus. + +![](/img/shenyu/monitor/request-metric-7.png) + +![](/img/shenyu/monitor/request-metric-8.png) + +* Config Custom Metric Dashboard `request_total`、`http_request_total` + +Click `Create` - `Import` and enter the [panel config json](https://shenyu.apache.org/img/shenyu/monitor/request_metric_dashboard.json) + +The final custom HTTP request monitoring panel looks like this: + +![](/img/shenyu/monitor/request-metric-1.png) + +![](/img/shenyu/monitor/request-metric-2.png) + +![](/img/shenyu/monitor/request-metric-3.png) + +![](/img/shenyu/monitor/request-metric-4.png) + +![](/img/shenyu/monitor/request-metric-5.png) diff --git a/versioned_docs/version-2.6.1/plugin-center/proxy/_category_.json b/versioned_docs/version-2.6.1/plugin-center/proxy/_category_.json new file mode 100644 index 00000000000..09c6722ca65 --- /dev/null +++ b/versioned_docs/version-2.6.1/plugin-center/proxy/_category_.json @@ -0,0 +1,4 @@ +{ + "label": "Proxy", + "position": 2 +} diff --git a/versioned_docs/version-2.6.1/plugin-center/proxy/divide-plugin.md b/versioned_docs/version-2.6.1/plugin-center/proxy/divide-plugin.md new file mode 100644 index 00000000000..5afd38ac67c --- /dev/null +++ b/versioned_docs/version-2.6.1/plugin-center/proxy/divide-plugin.md @@ -0,0 +1,145 @@ +--- +title: Divide Plugin +keywords: ["divide"] +description: divide plugin +--- + +# 1. Overview + +## 1.1 Plugin Name + +* `divide` Plugin + +## 1.2 Appropriate Scenario + +* Handling `http protocol` requests. +* Support traffic management, such as a/b test, grayscale test. +* Service Load Balancing. +* Set request timeout. + +## 1.3 Plugin functionality + +* Supports traffic management based on request information such as uri, header, and query. +* Supports setting the load balancing strategy for requests, and supports service warm-up. Currently, three strategies are supported: ip hash (consistent hash with virtual nodes), round-robbin (weighted polling), random (weighted random). +* Supports setting the maximum value of the request header, the maximum value of the request body, and the request level timeout. +* Supports setting the timeout retry policy and the number of retries. Currently, the retry policy supports: current (retrying the server that failed before) and failover (retrying other servers). + +## 1.4 Plugin Code + +* Core module is ```shenyu-plugin-divide```. +* Core class is ```org.apache.shenyu.plugin.divide.DividePlugin```. + +# 2. How to use plugin + +## 2.1 Plugin-use procedure chart + +![](/img/shenyu/plugin/divide/procedure-en.png) + +## 2.2 Import pom + +- Import maven in shenyu-bootstrap project's `pom.xml` file. + +```xml + + org.apache.shenyu + shenyu-spring-boot-starter-gateway + ${project.version} + +``` + +## 2.3 Enable plugin + +- In `shenyu-admin` --> BasicConfig --> Plugin --> `divide` set Status enable. + +![](/img/shenyu/plugin/divide/enable-en.png) + +## 2.4 Config plugin + +### 2.4.1 Configure access parameters in the client project configuration file + +* Client access method and server address. The following example uses the http access method. Currently, the client supports the following access methods: http, zookeeper, etcd, nacos, consul. For detailed access configuration parameters, please refer to [Client Access Configuration](docs/user-guide/property-config/register-center-access.md). +* Client configuration, including the protocol name and the routing address of the service, please use the http protocol here, and the value of contextPath must be configured as the routing address of each service. + +```yaml + shenyu: + register: + registerType: http + serverLists: http://localhost:9095 + props: + username: admin + password: 123456 + client: + http: # http protocol + props: + contextPath: /http # routing address for each service +``` + +### 2.4.2 Configure upstream validity detection parameters in the shenyu-admin configuration file + +The following example uses the http access method. Currently, the client supports the following access methods: http, zookeeper, etcd, nacos, consul. For detailed access configuration parameters, please refer to [Client Access Configuration](docs/user-guide/property-config/register-center-access.md). +> Only http-type registries support upstream detection. + +```yaml + shenyu: + register: + registerType: http # Only http-type register center support upstream detection. + serverLists: + props: + checked: true # The default is true, set to false, do not detect. + zombieCheckTimes: 5 # The maximum number of zombie upstream detections. If it exceeds 5 times, its validity will no longer be detected. The default value is 5. + scheduledTime: 10 # Timing detection interval, the default is 10 seconds. + zombieRemovalTimes: 60 # How many seconds the upstream is offline to be considered as a zombie upstream, the default is 60 seconds. +``` + +### 2.4.3 Configure the selector and rule information of the divide plugin in shenyu-admin + +After the client is started, the [selector and rule](../../user-guide/admin-usage/selector-and-rule) information will be automatically registered in shenyu-admin -> Plugin List -> Proxy -> Divide. + +![](/img/shenyu/plugin/divide/select-and-rule-en.png) + +#### 2.4.3.1 Selector configuration + +Example of divide selector. For general selector configuration, please refer to [Selectors and Rules](../../user-guide/admin-usage/selector-and-rule). + +![](/img/shenyu/plugin/divide/selector-en.png) + +##### 2.4.3.1.1 Selector handling information configuration + +- `host`: fill in `localhost`, this field is not used currently. +- `ip:port`: `ip` and port, fill in the `ip` + port of your real service here. +- `protocol`: `http` protocol, fill in `http:` or `https:`, if not fill in, the default is: `http:`. +- `startupTime`: Startup time in milliseconds. +- `weight`: load balancing weight, the default value of service startup automatic registration is 50. +- `warmupTime`: Warmup time, in milliseconds. The server during warmup will calculate the instantaneous weight, and the calculated value will be smaller than the actual configured weight to protect the server just started. The default value of service startup registration is 10. For example, the warm-up time is 100 milliseconds, the current startup is 50 milliseconds, the configured weight is 50, and the actual weight is 25. +- `status`: On or off, this selector is valid only in the on state. + +#### 2.4.3.2 Processing information configuration of rules + +Example of divide rule. For general rule configuration, please refer to [selectors and rules](../../user-guide/admin-usage/selector-and-rule). + +![](/img/shenyu/plugin/divide/rule-en.png) + +##### 2.4.3.2.1 Rule processing information configuration + +- `loadStrategy`: If the `http` client is a cluster, which load balancing strategy is used when the `Apache ShenYu` gateway is called, currently supports `roundRobin`, `random` and `hash`. +- `timeout`: The timeout for calling the `http` client. +- `retry Count`: The number of retries that failed to call the `http` client timeout. +- `headerMaxSize`: The maximum value of the requested `header`. +- `requestMaxSize`: The maximum value of the request body. +- `retryStrategy`: Supported since `2.4.3`, retry strategy after failure, default `current` to maintain compatibility with lower versions. For example, there are 3 downstream services `http:localhost:1111`, `http:localhost:1112` and `http:localhost:1113`, assuming the first load balancing to `http:localhost:1111` and `call failed`. Using the `current` strategy will continue to retry calling `http:localhost:1111`; using the `failover` strategy will retry calling other services such as `http:localhost:1112` through the `load balancing`, if it fails again at this time , call to `http:localhost:1113` until no service is available. + +## 2.5 Examples + +### 2.5.1 Example A/B Test + +To be added, welcome contribute. + +### 2.5.2 Example Grayscale Test + +To be added, welcome contribute. + +# 3. How to disable plugin + +- In `shenyu-admin` --> BasicConfig --> Plugin --> `divide` set Status disable. + +![](/img/shenyu/plugin/divide/disable-en.png) diff --git a/versioned_docs/version-2.6.1/plugin-center/proxy/dubbo-plugin.md b/versioned_docs/version-2.6.1/plugin-center/proxy/dubbo-plugin.md new file mode 100644 index 00000000000..0789ee9690e --- /dev/null +++ b/versioned_docs/version-2.6.1/plugin-center/proxy/dubbo-plugin.md @@ -0,0 +1,137 @@ +--- +title: Dubbo Plugin +keywords: ["dubbo"] +description: dubbo plugin +--- + +## Explanation + +* Dubbo is a plugin that converts `http protocol` into `Dubbo protocol` and it is also the key for gateway to realize dubbo generic service. +* Dubbo plugin needs to cooperate with metadata to realize dubbo calls. +* Apache Dubbo and Alibaba Dubbo users both use the same plugin. + +## Plugin Setting + +* Add related dependencies and enable plugin, please refer to: [Quick start with Dubbo](../../quick-start/quick-start-dubbo) . + +* `Dubbo` client access, please refer to: [Dubbo Proxy](../../user-guide/proxy/dubbo-proxy.md) . + +* Set selector and rule, please refer to: [Selector And Rule Config](../../user-guide/admin-usage/selector-and-rule) . + +* Since `version 2.4.3`, the new fields and meanings of the dubbo plugin: + + + + * `corethreads`:The number of core threads in the business thread pool。 + + * `queues`:The length of the blocking queue of the business thread pool, 0 means `unbounded blocking queue`。 + + * `threadpool`:There are five types of business thread pools: `fixed`, `eager`, `cached`, `limited` and `shared`. The first 4 types correspond to the thread pools officially provided by dubbo. Let's talk about `shared`, as its name implies, `all proxy plugins` share a `shared` thread pool, the advantage of this is that it can reduce the number of thread pools, thereby reducing memory and improving resource utilization。 + + * `threads`:The maximum number of threads in the business thread pool。 + +## Plugin Detail + +After the client accesses the `ShenYu` gateway, it will automatically register the selector and rule information. For details about the selector and rule configuration, see [Selector and Rule Config](../../user-guide/admin-usage/selector-and-rule) . + +#### Selector Handler + + + +Selector Handler, the `handle` field, is an operation that can be processed by the gateway after matching the traffic. For more information, please refer to [Plugin handle management](../plugin-handle-explanation) in Plugin Config. + +* details: + + * `host`:host string. + + * `ip:port`:ip+port string. + + * `protocol`:protocol default is 'http'. + + * `group`:the group of dubbo service. + + * `version`:the version of dubbo service. + + * `weight`:the server instance and participate in load balancing calculation. + + * `warmupTime`:the server's warm up time and and participate in load balancing calculation. + + * `startupTime`:the server's start time. + + * `status`:true: the server is available,false: the server is unavailable. + + * `gray`:enable gray routing. + +Gray routing + +if you want to user gray route in dubbo-plugin, you can click the `gray` button. + +* Gray level publishing can customize and control the traffic proportion of new version applications when publishing new version applications, gradually complete the full launch of new version applications, maximize the business risk caused by new version publishing, reduce the impact surface caused by faults, and support rapid roll back. + +when the gray is open,Gateway load balancing will select one node from the current node list for routing and you can modify node weights to change the weight of nodes in the load balancing algorithm. +It should be noted that,if your business instance not use the client jar of 'shenyu-client-apache-dubbo' or 'shenyu-client-alibaba-dubbo', You should add gray node information manually on this selector page. + +#### Rule Handler + + + +Rule Handler, the `handle` field, can be performed by the gateway after the final matching of traffic. For more information, please refer to [Plugin handle management](../plugin-handle-explanation) in Plugin Config. + +* details: + + * `loadbalance`:the loadbalance of dubbo service, if the gray node selection fails, the default load balancing method will be used. + +* Apache ShenYu will obtain the real IP of the corresponding service and initiate rpc proxy calls from registration center of dubbo. + + +## Metadata + +* Every dubbo interface method corresponds to a piece of metadata, which can be found in `shenyu-admin` --> BasicConfig -> Metadata . + + + +* AppName: The name of the application to which this piece of metadata belongs. + +* MethodName: The name of the method that needs to be called. + +* Path: your http request path. + +* PathDescribe: Description of the path, for easy viewing. + +* ParamsType: List of parameter types of dubbo interface, there are two declaration methods here: + e.g. we have an interface `update(Integer id, String name, Integer age)` + + * Type list + + ```yaml + java.lang.Integer,java.lang.String,java.lang.Integer + ``` + + * According to the order of the parameter types of the interface, separated by `,` + + * When requesting to pass parameters, **the parameters must be passed in strictly in accordance with the order of the parameter types**, if a parameter without value use `null` as a placeholder. + + Request body example: `{"id":1,"name": null,"age":18}` + + * Name mapping + + ```yaml + {"id":"java.lang.Integer","name":"java.lang.String","age":"java.lang.Integer"} + ``` + + * Use `"parameter name":"parameter type"` to represent a parameter, set in order of interface parameter type, separated by `,` + + * No need to pay attention to the order when requesting, and no need to use null placeholders. + + Request body example: `{"name":"Mike","id":1}` + +* RpcExpand: corresponding to some configurations of dubbo interface; If you want to adjust, please modify here, which support json format like the following fields: + +```yaml +{"timeout":10000,"group":"",version":"","loadbalance":"","retries":1} +``` + +* Interface: The fully-qualified name for dubbo interface . + +* RpcType: Choose `dubbo` . + diff --git a/versioned_docs/version-2.6.1/plugin-center/proxy/grpc-plugin.md b/versioned_docs/version-2.6.1/plugin-center/proxy/grpc-plugin.md new file mode 100644 index 00000000000..85a298e66c1 --- /dev/null +++ b/versioned_docs/version-2.6.1/plugin-center/proxy/grpc-plugin.md @@ -0,0 +1,81 @@ +--- +title: gRPC Plugin +keywords: ["grpc-plugin"] +description: grpc-plugin +--- + + +## Description + +* The grpc plugin is a plugin that converts the Http protocol into the grpc protocol. + + +## Plugin Setting + +* Add related dependencies and enable plugin, please refer to: [Quick start with gRPC](../../quick-start/quick-start-grpc) . + +* `gRPC` client access, please refer to: [gRPC Proxy](../../user-guide/proxy/grpc-proxy.md) . + +* New fields and meanings of grpc plugin since `2.4.3`: + + * `threadpool`:There are two types of business thread pools, `cached` and `shared`. + + `cached` is equivalent to the default thread pool officially provided by grpc; + + `shared` thread pool, just as its name, `all proxy plugins` share a `shared` `Thread pool, the advantage of doing this is that it can reduce the number of thread pools, thereby reducing memory and improving resource utilization. + + +## Plugin Detail + + +After the client accesses the `Apache ShenYu` gateway, it will automatically register the selector and rule information. You can see it in PluginList -> rpc proxy -> grpc. For details about the selector and rule configuration, see [Selector And Rule Config](../../user-guide/admin-usage/selector-and-rule) . + + +#### Selector Handler + + + + +Selector Handler, the `handle` field, is the processing operation that the gateway can perform after matching the traffic. + + +* config details: + + * `ip:port`:enter the ip:port of your real service . + + * `protocol`:indicates the Http protocol. Generally, the value is `http://` or `https://`. If the value is not specified, the default value is `http://` . + + * `weight`:service weight. + + * `status`:open or close. + + +## Metadata + +Each `grpc` interface method, will correspond to a metadata, when the `grpc` application client access to the `Apache ShenYu` gateway, will be automatically registered, can be viewed in the `shenyu-admin` background management system of the BasicConfig --> Metadata management. + + + + +* AppName: specifies the name of the application to which the metadata belongs. + +* MethodName: the name of the method to call. + +* Path: http request path. + +* PathDescribe: the description of the path is easy to view. + +* ParamsType: the parameters are separated by commas (,) in the order of interface parameter types. + +* RpcExpand: other configurations of the `grpc` interface, which support the `JSON` format, are as follows: + +```json +{ + "timeout": 5000, + "methodType": "SERVER_STREAMING" +} +``` + +* Interface: The fully qualified class name of the `grpc` interface. + +* RpcType:choose `grpc`. diff --git a/versioned_docs/version-2.6.1/plugin-center/proxy/motan-plugin.md b/versioned_docs/version-2.6.1/plugin-center/proxy/motan-plugin.md new file mode 100644 index 00000000000..e94e497c266 --- /dev/null +++ b/versioned_docs/version-2.6.1/plugin-center/proxy/motan-plugin.md @@ -0,0 +1,68 @@ +--- +title: Motan Plugin +keywords: ["motan-plugin"] +description: motan-plugin +--- + + +## Description + +* The motan plugin is a plugin that converts the Http protocol into the motan protocol. + + +## Plugin Setting + +* Add related dependencies and enable plugin, please refer to: [Quick start with Motan](../../quick-start/quick-start-motan) . + +* `Motan` client access, please refer to: [Motan Proxy](../../user-guide/proxy/motan-proxy.md) . + + + +## Plugin Detail + +After the client accesses the `Apache ShenYu` gateway, it will automatically register the selector and rule information. + +You can see it in PluginList -> rpc proxy -> motan. For details about the selector and rule configuration, see [Selector And Rule Config](../../user-guide/admin-usage/selector-and-rule) . + +## Metadata + +Each `motan` interface method, will correspond to a metadata, when the `motan` application client access to the `Apache ShenYu` gateway, will be automatically registered, can be viewed in the `shenyu-admin` background management system of the BasicConfig --> Metadata management. + + + + +* AppName: specifies the name of the application to which the metadata belongs. + +* MethodName: the name of the method to call. + +* Path: http request path. + +* PathDescribe: the description of the path is easy to view. + +* ParamsType: the parameters are separated by commas (,) in the order of interface parameter types. + +* RpcExpand: description of each interface in a `motan` service. For example, here is the interface information for the `motan` service: + + + +```json +{ + "methodInfo": [ + { + "methodName": "hello", + "params": [ + { + "left": "java.lang.String", + "right": "name" + } + ] + } + ], + "group": "motan-shenyu-rpc" +} +``` + + +* Interface: The fully qualified class name of the `motan` interface. + +* RpcType:choose `motan`. diff --git a/versioned_docs/version-2.6.1/plugin-center/proxy/mqtt-plugin.md b/versioned_docs/version-2.6.1/plugin-center/proxy/mqtt-plugin.md new file mode 100644 index 00000000000..07f49b2f40d --- /dev/null +++ b/versioned_docs/version-2.6.1/plugin-center/proxy/mqtt-plugin.md @@ -0,0 +1,46 @@ +--- +title: Mqtt Plugin +keywords: ["Mqtt"] +description: Mqtt access shenyu gateway +--- + +## Description + +* After the plugin is used, it will give the ability of mqtt. + +## Introducing Plugin Support of Mqtt Gateway + +* Introducing those dependencies in the pom.xml file of the gateway. + +```xml + + + org.apache.shenyu + shenyu-spring-boot-starter-plugin-mqtt + ${project.version} + +``` + +## Plugin Setting + +* port: MQTT BS port designation. + +* bossGroupThreadCount: default 1. + +* maxPayloadSize: Maximum packet size. + +* workerGroupThreadCount: default 12. + +* username: default shenyu. + +* password: default shenyu. + +* isEncryptPassword: The default is false , whether to encrypt the password. + +* encryptMode: encryption mode, currently only MD5 is implemented, the encryption mode can be customized, `org.apache.shenyu.protocol.mqtt.utils.EncryptUtil` view the implementation of this encryption class. + +* leakDetectorLevel: default DISABLED, resource target detection or detection level. + +## Notice + +* Mqtt does not have selector and ruler configurations. diff --git a/versioned_docs/version-2.6.1/plugin-center/proxy/sofa-plugin.md b/versioned_docs/version-2.6.1/plugin-center/proxy/sofa-plugin.md new file mode 100644 index 00000000000..b0b86cc58a8 --- /dev/null +++ b/versioned_docs/version-2.6.1/plugin-center/proxy/sofa-plugin.md @@ -0,0 +1,213 @@ +--- +title: Sofa Plugin +keywords: ["sofa"] +description: Sofa Plugin +--- + +# 1. Overview + +## 1.1 Plugin name + +- Sofa plugin + +## 1.2 Appropriate scenario + +- Protocol conversion, a plugin that converts http protocol requests into the sofa framework protocol +- Service Load Balancing. + +## 1.3 Plugin functionality + +- Converting http protocol requests to sofa framework protocol. + +## 1.4 Plugin code + +- Core Module `shenyu-plugin-sofa` +- Core Class `org.apache.shenyu.plugin.sofa.SofaPlugin` + +## 1.5 Added since which shenyu version + +- 2.3.0 + +# 2. How to use plugin + +## 2.1 Plugin-use procedure chart + +![image-20220828222022336](/img/shenyu/plugin/sofa/procedure_chart_en.png) + +## 2.2 Import pom + +```xml + + com.alipay.sofa + rpc-sofa-boot-starter + ${rpc-sofa-boot-starter.version} + + + org.apache.shenyu + shenyu-spring-boot-starter-client-sofa + ${project.version} + + + guava + com.google.guava + + + +``` + +## 2.3 Configure in the client project + +1. Configure the sofa configuration in application.yml. + +```yaml +com: + alipay: + sofa: + rpc: + registry-address: zookeeper://127.0.0.1:2181 # consul # nacos + bolt-port: 8888 +shenyu: + register: + registerType: http #zookeeper #etcd #nacos #consul + serverLists: http://localhost:9095 #localhost:2181 #http://localhost:2379 #localhost:8848 + props: + username: admin + password: 123456 + client: + sofa: + props: + contextPath: /sofa + ipAndPort: sofa + appName: sofa + port: 8888 +``` + +2. Configure the service interface exposed by the sofa service in the xml file in the resources directory. + +```xml + + + + + + + + + + +``` + +3. Add the `@ShenyuSofaClient` annotation to the interface. + +```java +@ShenyuSofaClient("/demo") +@Service +public class SofaClientMultiParamServiceImpl implements SofaClientMultiParamService { + + @Override + @ShenyuSofaClient("/findByIdsAndName") + public SofaSimpleTypeBean findByIdsAndName(final List ids, final String name) { + return new SofaSimpleTypeBean(ids.toString(), "hello world shenyu sofa param findByIdsAndName :" + name); + } +} +``` + +## 2.4 Enable plugin + +- In shenyu-admin --> BasicConfig --> Plugin --> `sofa` set Status enabled. + + ![image-20220829193836286](/img/shenyu/plugin/sofa/enable_sofa_en.png) + + +## 2.5 Config plugin + +### 2.5.1 Registry Config + +![image-20220829193913149](/img/shenyu/plugin/sofa/sofa_registry_en.png) + +- `protocol`: Register center protocol, currently supports zookeeper、consul、nacos. +- `register`: The service IP and PORT of the registry. +- `threadpool`:There are five types of business thread pools: `fixed`, `eager`, `cached`, `limited` and `shared`. The first 4 types correspond to the thread pools officially provided by dubbo. Let's talk about `shared`, as its name implies, `all proxy plugins` share a `shared` thread pool, the advantage of this is that it can reduce the number of thread pools, thereby reducing memory and improving resource utilization. +- `corethreads`:The number of core threads in the business thread pool. +- `threads`:The maximum number of threads in the business thread pool. +- `queues`:The length of the blocking queue of the business thread pool, 0 means `unbounded blocking queue`. + +### 2.5.2 Selector config + +> Flow needs to be matched by selector. + +![image-20220829193948830](/img/shenyu/plugin/sofa/selector_config_en.png) + +- Automatically configure the selector with the `@ShenyuSofaClient` annotation. + +### 2.5.3 Rule Config + +> After the traffic has been successfully matched by the selector, it will enter the rules for the final traffic matching. + +![image-20220829194018202](/img/shenyu/plugin/sofa/rule_config_en.png) + +- Automatically configure the selector with the `@ShenyuSofaClient` annotation. + +### 2.5.4 Metadata config + +> When the `sofa` application client accesses the `Apache ShenYu` gateway, it will be automatically registered, and can be viewed in the `-shenyu-admin` backend management system's basic configuration `-->` metadata management, each `sofa` interface method, will correspond to a metadata. + +![image-20220829194058044](/img/shenyu/plugin/sofa/metadata_config_en.png) + +- AppName: specifies the name of the application to which the metadata belongs. + +- MethodName: the name of the method to call. + +- Path: http request path. + +- PathDescribe: the description of the path is easy to view. + +- ParamsType: the parameters are separated by commas (,) in the order of interface parameter types. + +- RpcExpand: other configurations of the `sofa` interface, which support the `JSON` format. + + examples:`{"loadbalance":"hash","retries":3,"timeout":-1}` + + - `loadbalance`:Load balancing policy, currently supports roundRobin, random and hash. + - `retries`:Number of retries to call client timeout failures. + - `timeout`:Calling the client's timeout time. + +- Interface: The fully qualified class name of the `sofa` interface. + +- RpcType:choose `sofa`. + +## 2.6 Examples + +### 2.6.1 Accessing the sofa service via Zookeeper using ShenYu + +#### 2.6.1.1 Preparation + +- Start `Zookeeper` service. +- Start `ShenYu Admin`. +- Start `Shenyu Bootstrap`. + +#### 2.6.1.2 Plugin Config + +- In shenyu-admin --> BasicConfig --> Plugin --> `sofa` set Status enabled, And adjust the registry configuration as needed. +- Adjust to the actual situation [shenyu-examples-sofa](https://github.com/apache/shenyu/tree/master/shenyu-examples/shenyu-examples-sofa) application.yml configuration in the project and start it. + +#### 2.6.2.6 Request service and check result + +![image-20220828012420068](/img/shenyu/plugin/sofa/check_request_zh.png) + +# 3. How to disable plugin + +- In `shenyu-admin` --> BasicConfig --> Plugin --> `sofa` set Status disable. + +![image-20220829194151368](/img/shenyu/plugin/sofa/close_sofa_en.png) + + + + + + diff --git a/versioned_docs/version-2.6.1/plugin-center/proxy/spring-cloud-plugin.md b/versioned_docs/version-2.6.1/plugin-center/proxy/spring-cloud-plugin.md new file mode 100644 index 00000000000..82412c203c3 --- /dev/null +++ b/versioned_docs/version-2.6.1/plugin-center/proxy/spring-cloud-plugin.md @@ -0,0 +1,317 @@ +--- +title: Spring Cloud Plugin +keywords: ["SpringCloud"] +description: SpringCloud Plugin +--- + +# 1. Overview + +## 1.1 Plugin Name + +* SpringCloud Plugin + +## 1.2 Appropriate Scenario + +* transform http to springcloud +* springcloud gray flow control + +## 1.3 Plugin functionality + +* transform http protocol into springCloud protocol. + +## 1.4 Plugin code + +* Core Module `shenyu-plugin-springcloud` + +* Core Class `org.apache.shenyu.plugin.springcloud.SpringCloudPlugin` + +## 1.5 Added Since Which shenyu version + +Since ShenYu 2.4.0 + +# 2. How to use plugin + +* Add related dependencies and enable plugin, please refer to: [Quick start with Spring Cloud](../../quick-start/quick-start-springcloud) . + +* `Spring Cloud` client access, please refer to: [Spring Cloud Proxy](../../user-guide/proxy/spring-cloud-proxy.md) . + +## 2.1 Plugin-use procedure chart + +![](/img/shenyu/plugin/plugin_use_en.jpg) + +## 2.2 Import pom + +* Eureka Registry + +```xml + + org.apache.shenyu + shenyu-spring-boot-starter-plugin-springcloud + ${project.version} + + + + org.springframework.cloud + spring-cloud-starter-netflix-eureka-client + ${eureka-client.version} + + + + org.springframework.cloud + spring-cloud-commons + ${spring-cloud-commons.version} + + + + org.apache.shenyu + shenyu-spring-boot-starter-plugin-httpclient + ${project.version} + +``` + +* Nacos Registry + +```xml + + org.apache.shenyu + shenyu-spring-boot-starter-plugin-springcloud + ${project.version} + + + + com.alibaba.cloud + spring-cloud-starter-alibaba-nacos-discovery + ${nacos-discovery.version} + + + + org.springframework.cloud + spring-cloud-commons + ${spring-cloud-commons.version} + + + + org.apache.shenyu + shenyu-spring-boot-starter-plugin-httpclient + ${project.version} + +``` + +## 2.3 Config SpringCloud in ShenYu-Boostrap + +### 2.3.1 Config SpringCloud Registry With Eureka + +```yaml +spring: + cloud: + discovery: + enabled: true + +eureka: + client: + enabled: true + serviceUrl: + defaultZone: http://localhost:8761/eureka/ + instance: + prefer-ip-address: true +``` + +### 2.3.2 Config SpringCloud Registry With Nacos + +```yaml +spring: + cloud: + discovery: + enabled: true + nacos: + discovery: + server-addr: 127.0.0.1:8848 # Spring Cloud Alibaba Dubbo use this. + enabled: true + namespace: ShenyuRegisterCenter +``` + +### 2.3.3 Config SpringCloud LoadBalancer + +> *Notice* +> +> After ShenYu 2.5.0(include), ShenYu use `shenyu-loadbalancer` as loadbalancer client, you just config loadbalance in springcloud plugin rule. +> if you don't config loadbalance, springcloud plugin will use `roundRobin` algorithm. +> +> Before ShenYu 2.4.3(include), ShenYu use `Ribbon` as loadbalancer client, you must config loadbalancer as follows. + +```yaml +spring: + cloud: + loadbalancer: + ribbon: + enabled: true +``` + +## 2.4 Enable plugin + +- In shenyu-admin --> BasicConfig --> Plugin --> `springCloud` set Status enabled. + + + +## 2.5 Config plugin + +### 2.5.1 Plugin config + +* you must config springcloud registry and set springcloud plugin enabled. + +### 2.5.2 Selector And Gray Config + +![](/img/shenyu/plugin/springcloud/selector_en_2.png) + +* Gray routing + +if you want to user gray route in springCloud-plugin, you can click the `gray` button. + +![](/img/shenyu/plugin/springcloud/gray_en_2.png) + +* Gray level publishing can customize and control the traffic proportion of new version applications when publishing new version applications, gradually complete the full launch of new version applications, maximize the business risk caused by new version publishing, reduce the impact surface caused by faults, and support rapid roll back. + +when the gray is open,Gateway load balancing will select one node from the current node list for routing and you can modify node weights to change the weight of nodes in the load balancing algorithm. + + + +It should be noted that,if your business instance not use the client jar of `shenyu-client-springcloud`, You should add gray node information manually on this selector page. + +* `serviceId`: your springcloud service id + +* `gray`:enable gray routing. + + * `protocol`: protocol default is 'http://'. + + * `upstreamUrl`: the server instance host, ip:port. + + * `weight`: the server instance and participate in load balancing calculation. + + * `status`: true: the server is available,false: the server is unavailable. + + * `timestamp`: the server's start time. + + * `warmup`: the server's warm up time and and participate in load balancing calculation. + +### 2.5.3 Rule Config + +Rule Handler, the `handle` field, can be performed by the gateway after the final matching of traffic. For more information, please refer to [Plugin handle management](../plugin-handle-explanation) in Plugin Config. + +* use `shenyu-client-springcloud` rule config + +![](/img/shenyu/plugin/springcloud/rule_en_2.png) + +* details: + + * `timeout`:set time out. + * `loadbalance`:loadbalance algorithm,there are three options: `roundRobin`,`random`,`hash` + +* not use `shenyu-client-springcloud` rule config + +![](/img/shenyu/plugin/springcloud/rule_en.png) + +* details: + + * `path`:request path. + * `timeout`:set time out. + +### 2.5.4 SpringCloud ServiceInstance Cache Config + +you can config springcloud serviceInstance cache in `shenyu-bootstrap.yml` as follows. + +```yaml +shenyu: + springCloudCache: + enabled: false +``` + +this config will help you get serviceInstance from springcloud registry every heartbeat time(listen to spring cloud heartbeat event) + +* when you use nacos or eureka as registry, you can config springcloud serviceInstance cache to `false`. +* when you use zookeeper or consul as registry, you can config springcloud serviceInstance cache to `true`. + +## 2.6 Examples + +### 2.6.1 Use ShenYu Request SpringCloud Service + +#### 2.6.1.1 Preparation + +- Start `Eureka` or `Nacos` Registry, if you use eureka, start `shenyu-examples-eureka` in `shenyu-example` +- Start `ShenYu Admin` application +- Start `shenyu-examples-springcloud` + +#### 2.6.1.2 Plugin Config + +- In shenyu-admin --> BasicConfig --> Plugin --> `springCloud` set Status enabled. + +- Config SpringCloud Registry in `ShenYu Bootstrap`, please read [2.3 Config SpringCloud in ShenYu-Boostrap](#2.3 Config SpringCloud in ShenYu-Boostrap) + +#### 2.6.1.3 Selector Config + +![](/img/shenyu/plugin/springcloud/selector_en_2.png) + +if your want to use gray flow and the gray flow have registered to `ShenyYu`, you must config gray upstream as follows. + +![](/img/shenyu/plugin/springcloud/gray_en_2.png) + +#### 2.6.1.4 Rule Config + +if you use `shenyu-client-springcloud` register service to `ShenYu`, you don't config rule, if you want to change rule config, +please read [2.5.3 Rule Config](#2.5.3 Rule Config) + +#### 2.6.1.5 Request SpringCloud Service and Check Result + +![](/img/shenyu/plugin/springcloud/springcloud-request.png) + +### 2.6.2 Use ShenYu Request Unregistered SpringCloud Service + +#### 2.6.2.1 Preparation + +- Start `Eureka` or `Nacos` Registry, if you use eureka, start `shenyu-examples-eureka` in `shenyu-example` +- Start `ShenYu Admin` application +- Start `shenyu-examples-springcloud` + +#### 2.6.2.2 Plugin Config + +- In shenyu-admin --> BasicConfig --> Plugin --> `springCloud` set Status enabled. + +- Config SpringCloud Registry in `ShenYu Bootstrap`, please read [2.3 Config SpringCloud in ShenYu-Boostrap](#2.3 Config SpringCloud in ShenYu-Boostrap) + +#### 2.6.2.3 Selector Config + +![](/img/shenyu/plugin/springcloud/selector_en_2.png) + +if your want to use gray flow and the gray flow unregister to `ShenyYu`, you must config gray upstream as follows. + +![](/img/shenyu/plugin/springcloud/gray_en_2.png) + +#### 2.6.2.4 Rule Config + +![](/img/shenyu/plugin/springcloud/rule_en.png) + +you must config `path` in rule config, `path` is your service uri, for example: `/springcloud/new/feature/gateway/not`, +`timeout` is your service allow timeout. + +#### 2.6.2.5 Access Unregistered Services Through Configuration + +##### 2.6.2.5.1 use the field `rpc_type` in http request header + +``` +### shengyu getway proxy not support +POST http://localhost:9195/springcloud/new/feature/gateway/not +Accept: application/json +Content-Type: application/json +rpc_type: springCloud +``` + +##### 2.6.2.5.2 add meta_data in ShenYu Admin + +![](/img/shenyu/plugin/springcloud/springcloud_metadata_en.png) + +#### 2.6.2.6 Request SpringCloud Service and Check Result + +![](/img/shenyu/plugin/springcloud/springcloud-request-unregistered.png) + +# 3. How to disable plugin + +- In `shenyu-admin` --> BasicConfig --> Plugin --> `springCloud` set Status disable. diff --git a/versioned_docs/version-2.6.1/plugin-center/proxy/tars-plugin.md b/versioned_docs/version-2.6.1/plugin-center/proxy/tars-plugin.md new file mode 100644 index 00000000000..fd9c3628b02 --- /dev/null +++ b/versioned_docs/version-2.6.1/plugin-center/proxy/tars-plugin.md @@ -0,0 +1,170 @@ +--- +title: Tars Plugin +keywords: ["Tars"] +description: Tars Plugin +--- + +# 1. Overview + +## 1.1 Plugin name + +- Tars plugin + +## 1.2 Appropriate scenario + +- Protocol conversion, a plugin that converts http protocol requests into the Tars framework protocol +- Service Load Balancing. + +## 1.3 Plugin functionality + +- Converting http protocol requests to Tars framework protocol. + +## 1.4 Plugin code + +- Core Module `shenyu-plugin-tars` +- Core Class `org.apache.shenyu.plugin.tars.TarsPlugin` + +## 1.5 Added since which shenyu version + +- 2.3.0 + +# 2. How to use plugin + +## 2.1 Plugin-use procedure chart + +![image-20221206221707914](/img/shenyu/plugin/tars/produce_chart_en.png) + +## 2.2 Import pom + +```xml + + org.apache.shenyu + shenyu-spring-boot-starter-client-tars + ${shenyu.version} + +``` + +## 2.3 Configure in the client project + +1. Configure the Tars configuration in application.yml. + +```yaml +shenyu: + register: + registerType: http #zookeeper #etcd #nacos #consul + serverLists: http://localhost:9095 #localhost:2181 #http://localhost:2379 #localhost:8848 + props: + username: admin + password: 123456 + client: + tars: + props: + contextPath: /tars + appName: tars + port: 21715 + host: 192.168.41.103 # client IP +``` + +2. Add the `@ShenyuTarsService` and `@ShenyuTarsClient` and annotation to the interface. + +```java +@TarsServant("HelloObj") +@ShenyuTarsService(serviceName = "ShenyuExampleServer.ShenyuExampleApp.HelloObj") +public class HelloServantImpl implements HelloServant { + + @Override + @ShenyuTarsClient("/hello") + public String hello(final int no, final String name) { + return String.format("hello no=%s, name=%s, time=%s", no, name, System.currentTimeMillis()); + } +} +``` + + +## 2.4 Enable plugin + +- In shenyu-admin --> BasicConfig --> Plugin --> `tars` set Status enabled. + +![enable_tars_en](/img/shenyu/plugin/tars/enable_tars_en.png) + + +## 2.5 Config plugin + +### 2.5.1 Config plugin + +![plugin_config_en](/img/shenyu/plugin/tars/plugin_config_en.png) + +- `multiSelectorHandle`:Set to enable multiple selector processing, multiple selector processing services can be configured in the selector list. +- `multiRuleHandle`:Set to multiple rules processing, configure multiple processing rules in the rule list, it is recommended to configure as single rule. +- `threadpool`:There are five types of business thread pools: `fixed`, `eager`, `cached`, `limited` and `shared`. The first 4 types correspond to the thread pools officially provided by dubbo. Let's talk about `shared`, as its name implies, `all proxy plugins` share a `shared` thread pool, the advantage of this is that it can reduce the number of thread pools, thereby reducing memory and improving resource utilization. +- `corethreads`:The number of core threads in the business thread pool. +- `threads`:The maximum number of threads in the business thread pool. +- `queues`:The length of the blocking queue of the business thread pool, 0 means `unbounded blocking queue`. + +### 2.5.2 Selector config + +> Flow needs to be matched by selector. + +![selector_config_en](/img/shenyu/plugin/tars/selector_config_en.png) + +Automatically configure the selectors with the `@ShenyuTarsClient` annotation. + +### 2.5.3 Rule Config + +> After the traffic has been successfully matched by the selector, it will enter the rules for the final traffic matching. + +![rule_config_en](/img/shenyu/plugin/tars/rule_config_en.png) + +Automatically configure the rules with the `@ShenyuTarsClient` annotation. + +### 2.5.4 Metadata config + +> When the `Tars` application client accesses the `Apache ShenYu` gateway, it will be automatically registered, and can be viewed in the `shenyu-admin` backend management system's basic configuration `-->` metadata management, each `Tars` interface method, will correspond to a metadata. + +![metadata_config_en](/img/shenyu/plugin/tars/metadata_config_en.png) + +- AppName: specifies the name of the application to which the metadata belongs. + +- MethodName: the name of the method to call. + +- Path: http request path. + +- PathDescribe: the description of the path is easy to view. + +- ParamsType: the parameters are separated by commas (,) in the order of interface parameter types. + +- RpcExpand: other configurations of the `Tars` interface, which support the `JSON` format. + + examples:`{"loadbalance":"hash","retries":3,"timeout":-1}` + + - `loadbalance`:Load balancing policy, currently supports roundRobin, random and hash. + - `retries`:Number of retries to call client timeout failures. + - `timeout`:Calling the client's timeout time. + +- Interface: The fully qualified class name of the `Tars` interface. + +- RpcType:Auto-registration defaults to `Tars`. + +## 2.6 Examples + +### 2.6.1 Using ShenYu to access the Tars service + +#### 2.6.1.1 Preparation + +- Start `ShenYu Admin`. +- Start `Shenyu Bootstrap`. + +#### 2.6.1.2 Plugin Config + +- In shenyu-admin --> BasicConfig --> Plugin --> `tars` set Status enabled, And adjust the registry configuration as needed. +- Adjust to the actual situation [shenyu-examples-tars](https://github.com/apache/shenyu/tree/master/shenyu-examples/shenyu-examples-tars) application.yml configuration in the project and start it. + +#### 2.6.2.6 Request service and check result + +![check_request_zh](/img/shenyu/plugin/tars/check_request_zh.png) + +# 3. How to disable plugin + +- In `shenyu-admin` --> BasicConfig --> Plugin --> `tars` set Status disable. + +![close_tars_en](/img/shenyu/plugin/tars/close_tars_en.png) diff --git a/versioned_docs/version-2.6.1/plugin-center/proxy/tcp-plugin.md b/versioned_docs/version-2.6.1/plugin-center/proxy/tcp-plugin.md new file mode 100644 index 00000000000..a7b3724e3c5 --- /dev/null +++ b/versioned_docs/version-2.6.1/plugin-center/proxy/tcp-plugin.md @@ -0,0 +1,156 @@ +--- +title: Tcp Plugin +keywords: [ "Tcp" ] +description: TcpPlugin +--- + +# 1. Overview + +## 1.1 Plugin name + +- TCP Plugin + +## 1.2 Appropriate Scenario + +- Process TCP protocol requests and forward them to backend services of other TCP protocols +- Service load balancing + +## 1.3 Plugin functionality + +* Supports TCP proxy based on configured upstream list +* The upstream list can be hot-synchronized to the gateway by the admin module +* Support setting load balancing policy for requests, currently support shenyu load balancing module policy +* Configurable open port for listening, configurable reactor-netty parameter +* Enable multiple proxy selectors + +> __Note__: When a connection is established with the gateway, after the connection is established, the traffic continues to stay in the upstream that has been selected by the load balancing module + +## 1.4 Plugin code + +- Core Module: `shenyu-plugin-tcp` `shenyu-protocol-tcp` + +## 1.5 Added since which shenyu version + +- 2.6.0 + +# 2. How to use plugin + +## 2.1 Enable plugin + +- When using it for the first time, start the admin server, +in `shenyu-admin` --> BasicConfig --> Plugin, search for the tcp plugin and click "Resource" to activate the TCP plugin module. + +![init-tcp-en](/img/shenyu/plugin/tcp/init_tcp_en.png) + +- In `shenyu-admin` --> BasicConfig--> Plugin --> `tcp`, set status enabled. + +![start-tcp-en](/img/shenyu/plugin/tcp/start_tcp_en.png) + +## 2.2 Configure plugin + +- The TCP plugin is created in units of proxy-selectors, so configuring the plugin is to configure the properties of the proxy-selector. +When creating a proxy-selector, click the "Add" button on the page, and in the pop-up selector form, you can configure the selector properties: + +![selector_props_en](/img/shenyu/plugin/tcp/selector_props_en.png) + +The default configuration is as follows: + +```json +{ + "loadBalanceAlgorithm": "random", + "bossGroupThreadCount": "1", + "workerGroupThreadCount": "12", + "clientMaxConnections": "20", + "clientMaxIdleTimeMs": "30000", + "clientMaxLifeTimeMs": "60000", + "clientPendingAcquireTimeout": "5", + "clientPendingAcquireMaxCount": "5" +} +``` + +- `loadBalanceAlgorithm` : shenyu load balancing algorithm, random by default +- `bossGroupThreadCount` , `workerGroupThreadCount`: +ReactorNetty TcpServer For configuration details, see `shenyu-protocol-tcp#TcpBootstrapServer#start` for details +- `clientMaxConnections` , `clientMaxIdleTimeMs` , `clientMaxLifeTimeMs` , `clientPendingAcquireTimeout` , + `clientPendingAcquireMaxCount` +ReactorNetty `ConnectionProvider` , see `shenyu-protocol-tcp#ConnectionContext` for details + +You can search for the tcp plugin in `shenyu-admin` --> BasicConfig --> PluginHandle, and modify the default configuration: + +![plugin_handle_en](/img/shenyu/plugin/tcp/plugin_handle_en.png) + +## 2.3 Configure service discovery + +`discovery` see [discovery-mode](../discovery/discovery-mode.md) + +The TCP plugin supports two levels of discovery configuration: plugin-level and selector-level: + +① You can click the "Discovery Configuration" button on the page to configure plugin-level discovery in the pop-up form. +After the configuration is complete, you can open the form again to modify or delete the previous configuration. +After the plug-in level discovery is configured, the discovery settings of the selectors are consistent with the plugin-level config by default: + +![discovery_config_en](/img/shenyu/plugin/tcp/discovery_config_en.png) + +② If you have not configured plugin-level discovery, +you can configure the selector-level discovery every time you create a proxy-selector: + +![selector_discovery_en](/img/shenyu/plugin/tcp/selector_discovery_en.png) + +Discovery `Zookeeper` and `Local` modes are currently supported. + +### 2.3.1 Zookeeper Mode + + +- When the type of service Discovery is Zookeeper, you need to fill out the Discovery-ZooKeeper configuration training for details [discovery-mode](../discovery/discovery-mode.md) + +- In zookeeper mode, the discovery module will automatically monitor the user's zookeeper registration center +and automatically maintain discovery upstreams: + +![zookeeper.png](/img/shenyu/plugin/tcp/zookeeper.png) + +### 2.3.2 Local Mode + +- When "local" is selected as the discovery type, +you need to manually fill in the discovery upstream list. +As shown in the figure below, the discovery upstream list is an editable table. + Double-click each cell to modify the table content: + +![local_selector_en.png](/img/shenyu/plugin/tcp/local_selector_en.png) + +## 2.4 Configure selectors + +- In addition to the discovery configuration above, when creating a selector, +you also need to fill in the "basic config" part of the selector, +including name and forward port, etc. In order to improve the convenience of filling in, +you can click "Copy Selector" to copy part of the information of the created selector. + +> __Note__: The name of the selector uniquely identifies the selector and cannot be repeated + +![selector_basic_en.png](/img/shenyu/plugin/tcp/selector_basic_en.png) + +- After the selectors are created, +the selectors are displayed in the form of cards. +When the mouse hovers over the cards, the creation time, update time and properties of the selectors will be displayed. + At the bottom of the card there are three clickable icons, from left to right the Sync, Edit, and Delete selector icons: + +![card_list_en.png](/img/shenyu/plugin/tcp/card_list_en.png) + + +- If there is difference between the discovery upstream list of the current admin and the gateway, +you can click the "Sync" icon to force synchronization to the gateway. + + +## 2.5 Shenyu log + +- shenyu-gateway port start log +![gateway_start_port_log.png](/img/shenyu/plugin/tcp/gateway_start_port_log.png) + +- shenyu-gateway proxy upstreamList‘s success log +![gateway_upstream_list.png](/img/shenyu/plugin/tcp/gateway_upstream_list.png) + +## 2.6 Example + +Take proxying redis as an example, use `redis-cli -p {forwardPort}` to access. + +![connection.png](/img/shenyu/plugin/tcp/redis_connection.png) + diff --git a/versioned_docs/version-2.6.1/plugin-center/proxy/websocket-plugin.md b/versioned_docs/version-2.6.1/plugin-center/proxy/websocket-plugin.md new file mode 100644 index 00000000000..5fd8651b671 --- /dev/null +++ b/versioned_docs/version-2.6.1/plugin-center/proxy/websocket-plugin.md @@ -0,0 +1,277 @@ +--- +title: Websocket Plugin +keywords: ["Websocket"] +description: Websocket Plugin +--- + +# 1. Overview + +## 1.1 Plugin Name + +* Websocket Plugin. + +## 1.2 Appropriate Scenario + +* Forwarding scenarios, processing websocket protocol requests and forwarding them to other websocket protocol services on the backend. +* Service Load Balancing. + +## 1.3 Plugin functionality + +* Support traffic management based on host, uri, query and other request information. +* Supports setting load balancing policies for requests and also supports service warm-up, currently supports three policies: ip hash (consistent hashing with virtual nodes), round-robbin (weighted polling), random (weighted random). +* Support setting interface level request timeout time. +* Support setting the number of timeout retries. + +## 1.4 Plugin code + +* Core Module ```shenyu-plugin-websocket```. +* Core Class ```org.apache.shenyu.plugin.websocket.WebSocketPlugin```. + +## 1.5 Added Since Which shenyu version + +- 2.4.3 + +# 2. How to use plugin + +## 2.1 Plugin-use procedure chart + +![image-20220726223545558](/img/shenyu/plugin/websocket/procedure_chart_en.png) + +**Explanation of terms** +- Shenyu gateway service:Include shenyu-admin and shenyu-bootstrap services. +- Client services:Real backend websocket service. + +**Explanation of the process** +1. Start shenyu gateway service: Refer to the deployment, start shenyu-admin and shenyu-bootstrap to make sure shenyu gateway service is normal. +2. Enable the websocket plugin in shenyu-admin: Turn on the websocket plugin in the shenyu-admin plugin management page. +3. Configure and start the client service: start the client project (real websocket service on the back end) and configure the service information into the shenyu gateway, in two ways: manual configuration and automatic configuration. +4. Check if forwarding is normal: Check if forwarding is successful. + +## 2.2 Enable plugin + +- In shenyu-admin --> BasicConfig --> Plugin --> websocket is set to on. + +![image-20220726224444058](/img/shenyu/plugin/websocket/enable_websocket_en.png) + + +## 2.3 Client Services configuration + +### 2.3.1 Manual configuration + +> Manually configure the client service on the shenyu-admin page, and the backend service will implement the websocket protocol forwarding without any changes. + +1. Adding selectors to the websocket plugin. + +![image-20220726225217950](/img/shenyu/plugin/websocket/add_selector_en.png) + +2. Add rules to the websocket plugin. + +![image-20220726225315550](/img/shenyu/plugin/websocket/add_rule_en.png) + +3. Start the client service (backend websocket service). + +4. Test the success of service forwarding. + +- See Annex 5.1 for the test code. + +![image-20220726222003131](/img/shenyu/plugin/websocket/test_result_en.png) + +### 2.3.2 Automatic configuration + +> If there are scenarios where you need to automate configuration to reduce workload, you can add annotations to the backend service to automate the configuration of the service to the shenyu gateway. + +1. Add the plugin maven configuration to the pom.xml file in the backend service project. + +```xml + + org.apache.shenyu + shenyu-spring-boot-starter-plugin-websocket + ${project.version} + +``` + +2. Use the `@ShenyuSpringWebSocketClient` annotation, which will automatically register the websocket service to the shenyu gateway. +3. Adjust the plugin configuration, see 2.4.1 for details of the configuration parameters. +4. Start the client project (the backend `websocket service), see 2.5 for sample code. +5. Check whether the PluginList service registration information in the shenyu-admin page is registered successfully. +6. Test the success of service forwarding. + +- See Annex 5.1 for the test code. + +![image-20220726221945414](/img/shenyu/plugin/websocket/test_result_en.png) + +## 2.4 Config plugin + +### 2.4.1 Configure access parameters in the configuration file in the client service + +* Client access method and server address, the parameters are: `shenyu.register.*`, the following example uses the http access method, currently the client supports the following access methods: http, zookeeper, etcd, nacos, consul, please refer to [client access configuration](../../user-guide/property-config/register-center-access) for detailed access configuration parameters. +* Client configuration with the parameter: `shenyu.client.websocket.*`, containing the service name, routing address and port, and the contextPath value must be configured as the routing address for each service. + +```yaml +shenyu: + register: + registerType: http + serverLists: http://localhost:9095 + props: + username: admin + password: 123456 + client: + websocket: + props: + contextPath: /ws-annotation + appName: ws-annotation + port: 8001 # Need to be consistent with the service port +``` + +### 2.4.2 Configure the websocket plugin's selector and rule information in shenyu-admin + +Using auto-configuration, after the client starts it will automatically register [selectors and rules](../../user-guide/admin-usage/selector-and-rule.md) in shenyu-admin -> Plugin List -> Proxy -> Websocket information. +![image-20220725222628106](/img/shenyu/plugin/websocket/auto_register_en.png) + +#### 2.4.2.1 Configuration of selectors + +The example of websocket selector configuration, please refer to [selectors and rules](../../user-guide/admin-usage/selector-and-rule.md) for general selector configuration. + +![image-20220725222913298](/img/shenyu/plugin/websocket/config_selectors_en.png) + +##### 2.4.2.1.1 Selector handler configuration + +- `host`:Fill in `localhost`, this field is not used for now. +- `ip:port`:`ip` and port, here fill in the `ip` + port of your real service. +- `protocol`:`ws` protocol, do not fill in the default: `ws://`. +- `startupTime`:Start-up time in milliseconds. +- `weight`:The default value for load balancing weight, which is automatically registered for service startup, is 50. +- `warmupTime`:Warm-up time, in milliseconds, the server in warm-up will calculate the instantaneous weight, the calculated value will be less than the actual weight configured to protect the server just started, the default value of service start registration is 10. For example, the warm-up time is 100 milliseconds, currently started 50 milliseconds, the configured weight is 50, the actual weight is 25. +- `status`:open or close, the start state of this processor is only valid. + +#### 2.4.2.2 Configuration of rules + +The example of websocket rule configuration, please refer to [selectors and rules](../../user-guide/admin-usage/selector-and-rule.md) for general rule configuration . + +![image-20220725223225388](/img/shenyu/plugin/websocket/config_rules_en.png) + +##### 2.4.2.2.1 Rule handler configuration + +- `loadStrategy`: if the websocket client is a cluster, which load balancing strategy to take when the Apache ShenYu gateway is invoked, currently supports roundRobin, random and hash. +- `timeout`: The timeout period for calling the client. +- `retryCount`: The number of retries to call client timeout failures. + +## 2.5 示例 + +### 2.5.1 Spring Annotation Websocket Example + +[shenyu-example-spring-annotation-websocket](https://github.com/apache/shenyu/tree/master/shenyu-examples/shenyu-examples-websocket/shenyu-example-spring-annotation-websocket) + +### 2.5.2 Spring Native Websocket Example + +[shenyu-example-spring-native-websocket](https://github.com/apache/shenyu/tree/master/shenyu-examples/shenyu-examples-websocket/shenyu-example-spring-native-websocket) + +### 2.5.3 Spring Reactive Websocket Example + +[shenyu-example-spring-reactive-websocket](https://github.com/apache/shenyu/tree/master/shenyu-examples/shenyu-examples-websocket/shenyu-example-spring-reactive-websocket) + +# 3. How to disable plugin + +- shenyu-admin --> BasicConfig --> Plugin --> Close websocket plugin status. + +![image-20220726231206572](/img/shenyu/plugin/websocket/close_websocket_en.png) + +# 4. Frequently Asked Questions + +**4.1 Websocket connection establishment error 1002** + +Possible causes: client service is not normal, shenyu gateway and client project can not establish a normal connection, please check the gateway to the client network, client service is normal. + +**4.2 Multiple client services are displayed as empty in the websocket selector** + +Possible cause: BasicConfig -> Plugin -> websocket -> multiSelectorHandle option select multiple handle. + +![image-20220726222250136](/img/shenyu/plugin/websocket/questions_multiSelectorHandle_en.png) + +# 5. Annexes + +## 5.1 websocket debugging code + +- Create a file called websocket.html and copy the following code into the file. +- Open websocket.html with Chrome. + +```html + + + + + Shenyu WebSocket Test + + + +
+
+ + +
+
+ + + +``` diff --git a/versioned_docs/version-2.6.1/plugin-center/security/_category_.json b/versioned_docs/version-2.6.1/plugin-center/security/_category_.json new file mode 100644 index 00000000000..45fba4709cc --- /dev/null +++ b/versioned_docs/version-2.6.1/plugin-center/security/_category_.json @@ -0,0 +1,4 @@ +{ + "label": "Security", + "position": 4 +} diff --git a/versioned_docs/version-2.6.1/plugin-center/security/casdoor.md b/versioned_docs/version-2.6.1/plugin-center/security/casdoor.md new file mode 100644 index 00000000000..3fecb12048d --- /dev/null +++ b/versioned_docs/version-2.6.1/plugin-center/security/casdoor.md @@ -0,0 +1,70 @@ +--- +title: Casdoor Plugin +keywords: [Casdoor] +description: Casdoor plugin +--- + +ShenYu has Casdoor plugin to use Casdoor + +## Step1. Deploy Casdoor + +Firstly, the Casdoor should be deployed. + +You can refer to the Casdoor official documentation + +After a successful deployment, you need to ensure: + +- The Casdoor server is successfully running on **http://localhost:8000**. +- Open your favorite browser and visit **http://localhost:7001**, you will see the login page of Casdoor. +- Input `admin` and `123` to test login functionality is working fine. + +Then you can quickly implement a Casdoor based login page in your own app with the following steps. + +## Step2. Configure Casdoor application + +### 1. Create or use an existing Casdoor application + +### 2. Add Your redirect url + + ![casdoor_config](/img/shenyu/plugin/casdoor/casdoor_config.png) + +### 3. On the certificate editing page, you can see your `certificate` + + ![casdoor_cert](/img/shenyu/plugin/casdoor/casdoor_cert.png) + +## Step3. Use Casdoor plugin in Shenyu + +### 1. Config Casdoor plugin in Shenyu + + ![casdoor_configPlugin](/img/shenyu/plugin/casdoor/casdoor_configPlugin.png) + +note: because the shenyu only have Single line input box so we need add \n in every line of cert. + + ![casdoor_cert2](/img/shenyu/plugin/casdoor/casdoor_cert2.png) + +You can copy it and paste it on the certificate of shenyu casdoor config. + +**You don't need save it in Casdoor certificate editing page**,because it just for copying. + +### 2. Confing Shenyu Casdoor's plugin + + ![casdoor_casdoor](/img/shenyu/plugin/casdoor/casdoor_casdoor.png) + + You can config what you need to use Casdoor config + +### 3. Get the service and use + +#### 3.1 Visit the Web directly like + + ![casdoor_faillogin](/img/shenyu/plugin/casdoor/casdoor_faillogin.png) + +#### 3.2 Use Casdoor login like this + + ![casdoor_login](/img/shenyu/plugin/casdoor/casdoor_login.png) + ![casdoor_successlogin](/img/shenyu/plugin/casdoor/casdoor_successlogin.png) + +#### 3.3 Carry token in Headers,you also can visit it + + ![casdoor_token](/img/shenyu/plugin/casdoor/casdoor_token.png) + +#### 3.4 It also can save name,id and organization in Headers so that you can use them in next time diff --git a/versioned_docs/version-2.6.1/plugin-center/security/cryptor-request-plugin.md b/versioned_docs/version-2.6.1/plugin-center/security/cryptor-request-plugin.md new file mode 100644 index 00000000000..5cbd4acbabf --- /dev/null +++ b/versioned_docs/version-2.6.1/plugin-center/security/cryptor-request-plugin.md @@ -0,0 +1,62 @@ +--- +title: CryptorRequest plugin +keywords: ["CryptorRequest"] +description: CryptorRequest plugin +--- + +## Description + +* The `cryptorRequest` plugin uses `fieldNames` to match the parameters in `requestBody` for `decryption` processing, replacing the current `requestBody` content. + +## Plugin Setting + +1. In `shenyu-admin` BasicConfig --> plugin -> `cryptor_request` set to enable. + + + +2. Open `selector` to configure the traffic that needs to be matched. + +3. Open the `Rules` configuration corresponding to the `selector`. + + + +* strategyName: Algorithm name. Currently, based on shenyu's SPI mechanism, the encryption and decryption algorithms can be customized, + Need to implement the `org.apache.shenyu.plugin.cryptor.strategy.CryptorStrategy` interface. + + At the same time find the `org.apache.shenyu.plugin.cryptor.strategy.CryptorStrategy` file under `resources/META-INF/shenyu/`, + Write the name of the algorithm, and the package name of the class that implements the `CryptorStrategy` interface. + +* fieldNames: Matching parameter name. Support parsing multi-level json format matching, using `.` segmentation, such as data.id. + +```json5 + { + data: { + "id": "" + } + } +``` + +* decryptKey: Secret key. Used to decrypt data. + +* encryptKey: Secret key. Used to encrypt data. + +* way: Select encrypt or decrypt. + +## Plugin Use + +* Add support for `cryptorRequest` in the `pom.xml` file of shenyu-bootstrap. + +```xml + + + org.apache.shenyu + shenyu-spring-boot-starter-plugin-cryptor + ${project.version} + + +``` + +## Situation + +Prevent Internet hacking and obtain data maliciously. Improve data security. + diff --git a/versioned_docs/version-2.6.1/plugin-center/security/cryptor-response-plugin.md b/versioned_docs/version-2.6.1/plugin-center/security/cryptor-response-plugin.md new file mode 100644 index 00000000000..185ded13879 --- /dev/null +++ b/versioned_docs/version-2.6.1/plugin-center/security/cryptor-response-plugin.md @@ -0,0 +1,65 @@ +--- +title: CryptorResponse plugin +keywords: ["CryptorResponse"] +description: CryptorResponse plugin +--- + +## Description + +* The `CryptorResponse` plug-in uses `fieldNames` to match the parameters in `responseBody` for `encryption` processing, replacing the corresponding content of the current `fieldNames`. + +## Plugin Setting + +1. In `shenyu-admin` BasicConfig --> plugin -> `cryptor_response` set to enable. + + + +2. Open `selector` to configure the traffic that needs to be matched. + +3. Open the `Rules` configuration corresponding to the `selector`. + + + +* strategyName: Algorithm name. Currently, based on shenyu's SPI mechanism, the encryption and decryption algorithms can be customized, + Need to implement the `org.apache.shenyu.plugin.cryptor.strategy.CryptorStrategy` interface. + + At the same time find the `org.apache.shenyu.plugin.cryptor.strategy.CryptorStrategy` file under `resources/META-INF/shenyu/`, + Write the name of the algorithm, and the package name of the class that implements the `CryptorStrategy` interface. + + +* fieldNames: Matching parameter name. Support parsing multi-level json format matching, using `.` segmentation, such as data.id. + +```json5 + { + data: { + "id": "" + } + } +``` + +* decryptKey: Secret key. Used to decrypt data. + +* encryptKey: Secret key. Used to encrypt data. + +* way: Select encrypt or decrypt. + +## Plugin Use + +* Add support for `cryptorResponse` in the `pom.xml` file of shenyu-bootstrap. + +```xml + + + org.apache.shenyu + shenyu-spring-boot-starter-plugin-cryptor + ${project.version} + + +``` + +## Situation + +Prevent Internet hacking and obtain data maliciously. Improve data security. + + + diff --git a/versioned_docs/version-2.6.1/plugin-center/security/jwt-plugin.md b/versioned_docs/version-2.6.1/plugin-center/security/jwt-plugin.md new file mode 100644 index 00000000000..c58d2fa446d --- /dev/null +++ b/versioned_docs/version-2.6.1/plugin-center/security/jwt-plugin.md @@ -0,0 +1,156 @@ +--- +title: JWT plugin +keywords: ["JWT"] +description: JWT plugin +--- + +# 1. Overview + +## 1.1 Plugin Name + +* `jwt` plugin + +## 1.2 Appropriate Scenario + +* Requires unified authentication by jwt at the gateway. + + +## 1.3 Plugin functionality + +* The `jwt` plug-in is for the `token` attribute or `authorization` of the http request header to carry the attribute value for authentication judgment and judge `OAuth2.0` . + +## 1.4 Plugin code + +* Core module is `shenyu-plugin-jwt`. +* Core class is `org.apache.shenyu.plugin.jwt.JwtPlugin`. + +## 1.5 Added Since Which shenyu version + +* Since ShenYu 2.4.0 + +# 2.How to use plugin + +## 2.1 Plugin-use procedure chart + +![](/img/shenyu/plugin/plugin_use_en.jpg) + +## 2.2 Import pom + +```xml + + org.apache.shenyu + shenyu-spring-boot-starter-plugin-jwt + ${project.version} + +``` + +## 2.3 Enable plugin + +- In shenyu-admin --> BasicConfig --> Plugin --> jwt set Status enable. + +## 2.4 Config plugin + +### 2.4.1 Config plugin in ShenYu-Admin + +* Config secretKey of jwt-plugin in shenyu-admin, the secretKey must more than 256 bit. +* `secretKey`: The private key when using `jwt` to generate `token`, it is required. + +![](/img/shenyu/plugin/jwt/jwt-plugin-config-en.jpg) + +### 2.4.2 Selector config + +* Selector and rule Config. Please refer: [Selector and rule config](../../user-guide/admin-usage/selector-and-rule.md). + +### 2.4.3 Rule Config + +![](/img/shenyu/plugin/jwt/jwt-plugin-rule-handle-en.jpg) + +* convert means jwt converter +* jwtVal: jwt of body name +* headerVal: jwt header name + +custom covert algorithm:[custom-jwt-covert-algorithm](../../developer/custom-jwt-covert-algorithm.md) + +## 2.5 Examples + +### 2.5.1 Use jwt token for authentication judgment + +#### 2.5.1.1 Config jwt-plugin + +![](/img/shenyu/plugin/jwt/jwt-plugin-config-en.jpg) + +#### 2.5.1.2 Config selector match service + +![](/img/shenyu/plugin/jwt/jwt-plugin-selector-config-en.jpg) + +#### 2.5.1.3 Config rule match service + +![](/img/shenyu/plugin/jwt/jwt-plugin-rule-handle-en.jpg) + +#### 2.5.1.4 Generate json web token(jwt) with website + +* You can open `https://jwt.io/` in your browser and fill in the corresponding parameters. +* Config jwt header `HEADER` in `https://jwt.io/` +* Config jwt body `PAYLOAD` in `https://jwt.io/` +* Config jwt signature `VERIFY SIGNATURE` in `https://jwt.io/` + +![](/img/shenyu/plugin/jwt/jwt-web.jpg) + +#### 2.5.1.5 Generate json web token(jwt) with java code + +```java +public final class JwtPluginTest { + + public void generateJwtCode() { + final String secreteKey = "shenyu-test-shenyu-test-shenyu-test"; + Map map = new HashMap<>(); + map.put("id", "1"); + map.put("name", "xiaoming"); + Date date = new Date(); + date.setTime(1655524800000L); + String token = Jwts.builder() + .setIssuedAt(date) + .setExpiration(new Date()) + .setClaims(map) + .signWith(Keys.hmacShaKeyFor(secreteKey.getBytes(StandardCharsets.UTF_8)), SignatureAlgorithm.HS256) + .compact(); + System.out.println(token); + } +} +``` + +#### 2.5.1.6 Request Service + +##### 2.5.1.6.1 Request service with token + +* request your service with jwt token `token: eyJhbGciOiJIUzI1NiJ9.eyJuYW1lIjoieGlhb21pbmciLCJpZCI6IjEifQ.LdRzGlB49alhq204chwF7pf3C0z8ZpuowPvoQdJmSRw` in your request header. + +##### 2.5.1.6.2 Request service Authorization + +* request your service with Authorization `Authorization: Bearer eyJhbGciOiJIUzI1NiJ9.eyJuYW1lIjoieGlhb21pbmciLCJpZCI6IjEifQ.LdRzGlB49alhq204chwF7pf3C0z8ZpuowPvoQdJmSRw` in your request header. + +#### 2.5.1.7 Validate request result + +* error token request result + +``` +{ + "code": 401, + "message": "Illegal authorization" +} +``` + +* normal token request result + +``` +{ + "id": "123", + "name": "hello world save order" +} +``` + +# 3. How to disable plugin + +- In `shenyu-admin` --> BasicConfig --> Plugin --> `jwt` set Status disable. + +![](/img/shenyu/plugin/jwt/jwt-plugin-close_en.jpg) diff --git a/versioned_docs/version-2.6.1/plugin-center/security/oauth2-plugin.md b/versioned_docs/version-2.6.1/plugin-center/security/oauth2-plugin.md new file mode 100644 index 00000000000..39525e12760 --- /dev/null +++ b/versioned_docs/version-2.6.1/plugin-center/security/oauth2-plugin.md @@ -0,0 +1,54 @@ +--- +title: OAuth2 Plugin +keywords: ["OAuth2"] +description: OAuth2 plugin +--- + +## Description + +The `OAuth2` plugin in Apache Shenyu is implemented using the OAuth2 standard. It allows for secure and authorized access to protected resources on a web server by using a token-based authentication method. + +## How Does It Works? + +In Apache Shenyu, the OAuth2 plugin acts as the client application, while the authorization server and resource server are typically provided by external services like GitHub, Google, or Facebook. When a user attempts to access a protected resource on the Apache Shenyu server, the OAuth2 plugin redirects the user to the authorization server to request permission to access the resource. The user then logs in to the authorization server and grants permission for the client application (OAuth2 plugin) to access the requested resource on their behalf. The authorization server then sends a token to the client application, which it can use to access the resource server and retrieve the protected resource. + +## Plugin Setting + +Setting up the OAuth2 Plugin in Apache Shenyu + +To configure the OAuth2 plugin in Apache Shenyu, you will need to follow these steps: + +* Step 1: Install the OAuth2 Plugin + + First, you need to ensure that the OAuth2 plugin is installed and enabled in Apache Shenyu. If it is not already installed, you can download it from the Shenyu GitHub repository and follow the installation instructions. + +* Step 2: Register an OAuth2 Application with the Authorization Server + + Before you can use the OAuth2 plugin in Apache Shenyu, you need to register an OAuth2 application with the authorization server you plan to use (e.g., GitHub, Google, etc.). The registration process typically involves providing basic information about your application, such as the application name, website URL, and redirect URI. + + Once you have registered your OAuth2 application with the authorization server, you will receive a client ID and client secret, which you will need to use in the next step. + +* Step 3: Configure the OAuth2 Plugin + + To configure the OAuth2 plugin in Apache Shenyu, you will need to modify the shenyu-server.yaml configuration file. Here's an example of what the configuration might look like: + + ``` + plugins: + oauth2: + enabled: true + client_id: + client_secret: + authorization_url: + token_url: + user_info_url: + ``` + + * `enabled`: Set this to `true` to enable the OAuth2 plugin in Shenyu. + * `client_id` and `client_secret`: These are the client credentials you received when you registered your OAuth2 application with the authorization server. + * `authorization_url`: This is the URL of the authorization server's authorization endpoint. + * `token_url`: This is the URL of the authorization server's token endpoint. + * `user_info_url`: This is the URL of the authorization server's user info endpoint, which is used to retrieve information about the authenticated user. + +* Step 4: Test the OAuth2 Plugin + + To test the OAuth2 plugin in Apache Shenyu, you can try to access a protected resource on the Shenyu server that requires authentication. When you attempt to access the resource, the OAuth2 plugin should redirect you to the authorization server's login page. After you log in and grant permission to the client application (OAuth2 plugin), the plugin should be able to retrieve an access token and use it to access the protected resource on your behalf. diff --git a/versioned_docs/version-2.6.1/plugin-center/security/sign-plugin.md b/versioned_docs/version-2.6.1/plugin-center/security/sign-plugin.md new file mode 100644 index 00000000000..ed940f4960b --- /dev/null +++ b/versioned_docs/version-2.6.1/plugin-center/security/sign-plugin.md @@ -0,0 +1,501 @@ +--- +title: Sign Plugin +keywords: ["sign"] +description: sign plugin +--- + + +# 1. Overview + +## 1.1 Plugin Name + +* Sign Plugin + +## 1.2 Appropriate Scenario + +* Support http header to authorize +* Support http header and request body to authorize + +## 1.3 Plugin functionality + +* Process signature authentication of requests. + +## 1.4 Plugin code + +* Core Module: `shenyu-plugin-sign` + +* Core Class: `org.apache.shenyu.plugin.sign.SignPlugin` + +## 1.5 Added Since Which shenyu version + +* Since ShenYu 2.4.0 + +# 2. How to use plugin + +## 2.1 Plugin-use procedure chart + +![](/img/shenyu/plugin/plugin_use_en.jpg) + +## 2.2 Import pom + +* Introducing `sign` dependency in the `pom.xml` file of the gateway + +```xml + + + org.apache.shenyu + shenyu-spring-boot-starter-plugin-sign + ${project.version} + + +``` + +## 2.3 Enable plugin + +* In `shenyu-admin`--> BasicConfig --> Plugin --> `sign` set to enable. + +## 2.4 Config Plugin With Authorize(1.0.0) + +### 2.4.1 AK/SK Config + +#### 2.4.1.1 Explanation + +- Manage and control the permissions of requests passing through the Apache ShenYu gateway. +- Generate `AK/SK` and use it with the `Sign` plugin to achieve precise authority control based on URI level. + +#### 2.4.1.2 Tutorial + +First, we can add a piece of authentication information in `BasicConfig` - `Authentication` + + + +Then configure this authentication information + + + +- AppName:The application name associated with this account, it can can fill in or choose (data comes from the application name configured in the Metadata). +- TelPhone:Telphone information. +- AppParams:When the requested context path is the same as the AppName,add this value to the header, the key is `appParam`. +- UserId:Give the user a name, just as an information record. +- ExpandInfo:Description of the account. +- PathAuth:After opening, the account only allows access to the resource path configured below. +- ResourcePath:Allow access to the resource path, support path matching,e.g. `/order/**` . + +After submit, a piece of authentication information is generated, which contains `AppKey` and `AppSecret`, which is the `AK/SK` in the `Sign` plugin. + +Please refer to the detailed instructions of the `Sign` plugin: [Sign Plugin](../../plugin-center/authority-and-certification/sign-plugin). + +#### 2.4.1.3 PathOperation + +For the created authentication information, you can click `PathOperation` at the end of a piece of authentication information. + + + +- On the left is a list of configurable paths, and on the right is a list of paths that allow the account to access. +- Check the resource path, click the `>` or `<` in the middle to move the checked data to the corresponding list. +- In the list of configurable paths on the left, click "Editor" at the end of the account information line, and add them in the "Resource Path" in the pop-up box. + +### 2.4.2 Implementation of Gateway Technology + +* Adopt `AK/SK` authentication technical scheme. +* Adopt authentication plug-in and Chain of Responsibility Pattern to realize. +* Take effect when the authentication plugin is enabled and all interfaces are configured for authentication. + +### 2.4.3 Authentication Guide + +* Step 1: `AK/SK` is assigned by the gateway. For example, the `AK` assigned to you is: `1TEST123456781` SK is: ` 506eeb535cf740d7a755cb49f4a1536' + +* Step 2: Decide the gateway path you want to access, such as `/api/service/abc` + +* Step 3: Construct parameters (the following are general parameters) + +| Field | Value | Description | +| -------- | -------- | :--------: | +| timestamp | current timestamp(String) | The number of milliseconds of the current time(gateway will filter requests the before 5 minutes) | +| path | /api/service/abc | The path that you want to request(Modify by yourself according to your configuration of gateway) | +| version | 1.0.0 | `1.0.0` is a fixed string value | + +Sort the above three field natually according to the key, then splice fields and fields, finally splice SK. The following is a code example. + +#### 2.4.3.1 Generate sign with request header + +Step 1: First, construct a Map. + +```java + + Map map = Maps.newHashMapWithExpectedSize(3); + //timestamp is string format of millisecond. String.valueOf(LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli()) + map.put("timestamp","1571711067186"); // Value should be string format of milliseconds + map.put("path", "/api/service/abc"); + map.put("version", "1.0.0"); +``` + +Step 2: Sort the `Keys` naturally, then splice the key and values, and finally splice the `SK` assigned to you. + +```java +List storedKeys = Arrays.stream(map.keySet() + .toArray(new String[]{})) + .sorted(Comparator.naturalOrder()) + .collect(Collectors.toList()); +final String sign = storedKeys.stream() + .map(key -> String.join("", key, map.get(key))) + .collect(Collectors.joining()).trim() + .concat("506EEB535CF740D7A755CB4B9F4A1536"); +``` + +* The returned sign value should be:`path/api/service/abctimestamp1571711067186version1.0.0506EEB535CF740D7A755CB4B9F4A1536` + +Step 3: Md5 encryption and then capitalization. + +```java +DigestUtils.md5DigestAsHex(sign.getBytes()).toUpperCase() +``` + +* The final returned value is: `A021BF82BE342668B78CD9ADE593D683`. + +#### 2.4.3.2 Generate sign with request header and request body + +Step 1: First, construct a Map, and the map must save every request body parameters + +```java + + Map map = Maps.newHashMapWithExpectedSize(3); + //timestamp is string format of millisecond. String.valueOf(LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli()) + map.put("timestamp","1660659201000"); // Value should be string format of milliseconds + map.put("path", "/http/order/save"); + map.put("version", "1.0.0"); + // if your request body is:{"id":123,"name":"order"} + map.put("id", "1"); + map.put("name", "order") +``` + +Step 2: Sort the `Keys` naturally, then splice the key and values, and finally splice the `SK` assigned to you. + +```java +List storedKeys = Arrays.stream(map.keySet() + .toArray(new String[]{})) + .sorted(Comparator.naturalOrder()) + .collect(Collectors.toList()); +final String sign = storedKeys.stream() + .map(key -> String.join("", key, map.get(key))) + .collect(Collectors.joining()).trim() + .concat("2D47C325AE5B4A4C926C23FD4395C719"); +``` + +* The returned sign value should be:`id123nameorderpath/http/order/savetimestamp1660659201000version1.0.02D47C325AE5B4A4C926C23FD4395C719` + +Step 3: Md5 encryption and then capitalization. + +```java +DigestUtils.md5DigestAsHex(sign.getBytes()).toUpperCase() +``` + +* The final returned value is: `35FE61C21F73E9AAFC46954C14F299D7`. + +### 2.4.4 Request GateWay + +* If your visited path is:`/api/service/abc`. + +* Address: http: domain name of gateway `/api/service/abc`. + +* Set `header`,`header` Parameter: + +| Field | Value | Description | +| -------- | -----: | :----: | +| timestamp | `1571711067186` | Timestamp when signing | +| appKey | `1TEST123456781` | The AK value assigned to you | +| sign | `A90E66763793BDBC817CF3B52AAAC041` | The signature obtained above | +| version | `1.0.0` | `1.0.0` is a fixed value. | + +* The signature plugin will filter requests before `5` minutes by default + +* If the authentication fails, will return code `401`, message may change. + +```json +{ + "code": 401, + "message": "sign is not pass,Please check you sign algorithm!", + "data": null +} +``` + +### 2.4.5 Plugin Config + +![](/img/shenyu/plugin/sign/sign_open_en.jpg) + +### 2.4.6 Selector Config + +![](/img/shenyu/plugin/sign/selector-en.png) + +* Only those matched requests can be authenticated by signature. + +* Selectors and rules, please refer to: [Selector And Rule Config](../../user-guide/admin-usage/selector-and-rule) + +### 2.4.7 Rule Config + +![](/img/shenyu/plugin/sign/rule-en.png) + +* close(signRequestBody): generate signature with request header. +* open(signRequestBody): generate signature with request header and request body. + +## 2.5 Config Plugin With Authorize(2.0.0) + +This authentication algorithm is the version 2.0.0 algorithm, which is same as version1's except **Authentication Guide** and **Request GateWay.** + +### 2.5.1 Authentication Guide + +Authentication algorithm of Version 2.0.0 generates a Token based on the signature algorithm, and puts the Token value into the request header `ShenYu-Authorization` parameter when sending a request. To distinguish it from version 1.0.0, the `version` parameter of the request header is left, which is 2.0.0. + +#### 2.5.1.1 prepare + +* Step 1: `AK/SK` is assigned by the gateway. For example, the `AK` assigned to you is: `1TEST123456781` SK is: ` 506eeb535cf740d7a755cb49f4a1536' + +* Step 2: Decide the gateway path you want to access, such as `/api/service/abc` + +#### 2.5.1.2 Generate Token + ++ build parameter + + build the `parameters` that is json string + + ```json + { + "alg":"MD5", + "appKey":"506EEB535CF740D7A755CB4B9F4A1536", + "timestamp":"1571711067186" + } + ``` + + **alg**: signature algorithm(result is uppercase HEX string) + + - MD5: MD5-HASH(data+key) + - HMD5:HMAC-MD5 + - HS256:HMAC-SHA-256 + - HS512:HMAC-SHA-512 + + **appKey**:appKey + + **timestamp**: timestamp of the length is 13 + ++ Calculate signature value + + ```tex + signature = sign( + base64Encoding(parameters) + Relative URL + Body*, + secret + ); + * indicate Optional , it depends on handler config + Relative URL = path [ "?" query ] eg: /apache/shenyu/pulls?name=jack + ``` + + > note :`Relative URL` is not include fragment + ++ Calculate Token + + > token = base64Encoding(parameters) + '.' + base64Encoding(signature) + + Put the Token into the request header `ShenYu-Authorization` parameter. + +### 2.5.2 Request GateWay + +| Field | 值 | 描述 | +| :------------ | :------ |:------------------------------------------------------------| +| ShenYu-Authorization | Token | Token | +| version | `2.0.0` | Fixed value | + +>please change the Authorization field to ShenYu-Authorization as soon as possible to avoid conflicts with application Authorization. + +## 2.6 Examples + +### 2.6.1 Verify api with sign plugin(1.0.0) + +#### 2.6.1.1 Plugin Config + +![](/img/shenyu/plugin/sign/sign_open_en.jpg) + +#### 2.6.1.2 Selector Config + +![](/img/shenyu/plugin/sign/example-selector-en.png) + +#### 2.6.1.3 Rule Config + +![](/img/shenyu/plugin/sign/example-rule-en.png) + +#### 2.6.1.4 Add AppKey/SecretKey + +![](/img/shenyu/plugin/sign/example-sign-auth-en.png) + +#### 2.6.1.5 Request Service and check result + +* build request params with `Authentication Guide`, + +```java +public class Test1 { + public static void main(String[] args) { + Map map = Maps.newHashMapWithExpectedSize(3); + //timestamp为毫秒数的字符串形式 String.valueOf(LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli()) + map.put("timestamp","1660658725000"); //值应该为毫秒数的字符串形式 + map.put("path", "/http/order/save"); + map.put("version", "1.0.0"); + map.put("id", "123"); + map.put("name", "order"); + // map.put("body", "{\"id\":123,\"name\":\"order\"}"); + + List storedKeys = Arrays.stream(map.keySet() + .toArray(new String[]{})) + .sorted(Comparator.naturalOrder()) + .collect(Collectors.toList()); + final String sign = storedKeys.stream() + .map(key -> String.join("", key, map.get(key))) + .collect(Collectors.joining()).trim() + .concat("2D47C325AE5B4A4C926C23FD4395C719"); + System.out.println(sign); + + System.out.println(DigestUtils.md5DigestAsHex(sign.getBytes()).toUpperCase()); + } +} +``` + +* signature without body: `path/http/order/savetimestamp1571711067186version1.0.02D47C325AE5B4A4C926C23FD4395C719` +* sign without body result is: `9696D3E549A6AEBE763CCC2C7952DDC1` + +![](/img/shenyu/plugin/sign/result.png) + +```java +public class Test2 { + public static void main(String[] args) { + Map map = Maps.newHashMapWithExpectedSize(3); + //timestamp为毫秒数的字符串形式 String.valueOf(LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli()) + map.put("timestamp","1660659201000"); //值应该为毫秒数的字符串形式 + map.put("path", "/http/order/save"); + map.put("version", "1.0.0"); + + List storedKeys = Arrays.stream(map.keySet() + .toArray(new String[]{})) + .sorted(Comparator.naturalOrder()) + .collect(Collectors.toList()); + final String sign = storedKeys.stream() + .map(key -> String.join("", key, map.get(key))) + .collect(Collectors.joining()).trim() + .concat("2D47C325AE5B4A4C926C23FD4395C719"); + System.out.println(sign); + + System.out.println(DigestUtils.md5DigestAsHex(sign.getBytes()).toUpperCase()); + } +} +``` + +*signature with body:`id123nameorderpath/http/order/savetimestamp1660659201000version1.0.02D47C325AE5B4A4C926C23FD4395C719` +*sign with body result is:`35FE61C21F73E9AAFC46954C14F299D7` + +![](/img/shenyu/plugin/sign/result-with-body.png) + +### 2.6.2 Verify api with sign plugin(2.0.0) + +All the configuration parts are the same, so let's look directly at the the calculation part of parameter of request header and the part of sending request. + +#### 2.6.2.1 Request Service and check result + +- implements the algorithm + + Suppose we use a signature algorithm named MD5. According to the previous description, the signature value is to concatenate the data and key, and then hash. + + ```java + private static String sign(final String signKey, final String base64Parameters, final URI uri, final String body) { + + String data = base64Parameters + + getRelativeURL(uri) + + Optional.ofNullable(body).orElse(""); + + return DigestUtils.md5Hex(data+signKey).toUpperCase(); + } + + private static String getRelativeURL(final URI uri) { + if (Objects.isNull(uri.getQuery())) { + return uri.getPath(); + } + return uri.getPath() + "?" + uri.getQuery(); + } + ``` + +- verify without the request body + + ```java + public static void main(String[] args) { + + String appSecret = "2D47C325AE5B4A4C926C23FD4395C719"; + + URI uri = URI.create("/http/order/save"); + + String parameters = JsonUtils.toJson(ImmutableMap.of( + "alg","MD5", + "appKey","BD7980F5688A4DE6BCF1B5327FE07F5C", + "timestamp","1673708353996")); + + String base64Parameters = Base64.getEncoder() + .encodeToString(parameters.getBytes(StandardCharsets.UTF_8)); + + String signature = sign(appSecret,base64Parameters,uri,null); + + String Token = base64Parameters+"."+signature; + + System.out.println(Token); + + } + ``` + + Token: + + ```tex + eyJhbGciOiJNRDUiLCJhcHBLZXkiOiJCRDc5ODBGNTY4OEE0REU2QkNGMUI1MzI3RkUwN0Y1QyIsInRpbWVzdGFtcCI6IjE2NzM3MDgzNTM5OTYifQ==.33ED53DF79CA5B53C0BF2448B670AF35 + ``` + + 发送请求: + + ![image-20230114230500887](/img/shenyu/plugin/sign/version2_sign_request.png) + +- verify with the request body + +```java + public static void main(String[] args) { + String appSecret = "2D47C325AE5B4A4C926C23FD4395C719"; + + URI uri = URI.create("/http/order/save"); + + String parameters = JsonUtils.toJson(ImmutableMap.of( + "alg","MD5", + "appKey","BD7980F5688A4DE6BCF1B5327FE07F5C", + "timestamp","1673708905488")); + + String base64Parameters = Base64.getEncoder() + .encodeToString(parameters.getBytes(StandardCharsets.UTF_8)); + + String requestBody = "{\"id\":123,\"name\":\"order\"}"; + + String signature = sign(appSecret,base64Parameters,uri,requestBody); + + String Token = base64Parameters+"."+signature; + + System.out.println(Token); + + } +``` + +Token: + +```tex +eyJhbGciOiJNRDUiLCJhcHBLZXkiOiJCRDc5ODBGNTY4OEE0REU2QkNGMUI1MzI3RkUwN0Y1QyIsInRpbWVzdGFtcCI6IjE2NzM3MDg5MDU0ODgifQ==.FBCEB6D816644A98378635050AB85EF1 +``` + +![image-20230114231032837](/img/shenyu/plugin/sign/request_body.png) + +![image-20230114230922598](/img/shenyu/plugin/sign/version2_sign_request_with_body.png) + +# 3. How to disable plugin + +* In `shenyu-admin`--> BasicConfig --> Plugin --> `sign` set to disabled. + +# 4. Extension + +* Please refer to: [dev-sign](../../developer/custom-sign-algorithm). + diff --git a/versioned_docs/version-2.6.1/plugin-center/security/waf-plugin.md b/versioned_docs/version-2.6.1/plugin-center/security/waf-plugin.md new file mode 100644 index 00000000000..802dd9865b8 --- /dev/null +++ b/versioned_docs/version-2.6.1/plugin-center/security/waf-plugin.md @@ -0,0 +1,76 @@ +--- +title: Waf Plugin +keywords: ["waf"] +description: waf plugin +--- + +## Description + +* `Waf` is the core implementation of gateway to realize firewall function for network traffic. + +## Plugin Setting + +Please refer to the `deployment` document, choose a way to start `shenyu-admin`. For example, through [Local Deployment](../../deployment/deployment-local) to start the `Apache ShenYu` management system. + +* In `shenyu-admin` BasicConfig --> plugin -> `waf` set to enable.If you don't want to use this function, please disable this plugin in the `shenyu-admin`. + + + +* Add configuration mode in plugin editing. + +```yaml +{"model":"black"} +# model can be 'black' or 'mixed' +# The default mode is blacklist mode; If setting is mixed, it will be mixed mode. We will explain it specifically below. +``` + +## Add Dependency + +* Introducing `waf` dependency in the pom.xml of the gateway. + +```xml + + + org.apache.shenyu + shenyu-spring-boot-starter-plugin-waf + ${project.version} + + +``` + +## Waf Plugin Configuration + +For more instructions on selector and rule configuration, please refer to: [Selector And Rule Config](../../user-guide/admin-usage/selector-and-rule), here only some fields are introduced. + +`Waf` plugin rule configuration page: + + + +For requests that are denied access by `Waf` , the response header status code is: `403`. + +#### Black Model + +* When `model` is set to `black` mode, only the matched traffic will execute the rejection policy, and the unmatched traffic will be skipped directly. +* The `Handler` feild in the rule configuration is invalid and can be configured to be empty. + +#### Mixed Model + +* When `model` is set to `mixed` mode, all traffic will pass through waf plugin. For different matching traffic, users can set whether to reject or pass. + +* The `Handler` feild in the rule configuration must be configured: + + * `permission`: The handle logic that matches the rule. `reject`: deny access, `allow`: allow access. + + * `statusCode`: When access is denied, the value of the code field in the response body. `Will not modify the status code of the response header`. + + e.g.:`statusCode=10001`,The rejected response body is : + + ```json + {"code":10001,"message":"You are forbidden to visit"} + ``` + +## Situation + +* `Waf` is also the pre-plugin of `ShenYu`, which is mainly used to intercept illegal requests or exception requests and give relevant rejection policies. +* When faced with replay attacks, you can intercept illegal `ip` and `host`, and set reject strategy according to matched `ip` or `host`. +* How to determine `ip` and `host`, please refer to: [parsing-ip-and-host](../../developer/custom-parsing-ip-and-host) diff --git a/versioned_docs/version-2.6.1/quick-start/_category_.json b/versioned_docs/version-2.6.1/quick-start/_category_.json new file mode 100644 index 00000000000..6b00aae3947 --- /dev/null +++ b/versioned_docs/version-2.6.1/quick-start/_category_.json @@ -0,0 +1,4 @@ +{ + "label": "Quick Start", + "position": 4 +} diff --git a/versioned_docs/version-2.6.1/quick-start/quick-start-dubbo.md b/versioned_docs/version-2.6.1/quick-start/quick-start-dubbo.md new file mode 100644 index 00000000000..8fd022ffbd2 --- /dev/null +++ b/versioned_docs/version-2.6.1/quick-start/quick-start-dubbo.md @@ -0,0 +1,180 @@ +--- +title: Quick start with Dubbo +description: Quick start with Dubbo +--- + +This document introduces how to quickly access the Apache ShenYu gateway using Dubbo. You can get the code example of this document by clicking [here](https://github.com/apache/shenyu/tree/master/shenyu-examples/shenyu-examples-dubbo). + +## Environment to prepare + +Please refer to the deployment to select a way to start shenyu-admin. For example, start the Apache ShenYu gateway management system through [local deployment](../deployment/deployment-local) . + +After successful startup, you need to open the Dubbo plugin on in the BasicConfig `->` Plugin, and set your registry address. Please make sure the registry center is open locally. + + + +If you are a startup gateway by means of source, can be directly run the ShenyuBootstrapApplication of shenyu-bootstrap module. + +> Note: Before starting, make sure the gateway has added dependencies. + + +If client is `apache dubbo`, registry center is `Zookeeper`, please refer to the following configuration: + + +```xml + + + org.apache.shenyu + shenyu-spring-boot-starter-client-apache-dubbo + ${project.version} + + + org.apache.dubbo + dubbo + 2.7.5 + + + + org.apache.curator + curator-client + 4.0.1 + + + log4j + log4j + + + + + org.apache.curator + curator-framework + 4.0.1 + + + org.apache.curator + curator-recipes + 4.0.1 + + + +``` + +If client is `alibaba dubbo`, registry center is `Zookeeper`, please refer to the following configuration: + + +```xml + + + org.apache.shenyu + shenyu-spring-boot-starter-client-alibaba-dubbo + ${project.version} + + + com.alibaba + dubbo + ${alibaba.dubbo.version} + + + org.apache.curator + curator-client + ${curator.version} + + + log4j + log4j + + + + + org.apache.curator + curator-framework + ${curator.version} + + + org.apache.curator + curator-recipes + ${curator.version} + + +``` + + +## Run the shenyu-examples-dubbo project + +Download [shenyu-examples-dubbo](https://github.com/apache/shenyu/tree/master/shenyu-examples/shenyu-examples-dubbo) . + +replace the register address in `shenyu-examples-alibaba-dubbo-service/src/main/resources/spring-dubbo.xml` with your local zk address, such as: + +```xml + +``` + +Execute the `org.apache.shenyu.examples.alibaba.dubbo.service.TestAlibabaDubboApplication` main method to start dubbo project. + +The following log appears when the startup is successful: + +```shell +2021-02-06 20:58:01.807 INFO 3724 --- [pool-2-thread-1] o.d.s.client.common.utils.RegisterUtils : dubbo client register success: {"appName":"dubbo","contextPath":"/dubbo","path":"/dubbo/insert","pathDesc":"Insert a row of data","rpcType":"dubbo","serviceName":"org.dromara.shenyu.examples.dubbo.api.service.DubboTestService","methodName":"insert","ruleName":"/dubbo/insert","parameterTypes":"org.dromara.shenyu.examples.dubbo.api.entity.DubboTest","rpcExt":"{\"group\":\"\",\"version\":\"\",\"loadbalance\":\"random\",\"retries\":2,\"timeout\":10000,\"url\":\"\"}","enabled":true} +2021-02-06 20:58:01.821 INFO 3724 --- [pool-2-thread-1] o.d.s.client.common.utils.RegisterUtils : dubbo client register success: {"appName":"dubbo","contextPath":"/dubbo","path":"/dubbo/findAll","pathDesc":"Get all data","rpcType":"dubbo","serviceName":"org.dromara.shenyu.examples.dubbo.api.service.DubboTestService","methodName":"findAll","ruleName":"/dubbo/findAll","parameterTypes":"","rpcExt":"{\"group\":\"\",\"version\":\"\",\"loadbalance\":\"random\",\"retries\":2,\"timeout\":10000,\"url\":\"\"}","enabled":true} +2021-02-06 20:58:01.833 INFO 3724 --- [pool-2-thread-1] o.d.s.client.common.utils.RegisterUtils : dubbo client register success: {"appName":"dubbo","contextPath":"/dubbo","path":"/dubbo/findById","pathDesc":"Query by Id","rpcType":"dubbo","serviceName":"org.dromara.shenyu.examples.dubbo.api.service.DubboTestService","methodName":"findById","ruleName":"/dubbo/findById","parameterTypes":"java.lang.String","rpcExt":"{\"group\":\"\",\"version\":\"\",\"loadbalance\":\"random\",\"retries\":2,\"timeout\":10000,\"url\":\"\"}","enabled":true} +2021-02-06 20:58:01.844 INFO 3724 --- [pool-2-thread-1] o.d.s.client.common.utils.RegisterUtils : dubbo client register success: {"appName":"dubbo","contextPath":"/dubbo","path":"/dubbo/findByListId","pathDesc":"","rpcType":"dubbo","serviceName":"org.dromara.shenyu.examples.dubbo.api.service.DubboMultiParamService","methodName":"findByListId","ruleName":"/dubbo/findByListId","parameterTypes":"java.util.List","rpcExt":"{\"group\":\"\",\"version\":\"\",\"loadbalance\":\"random\",\"retries\":2,\"timeout\":10000,\"url\":\"\"}","enabled":true} +2021-02-06 20:58:01.855 INFO 3724 --- [pool-2-thread-1] o.d.s.client.common.utils.RegisterUtils : dubbo client register success: {"appName":"dubbo","contextPath":"/dubbo","path":"/dubbo/findByIdsAndName","pathDesc":"","rpcType":"dubbo","serviceName":"org.dromara.shenyu.examples.dubbo.api.service.DubboMultiParamService","methodName":"findByIdsAndName","ruleName":"/dubbo/findByIdsAndName","parameterTypes":"java.util.List,java.lang.String","rpcExt":"{\"group\":\"\",\"version\":\"\",\"loadbalance\":\"random\",\"retries\":2,\"timeout\":10000,\"url\":\"\"}","enabled":true} +2021-02-06 20:58:01.866 INFO 3724 --- [pool-2-thread-1] o.d.s.client.common.utils.RegisterUtils : dubbo client register success: {"appName":"dubbo","contextPath":"/dubbo","path":"/dubbo/batchSave","pathDesc":"","rpcType":"dubbo","serviceName":"org.dromara.shenyu.examples.dubbo.api.service.DubboMultiParamService","methodName":"batchSave","ruleName":"/dubbo/batchSave","parameterTypes":"java.util.List","rpcExt":"{\"group\":\"\",\"version\":\"\",\"loadbalance\":\"random\",\"retries\":2,\"timeout\":10000,\"url\":\"\"}","enabled":true} +2021-02-06 20:58:01.876 INFO 3724 --- [pool-2-thread-1] o.d.s.client.common.utils.RegisterUtils : dubbo client register success: {"appName":"dubbo","contextPath":"/dubbo","path":"/dubbo/findByArrayIdsAndName","pathDesc":"","rpcType":"dubbo","serviceName":"org.dromara.shenyu.examples.dubbo.api.service.DubboMultiParamService","methodName":"findByArrayIdsAndName","ruleName":"/dubbo/findByArrayIdsAndName","parameterTypes":"[Ljava.lang.Integer;,java.lang.String","rpcExt":"{\"group\":\"\",\"version\":\"\",\"loadbalance\":\"random\",\"retries\":2,\"timeout\":10000,\"url\":\"\"}","enabled":true} +2021-02-06 20:58:01.889 INFO 3724 --- [pool-2-thread-1] o.d.s.client.common.utils.RegisterUtils : dubbo client register success: {"appName":"dubbo","contextPath":"/dubbo","path":"/dubbo/saveComplexBeanTestAndName","pathDesc":"","rpcType":"dubbo","serviceName":"org.dromara.shenyu.examples.dubbo.api.service.DubboMultiParamService","methodName":"saveComplexBeanTestAndName","ruleName":"/dubbo/saveComplexBeanTestAndName","parameterTypes":"org.dromara.shenyu.examples.dubbo.api.entity.ComplexBeanTest,java.lang.String","rpcExt":"{\"group\":\"\",\"version\":\"\",\"loadbalance\":\"random\",\"retries\":2,\"timeout\":10000,\"url\":\"\"}","enabled":true} +2021-02-06 20:58:01.901 INFO 3724 --- [pool-2-thread-1] o.d.s.client.common.utils.RegisterUtils : dubbo client register success: {"appName":"dubbo","contextPath":"/dubbo","path":"/dubbo/batchSaveAndNameAndId","pathDesc":"","rpcType":"dubbo","serviceName":"org.dromara.shenyu.examples.dubbo.api.service.DubboMultiParamService","methodName":"batchSaveAndNameAndId","ruleName":"/dubbo/batchSaveAndNameAndId","parameterTypes":"java.util.List,java.lang.String,java.lang.String","rpcExt":"{\"group\":\"\",\"version\":\"\",\"loadbalance\":\"random\",\"retries\":2,\"timeout\":10000,\"url\":\"\"}","enabled":true} +2021-02-06 20:58:01.911 INFO 3724 --- [pool-2-thread-1] o.d.s.client.common.utils.RegisterUtils : dubbo client register success: {"appName":"dubbo","contextPath":"/dubbo","path":"/dubbo/saveComplexBeanTest","pathDesc":"","rpcType":"dubbo","serviceName":"org.dromara.shenyu.examples.dubbo.api.service.DubboMultiParamService","methodName":"saveComplexBeanTest","ruleName":"/dubbo/saveComplexBeanTest","parameterTypes":"org.dromara.shenyu.examples.dubbo.api.entity.ComplexBeanTest","rpcExt":"{\"group\":\"\",\"version\":\"\",\"loadbalance\":\"random\",\"retries\":2,\"timeout\":10000,\"url\":\"\"}","enabled":true} +2021-02-06 20:58:01.922 INFO 3724 --- [pool-2-thread-1] o.d.s.client.common.utils.RegisterUtils : dubbo client register success: {"appName":"dubbo","contextPath":"/dubbo","path":"/dubbo/findByStringArray","pathDesc":"","rpcType":"dubbo","serviceName":"org.dromara.shenyu.examples.dubbo.api.service.DubboMultiParamService","methodName":"findByStringArray","ruleName":"/dubbo/findByStringArray","parameterTypes":"[Ljava.lang.String;","rpcExt":"{\"group\":\"\",\"version\":\"\",\"loadbalance\":\"random\",\"retries\":2,\"timeout\":10000,\"url\":\"\"}","enabled":true} +``` + +Note: When you need to expose `multiple protocols` at the same time, please do not configure `shenyu.client.dubbo.props.port`. + +## Test + +The `shenyu-examples-dubbo` project will automatically register interface methods annotated with `@ShenyuDubboClient` in the Apache ShenYu gateway after successful startup. + +Open PluginList -> rpc proxy -> dubbo to see the list of plugin rule configurations: + +![](/img/shenyu/quick-start/dubbo/rule-list.jpg) + +Use `PostMan` to simulate `HTTP` to request your `Dubbo` service: + +![](/img/shenyu/quick-start/dubbo/postman-findbyid.jpg) + +Complex multi-parameter example: The related interface implementation class is `org.apache.shenyu.examples.alibaba.dubbo.service.impl.DubboMultiParamServiceImpl#batchSaveAndNameAndId`. + +```java +@Override +@ShenyuDubboClient(path = "/batchSaveAndNameAndId") +public DubboTest batchSaveAndNameAndId(List dubboTestList, String id, String name) { + DubboTest test = new DubboTest(); + test.setId(id); + test.setName("hello world shenyu alibaba dubbo param batchSaveAndNameAndId :" + name + ":" + dubboTestList.stream().map(DubboTest::getName).collect(Collectors.joining("-"))); + return test; +} +``` + +![](/img/shenyu/quick-start/dubbo/postman-multiparams.jpg) + +When your arguments do not match, the following exception will occur: + +```java +2021-02-07 22:24:04.015 ERROR 14860 --- [:20888-thread-3] o.d.shenyu.web.handler.GlobalErrorHandler : [e47b2a2a] Resolved [ShenyuException: org.apache.dubbo.remoting.RemotingException: java.lang.IllegalArgumentException: args.length != types.length +java.lang.IllegalArgumentException: args.length != types.length + at org.apache.dubbo.common.utils.PojoUtils.realize(PojoUtils.java:91) + at org.apache.dubbo.rpc.filter.GenericFilter.invoke(GenericFilter.java:82) + at org.apache.dubbo.rpc.protocol.ProtocolFilterWrapper$1.invoke(ProtocolFilterWrapper.java:81) + at org.apache.dubbo.rpc.filter.ClassLoaderFilter.invoke(ClassLoaderFilter.java:38) + at org.apache.dubbo.rpc.protocol.ProtocolFilterWrapper$1.invoke(ProtocolFilterWrapper.java:81) + at org.apache.dubbo.rpc.filter.EchoFilter.invoke(EchoFilter.java:41) + at org.apache.dubbo.rpc.protocol.ProtocolFilterWrapper$1.invoke(ProtocolFilterWrapper.java:81) + at org.apache.dubbo.rpc.protocol.dubbo.DubboProtocol$1.reply(DubboProtocol.java:150) + at org.apache.dubbo.remoting.exchange.support.header.HeaderExchangeHandler.handleRequest(HeaderExchangeHandler.java:100) + at org.apache.dubbo.remoting.exchange.support.header.HeaderExchangeHandler.received(HeaderExchangeHandler.java:175) + at org.apache.dubbo.remoting.transport.DecodeHandler.received(DecodeHandler.java:51) + at org.apache.dubbo.remoting.transport.dispatcher.ChannelEventRunnable.run(ChannelEventRunnable.java:57) + at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) + at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) + at java.lang.Thread.run(Thread.java:748) +] for HTTP POST /dubbo/batchSaveAndNameAndId +``` diff --git a/versioned_docs/version-2.6.1/quick-start/quick-start-grpc.md b/versioned_docs/version-2.6.1/quick-start/quick-start-grpc.md new file mode 100644 index 00000000000..36d1300ce9a --- /dev/null +++ b/versioned_docs/version-2.6.1/quick-start/quick-start-grpc.md @@ -0,0 +1,169 @@ +--- +title: Quick start with gRPC +description: Quick start with gRPC +--- + +This document introduces how to quickly access the Apache ShenYu gateway using gRPC. You can get the code example of this document by clicking [here](https://github.com/apache/shenyu/tree/master/shenyu-examples/shenyu-examples-grpc) . + +## Prepare For Environment + +Please refer to the deployment to select a way to start shenyu-admin. For example, start the Apache ShenYu gateway management system through [local deployment](../deployment/deployment-local) . + +After successful startup, you need to open the gRPC plugin on in the BasicConfig `->` Plugin. + + + +If you are a startup gateway by means of source, can be directly run the ShenyuBootstrapApplication of shenyu-bootstrap module. + +> Note: Before starting, make sure the gateway has added dependencies. + + +Add the following dependencies to the gateway's `pom.xml` file: + +```xml + + + org.apache.shenyu + shenyu-spring-boot-starter-plugin-grpc + ${project.version} + + +``` + +## Run the shenyu-examples-grpc project + +Download [shenyu-examples-grpc](https://github.com/apache/shenyu/tree/master/shenyu-examples/shenyu-examples-grpc) + +Run the following command under `shenyu-examples-grpc` to generate Java code: + +```shell +mvn protobuf:compile +mvn protobuf:compile-custom +``` + +Execute the `org.apache.shenyu.examples.grpc.ShenyuTestGrpcApplication` main method to start project. + +The following log appears when the startup is successful: + +```shell +2021-06-18 19:33:32.866 INFO 11004 --- [or_consumer_-19] o.a.s.r.client.http.utils.RegisterUtils : grpc client register success: {"appName":"127.0.0.1:8080","contextPath":"/grpc","path":"/grpc/clientStreamingFun","pathDesc":"clientStreamingFun","rpcType":"grpc","serviceName":"stream.StreamService","methodName":"clientStreamingFun","ruleName":"/grpc/clientStreamingFun","parameterTypes":"io.grpc.stub.StreamObserver","rpcExt":"{\"timeout\":5000,\"methodType\":\"CLIENT_STREAMING\"}","enabled":true,"host":"172.20.10.6","port":8080,"registerMetaData":false} +2021-06-18 19:33:32.866 INFO 11004 --- [or_consumer_-17] o.a.s.r.client.http.utils.RegisterUtils : grpc client register success: {"appName":"127.0.0.1:8080","contextPath":"/grpc","path":"/grpc/echo","pathDesc":"echo","rpcType":"grpc","serviceName":"echo.EchoService","methodName":"echo","ruleName":"/grpc/echo","parameterTypes":"echo.EchoRequest,io.grpc.stub.StreamObserver","rpcExt":"{\"timeout\":5000,\"methodType\":\"UNARY\"}","enabled":true,"host":"172.20.10.6","port":8080,"registerMetaData":false} +2021-06-18 19:33:32.866 INFO 11004 --- [or_consumer_-20] o.a.s.r.client.http.utils.RegisterUtils : grpc client register success: {"appName":"127.0.0.1:8080","contextPath":"/grpc","path":"/grpc/bidiStreamingFun","pathDesc":"bidiStreamingFun","rpcType":"grpc","serviceName":"stream.StreamService","methodName":"bidiStreamingFun","ruleName":"/grpc/bidiStreamingFun","parameterTypes":"io.grpc.stub.StreamObserver","rpcExt":"{\"timeout\":5000,\"methodType\":\"BIDI_STREAMING\"}","enabled":true,"host":"172.20.10.6","port":8080,"registerMetaData":false} +2021-06-18 19:33:32.866 INFO 11004 --- [or_consumer_-21] o.a.s.r.client.http.utils.RegisterUtils : grpc client register success: {"appName":"127.0.0.1:8080","contextPath":"/grpc","path":"/grpc/unaryFun","pathDesc":"unaryFun","rpcType":"grpc","serviceName":"stream.StreamService","methodName":"unaryFun","ruleName":"/grpc/unaryFun","parameterTypes":"stream.RequestData,io.grpc.stub.StreamObserver","rpcExt":"{\"timeout\":5000,\"methodType\":\"UNARY\"}","enabled":true,"host":"172.20.10.6","port":8080,"registerMetaData":false} +2021-06-18 19:33:32.866 INFO 11004 --- [or_consumer_-18] o.a.s.r.client.http.utils.RegisterUtils : grpc client register success: {"appName":"127.0.0.1:8080","contextPath":"/grpc","path":"/grpc/serverStreamingFun","pathDesc":"serverStreamingFun","rpcType":"grpc","serviceName":"stream.StreamService","methodName":"serverStreamingFun","ruleName":"/grpc/serverStreamingFun","parameterTypes":"stream.RequestData,io.grpc.stub.StreamObserver","rpcExt":"{\"timeout\":5000,\"methodType\":\"SERVER_STREAMING\"}","enabled":true,"host":"172.20.10.6","port":8080,"registerMetaData":false} +``` + + +## Test + +The `shenyu-examples-grpc` project will automatically register interface methods annotated with `@ShenyuGrpcClient` in the Apache ShenYu gateway after successful startup. + +Open PluginList -> rpc proxy -> gRPC to see the list of plugin rule configurations: + +![](/img/shenyu/quick-start/grpc/grpc-service-en.png) + +Use `postman` to simulate `http` to request your gRPC service. The following is the request body. + +```json +{ + "data": [ + { + "message": "hello grpc" + } + ] +} +``` + +![](/img/shenyu/quick-start/grpc/grpc-echo.png) + +The parameters are passed in json format. The name of the key is `data` by default, and you can reset it in `GrpcConstants.JSON_DESCRIPTOR_PROTO_FIELD_NAME`. The input of value is based on the proto file defined by you. + +## Streaming + +the Apache ShenYu can support streaming of gRPC. The following shows the calls of the four method types of gRPC. In streaming, you can pass multiple parameters in the form of an array. + + +- `UNARY` + +The request body like this. + +```json +{ + "data": [ + { + "text": "hello grpc" + } + ] +} +``` + +Then, call gRPC service by `UNARY` method type. + +![](/img/shenyu/quick-start/grpc/grpc-unary.png) + +- `CLIENT_STREAMING` + +The request body like this. + +```json +{ + "data": [ + { + "text": "hello grpc" + }, + { + "text": "hello grpc" + }, + { + "text": "hello grpc" + } + ] +} +``` + +Then, call gRPC service by `CLIENT_STREAMING` method type. + +![](/img/shenyu/quick-start/grpc/grpc-client-stream.png) + +- `SERVER_STREAMING` + +The request body like this. + +```json +{ + "data": [ + { + "text": "hello grpc" + } + ] +} +``` + +Then, call gRPC service by `SERVER_STREAMING` method type. + +![](/img/shenyu/quick-start/grpc/grpc-server-stream.png) + +- `BIDI_STREAMING` + + +The request body like this. + +```json +{ + "data": [ + { + "text": "hello grpc" + }, + { + "text": "hello grpc" + }, + { + "text": "hello grpc" + } + ] +} +``` + +Then, call gRPC service by `BIDI_STREAMING` method type. + +![](/img/shenyu/quick-start/grpc/grpc-bidi-stream.png) diff --git a/versioned_docs/version-2.6.1/quick-start/quick-start-http.md b/versioned_docs/version-2.6.1/quick-start/quick-start-http.md new file mode 100644 index 00000000000..21d05c79d11 --- /dev/null +++ b/versioned_docs/version-2.6.1/quick-start/quick-start-http.md @@ -0,0 +1,80 @@ +--- +title: Quick start with Http +description: Quick start with http +--- + +This document introduces how to quickly access the Apache ShenYu gateway using Http. You can get the code example of this document by clicking [here](https://github.com/apache/shenyu/tree/master/shenyu-examples/shenyu-examples-http). + +## Environment to prepare + +Please refer to the deployment to select a way to start shenyu-admin. For example, start the Apache ShenYu gateway management system through [local deployment](../deployment/deployment-local) . + +After successful startup, you need to open the Divide plugin on in the BasicConfig `->` Plugin. In the Apache ShenYu gateway, the HTTP request is handled by the Divide plugin. + + + +If you are a startup gateway by means of source, can be directly run the ShenyuBootstrapApplication of shenyu-bootstrap module. + +> Note: Before starting, make sure the gateway has added dependencies. + + +Add the following dependencies to the gateway's `pom.xml` file: + + +```xml + + + org.apache.shenyu + shenyu-spring-boot-starter-plugin-divide + ${project.version} + + + + org.apache.shenyu + shenyu-spring-boot-starter-plugin-httpclient + ${project.version} + +``` + + +## Run the shenyu-examples-http project + +Download [shenyu-examples-http](https://github.com/apache/shenyu/tree/master/shenyu-examples/shenyu-examples-http) + +Execute the `org.apache.shenyu.examples.http.ShenyuTestHttpApplication` main method to start project. + +Since `2.4.3`, `shenyu.client.http.props.port` can be non-configured if you like. + +The following log appears when the startup is successful: + +```shell +2021-02-10 00:57:07.561 INFO 3700 --- [pool-1-thread-1] o.d.s.client.common.utils.RegisterUtils : http client register success: {"appName":"http","context":"/http","path":"/http/test/**","pathDesc":"","rpcType":"http","host":"192.168.50.13","port":8188,"ruleName":"/http/test/**","enabled":true,"registerMetaData":false} +2021-02-10 00:57:07.577 INFO 3700 --- [pool-1-thread-1] o.d.s.client.common.utils.RegisterUtils : http client register success: {"appName":"http","context":"/http","path":"/http/order/save","pathDesc":"Save order","rpcType":"http","host":"192.168.50.13","port":8188,"ruleName":"/http/order/save","enabled":true,"registerMetaData":false} +2021-02-10 00:57:07.587 INFO 3700 --- [pool-1-thread-1] o.d.s.client.common.utils.RegisterUtils : http client register success: {"appName":"http","context":"/http","path":"/http/order/path/**/name","pathDesc":"","rpcType":"http","host":"192.168.50.13","port":8188,"ruleName":"/http/order/path/**/name","enabled":true,"registerMetaData":false} +2021-02-10 00:57:07.596 INFO 3700 --- [pool-1-thread-1] o.d.s.client.common.utils.RegisterUtils : http client register success: {"appName":"http","context":"/http","path":"/http/order/findById","pathDesc":"Find by id","rpcType":"http","host":"192.168.50.13","port":8188,"ruleName":"/http/order/findById","enabled":true,"registerMetaData":false} +2021-02-10 00:57:07.606 INFO 3700 --- [pool-1-thread-1] o.d.s.client.common.utils.RegisterUtils : http client register success: {"appName":"http","context":"/http","path":"/http/order/path/**","pathDesc":"","rpcType":"http","host":"192.168.50.13","port":8188,"ruleName":"/http/order/path/**","enabled":true,"registerMetaData":false} +2021-02-10 00:57:08.023 INFO 3700 --- [ main] o.s.b.web.embedded.netty.NettyWebServer : Netty started on port(s): 8188 +2021-02-10 00:57:08.026 INFO 3700 --- [ main] o.d.s.e.http.ShenyuTestHttpApplication : Started ShenyuTestHttpApplication in 2.555 seconds (JVM running for 3.411) +``` + + + +## Test + +The `shenyu-examples-http` project will automatically register interface methods annotated with `@ShenyuSpringMvcClient` in the Apache ShenYu gateway after successful startup. + +Open PluginList -> Proxy -> divide to see the list of plugin rule configurations: + +![](/img/shenyu/quick-start/http/rule-list.png) + +Use PostMan to simulate HTTP to request your http service: + +![](/img/shenyu/quick-start/http/postman-test.png) + +Use IDEA HTTP Client Plugin to simulate HTTP to request your http service[local:no Shenyu proxy]: + +![](/img/shenyu/quick-start/http/idea-http-test-local.png) + +Use IDEA HTTP Client Plugin to simulate HTTP to request your http service[Shenyu proxy]: + +![](/img/shenyu/quick-start/http/idea-http-test-proxy.png) diff --git a/versioned_docs/version-2.6.1/quick-start/quick-start-motan.md b/versioned_docs/version-2.6.1/quick-start/quick-start-motan.md new file mode 100644 index 00000000000..536382c9c13 --- /dev/null +++ b/versioned_docs/version-2.6.1/quick-start/quick-start-motan.md @@ -0,0 +1,97 @@ +--- +title: Quick start with Motan +description: Motan quick start +--- + +This document introduces how to quickly access the Apache ShenYu gateway using Motan RPC. You can get the code example of this document by clicking [here](https://github.com/apache/shenyu/tree/master/shenyu-examples/shenyu-examples-motan). + + +## Environment to prepare + + +Please refer to the deployment to select a way to start shenyu-admin. For example, start the Apache ShenYu gateway management system through [local deployment](../deployment/deployment-local) . + +After successful startup, you need to open the Sofa plugin on in the BasicConfig `->` Plugin. + + + +If you are a startup gateway by means of source, can be directly run the ShenyuBootstrapApplication of shenyu-bootstrap module. + +> Note: Before starting, make sure the gateway has added dependencies. +> Start up zookeeper in local. + +Import the gateway proxy plugin for `Motan` and add the following dependencies to the gateway's `pom.xml` file: + + +```xml + + + org.apache.shenyu + shenyu-spring-boot-starter-plugin-motan + ${project.version} + + + + com.weibo + motan-core + 1.1.9 + + + + com.weibo + motan-registry-zookeeper + 1.1.9 + + + + com.weibo + motan-transport-netty4 + 1.1.9 + + + + com.weibo + motan-springsupport + 1.1.9 + +``` + + + +## Run the shenyu-examples-motan project + +Download [shenyu-examples-motan](https://github.com/apache/shenyu/tree/master/shenyu-examples/shenyu-examples-motan) . + +Run main method of `org.apache.shenyu.examples.motan.service.TestMotanApplication` to start this project. + +log info as follows after starting: + +```shell +2021-07-18 16:46:25.388 INFO 96 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8081 (http) with context path '' +2021-07-18 16:46:25.393 INFO 96 --- [ main] o.a.s.e.m.service.TestMotanApplication : Started TestMotanApplication in 3.89 seconds (JVM running for 4.514) +2021-07-18 16:46:25.396 INFO 96 --- [ main] info : [ZookeeperRegistry] Url (null) will set to available to Registry [zookeeper://localhost:2181/default_rpc/com.weibo.api.motan.registry.RegistryService/1.0/service] +2021-07-18 16:46:25.399 INFO 96 --- [ Thread-6] o.a.s.c.c.s.ShenyuClientShutdownHook : hook Thread-0 will sleep 3000ms when it start +2021-07-18 16:46:25.399 INFO 96 --- [ Thread-6] o.a.s.c.c.s.ShenyuClientShutdownHook : hook SpringContextShutdownHook will sleep 3000ms when it start +2021-07-18 16:46:25.445 INFO 96 --- [ntLoopGroup-3-2] info : NettyChannelHandler channelActive: remote=/192.168.1.8:49740 local=/192.168.1.8:8002 +2021-07-18 16:46:25.445 INFO 96 --- [ntLoopGroup-3-1] info : NettyChannelHandler channelActive: remote=/192.168.1.8:49739 local=/192.168.1.8:8002 +2021-07-18 16:46:25.925 INFO 96 --- [or_consumer_-17] o.a.s.r.client.http.utils.RegisterUtils : motan client register success: {"appName":"motan","contextPath":"/motan","path":"/motan/hello","pathDesc":"","rpcType":"motan","serviceName":"org.apache.shenyu.examples.motan.service.MotanDemoService","methodName":"hello","ruleName":"/motan/hello","parameterTypes":"java.lang.String","rpcExt":"{\"methodInfo\":[{\"methodName\":\"hello\",\"params\":[{\"left\":\"java.lang.String\",\"right\":\"name\"}]}],\"group\":\"motan-shenyu-rpc\"}","enabled":true,"host":"192.168.220.1","port":8081,"registerMetaData":false} + +``` + + + +## Test + +The `shenyu-examples-motan` project will automatically register the `@ShenyuMotanClient` annotated interface methods with the gateway and add selectors and rules. If not, you can manually add them. + + +Open PluginList -> rpc proxy -> motan to see the list of plugin rule configurations: + + + + +Use PostMan to simulate HTTP to request your Motan service: + + + + diff --git a/versioned_docs/version-2.6.1/quick-start/quick-start-sofa.md b/versioned_docs/version-2.6.1/quick-start/quick-start-sofa.md new file mode 100644 index 00000000000..713ed8c12fd --- /dev/null +++ b/versioned_docs/version-2.6.1/quick-start/quick-start-sofa.md @@ -0,0 +1,138 @@ +--- +title: Quick start with Sofa +description: Quick start with Sofa +--- + +This document introduces how to quickly access the Apache ShenYu gateway using Sofa RPC. You can get the code example of this document by clicking [here](https://github.com/apache/shenyu/tree/master/shenyu-examples/shenyu-examples-sofa). + +## Environment to prepare + + +Please refer to the deployment to select a way to start shenyu-admin. For example, start the Apache ShenYu gateway management system through [local deployment](../deployment/deployment-local) . + +After successful startup, you need to open the Sofa plugin on in the BasicConfig `->` Plugin, and set your registry address. Please make sure the registry center is open locally. + + + +If you are a startup gateway by means of source, can be directly run the ShenyuBootstrapApplication of shenyu-bootstrap module. + +> Note: Before starting, make sure the gateway has added dependencies. + + +If client is `sofa`, registry center is `Zookeeper`, please refer to the following configuration: + + + +```xml + + + com.alipay.sofa + sofa-rpc-all + 5.7.6 + + + org.apache.curator + curator-client + 4.0.1 + + + org.apache.curator + curator-framework + 4.0.1 + + + org.apache.curator + curator-recipes + 4.0.1 + + + + org.apache.shenyu + shenyu-spring-boot-starter-plugin-sofa + ${project.version} + + + +``` + +## Run the shenyu-examples-sofa project + +Download [shenyu-examples-sofa](https://github.com/apache/shenyu/tree/master/shenyu-examples/shenyu-examples-sofa), replace the register address in `spring-dubbo.xml` with your local zk address, such as: + +```yaml +com: + alipay: + sofa: + rpc: + registry-address: zookeeper://127.0.0.1:2181 +``` + +Execute the `org.apache.shenyu.examples.sofa.service.TestSofaApplication` main method to start sofa service. + +The following log appears when the startup is successful: + +```shell +2021-02-10 02:31:45.599 INFO 2156 --- [pool-1-thread-1] o.d.s.client.common.utils.RegisterUtils : sofa client register success: {"appName":"sofa","contextPath":"/sofa","path":"/sofa/insert","pathDesc":"Insert a row of data","rpcType":"sofa","serviceName":"org.dromara.shenyu.examples.sofa.api.service.SofaSingleParamService","methodName":"insert","ruleName":"/sofa/insert","parameterTypes":"org.dromara.shenyu.examples.sofa.api.entity.SofaSimpleTypeBean","rpcExt":"{\"loadbalance\":\"hash\",\"retries\":3,\"timeout\":-1}","enabled":true} +2021-02-10 02:31:45.605 INFO 2156 --- [pool-1-thread-1] o.d.s.client.common.utils.RegisterUtils : sofa client register success: {"appName":"sofa","contextPath":"/sofa","path":"/sofa/findById","pathDesc":"Find by Id","rpcType":"sofa","serviceName":"org.dromara.shenyu.examples.sofa.api.service.SofaSingleParamService","methodName":"findById","ruleName":"/sofa/findById","parameterTypes":"java.lang.String","rpcExt":"{\"loadbalance\":\"hash\",\"retries\":3,\"timeout\":-1}","enabled":true} +2021-02-10 02:31:45.611 INFO 2156 --- [pool-1-thread-1] o.d.s.client.common.utils.RegisterUtils : sofa client register success: {"appName":"sofa","contextPath":"/sofa","path":"/sofa/findAll","pathDesc":"Get all data","rpcType":"sofa","serviceName":"org.dromara.shenyu.examples.sofa.api.service.SofaSingleParamService","methodName":"findAll","ruleName":"/sofa/findAll","parameterTypes":"","rpcExt":"{\"loadbalance\":\"hash\",\"retries\":3,\"timeout\":-1}","enabled":true} +2021-02-10 02:31:45.616 INFO 2156 --- [pool-1-thread-1] o.d.s.client.common.utils.RegisterUtils : sofa client register success: {"appName":"sofa","contextPath":"/sofa","path":"/sofa/batchSaveNameAndId","pathDesc":"","rpcType":"sofa","serviceName":"org.dromara.shenyu.examples.sofa.api.service.SofaMultiParamService","methodName":"batchSaveNameAndId","ruleName":"/sofa/batchSaveNameAndId","parameterTypes":"java.util.List,java.lang.String,java.lang.String#org.dromara.shenyu.examples.sofa.api.entity.SofaSimpleTypeBean","rpcExt":"{\"loadbalance\":\"hash\",\"retries\":3,\"timeout\":-1}","enabled":true} +2021-02-10 02:31:45.621 INFO 2156 --- [pool-1-thread-1] o.d.s.client.common.utils.RegisterUtils : sofa client register success: {"appName":"sofa","contextPath":"/sofa","path":"/sofa/saveComplexBeanAndName","pathDesc":"","rpcType":"sofa","serviceName":"org.dromara.shenyu.examples.sofa.api.service.SofaMultiParamService","methodName":"saveComplexBeanAndName","ruleName":"/sofa/saveComplexBeanAndName","parameterTypes":"org.dromara.shenyu.examples.sofa.api.entity.SofaComplexTypeBean,java.lang.String","rpcExt":"{\"loadbalance\":\"hash\",\"retries\":3,\"timeout\":-1}","enabled":true} +2021-02-10 02:31:45.627 INFO 2156 --- [pool-1-thread-1] o.d.s.client.common.utils.RegisterUtils : sofa client register success: {"appName":"sofa","contextPath":"/sofa","path":"/sofa/findByArrayIdsAndName","pathDesc":"","rpcType":"sofa","serviceName":"org.dromara.shenyu.examples.sofa.api.service.SofaMultiParamService","methodName":"findByArrayIdsAndName","ruleName":"/sofa/findByArrayIdsAndName","parameterTypes":"[Ljava.lang.Integer;,java.lang.String","rpcExt":"{\"loadbalance\":\"hash\",\"retries\":3,\"timeout\":-1}","enabled":true} +2021-02-10 02:31:45.632 INFO 2156 --- [pool-1-thread-1] o.d.s.client.common.utils.RegisterUtils : sofa client register success: {"appName":"sofa","contextPath":"/sofa","path":"/sofa/findByStringArray","pathDesc":"","rpcType":"sofa","serviceName":"org.dromara.shenyu.examples.sofa.api.service.SofaMultiParamService","methodName":"findByStringArray","ruleName":"/sofa/findByStringArray","parameterTypes":"[Ljava.lang.String;","rpcExt":"{\"loadbalance\":\"hash\",\"retries\":3,\"timeout\":-1}","enabled":true} +2021-02-10 02:31:45.637 INFO 2156 --- [pool-1-thread-1] o.d.s.client.common.utils.RegisterUtils : sofa client register success: {"appName":"sofa","contextPath":"/sofa","path":"/sofa/saveTwoList","pathDesc":"","rpcType":"sofa","serviceName":"org.dromara.shenyu.examples.sofa.api.service.SofaMultiParamService","methodName":"saveTwoList","ruleName":"/sofa/saveTwoList","parameterTypes":"java.util.List,java.util.Map#org.dromara.shenyu.examples.sofa.api.entity.SofaComplexTypeBean","rpcExt":"{\"loadbalance\":\"hash\",\"retries\":3,\"timeout\":-1}","enabled":true} +2021-02-10 02:31:45.642 INFO 2156 --- [pool-1-thread-1] o.d.s.client.common.utils.RegisterUtils : sofa client register success: {"appName":"sofa","contextPath":"/sofa","path":"/sofa/batchSave","pathDesc":"","rpcType":"sofa","serviceName":"org.dromara.shenyu.examples.sofa.api.service.SofaMultiParamService","methodName":"batchSave","ruleName":"/sofa/batchSave","parameterTypes":"java.util.List#org.dromara.shenyu.examples.sofa.api.entity.SofaSimpleTypeBean","rpcExt":"{\"loadbalance\":\"hash\",\"retries\":3,\"timeout\":-1}","enabled":true} +2021-02-10 02:31:45.647 INFO 2156 --- [pool-1-thread-1] o.d.s.client.common.utils.RegisterUtils : sofa client register success: {"appName":"sofa","contextPath":"/sofa","path":"/sofa/findByListId","pathDesc":"","rpcType":"sofa","serviceName":"org.dromara.shenyu.examples.sofa.api.service.SofaMultiParamService","methodName":"findByListId","ruleName":"/sofa/findByListId","parameterTypes":"java.util.List","rpcExt":"{\"loadbalance\":\"hash\",\"retries\":3,\"timeout\":-1}","enabled":true} +2021-02-10 02:31:45.653 INFO 2156 --- [pool-1-thread-1] o.d.s.client.common.utils.RegisterUtils : sofa client register success: {"appName":"sofa","contextPath":"/sofa","path":"/sofa/saveComplexBean","pathDesc":"","rpcType":"sofa","serviceName":"org.dromara.shenyu.examples.sofa.api.service.SofaMultiParamService","methodName":"saveComplexBean","ruleName":"/sofa/saveComplexBean","parameterTypes":"org.dromara.shenyu.examples.sofa.api.entity.SofaComplexTypeBean","rpcExt":"{\"loadbalance\":\"hash\",\"retries\":3,\"timeout\":-1}","enabled":true} +2021-02-10 02:31:45.660 INFO 2156 --- [pool-1-thread-1] o.d.s.client.common.utils.RegisterUtils : sofa client register success: {"appName":"sofa","contextPath":"/sofa","path":"/sofa/findByIdsAndName","pathDesc":"","rpcType":"sofa","serviceName":"org.dromara.shenyu.examples.sofa.api.service.SofaMultiParamService","methodName":"findByIdsAndName","ruleName":"/sofa/findByIdsAndName","parameterTypes":"java.util.List,java.lang.String","rpcExt":"{\"loadbalance\":\"hash\",\"retries\":3,\"timeout\":-1}","enabled":true} +2021-02-10 02:31:46.055 INFO 2156 --- [ main] o.a.c.f.imps.CuratorFrameworkImpl : Starting +2021-02-10 02:31:46.059 INFO 2156 --- [ main] org.apache.zookeeper.ZooKeeper : Client environment:zookeeper.version=3.4.6-1569965, built on 02/20/2014 09:09 GMT +2021-02-10 02:31:46.059 INFO 2156 --- [ main] org.apache.zookeeper.ZooKeeper : Client environment:host.name=host.docker.internal +2021-02-10 02:31:46.059 INFO 2156 --- [ main] org.apache.zookeeper.ZooKeeper : Client environment:java.version=1.8.0_211 +2021-02-10 02:31:46.059 INFO 2156 --- [ main] org.apache.zookeeper.ZooKeeper : Client environment:java.vendor=Oracle Corporation +2021-02-10 02:31:46.059 INFO 2156 --- [ main] org.apache.zookeeper.ZooKeeper : Client environment:java.home=C:\Program Files\Java\jdk1.8.0_211\jre +2021-02-10 02:31:46.059 INFO 2156 --- [ main] org.apache.zookeeper.ZooKeeper : Client environment:java.class.path=C:\Program Files\Java\jdk1.8.0_211\jre\lib\charsets.jar;C:\Program Files\Java\jdk1.8.0_211\jre\lib\deploy.jar;C:\Program Files\Java\jdk1.8.0_211\jre\lib\ext\access-bridge-64.jar;C:\Program Files\Java\jdk1.8.0_211\jre\lib\ext\cldrdata.jar;C:\Program Files\Java\jdk1.8.0_211\jre\lib\ext\dnsns.jar;C:\Program Files\Java\jdk1.8.0_211\jre\lib\ext\jaccess.jar;C:\Program Files\Java\jdk1.8.0_211\jre\lib\ext\jfxrt.jar;C:\Program Files\Java\jdk1.8.0_211\jre\lib\ext\localedata.jar;C:\Program Files\Java\jdk1.8.0_211\jre\lib\ext\nashorn.jar;C:\Program Files\Java\jdk1.8.0_211\jre\lib\ext\sunec.jar;C:\Program Files\Java\jdk1.8.0_211\jre\lib\ext\sunjce_provider.jar;C:\Program Files\Java\jdk1.8.0_211\jre\lib\ext\sunmscapi.jar;C:\Program Files\Java\jdk1.8.0_211\jre\lib\ext\sunpkcs11.jar;C:\Program Files\Java\jdk1.8.0_211\jre\lib\ext\zipfs.jar;C:\Program Files\Java\jdk1.8.0_211\jre\lib\javaws.jar;C:\Program Files\Java\jdk1.8.0_211\jre\lib\jce.jar;C:\Program Files\Java\jdk1.8.0_211\jre\lib\jfr.jar;C:\Program Files\Java\jdk1.8.0_211\jre\lib\jfxswt.jar;C:\Program Files\Java\jdk1.8.0_211\jre\lib\jsse.jar;C:\Program Files\Java\jdk1.8.0_211\jre\lib\management-agent.jar;C:\Program Files\Java\jdk1.8.0_211\jre\lib\plugin.jar;C:\Program Files\Java\jdk1.8.0_211\jre\lib\resources.jar;C:\Program Files\Java\jdk1.8.0_211\jre\lib\rt.jar;D:\X\dlm_github\shenyu\shenyu-examples\shenyu-examples-sofa\shenyu-examples-sofa-service\target\classes;D:\SOFT\m2\repository\com\alipay\sofa\rpc-sofa-boot-starter\6.0.4\rpc-sofa-boot-starter-6.0.4.jar;D:\SOFT\m2\repository\com\alipay\sofa\rpc-sofa-boot-core\6.0.4\rpc-sofa-boot-core-6.0.4.jar;D:\SOFT\m2\repository\com\alipay\sofa\sofa-rpc-all\5.5.7\sofa-rpc-all-5.5.7.jar;D:\SOFT\m2\repository\com\alipay\sofa\bolt\1.4.6\bolt-1.4.6.jar;D:\SOFT\m2\repository\org\javassist\javassist\3.20.0-GA\javassist-3.20.0-GA.jar;D:\SOFT\m2\repository\io\netty\netty-all\4.1.43.Final\netty-all-4.1.43.Final.jar;D:\SOFT\m2\repository\com\alipay\sofa\hessian\3.3.6\hessian-3.3.6.jar;D:\SOFT\m2\repository\com\alipay\sofa\tracer-core\2.1.2\tracer-core-2.1.2.jar;D:\SOFT\m2\repository\io\opentracing\opentracing-api\0.22.0\opentracing-api-0.22.0.jar;D:\SOFT\m2\repository\io\opentracing\opentracing-noop\0.22.0\opentracing-noop-0.22.0.jar;D:\SOFT\m2\repository\io\opentracing\opentracing-mock\0.22.0\opentracing-mock-0.22.0.jar;D:\SOFT\m2\repository\io\opentracing\opentracing-util\0.22.0\opentracing-util-0.22.0.jar;D:\SOFT\m2\repository\com\alipay\sofa\lookout\lookout-api\1.4.1\lookout-api-1.4.1.jar;D:\SOFT\m2\repository\com\alipay\sofa\runtime-sofa-boot-starter\3.1.4\runtime-sofa-boot-starter-3.1.4.jar;D:\SOFT\m2\repository\org\apache\curator\curator-client\2.9.1\curator-client-2.9.1.jar;D:\SOFT\m2\repository\org\apache\zookeeper\zookeeper\3.4.6\zookeeper-3.4.6.jar;D:\SOFT\m2\repository\log4j\log4j\1.2.16\log4j-1.2.16.jar;D:\SOFT\m2\repository\jline\jline\0.9.94\jline-0.9.94.jar;D:\SOFT\m2\repository\io\netty\netty\3.7.0.Final\netty-3.7.0.Final.jar;D:\SOFT\m2\repository\com\google\guava\guava\16.0.1\guava-16.0.1.jar;D:\SOFT\m2\repository\org\apache\curator\curator-framework\2.9.1\curator-framework-2.9.1.jar;D:\SOFT\m2\repository\org\apache\curator\curator-recipes\2.9.1\curator-recipes-2.9.1.jar;D:\SOFT\m2\repository\org\jboss\resteasy\resteasy-jaxrs\3.0.12.Final\resteasy-jaxrs-3.0.12.Final.jar;D:\SOFT\m2\repository\org\jboss\spec\javax\annotation\jboss-annotations-api_1.1_spec\1.0.1.Final\jboss-annotations-api_1.1_spec-1.0.1.Final.jar;D:\SOFT\m2\repository\javax\activation\activation\1.1.1\activation-1.1.1.jar;D:\SOFT\m2\repository\org\apache\httpcomponents\httpclient\4.5.10\httpclient-4.5.10.jar;D:\SOFT\m2\repository\org\apache\httpcomponents\httpcore\4.4.12\httpcore-4.4.12.jar;D:\SOFT\m2\repository\commons-io\commons-io\2.1\commons-io-2.1.jar;D:\SOFT\m2\repository\net\jcip\jcip-annotations\1.0\jcip-annotations-1.0.jar;D:\SOFT\m2\repository\org\jboss\resteasy\resteasy-client\3.0.12.Final\resteasy-client-3.0.12.Final.jar;D:\SOFT\m2\repository\org\jboss\resteasy\resteasy-jackson-provider\3.0.12.Final\resteasy-jackson-provider-3.0.12.Final.jar;D:\SOFT\m2\repository\org\codehaus\jackson\jackson-core-asl\1.9.12\jackson-core-asl-1.9.12.jar;D:\SOFT\m2\repository\org\codehaus\jackson\jackson-mapper-asl\1.9.12\jackson-mapper-asl-1.9.12.jar;D:\SOFT\m2\repository\org\codehaus\jackson\jackson-jaxrs\1.9.12\jackson-jaxrs-1.9.12.jar;D:\SOFT\m2\repository\org\codehaus\jackson\jackson-xc\1.9.12\jackson-xc-1.9.12.jar;D:\SOFT\m2\repository\org\jboss\resteasy\resteasy-netty4\3.0.12.Final\resteasy-netty4-3.0.12.Final.jar;D:\SOFT\m2\repository\org\jboss\resteasy\resteasy-validator-provider-11\3.0.12.Final\resteasy-validator-provider-11-3.0.12.Final.jar;D:\SOFT\m2\repository\com\fasterxml\classmate\1.5.1\classmate-1.5.1.jar;D:\SOFT\m2\repository\org\jboss\resteasy\jaxrs-api\3.0.12.Final\jaxrs-api-3.0.12.Final.jar;D:\SOFT\m2\repository\org\jboss\resteasy\resteasy-multipart-provider\3.0.12.Final\resteasy-multipart-provider-3.0.12.Final.jar;D:\SOFT\m2\repository\org\jboss\resteasy\resteasy-jaxb-provider\3.0.12.Final\resteasy-jaxb-provider-3.0.12.Final.jar;D:\SOFT\m2\repository\com\sun\xml\bind\jaxb-impl\2.2.7\jaxb-impl-2.2.7.jar;D:\SOFT\m2\repository\com\sun\xml\bind\jaxb-core\2.2.7\jaxb-core-2.2.7.jar;D:\SOFT\m2\repository\javax\xml\bind\jaxb-api\2.3.1\jaxb-api-2.3.1.jar;D:\SOFT\m2\repository\javax\activation\javax.activation-api\1.2.0\javax.activation-api-1.2.0.jar;D:\SOFT\m2\repository\com\sun\istack\istack-commons-runtime\2.16\istack-commons-runtime-2.16.jar;D:\SOFT\m2\repository\com\sun\xml\fastinfoset\FastInfoset\1.2.12\FastInfoset-1.2.12.jar;D:\SOFT\m2\repository\javax\xml\bind\jsr173_api\1.0\jsr173_api-1.0.jar;D:\SOFT\m2\repository\javax\mail\mail\1.5.0-b01\mail-1.5.0-b01.jar;D:\SOFT\m2\repository\org\apache\james\apache-mime4j\0.6\apache-mime4j-0.6.jar;D:\SOFT\m2\repository\commons-logging\commons-logging\1.1.1\commons-logging-1.1.1.jar;D:\SOFT\m2\repository\com\alibaba\dubbo\2.4.10\dubbo-2.4.10.jar;D:\SOFT\m2\repository\org\jboss\netty\netty\3.2.5.Final\netty-3.2.5.Final.jar;D:\SOFT\m2\repository\com\101tec\zkclient\0.10\zkclient-0.10.jar;D:\SOFT\m2\repository\com\alibaba\nacos\nacos-api\1.0.0\nacos-api-1.0.0.jar;D:\SOFT\m2\repository\com\alibaba\fastjson\1.2.47\fastjson-1.2.47.jar;D:\SOFT\m2\repository\org\apache\commons\commons-lang3\3.9\commons-lang3-3.9.jar;D:\SOFT\m2\repository\com\alibaba\nacos\nacos-client\1.0.0\nacos-client-1.0.0.jar;D:\SOFT\m2\repository\com\alibaba\nacos\nacos-common\1.0.0\nacos-common-1.0.0.jar;D:\SOFT\m2\repository\commons-codec\commons-codec\1.13\commons-codec-1.13.jar;D:\SOFT\m2\repository\com\fasterxml\jackson\core\jackson-core\2.10.1\jackson-core-2.10.1.jar;D:\SOFT\m2\repository\com\fasterxml\jackson\core\jackson-databind\2.10.1\jackson-databind-2.10.1.jar;D:\SOFT\m2\repository\com\fasterxml\jackson\core\jackson-annotations\2.10.1\jackson-annotations-2.10.1.jar;D:\SOFT\m2\repository\io\prometheus\simpleclient\0.5.0\simpleclient-0.5.0.jar;D:\SOFT\m2\repository\org\springframework\spring-beans\5.2.2.RELEASE\spring-beans-5.2.2.RELEASE.jar;D:\SOFT\m2\repository\org\springframework\spring-core\5.2.2.RELEASE\spring-core-5.2.2.RELEASE.jar;D:\SOFT\m2\repository\org\springframework\spring-jcl\5.2.2.RELEASE\spring-jcl-5.2.2.RELEASE.jar;D:\SOFT\m2\repository\com\alipay\sofa\infra-sofa-boot-starter\3.1.4\infra-sofa-boot-starter-3.1.4.jar;D:\SOFT\m2\repository\com\alipay\sofa\common\log-sofa-boot-starter\1.0.18\log-sofa-boot-starter-1.0.18.jar;D:\SOFT\m2\repository\org\springframework\spring-context\5.2.2.RELEASE\spring-context-5.2.2.RELEASE.jar;D:\SOFT\m2\repository\org\springframework\spring-aop\5.2.2.RELEASE\spring-aop-5.2.2.RELEASE.jar;D:\SOFT\m2\repository\org\springframework\spring-expression\5.2.2.RELEASE\spring-expression-5.2.2.RELEASE.jar;D:\SOFT\m2\repository\com\alipay\sofa\common\sofa-common-tools\1.0.18\sofa-common-tools-1.0.18.jar;D:\SOFT\m2\repository\org\springframework\boot\spring-boot-starter-validation\2.2.2.RELEASE\spring-boot-starter-validation-2.2.2.RELEASE.jar;D:\SOFT\m2\repository\jakarta\validation\jakarta.validation-api\2.0.1\jakarta.validation-api-2.0.1.jar;D:\SOFT\m2\repository\org\hibernate\validator\hibernate-validator\6.0.18.Final\hibernate-validator-6.0.18.Final.jar;D:\SOFT\m2\repository\org\jboss\logging\jboss-logging\3.4.1.Final\jboss-logging-3.4.1.Final.jar;D:\SOFT\m2\repository\org\apache\tomcat\embed\tomcat-embed-el\9.0.29\tomcat-embed-el-9.0.29.jar;D:\SOFT\m2\repository\org\springframework\boot\spring-boot-autoconfigure\2.2.2.RELEASE\spring-boot-autoconfigure-2.2.2.RELEASE.jar;D:\SOFT\m2\repository\org\springframework\boot\spring-boot\2.2.2.RELEASE\spring-boot-2.2.2.RELEASE.jar;D:\X\dlm_github\shenyu\shenyu-examples\shenyu-examples-sofa\shenyu-examples-sofa-api\target\classes;D:\SOFT\m2\repository\org\projectlombok\lombok\1.18.10\lombok-1.18.10.jar;D:\X\dlm_github\shenyu\shenyu-spring-boot-starter\shenyu-spring-boot-starter-client\shenyu-spring-boot-starter-client-sofa\target\classes;D:\SOFT\m2\repository\org\springframework\boot\spring-boot-starter\2.2.2.RELEASE\spring-boot-starter-2.2.2.RELEASE.jar;D:\SOFT\m2\repository\org\springframework\boot\spring-boot-starter-logging\2.2.2.RELEASE\spring-boot-starter-logging-2.2.2.RELEASE.jar;D:\SOFT\m2\repository\ch\qos\logback\logback-classic\1.2.3\logback-classic-1.2.3.jar;D:\SOFT\m2\repository\ch\qos\logback\logback-core\1.2.3\logback-core-1.2.3.jar;D:\SOFT\m2\repository\org\apache\logging\log4j\log4j-to-slf4j\2.12.1\log4j-to-slf4j-2.12.1.jar;D:\SOFT\m2\repository\org\apache\logging\log4j\log4j-api\2.12.1\log4j-api-2.12.1.jar;D:\SOFT\m2\repository\org\slf4j\jul-to-slf4j\1.7.29\jul-to-slf4j-1.7.29.jar;D:\SOFT\m2\repository\jakarta\annotation\jakarta.annotation-api\1.3.5\jakarta.annotation-api-1.3.5.jar;D:\SOFT\m2\repository\org\yaml\snakeyaml\1.25\snakeyaml-1.25.jar;D:\X\dlm_github\shenyu\shenyu-client\shenyu-client-sofa\target\classes;D:\X\dlm_github\shenyu\shenyu-client\shenyu-client-common\target\classes;D:\X\dlm_github\shenyu\shenyu-common\target\classes;D:\SOFT\m2\repository\org\springframework\boot\spring-boot-starter-json\2.2.2.RELEASE\spring-boot-starter-json-2.2.2.RELEASE.jar;D:\SOFT\m2\repository\org\springframework\spring-web\5.2.2.RELEASE\spring-web-5.2.2.RELEASE.jar;D:\SOFT\m2\repository\com\fasterxml\jackson\datatype\jackson-datatype-jdk8\2.10.1\jackson-datatype-jdk8-2.10.1.jar;D:\SOFT\m2\repository\com\fasterxml\jackson\datatype\jackson-datatype-jsr310\2.10.1\jackson-datatype-jsr310-2.10.1.jar;D:\SOFT\m2\repository\com\fasterxml\jackson\module\jackson-module-parameter-names\2.10.1\jackson-module-parameter-names-2.10.1.jar;D:\SOFT\m2\repository\com\squareup\okhttp3\okhttp\3.14.4\okhttp-3.14.4.jar;D:\SOFT\m2\repository\com\squareup\okio\okio\1.17.2\okio-1.17.2.jar;D:\SOFT\m2\repository\com\google\code\gson\gson\2.8.6\gson-2.8.6.jar;D:\SOFT\m2\repository\org\slf4j\slf4j-api\1.7.29\slf4j-api-1.7.29.jar;D:\SOFT\m2\repository\org\slf4j\jcl-over-slf4j\1.7.29\jcl-over-slf4j-1.7.29.jar;C:\Program Files\JetBrains\IntelliJ IDEA 2019.3.3\lib\idea_rt.jar +2021-02-10 02:31:46.060 INFO 2156 --- [ main] org.apache.zookeeper.ZooKeeper : Client environment:java.library.path=C:\Program Files\Java\jdk1.8.0_211\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;C:\Program Files\Common Files\Oracle\Java\javapath;C:\ProgramData\Oracle\Java\javapath;C:\Program Files (x86)\Common Files\Oracle\Java\javapath;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Windows\System32\OpenSSH\;C:\Program Files\Java\jdk1.8.0_211\bin;C:\Program Files\Java\jdk1.8.0_211\jre\bin;D:\SOFT\apache-maven-3.5.0\bin;C:\Program Files\Go\bin;C:\Program Files\nodejs\;C:\Program Files\Python\Python38\;C:\Program Files\OpenSSL-Win64\bin;C:\Program Files\Git\bin;D:\SOFT\protobuf-2.5.0\src;D:\SOFT\zlib-1.2.8;c:\Program Files (x86)\Microsoft SQL Server\100\Tools\Binn\;c:\Program Files\Microsoft SQL Server\100\Tools\Binn\;c:\Program Files\Microsoft SQL Server\100\DTS\Binn\;C:\Program Files\Docker\Docker\resources\bin;C:\ProgramData\DockerDesktop\version-bin;D:\SOFT\gradle-6.0-all\gradle-6.0\bin;C:\Program Files\mingw-w64\x86_64-8.1.0-posix-seh-rt_v6-rev0\mingw64\bin;D:\SOFT\hugo_extended_0.55.5_Windows-64bit;C:\Users\DLM\AppData\Local\Microsoft\WindowsApps;C:\Users\DLM\go\bin;C:\Users\DLM\AppData\Roaming\npm;;C:\Program Files\Microsoft VS Code\bin;C:\Program Files\nimbella-cli\bin;. +2021-02-10 02:31:46.060 INFO 2156 --- [ main] org.apache.zookeeper.ZooKeeper : Client environment:java.io.tmpdir=C:\Users\DLM\AppData\Local\Temp\ +2021-02-10 02:31:46.060 INFO 2156 --- [ main] org.apache.zookeeper.ZooKeeper : Client environment:java.compiler= +2021-02-10 02:31:46.060 INFO 2156 --- [ main] org.apache.zookeeper.ZooKeeper : Client environment:os.name=Windows 10 +2021-02-10 02:31:46.060 INFO 2156 --- [ main] org.apache.zookeeper.ZooKeeper : Client environment:os.arch=amd64 +2021-02-10 02:31:46.060 INFO 2156 --- [ main] org.apache.zookeeper.ZooKeeper : Client environment:os.version=10.0 +2021-02-10 02:31:46.060 INFO 2156 --- [ main] org.apache.zookeeper.ZooKeeper : Client environment:user.name=DLM +2021-02-10 02:31:46.060 INFO 2156 --- [ main] org.apache.zookeeper.ZooKeeper : Client environment:user.home=C:\Users\DLM +2021-02-10 02:31:46.060 INFO 2156 --- [ main] org.apache.zookeeper.ZooKeeper : Client environment:user.dir=D:\X\dlm_github\shenyu +2021-02-10 02:31:46.061 INFO 2156 --- [ main] org.apache.zookeeper.ZooKeeper : Initiating client connection, connectString=127.0.0.1:21810 sessionTimeout=60000 watcher=org.apache.curator.ConnectionState@3e850122 +2021-02-10 02:31:46.069 INFO 2156 --- [27.0.0.1:21810)] org.apache.zookeeper.ClientCnxn : Opening socket connection to server 127.0.0.1/127.0.0.1:21810. Will not attempt to authenticate using SASL (unknown error) +2021-02-10 02:31:46.071 INFO 2156 --- [27.0.0.1:21810)] org.apache.zookeeper.ClientCnxn : Socket connection established to 127.0.0.1/127.0.0.1:21810, initiating session +2021-02-10 02:31:46.078 INFO 2156 --- [27.0.0.1:21810)] org.apache.zookeeper.ClientCnxn : Session establishment complete on server 127.0.0.1/127.0.0.1:21810, sessionid = 0x10005b0d05e0001, negotiated timeout = 40000 +2021-02-10 02:31:46.081 INFO 2156 --- [ain-EventThread] o.a.c.f.state.ConnectionStateManager : State change: CONNECTED +2021-02-10 02:31:46.093 WARN 2156 --- [ main] org.apache.curator.utils.ZKPaths : The version of ZooKeeper being used doesn't support Container nodes. CreateMode.PERSISTENT will be used instead. +2021-02-10 02:31:46.141 INFO 2156 --- [ main] o.d.s.e.s.service.TestSofaApplication : Started TestSofaApplication in 3.41 seconds (JVM running for 4.423) +``` + + +## Test + +The `shenyu-examples-sofa` project will automatically register interface methods annotated with `@ShenyuSofaClient` in the Apache ShenYu gateway after successful startup. + +Open PluginList -> rpc proxy -> sofa to see the list of plugin rule configurations: + +![](/img/shenyu/quick-start/sofa/rule-list.png) + +Use PostMan to simulate HTTP to request your Sofa service: + +![](/img/shenyu/quick-start/sofa/postman-findbyid.png) + +Complex multi-parameter example: The related interface implementation class is `org.apache.shenyu.examples.sofa.service.impl.SofaMultiParamServiceImpl#batchSaveNameAndId` + +```java +@Override +@ShenyuSofaClient(path = "/batchSaveNameAndId") +public SofaSimpleTypeBean batchSaveNameAndId(final List sofaTestList, final String id, final String name) { + SofaSimpleTypeBean simpleTypeBean = new SofaSimpleTypeBean(); + simpleTypeBean.setId(id); + simpleTypeBean.setName("hello world shenyu sofa param batchSaveAndNameAndId :" + name + ":" + sofaTestList.stream().map(SofaSimpleTypeBean::getName).collect(Collectors.joining("-"))); + return simpleTypeBean; +} +``` + +![](/img/shenyu/quick-start/sofa/postman-multiparams.png) diff --git a/versioned_docs/version-2.6.1/quick-start/quick-start-springcloud.md b/versioned_docs/version-2.6.1/quick-start/quick-start-springcloud.md new file mode 100644 index 00000000000..710c8045359 --- /dev/null +++ b/versioned_docs/version-2.6.1/quick-start/quick-start-springcloud.md @@ -0,0 +1,166 @@ +--- +title: Quick start with Spring Cloud +description: Quick start with SpringCloud +--- + +This document introduces how to quickly access the Apache ShenYu gateway using Spring Cloud. You can get the code example of this document by clicking [here](https://github.com/apache/shenyu/tree/master/shenyu-examples/shenyu-examples-springcloud) . + +## Environment to prepare + + +Please refer to the deployment to select a way to start shenyu-admin. For example, start the Apache ShenYu gateway management system through [local deployment](../deployment/deployment-local) . + +After successful startup, you need to open the springCloud plugin on in the BasicConfig `->` Plugin. + + + +If you are a startup gateway by means of source, can be directly run the ShenyuBootstrapApplication of shenyu-bootstrap module. + +> Note: Before starting, make sure the gateway has added dependencies. + +Add the gateway proxy plugin for `Spring Cloud` and add your registry center dependencies: + +```xml + + + org.apache.shenyu + shenyu-spring-boot-starter-plugin-springcloud + ${project.version} + + + + org.springframework.cloud + spring-cloud-commons + 2.2.0.RELEASE + + + + org.apache.shenyu + shenyu-spring-boot-starter-plugin-httpclient + ${project.version} + + + + org.springframework.cloud + spring-cloud-starter-netflix-eureka-client + 2.2.0.RELEASE + + +``` + + +`eureka` config information: + +```yml +eureka: + client: + serviceUrl: + defaultZone: http://localhost:8761/eureka/ + instance: + prefer-ip-address: true +``` + +Note: Please ensure that the spring Cloud registry service discovery configuration is enabled + +* Configuration method + +```yml +spring: + cloud: + discovery: + enabled: true +``` + +* code method + +```java +@SpringBootApplication +@EnableDiscoveryClient +public class ShenyuBootstrapApplication { + + /** + * Main Entrance. + * + * @param args startup arguments + */ + public static void main(final String[] args) { + SpringApplication.run(ShenyuBootstrapApplication.class, args); + } +} +``` + +Restart the `shenyu-bootstrap` project. + +## Run the shenyu-examples-springcloud project + +In the example project we used `Eureka` as the registry for `Spring Cloud`. You can use the local `Eureka` or the application provided in the example. + + +Download [shenyu-examples-eureka](https://github.com/apache/shenyu/tree/master/shenyu-examples/shenyu-examples-eureka) 、[shenyu-examples-springcloud](https://github.com/apache/shenyu/tree/master/shenyu-examples/shenyu-examples-springcloud) . + + +Startup the Eureka service: +Execute the `org.apache.shenyu.examples.eureka.EurekaServerApplication` main method to start project. + +Startup the Spring Cloud service: +Execute the `org.apache.shenyu.examples.springcloud.ShenyuTestSpringCloudApplication` main method to start project. + +Since `2.4.3`, `shenyu.client.springCloud.props.port` can be non-configured if you like. + +The following log appears when the startup is successful: + +```shell +2021-02-10 14:03:51.301 INFO 2860 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor' +2021-02-10 14:03:51.669 INFO 2860 --- [pool-1-thread-1] o.d.s.client.common.utils.RegisterUtils : springCloud client register success: {"appName":"springCloud-test","context":"/springcloud","path":"/springcloud/order/save","pathDesc":"","rpcType":"springCloud","ruleName":"/springcloud/order/save","enabled":true} +2021-02-10 14:03:51.676 INFO 2860 --- [pool-1-thread-1] o.d.s.client.common.utils.RegisterUtils : springCloud client register success: {"appName":"springCloud-test","context":"/springcloud","path":"/springcloud/order/path/**","pathDesc":"","rpcType":"springCloud","ruleName":"/springcloud/order/path/**","enabled":true} +2021-02-10 14:03:51.682 INFO 2860 --- [pool-1-thread-1] o.d.s.client.common.utils.RegisterUtils : springCloud client register success: {"appName":"springCloud-test","context":"/springcloud","path":"/springcloud/order/findById","pathDesc":"","rpcType":"springCloud","ruleName":"/springcloud/order/findById","enabled":true} +2021-02-10 14:03:51.688 INFO 2860 --- [pool-1-thread-1] o.d.s.client.common.utils.RegisterUtils : springCloud client register success: {"appName":"springCloud-test","context":"/springcloud","path":"/springcloud/order/path/**/name","pathDesc":"","rpcType":"springCloud","ruleName":"/springcloud/order/path/**/name","enabled":true} +2021-02-10 14:03:51.692 INFO 2860 --- [pool-1-thread-1] o.d.s.client.common.utils.RegisterUtils : springCloud client register success: {"appName":"springCloud-test","context":"/springcloud","path":"/springcloud/test/**","pathDesc":"","rpcType":"springCloud","ruleName":"/springcloud/test/**","enabled":true} +2021-02-10 14:03:52.806 WARN 2860 --- [ main] ockingLoadBalancerClientRibbonWarnLogger : You already have RibbonLoadBalancerClient on your classpath. It will be used by default. As Spring Cloud Ribbon is in maintenance mode. We recommend switching to BlockingLoadBalancerClient instead. In order to use it, set the value of `spring.cloud.loadbalancer.ribbon.enabled` to `false` or remove spring-cloud-starter-netflix-ribbon from your project. +2021-02-10 14:03:52.848 WARN 2860 --- [ main] iguration$LoadBalancerCaffeineWarnLogger : Spring Cloud LoadBalancer is currently working with default default cache. You can switch to using Caffeine cache, by adding it to the classpath. +2021-02-10 14:03:52.921 INFO 2860 --- [ main] o.s.c.n.eureka.InstanceInfoFactory : Setting initial instance status as: STARTING +2021-02-10 14:03:52.949 INFO 2860 --- [ main] com.netflix.discovery.DiscoveryClient : Initializing Eureka in region us-east-1 +2021-02-10 14:03:53.006 INFO 2860 --- [ main] c.n.d.provider.DiscoveryJerseyProvider : Using JSON encoding codec LegacyJacksonJson +2021-02-10 14:03:53.006 INFO 2860 --- [ main] c.n.d.provider.DiscoveryJerseyProvider : Using JSON decoding codec LegacyJacksonJson +2021-02-10 14:03:53.110 INFO 2860 --- [ main] c.n.d.provider.DiscoveryJerseyProvider : Using XML encoding codec XStreamXml +2021-02-10 14:03:53.110 INFO 2860 --- [ main] c.n.d.provider.DiscoveryJerseyProvider : Using XML decoding codec XStreamXml +2021-02-10 14:03:53.263 INFO 2860 --- [ main] c.n.d.s.r.aws.ConfigClusterResolver : Resolving eureka endpoints via configuration +2021-02-10 14:03:53.546 INFO 2860 --- [ main] com.netflix.discovery.DiscoveryClient : Disable delta property : false +2021-02-10 14:03:53.546 INFO 2860 --- [ main] com.netflix.discovery.DiscoveryClient : Single vip registry refresh property : null +2021-02-10 14:03:53.547 INFO 2860 --- [ main] com.netflix.discovery.DiscoveryClient : Force full registry fetch : false +2021-02-10 14:03:53.547 INFO 2860 --- [ main] com.netflix.discovery.DiscoveryClient : Application is null : false +2021-02-10 14:03:53.547 INFO 2860 --- [ main] com.netflix.discovery.DiscoveryClient : Registered Applications size is zero : true +2021-02-10 14:03:53.547 INFO 2860 --- [ main] com.netflix.discovery.DiscoveryClient : Application version is -1: true +2021-02-10 14:03:53.547 INFO 2860 --- [ main] com.netflix.discovery.DiscoveryClient : Getting all instance registry info from the eureka server +2021-02-10 14:03:53.754 INFO 2860 --- [ main] com.netflix.discovery.DiscoveryClient : The response status is 200 +2021-02-10 14:03:53.756 INFO 2860 --- [ main] com.netflix.discovery.DiscoveryClient : Starting heartbeat executor: renew interval is: 30 +2021-02-10 14:03:53.758 INFO 2860 --- [ main] c.n.discovery.InstanceInfoReplicator : InstanceInfoReplicator onDemand update allowed rate per min is 4 +2021-02-10 14:03:53.761 INFO 2860 --- [ main] com.netflix.discovery.DiscoveryClient : Discovery Client initialized at timestamp 1612937033760 with initial instances count: 0 +2021-02-10 14:03:53.762 INFO 2860 --- [ main] o.s.c.n.e.s.EurekaServiceRegistry : Registering application SPRINGCLOUD-TEST with eureka with status UP +2021-02-10 14:03:53.763 INFO 2860 --- [ main] com.netflix.discovery.DiscoveryClient : Saw local status change event StatusChangeEvent [timestamp=1612937033763, current=UP, previous=STARTING] +2021-02-10 14:03:53.765 INFO 2860 --- [nfoReplicator-0] com.netflix.discovery.DiscoveryClient : DiscoveryClient_SPRINGCLOUD-TEST/host.docker.internal:springCloud-test:8884: registering service... +2021-02-10 14:03:53.805 INFO 2860 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8884 (http) with context path '' +2021-02-10 14:03:53.807 INFO 2860 --- [ main] .s.c.n.e.s.EurekaAutoServiceRegistration : Updating port to 8884 +2021-02-10 14:03:53.837 INFO 2860 --- [nfoReplicator-0] com.netflix.discovery.DiscoveryClient : DiscoveryClient_SPRINGCLOUD-TEST/host.docker.internal:springCloud-test:8884 - registration status: 204 +2021-02-10 14:03:54.231 INFO 2860 --- [ main] o.d.s.e.s.ShenyuTestSpringCloudApplication : Started ShenyuTestSpringCloudApplication in 6.338 seconds (JVM running for 7.361) +``` + +## Test + +The `shenyu-examples-springcloud` project will automatically register interface methods annotated with `@ShenyuSpringCloudClient` in the Apache ShenYu gateway after successful startup. + +Open PluginList -> rpc proxy -> springCloud to see the list of plugin rule configurations: + +![](/img/shenyu/quick-start/springcloud/rule-list.png) + +Use PostMan to simulate HTTP to request your SpringCloud service: + +![](/img/shenyu/quick-start/springcloud/postman-test.png) + +Use IDEA HTTP Client Plugin to simulate HTTP to request your SpringCloud service[local:no Shenyu proxy]: + +![](/img/shenyu/quick-start/springcloud/idea-http-test-local.png) + +Use IDEA HTTP Client Plugin to simulate HTTP to request your SpringCloud service[Shenyu proxy]: + +![](/img/shenyu/quick-start/springcloud/idea-http-test-proxy.png) diff --git a/versioned_docs/version-2.6.1/quick-start/quick-start-tars.md b/versioned_docs/version-2.6.1/quick-start/quick-start-tars.md new file mode 100644 index 00000000000..5302f435ae6 --- /dev/null +++ b/versioned_docs/version-2.6.1/quick-start/quick-start-tars.md @@ -0,0 +1,118 @@ +--- +title: Quick start with Tars +description: Quick start with Tars +--- + +This document introduces how to quickly access the Apache ShenYu Gateway using Tars. You can get the code example of this document by clicking [here](https://github.com/apache/shenyu/tree/master/shenyu-examples/shenyu-examples-tars) . + +## Environment to prepare + + +Please refer to the deployment to select a way to start shenyu-admin. For example, start the Apache ShenYu gateway management system through [local deployment](../deployment/deployment-local) . + +After successful startup, you need to open the Sofa plugin on in the BasicConfig `->` Plugin. + + + +If you are a startup gateway by means of source, can be directly run the ShenyuBootstrapApplication of shenyu-bootstrap module. + +> Note: Before starting, make sure the gateway has added dependencies. + + + +`shenyu-bootstrap` need to import tars dependencies: + +```xml + + org.apache.shenyu + shenyu-spring-boot-starter-plugin-tars + ${project.version} + + + + com.tencent.tars + tars-client + 1.7.2 + +``` + +## Run the shenyu-examples-tars project + +Download [shenyu-examples-tars](https://github.com/apache/shenyu/tree/master/shenyu-examples/shenyu-examples-tars) . + +Modify `host` in `application.yml` to be your local IP + +Modify config `src/main/resources/ShenyuExampleServer.ShenyuExampleApp.config.conf`: + +* It is recommended to make clear the meaning of the main configuration items of config, [refer to the development guide](https://github.com/TarsCloud/TarsJava/blob/master/docs/tars_java_user_guide.md) +* bind IP in config should pay attention to providing cost machine +* local=..., Indicates the open port that the native machine connects to the tarsnode. If there is no tarsnode, this configuration can be dropped +* `locator`: Indicates the address (frame address) of the main control center, which is used to obtain the IP list according to the service name, If Registry is not required to locate the service, this configuration can be dropped +* `node=tars.tarsnode.ServerObj@xxxx`, Indicates the address of the connected tarsnode. If there is no tarsnode locally, this configuration can be removed + +More config configuration instructions, Please refer to [TARS Official Documentation](https://github.com/TarsCloud/TarsJava/blob/master/docs/tars_java_user_guide.md) + +Execute the `org.apache.shenyu.examples.tars.ShenyuTestTarsApplication` main method to start project. + +**Note:** The `configuration file address` needs to be specified in the startup command when the service starts **-Dconfig=xxx/ShenyuExampleServer.ShenyuExampleApp.config.conf** + +If the `-Dconfig` parameter is not added, the configuration may throw the following exceptions: + +```text +com.qq.tars.server.config.ConfigurationException: error occurred on load server config + at com.qq.tars.server.config.ConfigurationManager.loadServerConfig(ConfigurationManager.java:113) + at com.qq.tars.server.config.ConfigurationManager.init(ConfigurationManager.java:57) + at com.qq.tars.server.core.Server.loadServerConfig(Server.java:90) + at com.qq.tars.server.core.Server.(Server.java:42) + at com.qq.tars.server.core.Server.(Server.java:38) + at com.qq.tars.spring.bean.PropertiesListener.onApplicationEvent(PropertiesListener.java:37) + at com.qq.tars.spring.bean.PropertiesListener.onApplicationEvent(PropertiesListener.java:31) + at org.springframework.context.event.SimpleApplicationEventMulticaster.doInvokeListener(SimpleApplicationEventMulticaster.java:172) + at org.springframework.context.event.SimpleApplicationEventMulticaster.invokeListener(SimpleApplicationEventMulticaster.java:165) + at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:139) + at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:127) + at org.springframework.boot.context.event.EventPublishingRunListener.environmentPrepared(EventPublishingRunListener.java:76) + at org.springframework.boot.SpringApplicationRunListeners.environmentPrepared(SpringApplicationRunListeners.java:53) + at org.springframework.boot.SpringApplication.prepareEnvironment(SpringApplication.java:345) + at org.springframework.boot.SpringApplication.run(SpringApplication.java:308) + at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226) + at org.springframework.boot.SpringApplication.run(SpringApplication.java:1215) + at org.apache.shenyu.examples.tars.ShenyuTestTarsApplication.main(ShenyuTestTarsApplication.java:38) +Caused by: java.lang.NullPointerException + at java.io.FileInputStream.(FileInputStream.java:130) + at java.io.FileInputStream.(FileInputStream.java:93) + at com.qq.tars.common.util.Config.parseFile(Config.java:211) + at com.qq.tars.server.config.ConfigurationManager.loadServerConfig(ConfigurationManager.java:63) + ... 17 more +The exception occurred at load server config +``` + +The following log appears when the startup is successful: + +```shell +[SERVER] server starting at tcp -h 127.0.0.1 -p 21715 -t 60000... +[SERVER] server started at tcp -h 127.0.0.1 -p 21715 -t 60000... +[SERVER] server starting at tcp -h 127.0.0.1 -p 21714 -t 3000... +[SERVER] server started at tcp -h 127.0.0.1 -p 21714 -t 3000... +[SERVER] The application started successfully. +The session manager service started... +[SERVER] server is ready... +2021-02-09 13:28:24.643 INFO 16016 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 55290 (http) with context path '' +2021-02-09 13:28:24.645 INFO 16016 --- [ main] o.d.s.e.tars.ShenyuTestTarsApplication : Started ShenyuTestTarsApplication in 4.232 seconds (JVM running for 5.1) +2021-02-09 13:28:24.828 INFO 16016 --- [pool-2-thread-1] o.d.s.client.common.utils.RegisterUtils : tars client register success: {"appName":"127.0.0.1:21715","contextPath":"/tars","path":"/tars/helloInt","pathDesc":"","rpcType":"tars","serviceName":"ShenyuExampleServer.ShenyuExampleApp.HelloObj","methodName":"helloInt","ruleName":"/tars/helloInt","parameterTypes":"int,java.lang.String","rpcExt":"{\"methodInfo\":[{\"methodName\":\"helloInt\",\"params\":[{},{}],\"returnType\":\"java.lang.Integer\"},{\"methodName\":\"hello\",\"params\":[{},{}],\"returnType\":\"java.lang.String\"}]}","enabled":true} +2021-02-09 13:28:24.837 INFO 16016 --- [pool-2-thread-1] o.d.s.client.common.utils.RegisterUtils : tars client register success: {"appName":"127.0.0.1:21715","contextPath":"/tars","path":"/tars/hello","pathDesc":"","rpcType":"tars","serviceName":"ShenyuExampleServer.ShenyuExampleApp.HelloObj","methodName":"hello","ruleName":"/tars/hello","parameterTypes":"int,java.lang.String","rpcExt":"{\"methodInfo\":[{\"methodName\":\"helloInt\",\"params\":[{},{}],\"returnType\":\"java.lang.Integer\"},{\"methodName\":\"hello\",\"params\":[{},{}],\"returnType\":\"java.lang.String\"}]}","enabled":true} +``` + + +## Test + +The `shenyu-examples-tars` project will automatically register interface methods annotated with `@ShenyuTarsClient` in the Apache ShenYu gateway after successful startup. + +Open PluginList -> rpc proxy -> tars to see the list of plugin rule configurations: + +![](/img/shenyu/quick-start/tars/rule-list.png) + +Use PostMan to simulate HTTP to request your tars service: + +![](/img/shenyu/quick-start/tars/postman-test.png) + diff --git a/versioned_docs/version-2.6.1/quick-start/quick-start-websocket.md b/versioned_docs/version-2.6.1/quick-start/quick-start-websocket.md new file mode 100644 index 00000000000..754086e8c99 --- /dev/null +++ b/versioned_docs/version-2.6.1/quick-start/quick-start-websocket.md @@ -0,0 +1,152 @@ +--- +title: Quick start with Websocket +description: Websocket quick start +--- + +This document introduces how to quickly access the Apache ShenYu gateway using Websocket. + + +## Environment to prepare + +> Refer to [local deployment](../deployment/deployment-local) to deploy the Shenyu gateway. + +1. Deploy the `shenyu-admin` service. + +- After successful launch, you need to set the `Websocket` plugin to be enabled in the page's basic configuration `->`Plugin Management. + + + +2. Deploy the `shenyu-bootstrap` service. +- After starting, `shenyu-bootstrap` will synchronize the data via the `websocket` protocol according to the address configured in `shenyu.sync.websocket.url`. + +> Note: Before starting, make sure that the gateway has introduced the relevant dependency, which is introduced by default. + +Import the gateway proxy plugin for `Websocket` and add the following dependencies to the gateway's `pom.xml` file. + + +```xml + + + org.apache.shenyu + shenyu-spring-boot-starter-plugin-websocket + ${project.version} + +``` + + + +## Run the shenyu-examples-websocket project + +1. Download [shenyu-examples-websocket](https://github.com/apache/shenyu/tree/master/shenyu-examples/shenyu-examples-websocket/shenyu-example-spring-annotation-websocket) (`native-websocket` and `reactive-websocket` can refer to the subprojects under [shenyu-examples-websocket](https://github.com/apache/shenyu/tree/master/shenyu-examples/shenyu-examples-websocket)). + +2. Run main method of `org.apache.shenyu.examples.websocket.TestAnnotationWebsocketApplication` to start this project. +- The examples project will synchronize the websocket service information to `shenyu-admin` via the `http` protocol according to the address configured in `shenyu.register.serverLists`, and then to `shenyu-bootstrap` by `shenyu-admin`. + +log info as follows after starting: + +```shell +2022-08-09 23:37:34.994 INFO 61398 --- [or_consumer_-21] o.a.s.r.client.http.utils.RegisterUtils : metadata client register success: {"appName":"ws-annotation","contextPath":"/ws-annotation","path":"/ws-annotation/myWs","rpcType":"websocket","ruleName":"/ws-annotation/myWs","enabled":true,"pluginNames":[],"registerMetaData":false,"timeMillis":1660059454701} +2022-08-09 23:37:35.019 INFO 61398 --- [or_consumer_-18] o.a.s.r.client.http.utils.RegisterUtils : uri client register success: {"protocol":"ws://","appName":"ws-annotation","contextPath":"/ws-annotation","rpcType":"websocket","host":"192.168.1.3","port":8001} +``` + + + +## Test + +1. The `shenyu-examples-websocket` project will automatically register the interface methods annotated with `@ShenyuSpringWebSocketClient` to the gateway and add selectors and rules after successful start, you can see the information of `shenyu-examples-websocket` service registration by visiting `shenyu-admin` page -> PluginList -> Proxy -> Websocket to see the `shenyu-examples-websocket` service registration information, if not, you can refer to [Websocket plugin](../plugin-center/proxy/websocket-plugin.md) to add the configuration manually. + + + +2. The following test code (see attachment) simulates the request method of the `Websocket` protocol to request your `Websocket` service. + + + + + +## Annexes + +**websocket debugging code** + +- Create a file called websocket.html and copy the following code into the file. +- Open websocket.html with Chrome. + +```html + + + + + Shenyu WebSocket Test + + + +
+
+ + +
+
+ + + +``` diff --git a/versioned_docs/version-2.6.1/user-guide/_category_.json b/versioned_docs/version-2.6.1/user-guide/_category_.json new file mode 100644 index 00000000000..2e41e63c016 --- /dev/null +++ b/versioned_docs/version-2.6.1/user-guide/_category_.json @@ -0,0 +1,4 @@ +{ + "label": "User Guide", + "position": 5 +} diff --git a/versioned_docs/version-2.6.1/user-guide/admin-usage/_category_.json b/versioned_docs/version-2.6.1/user-guide/admin-usage/_category_.json new file mode 100644 index 00000000000..f0c5b1288f2 --- /dev/null +++ b/versioned_docs/version-2.6.1/user-guide/admin-usage/_category_.json @@ -0,0 +1,4 @@ +{ + "label": "Admin Usage", + "position": 1 +} diff --git a/versioned_docs/version-2.6.1/user-guide/admin-usage/api-document.md b/versioned_docs/version-2.6.1/user-guide/admin-usage/api-document.md new file mode 100644 index 00000000000..8fc5dee3a97 --- /dev/null +++ b/versioned_docs/version-2.6.1/user-guide/admin-usage/api-document.md @@ -0,0 +1,86 @@ +--- +title: API Document Management +keywords: ["api doc Document"] +description: API document management +--- + +## 1. Design Notes + +When the front and back end are jointly debugged, it is usually necessary for the back end to give documents to detail the input and output of the interface; + +After the backend development is complete, you need to test whether the access gateway is successful. + +In order to reduce the sense of fragmentation and improve the user experience of front-end and back-end development, it is necessary to see the API documentation in shenyu-admin and test the API directly. + +## 2. How to use + +The brief introduce is as follows. +- Back-end development produces API documents in shenyu-admin. +> Three methods of `remotely pulling swagger`, `manual filling`, and `client registration` are already supported. From the perspective of functional integrity and user experience, `remotely pulling swagger` is currently recommended, and the latter two methods will be in Continuous function enhancement in later versions. +- The frontend looks at the API documentation in shenyu-admin and starts development. +> During joint debugging, developers (including front-end and backend) may use the testing function in shenyu-admin to request APIs directly. + +## 3. Set the global environment address + +In actual use, you may have multiple gateway addresses (such as production environment, test environment, or public network environment, intranet environment), you can manage them in `Apache ShenYu` Gateway Management System --> BasicConfig --> Dictionary, Set multiple gateway addresses. + +![apidoc-env-en](/img/shenyu/basicConfig/apiManagement/apidoc-env-en.png) + +> DictionaryType: Fill in the value must be `apidocEnv`; +> +> DictionaryCode: The identifier of the gateway address has no actual meaning. It is recommended to use `ENV_LABEL_` as a prefix, such as `ENV_LABEL_OFFLINE`; +> +> DictionaryName: Indicates the gateway type, such as filling in `test environment`, `production environment`. This value will appear on the API documentation details page; +> +> DictionaryValue: Indicates the gateway address, such as http://127.0.0.1:9195. This value will appear on the API documentation details page; +> +> DictionaryDescribe: Give a brief description of what scenario the gateway address is used for. This value will appear on the API documentation details page; +> +> Sort: The numerical value determines the display order of the gateway address; +> +> Status: open or close。 + +## 4. Support Multiple Ways to Aggregate API Documents + +### 4.1 Add API Document Manually + +Clicking the menu "Document -> API Document" to create api. + +##### Create Project + +If you have not created a project or you want to classify the new API into a new project, you need to create a project. + +![app-create-en](/img/shenyu/basicConfig/apiManagement/app-create-en.png) + +##### Add API Documentation + +![create-api-en](/img/shenyu/basicConfig/apiManagement/create-api-en.png) + +### 4.2 Remotely pull the swagger registration API Document. + +Automatically register API documentation by remotely pulling swager documentation. Please refer to [Remote pull swagger registration API document](../api-doc/swagger-apidoc.md) + +### 4.3 Shenyu Client Annotation Registration API Documentation + +Automatically register API documents through Shenyu client annotations. Please refer to [Client Registration API Documentation](../api-doc/shenyu-annotation-apidoc.md) +> This method is recommended if you do not expect to view the full interface documentation details. When you choose this automatic registration method, please turn off the registration method of remote automatic pull swagger, otherwise there will be conflicts. + +## 5. Publish API + +If the API has never been published and the user has not used the shenyu-client, shenyu-admin will automatically expose the API described in the API document to the gateway. + +![publish-api-en](/img/shenyu/basicConfig/apiManagement/publish-api-en.png) + +After clicking Save, you'll see that the registration data for the API is inserted below the selectors and rules. As shown below: + +![api-published-divide-list-en](/img/shenyu/basicConfig/apiManagement/api-published-divide-list-en.png) + +## 6. Offline API(optional) + +> Special Note: After clicking Offline, the API will still be visible in the API document list, but it will be deleted from the proxy plug-in and metadata management list. Before you republish the API, the gateway will not proxy the API. When you pass through the gateway When requesting this API, an exception will be reported. + +![offline-api-en](/img/shenyu/basicConfig/apiManagement/offline-api-en.png) + +## 7. API Debug + +![api-debug-en](/img/shenyu/basicConfig/apiManagement/api-debug-en.png) diff --git a/versioned_docs/version-2.6.1/user-guide/admin-usage/data-permission.md b/versioned_docs/version-2.6.1/user-guide/admin-usage/data-permission.md new file mode 100644 index 00000000000..6619373e605 --- /dev/null +++ b/versioned_docs/version-2.6.1/user-guide/admin-usage/data-permission.md @@ -0,0 +1,53 @@ +--- +title: Data Permission Management +keywords: ["user data permission"] +description: user data permission +--- +## Design Notes + +In order to achieve the different selector / rule represented by the plugin managed by different business units, the need for the plugin selector / rule data security for the user to control +When the user does not configure data permissions, it has all the data permissions, as long as the permissions are configured, the data permissions will be controlled. As shown in the following picture. + + + + +## How to use + +The Brief introduce is as follows. +- Users with administrative user resouce permissions (including the admin user) create a new user. +- Users with administrative user data resouce permissions (including admin user) click `ConfigureDataPermission` to manage the user's data permissions. +> Make sure the data exists in the plugin list before doing so. If not, you will have any data to configure. + +Now, let's look how to operation step by step: + +### Create User + +Clicking the menu "System Manage -> User" to create user, like this: + + +### Edit Date + +#### Add Plugin Data + +Adding data in the plugin list, this article uses `divide` as an example, like: + + +#### Configure Resource Permission + +Giving the `divide` plugin permission to the `default` role. + + +The `default` role has none permissions.The user can't login who we set `default` role to. So we must edit the permissions. + +#### Configure Data Permission + +When we create the common users, we can edit data permissions by the `ConfigureDataPermission` button. + + + +The datas in this list are the same as the plugin list. + +## New User Login + +When the user login, he just can see the data given to him. + diff --git a/versioned_docs/version-2.6.1/user-guide/admin-usage/dictionary-management.md b/versioned_docs/version-2.6.1/user-guide/admin-usage/dictionary-management.md new file mode 100644 index 00000000000..91b6989ebcf --- /dev/null +++ b/versioned_docs/version-2.6.1/user-guide/admin-usage/dictionary-management.md @@ -0,0 +1,32 @@ +--- +title: Dictionary Management +keywords: ["dict"] +description: dict management explanation +--- + +## Explanation + +This document will introduce the use of dictionary management in the Apache ShenYu background management system. Dictionary management is primarily used to maintain and manage common data dictionaries. + +Please refer to the `deployment` document, choose a way to start `shenyu-admin`. For example, [local deployment](../../deployment/deployment-local). After startup, visit `http://localhost:9095`, the default username and password are: `admin` and `123456` . + +The current usage scenario is in the [pluginHandle](./plugin-handle-explanation), when the data type is selected as the `dropdown`: + + + +In dictionary management, you can add dictionary types for other places: + + + +- DictionaryType: The field name used in the `pluginHandle` . +- DictionaryCode: Identify dictionary data. +- DictionaryName: The name of the `handle` field when adding plugins, selectors or rules. +- DictionaryValue: The actual value of the dictionary data. +- DictionaryDescribe: Description. +- Sort: Dictionary data order. + +e.g. `degradeRuleGrade` is one of fields of Sentinel's `handle` json. When it adds rules, it automatically looks up all the general dictionaries of `type='degradeRuleGrade'` in the `shenyu_dict` table as a select-box when you edit the General rules field. + + + + diff --git a/versioned_docs/version-2.6.1/user-guide/admin-usage/plugin-handle-explanation.md b/versioned_docs/version-2.6.1/user-guide/admin-usage/plugin-handle-explanation.md new file mode 100644 index 00000000000..82eb4af0c95 --- /dev/null +++ b/versioned_docs/version-2.6.1/user-guide/admin-usage/plugin-handle-explanation.md @@ -0,0 +1,51 @@ +--- +title: Plugin Config +keywords: ["plugin"] +description: plugin handle explanation +--- + +## Explanation + +This document will introduce the use of plugins in the `shenyu-admin` , including plugin management and plugin handle management. + +Please refer to the `deployment` document, choose a way to start `shenyu-admin`. For example, [local deployment](../../deployment/deployment-local). After startup, visit `http://localhost:9095`, the default username and password are: `admin` and `123456` . + +## Plugin management + +In the plugin management, you can manage all plugins in a unified manner, such as turning off or turning on plugins: + + + +You can also set configuration information for some plugins, such as setting a registry for `Dubbo` plugin: + + + +## Plugin handle management + +In plugin handle management, you can add `handle` fields to plugin, selector, and rule. + +For example, add a string type field `path` and a digital type field `timeout` to the rule list of the `SpringCloud` plugin. + +1. add/edit the `handle` field in the `shenyu-admin`-> BasicConfig -> PluginHandle : + + + +2. Fill in the field information: + + + +- PluginName: Drop down to select which plugin needs to add the `handle` field. +- Field: Add the name of the field. +- Describe: Field description. +- DataType: Field data type. + - If the `DropDown` is selected, the drop-down selection of the input box on the rule addition page is to go to the dictionary table to find all the available options through the field name to select, so you need to config the selection in [Dictionary Management](./dictionary-management). +- FieldType: This field belongs to selector, rule or plugin. +- Sort: Sequence number. +- Required: Is this field required. +- DefaultValue: Specify a default value for this field. +- Placeholder: The message that appears when the user fills in the field. +- Rule (RegExp): The verification rule when the user fills in the field。 + +3. When adding a rule in the PluginList -> rpc proxy -> `SpringCloud` -> you can enter `path` and `timeout` : + + diff --git a/versioned_docs/version-2.6.1/user-guide/admin-usage/role-management.md b/versioned_docs/version-2.6.1/user-guide/admin-usage/role-management.md new file mode 100644 index 00000000000..e3fa8f40b0e --- /dev/null +++ b/versioned_docs/version-2.6.1/user-guide/admin-usage/role-management.md @@ -0,0 +1,45 @@ +--- +title: Role Management +keywords: ["user role resource"] +description: user role resource permission management +--- + +This article focuses on the `admin` console to manage `admin` operation permissions through user-associated roles, roles that give permissions to resources such as menus and buttons. + + +## Resource + +Add Menus and Buttons Resource in "System Manage >> Resouce". + + + +The admin user shows all menus and buttons of the `Shenyu` gateway. If you need to customize adding and removing, add the menu first and under the corresponding menu, add the button. Edit the menu by clicking on the small edit icon on the right side of the menu. + + +## Role + +You can associate roles and resource permissions through the menu bar "System Administration >> Role Management". By default, two roles are created, one for super administrator and one for normal user. The super administrator is the admin user, which cannot be changed, and the normal user role can change its resource properties. By editing the corresponding role, you can give the role the appropriate menu and button permissions. + + +## User + +You can manage the users logged into admin through the menu bar "System Administration >> User Management". The default user is admin, which has all menu and data permissions, cannot be changed or deleted, and can only change password or username. +You can add a user by pressing the "Add Data" button. The user role is selected to manage the menu and button permissions that the user sees after logging in. When a user selects more than one role, the maximum set of all roles is taken together. After changing a user's role permissions, users who are already logged in can simply refresh the page to get the changed permissions. + +The following is an example of how the new user's permissions. + +- editor default user role permission + + + +- Add new roles and give the appropriate resource permissions + + + +- Create new users and give them the appropriate roles + + + +- User login to view their menu and button permissions + + diff --git a/versioned_docs/version-2.6.1/user-guide/admin-usage/selector-and-rule.md b/versioned_docs/version-2.6.1/user-guide/admin-usage/selector-and-rule.md new file mode 100644 index 00000000000..e2ad2e058eb --- /dev/null +++ b/versioned_docs/version-2.6.1/user-guide/admin-usage/selector-and-rule.md @@ -0,0 +1,336 @@ +--- +title: Selector And Rule Config +keywords: ["Selector", "Rule"] +description: detailed explanation of selector and rule +--- + +## Features + +This document will introduce the use of selectors and rules in the Apache ShenYu background management system. For the concept and design of selectors and rules, please refer to `Flow Control`. + + +Please refer to the `deployment` document, choose a way to start `shenyu-admin`. For example, [local deployment](../../deployment/deployment-local). After startup, visit `http://localhost:9095`, the default username and password are: `admin` and `123456` . + +## Selector + +All plugins are displayed in the PluginList, and selectors and rules can be added to each plugin: + + + +For example, add a selector to the `divide` plugin: + + + +* selector detailed explanation: + + * Name: create your selector with a distinguish name. + * Type: Choose request matching strategy. + * `custom`: Only handle requests that meet the following matching conditions. + * `full`: Handle all requests. + * MatchType: Condition combination type. + * `and`: Need to meet all conditions. + * `or`: Meet any of the conditions. + * Conditions: + * uri: filter request with uri. + * header: filter request with request header. + * query: filter request with query string. + * ip: filter request with your real ip. + * host: filter request with your real host. + * post: not recommend to use. + * cookie: filter request with cookie. + * req_method: filter request with request method. + * condition match: + * match : fuzzy string matching,recommend to combine with uri,support path-matching.(/test/**). + * = : matches only if they are equal. + * regEx : regex matching,match characters in regex expression. + * contains: when it contains the specified value, it matches. + * TimeBefore: before the specified time. + * TimeAfter: after the specified time. + * exclude: the inverse of the method of `match`. + * startsWith: when its prefix is equal to the specified value, it matches. In certain scenarios, `match` can be replaced (such as `/test/` instead of `/test/**`) for better performance. + * endsWith: when its suffix is equal to the specified value, it matches. + * pathPattern: it's an optimized version of `match`, which has better performance than `match`, but does not support writing `**` in the middle of the path (such as `/api/**/xxx`). + * Continued: whether the subsequent selector is still executed. + * PrintLogs: it will print the matching log with the open option enabled. + * Enable: whether to enable the plugin. + * Order:the smaller will have high priority to execute among multi-selectors. + * Handler: The operation when the request matches the selector. +* the above picture means: when the prefix of the request uri is `/http`, it will redirect to this service `127.0.0.1:8080`. +* selector advice : combine `uri` condition and `startsWith` prefix(/contextPath/)as the first request filter. +* selector(the same for rule) match condition fuzzy string matching rule: + * `?` matches one character + * `*` matches zero or more characters + * `**` matches zero or more directories in a path + +## Rule + + + +* when the request was passed by the selector, then it will be processed by the rule, the final filter. +* rule is the final confirmation about how to execute request logically. +* rule detailed explanation: + * Name:create your rule with a distinguish name. + + * MatchType: you can combine these conditions with 'and' , 'or' operators. + + * Conditions: + + * uri: filter request with uri. + * header: filter request with request header. + * query: filter request with query string. + * ip: filter request with your real ip. + * host: filter request with your real host. + * post: not recommend to use. + * cookie: filter request with cookie. + * req_method: filter request with request method. + + * condition match: + * match : fuzzy string matching,recommend to combine with uri,support path-matching.(/test/**). + * = : matches only if they are equal. + * regEx : regex matching,match characters in regex expression. + * contains: when it contains the specified value, it matches. + * TimeBefore: before the specified time. + * TimeAfter: after the specified time. + * exclude: Same function as `match`, flow selection is opposite. + * startsWith: when its prefix is equal to the specified value, it matches. In certain scenarios, `match` can be replaced (such as `/test/` instead of `/test/**`) for better performance. + * endsWith: when its suffix is equal to the specified value, it matches. + * pathPattern: it's an optimized version of `match`, which has better performance than `match`, but does not support writing `**` in the middle of the path (such as `/api/**/xxx`). + + * PrintLogs: it will print the matching log with the open option enabled. + + * Enable: whether to enable the plugin. + + * Order:the smaller will have high priority to execute among multi-rules. + + * handle: The operation when the request matches the rule. +* above picture means: when the request `uri` equals to `/http/order/save`, it will execute based on this rule,load strategy is `random`. +* rule advice: combine `uri` condition with `match` the real `uri path` condition as the final filter. +* combine selector means :when the request `uri` is `/http/order/save`, it will be redicted to `127.0.0.1:8080` by `random` method. + + +## Match Strategy + +Matching mode refers to the matching mode between multiple conditions when a selector or rule is matched. Currently, `and` and `or` are supported. + + +* `and` + + `and` indicates that a selector or rule can be matched only if more than one condition is met. + + The example below shows that a request must meet both the condition `uri = /http/order/findById` and the condition `id = 100` to match this rule. + + For example, a real request `http://localhost:9195/http/order/findById?id=100` satisfies both conditions, this rule can be matched. + + +![](/img/shenyu/basicConfig/selectorRule/match-strategy-and-en.png) + + +* `or` + + `or` indicates that one of the conditions matches a selector or rule. + + The example below shows that a request matches this rule if it meets either the condition `uri = /http/order/findById` or the condition `id = 100`. + + For example, a real request `http://localhost:9195/http/order/findById?id=99` satisfies the first condition `uri = /http/order/findById`, so it can also match this rule. + + +![](/img/shenyu/basicConfig/selectorRule/match-strategy-or-en.png) + + +## Condition Parameter Data + +Conditional parameter Settings in selectors and rules are explained again. Suppose the following is a request header for an `Http` request: + +```shell +GET http://localhost:9195/http/order/findById?id=100 +Accept: application/json +Cookie: shenyu=shenyu_cookie +MyHeader: custom-header +``` + +In `ShenYu` you can set different conditional parameters to get real data from the request information. + +- If the condition parameter is `uri`, then the actual data retrieved is `/http/order/findById`; +- If the condition parameter is `header`, the field name is `MyHeader`, then the actual data retrieved is `custom-header`; +- If the condition parameter is `query`, the field name is `id`, then the actual data retrieved is `100`; +- If the condition parameter is `ip`, then the actual data retrieved is `0:0:0:0:0:0:0:1`; +- If the condition parameter is `host`, then the actual data retrieved is `0:0:0:0:0:0:0:1`; +- If the condition parameter is `post`, the field name is `contextPath`, then the actual data retrieved is `/http`; +- If the condition parameter is `cookie`, the field name is `shenyu`, then the actual data retrieved is `shenyu_cookie`; +- If the condition parameter is `req_method`, then the actual data retrieved is `GET`; + +* `uri`(recommended) + + * `uri` matches are based on the `uri` in the path you requested, and there is almost no change in the front end when accessing the gateway. + + * When using `match`, the principle is the same as `SpringMVC` fuzzy matching. + + * In selectors, it is recommended to use prefixes in `URI` for matching, while in rules, specific paths are used for matching. + + * When using this matching method, fill in the value of the matching field, as shown in the figure `/http/**`. + + ![](/img/shenyu/basicConfig/selectorRule/parameter-data-uri-en.png) + +* `header` + + * The `header` is matched against the field values in your `http` request header. + + * When using this matching method, you need to fill in the field name and field value. The examples in the figure are `MyHeader` and `custom-header` respectively + + ![](/img/shenyu/basicConfig/selectorRule/parameter-data-header-en.png) + +* `query` + + * This matches the query parameters in your `uri`, such as `/test?id=1`, then the matching method can be selected. + + * When using this matching method, you need to fill in the field name and field value. The examples in the figure are `id` and 1 respectively. + + ![](/img/shenyu/basicConfig/selectorRule/parameter-data-query-en.png) + +* `ip` + + * This is matched against the `http` caller's `ip`. + + * Especially in waf plugin, if an `ip` address is found to be attacked, you can add a matching condition, fill in the `ip`, deny the `ip` access. + + * If you use nginx proxy before ShenYu, you can get the right ip with refering to [parsing-ip-and-host](../../developer/custom-parsing-ip-and-host) + + * When using this matching method, fill in the value of the matching field, as shown in the example `192.168.236.75`. + + ![](/img/shenyu/basicConfig/selectorRule/parameter-data-ip-en.png) + + +* `host` + + * This is matched against the `http` caller's `host`. + + * Especially in waf plugin, if an `host` address is found to be attacked, you can add a matching condition, fill in the `host`, deny the `host` access. + + * If you use nginx proxy before ShenYu, you can get the right ip with refering to [parsing-ip-and-host](../../developer/custom-parsing-ip-and-host) + + * When using this matching method, fill in the value of the matching field, as shown in the example `localhost`. + + ![](/img/shenyu/basicConfig/selectorRule/parameter-data-host-en.png) + +* `post` + + * To get condition parameters from the request context(`org.apache.shenyu.plugin.api.context.ShenyuContext`), reflection is required to get the value of the field, which is not recommended. + + * When using this matching method, the field name and value need to be specified. The examples in the figure are `contextPath` and `/http` respectively. + + ![](/img/shenyu/basicConfig/selectorRule/parameter-data-post-en.png) + + +* `cookie` + + * This is matched against the `Cookie` in the `http` caller's request header as a condition parameter. + + * When using this matching method, you need to fill in the field name and field value. The examples in the figure are `shenyu` and `shenyu_cookie` respectively. + + ![](/img/shenyu/basicConfig/selectorRule/parameter-data-cookie-en.png) + +* `req_method` + + * This matches the request form of the `http` caller, such as `GET`, `POST`, etc. + + * When using this matching method, fill in the value of the matching field, as shown in the example `GET`. + + ![](/img/shenyu/basicConfig/selectorRule/parameter-data-req_method-en.png) + +For a more in-depth understanding of condition parameter fetching, read the source code, package name is `org.apache.shenyu.plugin.base.condition.data`: + +|Condition Parameter | Class | +|:------------------------ |:----- | +|`uri` |`URIParameterData` | +|`header` |`HeaderParameterData` | +|`query` |`QueryParameterData` | +|`ip` |`IpParameterData` | +|`host` |`HostParameterData` | +|`post` |`PostParameterData` | +|`cookie` |`CookieParameterData` | +|`req_method` |`RequestMethodParameterData` | + + +## Condition Match Strategy + +Condition parameters allow you to retrieve the actual data of the request. How the real data matches the conditional data preset by the selector or rule is realized through the condition match strategy. + + +* `match` + + `match` supports fuzzy matching (`/**`). Request `/http/order/findById` will match if your selector condition is set as follows. + + ![](/img/shenyu/basicConfig/selectorRule/predicate-judge-match-en.png) + +* `=` + + `=` means that the requested real data is equal to the preset condition data. If your selector condition is set to request uri equal to `/http/order/findById`, then request`/http/order/findById?id=1` can match it. + + ![](/img/shenyu/basicConfig/selectorRule/predicate-judge-equals-en.png) + +* `regex` + + `regex` means that the requested real data can meet the preset condition of the regular expression to match successfully. Suppose your rule conditions are sets as follows: the request parameter contains an `id` and is a three-digit number. So request `/http/order/findById?id=900` will match. + + ![](/img/shenyu/basicConfig/selectorRule/predicate-judge-regex-en.png) + +* `contains` + + `contains` means that the requested real data contains the default condition data. Suppose your rule condition is set as follows: request uri contains `findById`. Request `/http/order/findById?id=1` will match. + + ![](/img/shenyu/basicConfig/selectorRule/predicate-judge-contains-en.png) + +* `TimeBefore` + + `TimeBefore` indicates that the request time will be matched before the preset condition time. Suppose your rule conditions are sets as follows: request parameters contain `date` and `date` is less than `2021-09-26 06:12:10`. Request `/http/order/findById?id=100&date=2021-09-22 06:12:10` will match. + + ![](/img/shenyu/basicConfig/selectorRule/predicate-judge-timebefore-en.png) + +* `TimeAfter` + + `TimeAfter` indicates that the request time will be matched before the preset condition time. Suppose your rule conditions are sets as follows: request parameters contain `date` and `date` is greater than `2021-09-26 06:12:10`. Request `/http/order/findById?id=100&date=2021-09-22 06:12:10` will match. + + ![](/img/shenyu/basicConfig/selectorRule/predicate-judge-timeafter-en.png) + +* `exclude` + + `exclude` is the inverse of the method of `match`, and some functions of `match` are also available, but it is a matching filter. If your selector condition is set as follows, the request `/http/order/findById` will filter this. + + ![](/img/shenyu/basicConfig/selectorRule/predicate-judge-exclude-en.png) + +* `startsWith` + + `startsWith` indicates that the prefix of the requested real data is equal to the preset condition data. Suppose your rule conditions are sets as follows: the prefix in the request `uri` is equal to `/http/`, the request `/http/order/findById?id=1` can be matched. + + ![](/img/shenyu/basicConfig/selectorRule/predicate-judge-startswith-en.png) + +* `endsWith` + + `endsWith` indicates that the suffix of the requested real data is equal to the preset condition data. Suppose your rule conditions are sets as follows: request `uri` suffix equals `Id`. Then the request `/http/order/findById?id=1` can be matched. + + ![](/img/shenyu/basicConfig/selectorRule/predicate-judge-endswith-en.png) + +* `pathPattern` + + Like `match`, `pathPattern` supports fuzzy matching (`/**`). If your rule conditions are sets as follows, then the request `/http/order/findById` can be matched; + + Notice: writing `**` in the middle of the path (such as `/api/**/xxx`) is not supported! + + ![](/img/shenyu/basicConfig/selectorRule/predicate-judge-pathpattern-en.png) + +If you want to further understand conditions matching strategy, please read the source code, the package name is `org.apache.shenyu.plugin.base.condition.judge`: + +| Match Strategy | Class | +|:---------------|:----- | +| `match` |`MatchPredicateJudge` | +| `=` |`EqualsPredicateJudge` | +| `regex` |`RegexPredicateJudge` | +| `contains` |`ContainsPredicateJudge` | +| `TimeBefore` |`TimerBeforePredicateJudge` | +| `TimeAfter` |`TimerAfterPredicateJudge` | +| `exclude` |`ExcludePredicateJudge` | +| `startsWith` |`StartsWithPredicateJudge` | +| `endsWith` |`EndsWithPredicateJudge` | +| `pathPattern` |`PathPatternPredicateJudge` | + +The examples in this article illustrate the use of selectors and rules. The Settings of specific conditions need to be selected according to actual conditions. diff --git a/versioned_docs/version-2.6.1/user-guide/api-doc/_category_.json b/versioned_docs/version-2.6.1/user-guide/api-doc/_category_.json new file mode 100644 index 00000000000..ae4f3bab406 --- /dev/null +++ b/versioned_docs/version-2.6.1/user-guide/api-doc/_category_.json @@ -0,0 +1,4 @@ +{ + "label": "API Document Aggregation", + "position": 6 +} diff --git a/versioned_docs/version-2.6.1/user-guide/api-doc/shenyu-annotation-apidoc.md b/versioned_docs/version-2.6.1/user-guide/api-doc/shenyu-annotation-apidoc.md new file mode 100644 index 00000000000..5343291aa1f --- /dev/null +++ b/versioned_docs/version-2.6.1/user-guide/api-doc/shenyu-annotation-apidoc.md @@ -0,0 +1,38 @@ +--- +title: The client registers the API documentation +keywords: ["api doc register"] +description: The client registers the API documentation +--- + +This article describes how to expose the `API documentation` to the `Apache ShenYu` gateway. + +Before accessing, please start `shenyu-admin` correctly. + +## Export API Documentation to shenyu-admin + +You can refer to any of the example codes below [shenyu-examples](https://github.com/apache/shenyu/tree/master/shenyu-examples). + +The only thing you need to do is to add `@ApiModule` and `@ApiDoc` annotations to your service, here is an example from `shenyu-examples-http`: + +```java +@RestController +@RequestMapping("/order") +@ShenyuSpringMvcClient("/order") +@ApiModule(value = "order") +public class OrderController { + + @GetMapping("/findById") + @ShenyuSpringMvcClient("/findById") + @ApiDoc(desc = "findById") + public OrderDTO findById(@RequestParam("id") final String id) { + return build(id, "hello world findById"); + } + + private OrderDTO build(final String id, final String name) { + OrderDTO orderDTO = new OrderDTO(); + orderDTO.setId(id); + orderDTO.setName(name); + return orderDTO; + } +} +``` diff --git a/versioned_docs/version-2.6.1/user-guide/api-doc/swagger-apidoc.md b/versioned_docs/version-2.6.1/user-guide/api-doc/swagger-apidoc.md new file mode 100644 index 00000000000..2c9d17a0efb --- /dev/null +++ b/versioned_docs/version-2.6.1/user-guide/api-doc/swagger-apidoc.md @@ -0,0 +1,57 @@ +--- +title: Pull the swagger registration API document +keywords: ["swagger api Interface Document Aggregation"] +description: Remotely pull swagger registration API documentation +--- + +This article introduces how to aggregate the `Swagger API documentation` of each backend microservice to the `Apache ShenYu` gateway management system. + +## 1. Description + +Remotely pull swagger documents, currently only supports swagger2.0, and only supports Divide and SpringCloud proxy plug-ins. + +## 2. Environment Preparation + +### 2.1 Run `shenyu-admin` + +Please refer to the `deployment` document, choose a way to run `shenyu-admin`. + +### 2.2 Enable the global switch for remotely pulling swagger documents. + +It is enabled by default. In the `Apache ShenYu` gateway management system --> BasicConfig --> Dictionary, find the data whose DictionaryType is `apidoc`, and modify the dictionary value: `true`. +> 【Notice】DictionaryValue: `true` means the switch is on, `false` means it is off. If it is closed, `shenyu-admin` will not automatically pull the swagger documents of each microservice. + +![apidoc-dictionary-en](/img/shenyu/api-doc/apidoc-dictionary-en.png) + +## 3. Run the Sample Project + +3.1. Download [shenyu-examples-http-swagger2](https://github.com/apache/shenyu/tree/master/shenyu-examples/shenyu-examples-http-swagger2) + +3.2. Run `org.apache.shenyu.examples.http.ShenyuTestSwaggerApplication` main method to start the project. + +The examples project will synchronize the service startup information to `shenyu-admin` through the Shenyu client annotation (such as `@ShenyuSpringMvcClient`) according to the address configured by `shenyu.register.serverLists`, and then trigger `shenyu-admin` to remotely pull the swagger document And complete the analysis, and finally aggregate to produce a new API document. + +## 4. Demonstration Effect + +### 4.1 List of API Documents + +In `Apache ShenYu` Gateway Management System --> Document --> API Document, you can see the aggregated API documents. + +![apidoc-swagger-list-en](/img/shenyu/api-doc/apidoc-swagger-list-en.png) + +### 4.2 API Details Effect + +![apidoc-detail-en](/img/shenyu/api-doc/apidoc-detail-en.png) + +## 5. How to Automatically Update API Documentation + +### 5.1 Restart Project + +As in the example above, an automatic update of the API docs is triggered by starting the project. + +### 5.2 Modify the startup time of the proxy plugin selector. + +In the PlugiList --> Proxy --> selector, find the target service, and then modify the startup time. +> Note: The startup time of the new setting must not be earlier than the original startup time, otherwise the API document will not be automatically pulled and refreshed. + +![app-proxy-startuptime-en](/img/shenyu/api-doc/app-proxy-startuptime-en.png) diff --git a/versioned_docs/version-2.6.1/user-guide/discovery/_category_.json b/versioned_docs/version-2.6.1/user-guide/discovery/_category_.json new file mode 100644 index 00000000000..7c0997e003e --- /dev/null +++ b/versioned_docs/version-2.6.1/user-guide/discovery/_category_.json @@ -0,0 +1,4 @@ +{ + "label": "Discovery", + "position": 4 +} diff --git a/versioned_docs/version-2.6.1/user-guide/discovery/discovery-mode.md b/versioned_docs/version-2.6.1/user-guide/discovery/discovery-mode.md new file mode 100644 index 00000000000..80837a074b5 --- /dev/null +++ b/versioned_docs/version-2.6.1/user-guide/discovery/discovery-mode.md @@ -0,0 +1,422 @@ +--- +title: Discovery +keywords: [ "Discovery" ] +description: Discovery +--- + +# Discovery + +## 1. Overview + +### 1.1 Module Name + +Discovery + +### 1.2 Design + +- Module Design Diagram + +![discovery-design.png](/img/shenyu/plugin/discovery/discovery-design.png) + + + +- Database Design + +![db-design.png](/img/shenyu/plugin/discovery/db-design.png) + + +### 1.3 Module Functionality + +The Discovery module endows the ShenYu Gateway with the ability to actively perceive and respond to changes in the list of services being proxied. +By actively listening to the admin service of the Discovery Gateway, the ShenYu Gateway can promptly track changes in the services being proxied. +This functionality is designed to be flexible and can be configured at either **the selector level or the plugin level**, as needed. +Currently, plugins that have incorporated the Discovery feature include TCP, Divide, Websocket and gRPC plugins. + + +### 1.4 Listening Mode + +LOCAL, ZOOKEEPER, NACOS, EUREKA, ETCD + +- LOCAL Mode: Primarily relies on manual maintenance of the upstream list and pushing it to the gateway. +- ZOOKEEPER Mode: Monitors changes in ephemeral nodes under a specified node in ZooKeeper to obtain data. +- NACOS Mode: Listens for changes in instances under a specified service name in Nacos to obtain data. +- EUREKA Mode: Listens for changes in instances under a specified service name in Eureka to obtain data. +- ETCD Mode: Obtains data by monitoring changes in key-value pairs under specified nodes in etcd. + +### 1.5 Scope of Effect + +- Plugin Level: Impacts the entire plugin, +and all selectors under that plugin will default to the current listening mode. +- Selector Level: Applies to the current selector, +allowing different selectors under the same plugin to use different listening modes. + +## 2. Usage + +### 2.1 Plugin-Level Configuration + +#### 2.1.1 Service Discovery Configuration + +- In plugins that support the Discovery module (currently, only the TCP plugin supports plugin-level discovery +configuration on the admin console page; other plugins can configure plugin-level discovery through shenyu-client, +as described in the "Using Shenyu-client" section below), click on `Discovery Configuration`. In the popup form, +select the desired listening mode and fill in the service discovery name, registration server URL, registry configuration parameters, etc.: + + +![config-discovery-plugin-en.png](/img/shenyu/plugin/discovery/config-discovery-plugin-en.png) + +![config-discovery-plugin-modal-en.png](/img/shenyu/plugin/discovery/config-discovery-plugin-modal-en.png) + +#### 2.1.2 Usage within Selectors + +- To add a new selector, click on `Add Selector`. In the new selector page, you will notice that the `Type` field enforces the previously configured plugin-level listening mode, +indicating that the added selector will also adopt the same configuration. +At this point, simply input the desired `ListeningNode`: + + ![add-selector-under-plugin-discovery-en.png](/img/shenyu/plugin/discovery/add-selector-under-plugin-discovery-en.png) + +- The `Handler` here refers to ShenYu's specified JSON format for transmitting upstream registration data, +as shown below: + - url: URL of the upstream + - protocol: communication protocol of the upstream + - status: status of the upstream node (0 for healthy, 1 for unhealthy) + - weight: Used for load balancing calculations + + + ```json + { + "url": "127.0.0.1::6379", + "protocol": "tcp", + "status": 0, + "weight": 10 + } + ``` + +- If your service alias does not match ShenYu's defined JSON format, +you can perform alias mapping in `Handler`. +For example, as shown in the above image, +if you need to change `status` to "healthy" while keeping other keys unchanged, +follow these steps: create a new alias, map `status` to `healthy`, +and retain the original JSON keys' format. +- Configure the remaining properties for the selector according to the specific plugin's documentation. + +### 2.2 Selector-Level Configuration + +- In plugins that support the Discovery module, click on `Add Selector`. +In the `Discovery Config` tab, configure the fields such as type, +listening node, server URL list, and registry properties. +This configuration only applies to the current selector and must be reconfigured each time a new selector is added. + +![add-selector-en.png](/img/shenyu/plugin/discovery/add-selector-en.png) + +- For the Divide, gRPC, and Websocket plugins, +the `Import Background Discovery Config` function on the selector creation page +allows you to import and use the backend configuration if the service connecting to the ShenYu Gateway +was configured with shenyu-discovery-related properties (see usage with shenyu-client). +As shown in the following image, click `Import Background Discovery Config` to view the backend configuration: + +![config-import-en.png](/img/shenyu/plugin/discovery/config-import-en.png) + +- If you confirm the import, clicking the `Import` button in the backend configuration popup will automatically populate the form with the backend service discovery properties. +At this point, you only need to configure the listening node: + +![after-import-en.png](/img/shenyu/plugin/discovery/after-import-en.png) + +> **Note**: If you confirm importing the backend configuration, +the backend service discovery properties will be automatically filled in the form and will continue to use the previous discovery object. +In this case, modifying service discovery properties in the form will be ineffective, and the backend configuration will be retained. + +- If you choose the LOCAL mode, there is no need to connect to a registry, and users must manually maintain the upstream list. + + +## 3. Configuration in Different Modes + +### 3.1 Local Mode + +- Local mode only supports configuration at the **selector level**. +There is no need to connect to a registry, and users must manually maintain the upstream list. +This list is an editable table. Click the `Edit` button for each row in the table to modify each parameter of the upstream: + +![local-selector-en.png](/img/shenyu/plugin/discovery/local-selector-en.png) + +### 3.2 ZooKeeper/Nacos/Eureka/Etcd Modes + +- In the ZooKeeper/Nacos/Eureka/Etcd modes, service discovery configuration is supported at both the plugin level and the selector level. +- For each registry property under these modes, taking ZooKeeper as an example, users can go to `shenyu-admin` --> `BasicConfig` --> `Dictionary`, +search for the dictionary name "zookeeper", and edit the dictionary values corresponding to the default properties +(**Note**: You cannot modify the dictionary type and dictionary name). +- In these modes, the gateway dynamically retrieves service instance information from the registry. Additions, removals, modifications, +and other changes to service instances will be displayed in real-time in the upstream list. + +![zk_dict_en.png](/img/shenyu/plugin/tcp/zk_dict_en.png) + +## 4. Using Shenyu-client + +### 4.1 Introduction + +- To use Shenyu-client, you need to depend on the corresponding mode's registry middleware: ZooKeeper, Nacos, Etcd, Eureka. +These modes can automatically detect service up and down events through ShenYu Admin. +- Additionally, if you are using the local mode, you will need to manually maintain the upstream list. +- For detailed instructions on using Shenyu-client, refer to the Shenyu-client module documentation. + +### 4.2 Local Mode Example + +#### 4.2.1 Using Shenyu-client + +- Shenyu-client defaults to the Local mode, so there is no need for any special discovery configuration. +It will automatically register the current service. +- For services that are automatically registered, you can manually add, modify, +or delete them in the upstream list on the page: + +![local-selector-en.png](/img/shenyu/plugin/discovery/local-selector-en.png) + +#### 4.2.2 Without Using Shenyu-client + + +- If you are not using Shenyu-client, you can manually add, modify, +or delete service information on the `Discovery Config` tab under `Add Selector`: + +![add-selector-local-en.png](/img/shenyu/plugin/discovery/add-selector-local-en.png) + +- Configure other selector information: + +![add-selector-basic-en.png](/img/shenyu/plugin/discovery/add-selector-basic-en.png) + +- Configure rules: + +![rule-en.png](/img/shenyu/plugin/discovery/rule-en.png) + +- Test Connection + +```text +curl http://localhost:9195/http/hello + +hello! I'm Shenyu-Gateway System. Welcome!% +``` + +### 4.2 Zookeeper Mode Example + +(Taking the Divide plugin as an example) + +- Add Dependencies + +```xml + + + org.apache.shenyu + shenyu-discovery-zookeeper + ${project.version} + + + + org.apache.shenyu + shenyu-spring-boot-starter-client-http + + +``` + +- Add the Following Configuration in application.yml + +```yaml +shenyu: + discovery: + enable: true + type: zookeeper + serverList: ${your.zookeeper.ip}:{your.zookeeper.port} + registerPath: /shenyu/discovery/demo_http_common + props: + baseSleepTimeMilliseconds: 1000 + maxRetries: 4 + maxSleepTimeMilliseconds: 5000 + connectionTimeoutMilliseconds: 60000 + sessionTimeoutMilliseconds: 8 +``` + +- Start the shenyu-examples-http service. +- Once the service registration is successful, +you can view the list of automatically registered service instances on the selector page: + +![zk-selector-en.png](/img/shenyu/plugin/discovery/zk-selector-en.png) + +- Users can click on `Edit` in the service instance list to edit the service instance information +(Note that in non-Local mode, the URL is maintained by the registry and cannot be manually edited): + + +![edit-zk-upstream-en.png](/img/shenyu/plugin/discovery/edit-zk-upstream-en.png) + +- Test Connection + +```text +curl http://localhost:9195/http/hello + +hello! I'm Shenyu-Gateway System. Welcome!% +``` + +### 4.3 Etcd Mode Example + +- Add Dependencies + +```xml + + + org.apache.shenyu + shenyu-discovery-etcd + ${project.version} + + + + org.apache.shenyu + shenyu-spring-boot-starter-client-http + + +``` + +- Add the Following Configuration in application.yml + +```yaml +shenyu: + discovery: + enable: true + protocol: http:// + type: etcd + serverList: http://${your.etcd.host}:${your.etcd.port} + registerPath: /shenyu/test/http_common + props: + etcdTimeout: 3000 + etcdTTL: 5 +``` + +- Start the shenyu-examples-http service. Similarly, on the selector page, +you can see the list of automatically registered service instances and edit them as needed: +![etcd-selector-en.png](/img/shenyu/plugin/discovery/etcd-selector-en.png) + +- Test Connection + +```text +curl http://localhost:9195/http/hello + +hello! I'm Shenyu-Gateway System. Welcome!% +``` + +### 4.4 Eureka Mode Example + +- Add Dependencies + +```xml + + + org.apache.shenyu + shenyu-discovery-eureka + ${project.version} + + + + org.apache.shenyu + shenyu-spring-boot-starter-client-http + + +``` + +- Add the Following Configuration in application.yml + (in this context, `registerPath` can be understood as the name of the service to be monitored): + +```yaml +shenyu: + discovery: + enable: true + protocol: http:// + type: eureka + serverList: http://${your.eureka.host}:${your.eureka.port}/eureka + registerPath: shenyu_discovery_demo_http_common + props: + eurekaClientRefreshInterval: 10 + eurekaClientRegistryFetchIntervalSeconds: 10 +``` + +- Start the shenyu-examples-http service. Similarly, on the selector page, +you can see the list of automatically registered service instances and edit them as needed: + +![eureka-selector-en.png](/img/shenyu/plugin/discovery/eureka-selector-en.png) + +- Test Connection + +```text +curl http://localhost:9195/http/hello + +hello! I'm Shenyu-Gateway System. Welcome!% +``` + +### 4.5 Nacos Mode Example + +- Add Dependencies + +```xml + + + org.apache.shenyu + shenyu-discovery-eureka + ${project.version} + + + + org.apache.shenyu + shenyu-spring-boot-starter-client-http + + +``` + +- Add the Following Configuration in application.yml +(Here, `registerPath` can also be understood as the name of the service to be monitored.) + +```yaml +shenyu: + discovery: + enable: true + protocol: http:// + type: nacos + serverList: ${your.nacos.host}:${your.nacos.port} + registerPath: shenyu_discovery_demo_http_common + props: + groupName: SHENYU_GROUP +``` + +- Start the shenyu-examples-http service. Similarly, on the selector page, +you can view the list of automatically registered service instances and edit them as needed. + +![nacos-selector-en.png](/img/shenyu/plugin/discovery/nacos-selector-en.png) + +- Test Connection + +```text +curl http://localhost:9195/http/hello + +hello! I'm Shenyu-Gateway System. Welcome!% +``` + +> **Note**:Configuring service discovery using Shenyu-client essentially configures service discovery at the plugin level. +Under the same service discovery mode, there is, in fact, only one discovery object +(meaning you can only configure the same set of type, server URL, and service discovery parameters), while multiple listening nodes can be configured. + + +![ws-selector-en.png](/img/shenyu/plugin/discovery/ws-selector-en.png) + +> **Note**:In the Divide and gRPC plugins, you can modify the protocol by configuring the protocol in the application.yml file. +The default protocol for the Websocket plugin is 'ws'. + + + +## 5. Considerations + +- In local mode, you can manually modify all parameters of the upstream on the service list page. +- In non-local modes, you can manually modify parameters other than URL and start time. +- Manually changing the status (open/close) and weight of service instances only affects the current plugin. +- For the same plugin, when configuring discovery-related parameters through Shenyu-client in the backend, it essentially configures service discovery at the plugin level. Although you can manually add selectors on the console page to configure selector-level service discovery, in reality, there is only one discovery object (meaning you can only configure the same set of type, server URL, and service discovery parameters), while multiple listening nodes can be configured. + + + +## 6. Test Report + +[Test Report](https://www.yuque.com/eureca/pgotw1/hkqkk5laubspgwl3#UojLR) + + + + diff --git a/versioned_docs/version-2.6.1/user-guide/kubernetes-controller/_category_.json b/versioned_docs/version-2.6.1/user-guide/kubernetes-controller/_category_.json new file mode 100644 index 00000000000..47a0b85e937 --- /dev/null +++ b/versioned_docs/version-2.6.1/user-guide/kubernetes-controller/_category_.json @@ -0,0 +1,4 @@ +{ + "label": "Kubernetes Controller", + "position": 5 +} diff --git a/versioned_docs/version-2.6.1/user-guide/kubernetes-controller/build-deploy.md b/versioned_docs/version-2.6.1/user-guide/kubernetes-controller/build-deploy.md new file mode 100644 index 00000000000..c8ecdbd9df4 --- /dev/null +++ b/versioned_docs/version-2.6.1/user-guide/kubernetes-controller/build-deploy.md @@ -0,0 +1,120 @@ +--- +title: Build And Deploy Kubernetes Controller +description: Build And Deploy Kubernetes Controller +--- + +This article introduces how to use ShenYu Ingress Controller. + +## Construct + +It is recommended to refer to [Custom Deployment](../../deployment/deployment-custom.md) to build a custom gateway, add the shenyu-kubernetes-controller dependency to the Maven dependency of the gateway, and the gateway can integrate the kubernetes controller. + +```xml + + org.apache.shenyu + shenyu-spring-boot-starter-k8s + ${project.version} + +``` + +You can also directly use the officially built docker image (TODO, unfinished) + +## deployment + +K8s deployment files can refer to: + +```yaml +apiVersion: v1 +kind: Namespace +metadata: + name: shenyu-ingress +--- +apiVersion: v1 +automountServiceAccountToken: true +kind: ServiceAccount +metadata: + name: shenyu-ingress-controller + namespace: shenyu-ingress +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: shenyu-ingress-controller + namespace: shenyu-ingress + labels: + app: shenyu-ingress-controller + all: shenyu-ingress-controller +spec: + replicas: 1 + selector: + matchLabels: + app: shenyu-ingress-controller + template: + metadata: + labels: + app: shenyu-ingress-controller + spec: + containers: + - name: shenyu-ingress-controller + image: apache/shenyu-integrated-test-k8s-ingress:latest + ports: + - containerPort: 9195 + imagePullPolicy: IfNotPresent + serviceAccountName: shenyu-ingress-controller +--- +apiVersion: v1 +kind: Service +metadata: + name: shenyu-ingress-controller + namespace: shenyu-ingress +spec: + selector: + app: shenyu-ingress-controller + type: NodePort + ports: + - port: 9195 + targetPort: 9195 + nodePort: 30095 +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + name: shenyu-ingress-controller +rules: +- apiGroups: + - "" + resources: + - namespaces + - services + - endpoints + - secrets + - pods + verbs: + - get + - list + - watch +- apiGroups: + - networking.k8s.io + resources: + - ingresses + verbs: + - get + - list + - watch +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRoleBinding +metadata: + name: shenyu-ingress-controller + namespace: shenyu-ingress +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: ClusterRole + name: shenyu-ingress-controller +subjects: +- kind: ServiceAccount + name: shenyu-ingress-controller + namespace: shenyu-ingress +``` + +Among them, Service can be changed to `LoadBalancer` type according to the actual situation. diff --git a/versioned_docs/version-2.6.1/user-guide/kubernetes-controller/config.md b/versioned_docs/version-2.6.1/user-guide/kubernetes-controller/config.md new file mode 100644 index 00000000000..3203e134b56 --- /dev/null +++ b/versioned_docs/version-2.6.1/user-guide/kubernetes-controller/config.md @@ -0,0 +1,115 @@ +--- +title: Kubernetes Controller Config +description: Kubernetes Controller Config +--- + +This article introduces Kubernetes Controller configuration. + +## Enable HTTPS + +To enable HTTPS, you need to configure the `sni protocol` in the `application.yml` file of the gateway: + +```yaml +shenyu: + netty: + http: + sni: + enabled: true + mod: k8s #k8s mode applies + defaultK8sSecretNamespace: shenyu-ingress #The namespace of the default secret resource + defaultK8sSecretName: default-cert #default secret resource name +``` + +Among them, the default secret resource must be available, but it will not be actually used at present. + +## Ingress configuration + +ShenYu Kubernetes Controller implements the K8s native Ingress standard, see [K8s official documentation](https://kubernetes.io/docs/concepts/services-networking/ingress/) for the use of the native standard + +In addition, Apache ShenYu has expanded based on the Annotation field of Ingress, and the configuration is shown in the following tables: + +### General + +| Name | Default | Required | Description | +| --------------------------- | ------ | -------- | ----- --- | +| kubernetes.io/ingress.class | | Yes | Fill in shenyu | + +### Divide plugin (HTTP proxy) + +| Name | Default | Required | Description | +| ------------------------------------- | ------ | ------- - | ------------------------------------------------ ------------ | +| shenyu.apache.org/loadbalancer | random | No | Load balancing algorithm, optional hash, random, roundRobin, leastActive, p2c, shortestResponse | +| shenyu.apache.org/retry | 3 | No | Number of failed retries | +| shenyu.apache.org/timeout | 3000 | No | Backend request timeout, in milliseconds | +| shenyu.apache.org/header-max-size | 10240 | No | The maximum size of the request header, unit byte | +| shenyu.apache.org/request-max-size | 102400 | No | Maximum request body size, unit byte | + +### Dubbo plugin + +| Name | Default | Required or not | Description | +| ---------------------------------------------- | -------- | --------------- | ------------------------------------------------------------ | +| shenyu.apache.org/loadbalancer | random | No | Load balancing algorithm, optional hash, random, roundRobin, lastActive, p2c, shortestResponse | +| shenyu.apache.org/retry | 3 | No | Number of failed retries | +| shenyu.apache.org/timeout | 3000 | no | Backend request timeout in milliseconds | +| shenyu.apache.org/header-max-size | 10240 | No | Maximum request header size in bytes | +| shenyu.apache.org/request-max-size | 102400 | No | Maximum request body size in bytes | +| shenyu.apache.org/upstreams-protocol | dubbo:// | No | Specify the protocol protocol used by upstream | +| shenyu.apache.org/plugin-dubbo-enabled | | No | Determines if the dubbo plugin is enabled | +| shenyu.apache.org/zookeeper-register-address | | Yes | Specify zookeeper address | +| shenyu.apache.org/plugin-dubbo-app-name | | Yes | Specify the metadata application name | +| shenyu.apache.org/plugin-dubbo-path | | Yes | Specify the request path for metadata | +| shenyu.apache.org/plugin-dubbo-rpc-type | | Yes | Specify the rpc type for metadata (dubbo, sofa, tars, springCloud, motan, grpc) | +| shenyu.apache.org/plugin-dubbo-service-name | | Yes | Specify the interface name for the metadata | +| shenyu.apache.org/plugin-dubbo-method-name | | Yes | Specifies the method name for metadata | +| shenyu.apache.org/plugin-dubbo-rpc-expand | | No | Specifies the rpc expansion parameter (json object) for the metadata | +| shenyu.apache.org/plugin-dubbo-parameter-types | | Yes | Specify parameter types for metadata | + +### Motan plugin + +| Name | Default | Required or not | Description | +| ---------------------------------------------- | ------- | --------------- | ------------------------------------------------------------ | +| shenyu.apache.org/loadbalancer | random | No | Load balancing algorithm, optional hash, random, roundRobin, lastActive, p2c, shortestResponse | +| shenyu.apache.org/retry | 3 | No | Number of failed retries | +| shenyu.apache.org/timeout | 3000 | No | Back-end request timeout in milliseconds | +| shenyu.apache.org/header-max-size | 10240 | No | Maximum request header size in bytes | +| shenyu.apache.org/request-max-size | 102400 | No | Maximum request body size in bytes | +| shenyu.apache.org/plugin-motan-enabled | No | Yes | Determines if the motan plugin is enabled | +| shenyu.apache.org/zookeeper-register-address | | Yes | Specify zookeeper address | +| shenyu.apache.org/plugin-motan-app-name | | Yes | Specify the metadata application name | +| shenyu.apache.org/plugin-motan-path | | Yes | Specify the request path for metadata | +| shenyu.apache.org/plugin-motan-rpc-type | | Yes | Specify the rpc type for metadata (dubbo, sofa, tars, springCloud, motan, grpc) | +| shenyu.apache.org/plugin-motan-service-name | | Yes | Specify the interface name for the metadata | +| shenyu.apache.org/plugin-motan-method-name | | Yes | Specifies the method name for metadata | +| shenyu.apache.org/plugin-motan-rpc-expand | | No | Specifies the rpc extension parameter (json object) for the metadata | +| shenyu.apache.org/plugin-motan-parameter-types | | Yes | Specify parameter types for metadata | + +### SpringCloud plugin + + + +| Name | Default | Required or not | Description | +| ----------------------------------------------------- | ------- | --------------- | ------------------------------------------------------------ | +| shenyu.apache.org/loadbalancer | random | No | Load balancing algorithm, optional hash, random, roundRobin, lastActive, p2c, shortestResponse | +| shenyu.apache.org/retry | 3 | No | Number of failed retries | +| shenyu.apache.org/timeout | 3000 | No | Backend request timeout in milliseconds | +| shenyu.apache.org/header-max-size | 10240 | No | Maximum request header size in bytes | +| shenyu.apache.org/request-max-size | 102400 | No | Maximum request body size in bytes | +| shenyu.apache.org/plugin-spring-cloud-enabled | | Yes | Determines whether to start the springCloud plugin | +| shenyu.apache.org/zookeeper-register-address | | Yes | Specify the zookeeper address | +| shenyu.apache.org/plugin-spring-cloud-app-name | | Yes | Specify the metadata application name | +| shenyu.apache.org/plugin-spring-cloud-path | | Yes | Specify the request path for metadata | +| shenyu.apache.org/plugin-spring-cloud-rpc-type | | Yes | Specify the rpc type (dubbo, sofa, tars, springCloud, motan, grpc) of the metadata | +| shenyu.apache.org/plugin-spring-cloud-service-name | | Yes | Specify the interface name for metadata | +| shenyu.apache.org/plugin-spring-cloud-method-name | | Yes | Specifies the method name for metadata | +| shenyu.apache.org/plugin-spring-cloud-rpc-expand | | No | Specifies the rpc extension parameter (json object) for the metadata | +| shenyu.apache.org/plugin-spring-cloud-parameter-types | | Yes | Specify parameter types for metadata | + +### WebSocket plugin + +| Name | Default | Required or not | Description | +| ---------------------------------- | ------- | --------------- | ------------------------------------------------------------ | +| shenyu.apache.org/loadbalancer | random | No | Load balancing algorithm, optional hash, random, roundRobin, lastActive, p2c, shortestResponse | +| shenyu.apache.org/retry | 3 | No | Number of failed retries | +| shenyu.apache.org/timeout | 3000 | No | Back-end request timeout in milliseconds | +| shenyu.apache.org/header-max-size | 10240 | No | Maximum request header size in bytes | +| shenyu.apache.org/request-max-size | 102400 | No | Maximum size of request body in byte | diff --git a/versioned_docs/version-2.6.1/user-guide/property-config/_category_.json b/versioned_docs/version-2.6.1/user-guide/property-config/_category_.json new file mode 100644 index 00000000000..b9d81b58d3e --- /dev/null +++ b/versioned_docs/version-2.6.1/user-guide/property-config/_category_.json @@ -0,0 +1,4 @@ +{ + "label": "Property Config", + "position": 2 +} diff --git a/versioned_docs/version-2.6.1/user-guide/property-config/admin-property-config.md b/versioned_docs/version-2.6.1/user-guide/property-config/admin-property-config.md new file mode 100644 index 00000000000..f3dd630d338 --- /dev/null +++ b/versioned_docs/version-2.6.1/user-guide/property-config/admin-property-config.md @@ -0,0 +1,270 @@ +--- +title: Admin Property Config +keywords: ["Config"] +description: Admin Property Config +--- + +This paper mainly explains how to configure Apache ShenYu properties on the admin side. + + + + +### Property Config + +```yaml +shenyu: + register: + registerType: http #http #zookeeper #etcd #nacos #consul + serverLists: #localhost:2181 #http://localhost:2379 #localhost:8848 + props: + sessionTimeout: 5000 + connectionTimeout: 2000 + checked: true + zombieCheckTimes: 5 + scheduledTime: 10 + nacosNameSpace: ShenyuRegisterCenter + sync: + websocket: + enabled: true + messageMaxSize: 10240 + allowOrigins: ws://localhost:9095;ws://localhost:9195; +# zookeeper: +# url: localhost:2181 +# sessionTimeout: 5000 +# connectionTimeout: 2000 +# http: +# enabled: true +# nacos: +# url: localhost:8848 +# namespace: 1c10d748-af86-43b9-8265-75f487d20c6c +# username: +# password: +# acm: +# enabled: false +# endpoint: acm.aliyun.com +# namespace: +# accessKey: +# secretKey: +# etcd: +# url: http://localhost:2379 +# consul: +# url: http://localhost:8500 + aes: + secret: + key: 2095132720951327 + iv: 6075877187097700 + ldap: + enabled: false + url: ldap://xxxx:xxx + bind-dn: cn=xxx,dc=xxx,dc=xxx + password: xxxx + base-dn: ou=xxx,dc=xxx,dc=xxx + object-class: person + login-field: cn + jwt: + expired-seconds: 86400000 + shiro: + white-list: + - / + - /favicon.* + - /static/** + - /index** + - /plugin + - /platform/** + - /websocket + - /configs/** + - /shenyu-client/** + - /error + - /actuator/health + - /swagger-ui.html + - /webjars/** + - /swagger-resources/** + - /v2/api-docs + - /csrf + swagger: + enable: true +``` + + +### Property Detail + +##### shenyu.register config + + +This section describes configurations related to client access. For details about client access principles, see: [Application Client Access](../../design/register-center-design) , for client access configuration, see: [Application Client Access Config](docs/user-guide/property-config/register-center-access.md) . + +|Name | Type | Default | Required | Description | +|:------------------------ |:----- |:-------: |:-------:|:----------------------------| +|registerType |String | http | Yes | Which mode to use for registry. Currently, http, zookeeper, etcd, consul and nacos are supported.| +|serverLists |String | null | No |Configure the address of the registry. If `http` is used, you do not need to enter this parameter. In clustering, multiple addresses are separated by commas (,).| +|props | | | | The value of the property varies according to the registerType.| + + +- `props` config + +The value of the attribute varies according to the registerType. + +When the registerType is `http`, the supported properties are as follows. + + +|Name | Type | Default | Required | Description | +|:------------------------ |:----- |:-------: |:-------:|:----------------------------| +|checked |boolean | false | No |is checked| +|zombieCheckTimes |int | 5 | No |how many times does it fail to detect the service.| +|scheduledTime |int | 10 | No | timed detection interval time| + +When the registerType is `zookeeper`, the supported properties are as follows. + +|Name | Type | Default | Required | Description | +|:------------------------ |:----- |:-------: |:-------:|:----------------------------| +|sessionTimeout | int | 30000 | No |session timeout(millisecond)| +|connectionTimeout | int | 3000 | No |connection timeout(millisecond)| + +When the registerType is `etcd`, no properties are provided for the time being. + +When the registerType is `nacos`, the supported properties are as follows. + +|Name | Type | Default | Required | Description | +|:------------------------ |:----- |:-------: |:-------:|:----------------------------| +|nacosNameSpace | String | null | Yes |namespace| +|username | String | "" | No |username| +|password | String | "" | No |password| +|accessKey | String | "" | No |accessKey| +|secretKey | String | "" | No |secretKey| + +When the registerType is `consul`, the supported properties are as follows. + +|Name | Type | Default | Required | Description | +|:------------------------ |:----- |:-------: |:-------:|:----------------------------| +|delay | int | 1 | No |The interval of each polling of monitoring metadata, in seconds, the default value is 1 second.| +|wait-time | int | 55 | No |# wait-time: The waiting time for each polling of metadata monitoring, in seconds, the default value is 55 second .| +|metadata-path | String | `shenyu/register` | No |Metadata path name, default is `shenyu/register`.| + + +When the registerType is `apollo`, the supported properties are as follows. + +| Name | Type | Default | Required | Description | +|:--------------|:-------|:-------:|:--------:|:---------------------| +| appId | String | null | Yes | Apollo appId | +| namespace | String | null | Yes | Apollo namespace | +| portalUrl | String | null | Yes | Apollo portalUrl | +| env | String | null | Yes | Apollo env | +| clusterName | String | null | Yes | Apollo clusterName | +| token | String | null | Yes | Apollo token | + + +##### shenyu.sync config + +The Admin System and the Apache ShenYu gateway use data synchronization configurations. + + +The following properties are configured for data synchronization using `websocket` : + +|Name | Type | Default | Required | Description | +|:------------------------ |:----- |:-------: |:-------:|:----------------------------| +|enabled | boolean | true | No |whether to enable websocket for data synchronization.| +|messageMaxSize | int | 0 | No |Set the `websocket` max buffer size in bytes.| +|allowOrigins | String | "" | No |Set allowed `origins`, multiple parameters separated by `;`.| + +The following properties are configured for data synchronization using `zookeeper` : + + +|Name | Type | Default | Required | Description | +|:------------------------ |:----- |:-------: |:-------:|:----------------------------| +|url | String | null | Yes |zookeeper server url| +|sessionTimeout | int | null | Yes |session timeout(millisecond)| +|connectionTimeout | int | null | Yes |connection timeout(millisecond)| + + +The following properties are configured for data synchronization using `http long polling` : + +|Name | Type | Default | Required | Description | +|:------------------------ |:----- |:-------: |:-------:|:----------------------------| +|enabled | boolean | true | No |whether to enable.| +|refreshInterval | int | 5(minute) | No |Periodically fetch data from the database and load it into memory.| +|notifyBatchSize | int | 100 | No |notify clients in batches| + + +The following properties are configured for data synchronization using `nacos` : + +|Name | Type | Default | Required | Description | +|:------------------------ |:----- |:-------: |:-------:|:----------------------------| +|url | String | null | 是 |nacos url| +|namespace | String | null | Yes |namespace| +|username | String | null | No |username| +|password | String | null | No |password| +|acm | | | No |aliyun ACM service configuration| + +- `acm` config + +|Name | Type | Default | Required | Description | +|:------------------------ |:----- |:-------: |:-------:|:----------------------------| +|enabled | boolean | false | No |whether to enable| +|endpoint | String | null | No |ACM service address| +|namespace | String | null | No |namespace| +|accessKey | String | null | No |accessKey| +|secretKey | String | null | No |secretKey| + + +The following properties are configured for data synchronization using `etcd` : + +|Name | Type | Default | Required | Description | +|:------------------------ |:----- |:-------: |:-------:|:----------------------------| +|url | String | null | Yes |etcd url| + + + +The following properties are configured for data synchronization using `consul` : + +|Name | Type | Default | Required | Description | +|:------------------------ |:----- |:-------: |:-------:|:----------------------------| +|url | String | null | Yes |consul url| + + +##### shenyu.aes.secret config + +aes secret properties: + + +|Name | Type | Default | Required | Description | +|:------------------------ |:----- |:-------: |:-------:|:----------------------------| +|key | String | `2095132720951327` | No |key| +|iv | String | null | No |iv| + + +##### shenyu.ldap config + +Spring ldap properties: + + +|Name | Type | Default | Required | Description | +|:------------------------ |:----- |:-------: |:-------:|:----------------------------| +|enabled | boolean | true | No |whether to enable| +|url | String | null | No |ldap url| +|bind-dn | String | null | No | UserDn | +|password | String | null | No |password| +|base-dn | String | null | No | searchBase | +|object-class | String | `person` | No | filter | +|login-field | String | `cn` | No | searchBase| +|connectTimeout | int | 3000 | No |connect timeout(millisecond)| +|readTimeout | int | 3000 | No |read timeout(millisecond)| + + +##### shenyu.jwt config + +`jwt` properties: + + +|Name | Type | Default | Required | Description | +|:------------------------ |:----- |:-------: |:-------:|:----------------------------| +| expired-seconds | long | 24 *60* 60 * 1000L | No |expiration time(millisecond)| + + +##### shenyu.shiro config + +`shiro` properties: + + +|Name | Type | Default | Required | Description | +|:------------------------ |:----- |:-------: |:-------:|:----------------------------| +| white-list | List | null | No |white list| diff --git a/versioned_docs/version-2.6.1/user-guide/property-config/client-property-config.md b/versioned_docs/version-2.6.1/user-guide/property-config/client-property-config.md new file mode 100644 index 00000000000..be863f087fb --- /dev/null +++ b/versioned_docs/version-2.6.1/user-guide/property-config/client-property-config.md @@ -0,0 +1,106 @@ +--- +title: Client Property Config +keywords: ["Config"] +description: Client Property Config +--- + +This paper mainly explains how to configure the properties of Apache ShenYu when the client accesses the gateway. + + +Set the `shenyu` property in your microservice, for example, in [shenyu-examples-http](https://github.com/apache/shenyu/tree/master/shenyu-examples/shenyu-examples-http) : + + + +### Property Config + +```yaml +shenyu: + client: + registerType: http #zookeeper #etcd #nacos #consul #apollo + serverLists: http://localhost:9095 #localhost:2181 #http://localhost:2379 #localhost:8848 #localhost:8080 + props: + contextPath: /http + appName: http + port: 8189 + nacosNameSpace: ShenyuRegisterCenter +``` + + +### Property Detail + +##### shenyu.client config + +This section describes configurations related to client access. For details about client access principles, see: [Application Client Access](../../design/register-center-design) , for client access configuration, see: [Application Client Access Config](register-center-access.md) . + + + +| Name | Type | Default | Required | Description | +|:-------------|:-------|:-------:|:--------:|:----------------------------------------------------------------------------------------------------------| +| registerType | String | http | Yes | Which mode to use for registry. Currently, http, zookeeper, etcd, consul ,apollo and nacos are supported. | +| serverLists | String | null | No | Configure the address of the registry. In clustering, multiple addresses are separated by commas (,). | +| props | | | | The value of the property varies according to the registerType. | + + + +- `props` config + +When microservices are built by different protocols, the property configuration is slightly different. The general attributes are as follows: + + + +|Name | Type | Default | Required | Description | +|:------------------------ |:----- |:-------: |:-------:|:----------------------------| +|contextPath |String | null | Yes |The route prefix of the microservice in the gateway.| +|appName |String | null | Yes |microservice name. `springcloud` service don't set, please set `spring.application.name`.| +|host |String | null | Yes | microservice address| +|port |int | null | Yes | microservice port| +|isFull |boolean | false | No | Whether to proxy the all service, currently just applies to `springmvc`/ `springcloud`| +|ipAndPort |String | null | No | Service IP and port address, currently just applies to `gRPC` Proxy.| +|shutdownWaitTime |int | 3000 | No | shutdown wait time(millisecond)| +|delayOtherHooksExecTime |int | 2000 | No | `hook` execute time(millisecond)| +|applicationShutdownHooksClassName |String | `java.lang.ApplicationShutdownHooks` | No | `hook` execute class name| +|applicationShutdownHooksFieldName |String | `hooks` | No | `hook` execute field name | + + +The value of the property varies according to the `registerType`. + +When the registerType is `nacos`, there has no other properties. + + + +When the registerType is `zookeeper`, the supported properties are as follows. + +|Name | Type | Default | Required | Description | +|:------------------------ |:----- |:-------: |:-------:|:----------------------------| +|sessionTimeout | int | 30000 | No |session time out(millisecond)| +|connectionTimeout | int | 3000 | No |connection time out(millisecond)| + +When the registerType is `etcd`, the supported properties are as follows. + +|Name | Type | Default | Required | Description | +|:------------------------ |:----- |:-------: |:-------:|:----------------------------| +|etcdTimeout | int | 30000 | No |etcd time out(millisecond)| +|etcdTTL | int | 5 | No |client lease time to live(second)| + +When the registerType is `nacos`, the supported properties are as follows. + +|Name | Type | Default | Required | Description | +|:------------------------ |:----- |:-------: |:-------:|:----------------------------| +|nacosNameSpace | String | null | Yes |namespace | +|username | String | "" | No |username| +|password | String | "" | No |password| +|accessKey | String | "" | No |accessKey| +|secretKey | String | "" | No |secretKey| + +When the registerType is `apollo`, the supported properties are as follows. + +| Name | Type | Default | Required | Description | +|:------------|:-------|:--------:|:--------:|:------------| +| appId | String | "shenyu" | Yes | appId | +| env | String | "" | Yes | env | +| clusterName | String | "" | Yes | clusterName | +| namespace | String | "" | Yes | namespace | +| token | String | "" | Yes | token | +| portalUrl | String | "" | Yes | portalUrl | + +When the registerType is `consul`, no other property configuration is provided. please set `spring.cloud.consul` for the configuration. diff --git a/versioned_docs/version-2.6.1/user-guide/property-config/gateway-property-config.md b/versioned_docs/version-2.6.1/user-guide/property-config/gateway-property-config.md new file mode 100644 index 00000000000..d7b90e98dee --- /dev/null +++ b/versioned_docs/version-2.6.1/user-guide/property-config/gateway-property-config.md @@ -0,0 +1,634 @@ +--- +title: Gateway Property Config +keywords: ["Config"] +description: Gateway Property Config +--- + +This paper mainly explains how to configure `Apache ShenYu` properties on the gateway side. + + + +### Property Config + +```yaml +shenyu: + selectorMatchCache: + ## selector L1 cache + cache: + enabled: false + initialCapacity: 10000 # initial capacity in cache + maximumSize: 10000 # max size in cache + ## selector L2 cache, use trie as L2 cache + trie: + enabled: false + cacheSize: 128 # the number of plug-ins + matchMode: antPathMatch + ruleMatchCache: + ## rule L1 cache + cache: + enabled: true + initialCapacity: 10000 # initial capacity in cache + maximumSize: 65536 # max size in cache + ## rule L2 cache, use trie as L2 cache + trie: + enabled: false + cacheSize: 1024 # the number of selectors + matchMode: antPathMatch + netty: + http: + webServerFactoryEnabled: true + selectCount: 1 + workerCount: 4 + accessLog: false + serverSocketChannel: + soRcvBuf: 87380 + soBackLog: 128 + soReuseAddr: true + connectTimeoutMillis: 30000 + writeBufferHighWaterMark: 65536 + writeBufferLowWaterMark: 32768 + writeSpinCount: 16 + autoRead: false + allocType: "pooled" + messageSizeEstimator: 8 + singleEventExecutorPerGroup: true + socketChannel: + soKeepAlive: false + soReuseAddr: true + soLinger: -1 + tcpNoDelay: true + soRcvBuf: 87380 + soSndBuf: 16384 + ipTos: 0 + allowHalfClosure: false + connectTimeoutMillis: 30000 + writeBufferHighWaterMark: 65536 + writeBufferLowWaterMark: 32768 + writeSpinCount: 16 + autoRead: false + allocType: "pooled" + messageSizeEstimator: 8 + singleEventExecutorPerGroup: true + instance: + enabled: false + registerType: zookeeper #etcd #consul + serverLists: localhost:2181 #http://localhost:2379 #localhost:8848 + props: +# httpclient: +# strategy: webClient +# connectTimeout: 45000 +# responseTimeout: 3000 +# readerIdleTime: 3000 +# writerIdleTime: 3000 +# allIdleTime: 3000 +# readTimeout: 3000 +# writeTimeout: 3000 +# wiretap: false +# keepAlive: false +# pool: +# type: ELASTIC +# name: proxy +# maxConnections: 16 +# acquireTimeout: 45000 +# maxIdleTime: 3000 +# proxy: +# host: +# port: +# username: +# password: +# nonProxyHostsPattern: +# ssl: +# useInsecureTrustManager: true +# keyStoreType: PKCS12 +# keyStorePath: classpath:keystore.p12 +# keyStorePassword: 123456 +# keyStoreProvider: +# keyPassword: 123456 +# trustedX509Certificates: +# handshakeTimeout: +# closeNotifyFlushTimeout: +# closeNotifyReadTimeout: +# defaultConfigurationType: + sync: + websocket: + urls: ws://localhost:9095/websocket + allowOrigin: ws://localhost:9195 +# zookeeper: +# url: localhost:2181 +# sessionTimeout: 5000 +# connectionTimeout: 2000 +# http: +# url: http://localhost:9095 +# nacos: +# url: localhost:8848 +# namespace: 1c10d748-af86-43b9-8265-75f487d20c6c +# username: +# password: +# acm: +# enabled: false +# endpoint: acm.aliyun.com +# namespace: +# accessKey: +# secretKey: +# etcd: +# url: http://localhost:2379 +# consul: +# url: http://localhost:8500 +# waitTime: 1000 +# watchDelay: 1000 + cross: + enabled: true + allowedHeaders: + allowedMethods: "*" + allowedAnyOrigin: false + allowedOrigin: + # format : schema://prefix spacer domain + # Access-Control-Allow-Origin: "http://a.apache.org,http://b.apache.org" + spacer: "." + domain: apache.org + prefixes: + - a # a.apache.org + - b # b.apache.org + origins: + - c.apache.org + - d.apache.org + - http://e.apache.org + originRegex: ^http(|s)://(.*\.|)abc.com$ + allowedExpose: "" + maxAge: "18000" + allowCredentials: true + switchConfig: + local: true + file: + enabled: true + maxSize : 10 + exclude: + enabled: false + paths: + - /favicon.ico + fallback: + enabled: false + paths: + - /fallback/hystrix + - /fallback/resilience4j + health: + enabled: false + paths: + - /actuator/health + - /health_check + alert: + enabled: true + admins: localhost:9095 + extPlugin: + path: + enabled: true + threads: 1 + scheduleTime: 300 + scheduleDelay: 30 + scheduler: + enabled: false + type: fixed + threads: 16 + upstreamCheck: + enabled: false + timeout: 3000 + healthyThreshold: 1 + unhealthyThreshold: 1 + interval: 5000 + printEnabled: true + printInterval: 60000 + ribbon: + serverListRefreshInterval: 10000 + metrics: + enabled: false + name : prometheus + host: 127.0.0.1 + port: 8090 + jmxConfig: + props: + jvm_enabled: true + sharedPool: + enable: true + prefix: "shenyu-shared" + corePoolSize: 200 + maximumPoolSize: 2000 + keepAliveTime: 60000 + maxWorkQueueMemory: 1073741824 # 1GB + maxFreeMemory: 268435456 # 256MB +``` + +### Property Detail + + + +##### shenyu.matchCache config + +* selector match cache + +| Field | Type | Default | Required | Description | +|-----------------|---------|---------|----------|-----------------------------------| +| enabled | Boolean | false | No | Whether to enable selector cache. | +| initialCapacity | Integer | 10000 | No | selector initial capacity | +| maximumSize | Integer | 10000 | No | selector max size | + +* selector trie cache + +| Field | Type | Default | Required | Description | +|--------------|---------|--------------|----------|-----------------------------------------------------------------------------------| +| enabled | Boolean | false | No | Whether to enable selector trie cache | +| cacheSize | Integer | 512 | No | trie cache size | +| matchMode | String | antPathMatch | Yes | path match mode, shenyu support two match modes, `antPathMatch` and `pathPattern` | + + +* rule match cache + +| Field | Type | Default | Required | Description | +|-----------------|---------|---------|----------|-------------------------------| +| enabled | Boolean | false | No | Whether to enable rule cache. | +| initialCapacity | Integer | 10000 | No | selector initial capacity | +| maximumSize | Integer | 10000 | No | selector max size | + +* rule trie cache + +| Field | Type | Default | Required | Description | +|--------------|---------|--------------|----------|-----------------------------------------------------------------------------------| +| enabled | Boolean | false | No | Whether to enable rule trie cache | +| cacheSize | Integer | 512 | No | trie cache size | +| matchMode | String | antPathMatch | Yes | path match mode, shenyu support two match modes, `antPathMatch` and `pathPattern` | + + +shenyu trie match support two match mode, we suggest use `pathPattern` as default match mode + +> pathPattern: org.springframework.web.util.pattern.PathPatternParser +> antPathMatch: org.springframework.util.AntPathMatcher + +when you mark `matchRestful` as true, we suggest mark all cache to `false` to avoid cache conflict. + +##### shenyu.NettyTcpProperties config + +The apache shenyu reactor-netty config. + +| Name | Type | Default | Required | Description | +|:------------------------------|:--------|:-------:|:--------:|:------------------------------------------------------------------------------------------------------------------------------------------| +| webServerFactoryEnabled | Boolean | true | No | Whether to enable custom parameters. True-enable. False-NettyReactiveWebServerFactory Can be configured by yourself. | +| selectCount | Integer | 1 | No | Number of netty selectors. | +| workerCount | Integer | 4 | No | Number of netty workers. | +| accessLog | Boolean | false | No | netty request parameters. | +| **ServerSocketChannelConfig** | | | | | +| soRcvBuf | Integer | -- | No | Socket config, the size of the socket receive buffer. The default value is system dependent. | +| soBackLog | Integer | 128 | No | Socket config, maximum length of the accept queue. | +| soReuseAddr | Boolean | true | No | Socket config, allow reuse of local addresses. The default value in reactor-netty is true. | +| connectTimeoutMillis | Integer | 30000 | No | Netty config, the connect timeout of the channel in milliseconds. | +| writeBufferHighWaterMark | Integer | 65536 | No | Netty config, the high water mark of the write buffer. | +| writeBufferLowWaterMark | Integer | 32768 | No | Netty config, the low water mark of the write buffer. | +| writeSpinCount | Integer | 16 | No | Netty config, the maximum loop count for a write operation. | +| autoRead | Boolean | false | No | Netty config, channel read method will be invoked automatically so that a user application doesn't need to call it at all. The default value in reactor-netty is false, and can only be false. | +| allocType | String | pooled | No | Netty config, set the ByteBufAllocator which is used for the channel to allocate buffers. | +| messageSizeEstimator | Integer | 8 | No | Netty config, message size estimator, estimate ByteBuf,ByteBufHolder and FileRegion size. | +| singleEventExecutorPerGroup | Boolean | true | No | Netty config, single thread execute the event of ChannelPipeline. | +| **SocketChannelConfig** | | | | | +| soKeepAlive | Boolean | false | No | Socket config, enable tcp keepalive. | +| soReuseAddr | Boolean | true | No | Socket config, allow reuse of local addresses. The default value in reactor-netty is true. | +| soLinger | Integer | -1 | No | Socket config, the delay time for closing the socket. | +| tcpNoDelay | Boolean | true | No | Socket config, enable Nagle algorithm. | +| soRcvBuf | Integer | -- | No | Socket config, the size of the socket receive buffer. The default value is system dependent. | +| soSndBuf | Integer | -- | No | Socket config, the size of the socket send buffer. The default value is system dependent. | +| ipTos | Integer | 0 | No | IP config, the Type of Service (ToS) octet in the Internet Protocol (IP) header. | +| allowHalfClosure | Boolean | false | No | Netty config, Sets whether the channel should not close itself when its remote peer shuts down output to make the connection half-closed. | +| connectTimeoutMillis | Integer | 30000 | No | Netty config, the connect timeout of the channel in milliseconds. | +| writeBufferHighWaterMark | Integer | 65536 | No | Netty config, the high water mark of the write buffer. | +| writeBufferLowWaterMark | Integer | 32768 | No | Netty config, the low water mark of the write buffer. | +| writeSpinCount | Integer | 16 | No | Netty config, the maximum loop count for a write operation. | +| autoRead | Boolean | false | No | Netty config, channel read method will be invoked automatically so that a user application doesn't need to call it at all. The default value in reactor-netty is false, and can only be false. | +| allocType | String | pooled | No | Netty config, set the ByteBufAllocator which is used for the channel to allocate buffers. | +| messageSizeEstimator | Integer | 8 | No | Netty config, message size estimator, estimate ByteBuf,ByteBufHolder and FileRegion size. | +| singleEventExecutorPerGroup | Boolean | true | No | Netty config, single thread execute the event of ChannelPipeline. | + +##### shenyu.register config + +This is the relevant configuration for the `ShenYu` gateway to register to the registration center. For the configuration of the registration center, please refer to [Register Center Instance Config](register-center-instance.md). + +| Name | Type | Default | Required | Description | +| :----------- | :-----: | :------------: | :------: | :----------------------------------------------------------- | +| enabled | boolean | false | Yes | Whether to start. | +| registerType | String | zookeeper | Yes | Which registry to use, currently supports zookeeper, etcd. | +| serverLists | String | localhost:2181 | Yes | The address of the register center. If using clusters, separate with `,`. | +| props | | | | When using different register types, the attribute values are different. | + +- `props` config + +When using different register center, the attribute values are different. + +When the registerType is `zookeeper`, the supported properties are as follows. + +|Name | Type | Default | Required | Description | +|:------------------------ |:----- |:-------: |:-------:|:----------------------------| +|sessionTimeout | int | 30000 | No |session time out(millisecond).| +|connectionTimeout | int | 3000 | No |connection time out(millisecond).| + +When the registerType is `etcd`, the supported properties are as follows. + +|Name | Type | Default | Required | Description | +|:------------------------ |:----- |:-------: |:-------:|:----------------------------| +|etcdTimeout | int | 30000 | No |etcd time out(millisecond).| +|etcdTTL | int | 5 | No |client lease time to live(second).| + +##### shenyu.httpclient config + +This is the HttpClient configuration used to send proxy requests after proxying the Http and SpringCloud protocols in the `ShenYu` gateway. + +| Name | Type | Default | Required | Description | +| :-------------- | :-----: | :-------: | :------: | :----------------------------------------------------------- | +| strategy | String | webClient | No | Type of http client, defaults to webClient.
- webClient: use by WebClientPlugin
- netty: use by NettyHttpClientPlugin. | +| connectTimeout | int | 45000 | No | Connection timeout (millisecond), the default value is 45000. | +| responseTimeout | int | 3000 | No | The response timeout (millisecond), the default value is 3000. | +| readerIdleTime | int | 3000 | No | The reader idle timeout (millisecond), the default value is 3000. | +| writerIdleTime | int | 3000 | No | The writer idle timeout (millisecond), the default value is 3000. | +| allIdleTime | int | 3000 | No | The all idle timeout (millisecond), the default value is 3000. | +| readTimeout | int | 3000 | No | Read timeout (millisecond), the default value is 3000. | +| writeTimeout | int | 3000 | No | Write timeout (millisecond), the default value is 3000. | +| wiretap | Boolean | false | No | Enables wiretap debugging for Netty HttpClient, the default value is 'false'. | +| keepAlive | Boolean | false | No | Enable or Disable Keep-Alive support for the outgoing request, the default value is 'false'. | +| pool | | | | HttpClient connection pool config. | +| proxy | | | | HttpClient proxy config. | +| ssl | | | | HttpClient ssl config. | + +- `pool` config + +HttpClient connection pool configuration: + +| Name | Type | Default | Required | Description | +| :------------- | :----: | :-------------------------------: | :------: | :----------------------------------------------------------- | +| type | String | ELASTIC | No | Type of pool for HttpClient to use, defaults to ELASTIC.
- ELASTIC: The connection pool can be cached and grown on demand
- FIXED: The connection pool cache and reuse a fixed maximum The number of connections.
- DISABLED: The connection pool will always create a new connection. | +| name | String | proxy | No | The channel pool map name, defaults to proxy. | +| maxConnections | int | the maximum value of 2*CPU and 16 | No | Only for type FIXED, the maximum number of connections before starting pending acquisition on existing ones.
the default value is available number of processors*2.
(but with a minimum value of 16). | +| acquireTimeout | int | 45000 | No | Only for type FIXED, the maximum time in millis to wait for acquiring. the default value is 45000. | +| maxIdleTime | int | NULL | No | After which the channel will be closed, if NULL there is no max idle time. | + +- `proxy` config + +Netty HttpClient proxy configuration: + +| Name | Type | Default | Required | Description | +| :------------------- | :----: | :-----: | :------: | :----------------------------------------------------------- | +| host | String | null | No | Hostname for proxy configuration of Netty HttpClient. | +| port | String | null | No | Port for proxy configuration of Netty HttpClient. | +| username | String | null | No | Username for proxy configuration of Netty HttpClient. | +| password | String | null | No | Password for proxy configuration of Netty HttpClient. | +| nonProxyHostsPattern | String | null | No | Regular expression (Java) for a configured list of hosts. that should be reached directly, bypassing the proxy. | + +- `SSL` config + +Gateway routing can support routing to http and https back-end services at the same time. The following is the SSL-related configuration: + +| Name | Type | Default | Required | Description | +| :----------------------- | :-----: | :-----: | :------: | :----------------------------------------------------------- | +| useInsecureTrustManager | Boolean | false | No | Installs the netty InsecureTrustManagerFactory. This is insecure and not suitable for production. | +| keyStoreType | String | PKCS12 | No | SSL key store type. | +| keyStorePath | String | | No | SSL key store path. | +| keyStorePassword | String | | No | SSL key store pass word. | +| keyStoreProvider | String | | No | SSL Keystore provider for netty httpClient and webclient. | +| keyPassword | String | | No | SSL key pass word. | +| trustedX509Certificates | String | Null | No | Trusted certificates for verifying the remote endpoint's certificate.(Use `,` to separate multiple values) | +| handshakeTimeout | int | 10000 | No | SSL handshake timeout. Default to 10000 ms | +| closeNotifyFlushTimeout | int | 3000 | No | SSL close_notify flush timeout. Default to 3000 ms. | +| closeNotifyReadTimeout | int | 0 | No | SSL close_notify read timeout. Default to 0 ms. | +| defaultConfigurationType | String | TCP | No | The default ssl configuration type. Defaults to TCP.
- H2: SslProvider will be set depending on OpenSsl.isAlpnSupported(), SslProvider.HTTP2_CIPHERS, ALPN support, HTTP/1.1 and HTTP/2 support.
- TCP: [`SslProvider`](https://netty.io/4.1/api/io/netty/handler/ssl/SslProvider.html?is-external=true) will be set depending on `OpenSsl.isAvailable()`.
- NONE: There will be no default configuration. | + +##### Filter Configuration + +- `shenyu.file` config + +File filter properties. + +|Name | Type | Default | Required | Description | +|:------------------------ |:----- |:-------: |:-------:|:----------------------------| +| enabled | Boolean | false | No | enable file size filtering | +| maxSize | Integer | 10 | No | upload file maxSize (MB) | + + +- `shenyu.cross` config + +Cross filter properties: + + +|Name | | Type | Default | Required | Description | +|:------------------------ |:----- |:-------: |:-------:|:----------------------------|:---------------------------:| +| enabled | | Boolean | false | No | allow cross-domain requests | +| allowedHeaders | | String | x-requested-with, authorization, Content-Type, Authorization, credential, X-XSRF-TOKEN, token, username, client | No | allowedHeaders, Use "," split in multiple cases. the new "allowedHeaders" will append to "Access-Control-Allow-Headers" based on the default value and remove the reduplicative header. | +| allowedMethods | | String | "*" | No | allowedMethods | +| allowedAnyOrigin | | Boolean | false | No | Whether to allow any Origin, if it is true, directly set the `Access-Control-Allow-Origin` to the same value as the Origin, that is, `request.getHeaders().getOrigin()`, and discard the `allowedOrigin` configuration. | +| allowedOrigin | | AllowedOriginConfig | - | No | Set the allowed request sources. | +| | spacer | String | "" | No | Set the allowed subdomains, need to use with `domain`, `prefixes`. | +| | domain | String | "" | No | Set the allowed subdomains, need to use with `spacer`, `prefixes`. | +| | prefixes | Set | [] | No | Set the allowed subdomains, need to use with `spacer`, `domain`. | +| | origins | Set | null | No | Set the domain names that are allowed to be accessed, which can be used separately. | +| | originRegex | String | "" | No | Set up access to domains that allow regular matching, available separately. | +| allowedExpose | | String | "" | No | allowedExpose | +| maxAge | | String | "18000" | No | maxAge (ms) | +| allowCredentials | | Boolean | true | No | allowCredentials | + + +- `shenyu.exclude` config + +Exculde filter properties. + +|Name | Type | Default | Required | Description | +|:------------------------ |:----- |:-------: |:-------:|:----------------------------| +| enabled | Boolean | false | No | whether to enable `exclude filter` and reject the specified request to pass through the gateway. | +| paths | Array | null | Yes | Requests matching this list can not pass through the gateway (support Path-Matching). | + +- `shenyu.fallback` config + +Related configuration of fallback response. + +| Name | Type | Default | Required | Description | +| :------ | :------ | :-----: | :------: | :---------------------------------------- | +| enabled | Boolean | false | No | Whether to turn on the fallback response. | +| paths | Array | [] | Yes | Address of the service fallback request. | + +- `shenyu.health` config + +Configuration related to service health status. + +| Name | Type | Default | Required | Description | +| :------ | :------ |:----------------------------------------:| :------: | :-------------------------------------- | +| enabled | Boolean | false | No | Whether to turn on health detection. | +| paths | Array | `"/actuator/health"` 、`"/health_check"` | No | Set up service health monitoring paths. | + +- `shenyu.local` config + +Local forwarding-related configuration. + +| Name | Type | Default | Required | Description | +| :-------- | :------ | :-----: | :------: | :----------------------------------------------------------- | +| enabled | Boolean | false | No | Whether to enable local forwarding. | +| sha512Key | String | "" | Yes | Secret key, according to the secret key to determine whether the need for local forwarding. | + +##### shenyu.switchConfig config + +The apache shenyu switch configuration. + +| Name | Type | Default | Required | Description | +| :---- | :------ | :-----: | :------: | :----------------------------------------------------------- | +| local | Boolean | true | No | Whether to open local mode, if so, local operation data, default open. | + +##### shenyu.sync config + +The apache shenyu gateway and the Admin System use data synchronization configurations. + + +The following properties are configured for data synchronization using `websocket` : + +|Name | Type | Default | Required | Description | +|:------------------------ |:----- |:-------: |:-------:|:----------------------------| +| urls | String | null | Yes | The websocket server address of `Admin`, separate multiple addresses with `,`. | +| allowOrigin | String | "" | No | Set the allowed `origins`, with multiple parameters separated by `;`. | + + + +The following properties are configured for data synchronization using `zookeeper` : + + +|Name | Type | Default | Required | Description | +|:------------------------ |:----- |:-------: |:-------:|:----------------------------| +|url | String | null | Yes |zookeeper server url.| +|sessionTimeout | int | null | Yes |session timeout (millisecond).| +|connectionTimeout | int | null | Yes |connection timeout (millisecond).| + + + +The following properties are configured for data synchronization using `http long polling` : + +|Name | Type | Default | Required | Description | +|:------------------------ |:----- |:-------: |:-------:|:----------------------------| +| url | String | null | Yes | `Admin` server address. | + + + +The following properties are configured for data synchronization using `nacos` : + +|Name | | Type | Default | Required | Description | +|:------------------------ |:----- |:-------: |:-------:|:---------|:---------------------------:| +|url | | String | null | Yes |nacos url| +|namespace | | String | null | Yes |namespace| +|username | | String | null | No |username| +|password | | String | null | No |password| +|acm | | Object | - | No |aliyun ACM service configuration.| +| |enabled | boolean | false | No |whether to enable.| +| |endpoint | String | null | No |ACM service address.| +| |namespace | String | null | No |namespace.| +| |accessKey | String | null | No |accessKey.| +| |secretKey | String | null | No |secretKey.| + +The following properties are configured for data synchronization using `apollo` : + +| Name | | Type | Default | Required | Description | +|:------------|:----|:------:|:-------:|:---------|:-----------:| +| namespace | | String | null | Yes | namespace | +| appId | | String | null | Yes | appId | +| token | | String | null | Yes | token | +| clusterName | | String | default | Yes | cluster | +| portalUrl | | String | null | Yes | portalUrl | +| meta | | String | null | Yes | meta | +| env | | String | null | Yes | env | + + + +The following properties are configured for data synchronization using `etcd` : + +|Name | Type | Default | Required | Description | +|:------------------------ |:----- |:-------: |:-------:|:----------------------------| +|url | String | null | Yes |`etcd` server url.| + + + +The following properties are configured for data synchronization using `consul` : + +|Name | Type | Default | Required | Description | +|:------------------------ |:----- |:-------: |:-------:|:----------------------------| +|url | String | null | Yes |`consul` server url.| +| waitTime | int | null | Yes | the timeout period for requesting consul service to pull configuration information (milliseconds). | +|watchDelay | int | null | Yes |Synchronization interval (milliseconds).| + +##### shenyu.extPlugin config + +The apache shenyu supports dynamic loading of custom plug-ins with the following configuration + +|Name | Type | Default | Required | Description | +|:------------------------ |:----- |:-------: |:-------:|:----------------------------| +| enabled | Boolean | true | No | open dynamic loading of custom plug-ins. | +| path | String | | False | custom plugins path, if not config, the path is /ext/lib. | +| threads | Integer | 1 | False | threads for dynamic loading custom plug-ins. | +| scheduleTime | Integer | 300 | False | schedule time (s) for dynamic loading custom plug-ins. | +| scheduleDelay | Integer | 30 | False | schedule delay when app startup. | + +##### shenyu.scheduler config + +Scheduler config for apache shenyu scheduler thread model. + +|Name | Type | Default | Required | Description | +|:------------------------ |:----- |:-------: |:-------:|:----------------------------| +| enabled | Boolean | false | No | Whether to turn on Scheduler Thread Model. | +| type | String | fixed | False | fixed Thread Pool or elastic Scheduler Thread Model. | +| threads | Integer | Math.max((Runtime.getRuntime().availableProcessors() << 1) + 1, 16) | False | threads for fixed Thread Pool. | + +##### shenyu.upstreamCheck config + +UpstreamCheck config is the configuration used by apache shenyu to detect upstream. + +|Name | Type | Default | Required | Description | +|:------------------------ |:----- |:-------: |:-------:|:----------------------------| +| enabled | Boolean | false | No | Whether to turn on upstreamCheck. | +| timeout | Integer | 3000 | No | timeout (ms). | +| healthyThreshold | Integer | 1 | No | healthyThreshold. | +| unhealthyThreshold | Integer | 1 | No | unhealthyThreshold. | +| interval | Integer | 5000 | No | schedule time (ms) for checked. | +| printEnabled | Boolean | true | No | Whether to turn on print logs. | +| printInterval | Integer | 60000 | No | schedule time (ms) for print logs. | + +##### shenyu.ribbon config + +The apache shenyu polling interval configuration. + +| Name | Type | Default | Required | Description | +| :------------------------ | :------ | :-----: | :------: | :----------------------------------------------------------- | +| serverListRefreshInterval | Integer | 10000 | No | Adjust the refresh interval parameter, refer to`com.netflix.client.config.CommonClientConfigKey#ServerListRefreshInterval`. | + +##### shenyu.metrics config + +The apache shenyu metrics config,the gateway is used to monitor its own operational status. + +| Name | | Type | Default | Required | Description | +| :-------- | :---------- | :-----: | :-----: | :------- | ------------------------------------------------------------ | +| enabled | | Boolean | false | No | Whether to enable metrics, true means enable. | +| name | | String | "" | No | name. | +| host | | String | "" | No | IP exposed by the gateway service to the collection service. | +| port | | Integer | Null | No | Port exposed by the gateway service to the collection service. | +| jmxConfig | | String | "" | No | jmx config. | +| props | | - | | No | properties. | +| | jvm_enabled | Boolean | Null | No | Turn on jvm's monitoring metrics. | + +##### shenyu.sharedPool config + +The apache shenyu shared thread pool configuration. + +| Name | Type | Default | Required | Description | +| :----------------- | ------- | :---------------------------------------------- | :------: | :-------------------------------------------------: | +| enabled | Boolean | false | No | Whether to enable shared thread pooling. | +| prefix | String | "shenyu-shared" | No | Thread pool name prefix. | +| corePoolSize | Integer | 200 | No | Number of core threads in the thread pool. | +| maximumPoolSize | Integer | Integer.MAX_VALUE | No | Maximum number of threads in the thread pool. | +| keepAliveTime | Long | 60000L | No | Excess idle thread keepAlive time, in milliseconds. | +| maxWorkQueueMemory | Long | 80% of the current JVM maximum available memory | No | Maximum memory used (byte). | +| maxFreeMemory | Integer | 无 | No | Maximum remaining memory (byte). | + +##### shenyu.alert config + +The apache shenyu alert notice configuration. + +| Name | Type | Default | Required | Description | +| :----------------- | ------- |:------------------------------------------------| :------: |:-------------------------------------------------:| +| enabled | Boolean | false | No | Whether to enable alarm message. | +| admins | String | "localhost:9095" | No | Report alarm message to shenyu admin server list. | + diff --git a/versioned_docs/version-2.6.1/user-guide/property-config/register-center-access.md b/versioned_docs/version-2.6.1/user-guide/property-config/register-center-access.md new file mode 100644 index 00000000000..e3f23d21ed0 --- /dev/null +++ b/versioned_docs/version-2.6.1/user-guide/property-config/register-center-access.md @@ -0,0 +1,109 @@ +--- +title: Application Client Access Config +keywords: ["register center"] +description: register center access +--- + +> *Notice* +> After ShenYu version 2.6.1, the ShenYu register just support http type, and the middleware register type has been removed. +> So, please use the http register type to register your service. +> ShenYu Register Center isn't microservice register center, it just register metadata, selector data, rule data to shenyu-admin, and then shenyu-admin will sync data to shenyu-gateway. + +Application client access means to access your microservice to ShenYu gateway, currently supports HTTP, Dubbo, Spring Cloud, gRPC, Motan, Sofa, Tars and other protocols access. Currently, ShenYu just support HTTP register type. + +This article describes how to configure the application client to access the Apache ShenYu gateway. For related principles, see [Application Client Access](../../design/register-center-design) in the design document . + + + + +### Http Registry Config + +#### shenyu-admin config + +Set the register type to '`Http` in the `yml` file. The configuration information is as follows: + +```yaml +shenyu: + register: + registerType: http + props: + checked: true # is checked + zombieCheckTimes: 5 # how many times does it fail to detect the service + scheduledTime: 10 # timed detection interval time +``` + + + + +#### shenyu-client config + +The following shows the configuration information registered through `Http` when the `Http` service accesses the `Apache ShenYu` gateway as a client. Other clients (such as `Dubbo` and `Spring Cloud`) can be configured in the same way. + +```yaml +shenyu: + register: + registerType: http + serverLists: http://localhost:9095 + props: + username: admin + password: 123456 + client: + http: + props: + contextPath: /http + appName: http + port: 8188 + isFull: false +# registerType : register type, set http +# serverList: when register type is http,set shenyu-admin address list,pls note 'http://' is necessary. +# port: your project port number; apply to springmvc/tars/grpc +# contextPath: your project's route prefix through shenyu gateway, such as /order ,/product etc,gateway will route based on it. +# appName:your project name,the default value is`spring.application.name`. +# isFull: set true means providing proxy for your entire service, or only a few controller. apply to springmvc/springcloud +``` + + + + +### Register different type API at same time + +> follow example use the http and dubbo. + +the `yml` configuration like follow: + +```yaml +shenyu: + register: + registerType: http + serverLists: localhost:9195 + props: + username: admin + password: 123456 + client: + http: + props: + contextPath: /http + appName: http + port: 8188 + isFull: false + dubbo: + props: + contextPath: /dubbo + appName: dubbo + port: 28080 + props: + nacosNameSpace: ShenyuRegisterCenter +# registerType : register type, set nacos +# serverList: when register type is nacos, add nacos address list +# http.port: your project port number; apply to springmvc +# http.contextPath: your project's route prefix through shenyu gateway, such as /order ,/product etc,gateway will route based on it. +# http.appName:your project name,the default value is`spring.application.name`. +# http.isFull: set true means providing proxy for your entire service, or only a few controller. apply to springmvc/springcloud +# dubbo.contextPath: your project dubbo service's context path +# dubbo.port: your project dubbo rpc port +# dubbo.appName: your project dubbo application name +# nacosNameSpace: nacos namespace +``` + +In conclusion, this paper mainly describes how to connect your microservices (currently supporting `Http`, `Dubbo`, `Spring Cloud`, `gRPC`, `Motan`, `Sofa`, `Tars` and other protocols) to the `Apache ShenYu` gateway. the Apache ShenYu gateway support registry has `Http` This paper introduces the different ways to register configuration information when `Http` service is used as the client to access `Apache ShenYu` gateway. + diff --git a/versioned_docs/version-2.6.1/user-guide/property-config/register-center-instance.md b/versioned_docs/version-2.6.1/user-guide/property-config/register-center-instance.md new file mode 100644 index 00000000000..0e41c573766 --- /dev/null +++ b/versioned_docs/version-2.6.1/user-guide/property-config/register-center-instance.md @@ -0,0 +1,72 @@ +--- +title: Register Center Instance Config +keywords: ["register center"] +description: Register Instance +--- + +This document will introduce how to register the gateway instance to the registry. The `Apache ShenYu` gateway currently supports registration to `zookeeper` , `etcd` and `consul`. + +### Add Maven dependency + +First, introduce the following dependencies in the gateway's `pom.xml` file. + +```xml + + + org.apache.shenyu + shenyu-spring-boot-starter-registry + ${project.version} + + +``` + +### Use zookeeper + +> Please pay attention! From ShenYu 2.5.0, ShenYu will no longer support Zookeeper 3.4.x or below version. If you're already using Zookeeper, You need to use Zookeeper with a higher version and initialize the data. + +Add the following configuration to the gateway's `yml` file: + +```yaml +registry: + enabled: true + registerType: zookeeper + serverLists: localhost:2181 #config with your zk address, used by the cluster environment, separated with (,). + props: + sessionTimeout: 3000 #Optional, default 3000 + connectionTimeout: 3000 #Optional, default 3000 +``` + +### Use etcd + +Add the following configuration to the gateway's `yml` file: + +```yaml +registry: + enabled: true + registerType: etcd + serverLists: http://localhost:2379 #config with your etcd address, used by the cluster environment, separated with (,). + props: + etcdTimeout: 3000 #Optional, default 3000 + etcdTTL: 5 #Optional, default 5 +``` + +### Use apollo + +Add the following configuration to the gateway's `yml` file: + +```yaml +registry: + enabled: true + registerType: apollo + serverLists: http://localhost:8080 + props: + env: dev + appId: shenyu + namespace: application + clusterName: default + token: 0fff5645fc74ee5e0d63a6389433c8c8afc0beea31eed0279ecc1c8961d12da9 + portalUrl: http://localhost:8070 +``` + + +> After the configuration is complete, start the gateway and it will successfully register to the corresponding registration center. diff --git a/versioned_docs/version-2.6.1/user-guide/property-config/use-data-sync.md b/versioned_docs/version-2.6.1/user-guide/property-config/use-data-sync.md new file mode 100644 index 00000000000..4aef68576a6 --- /dev/null +++ b/versioned_docs/version-2.6.1/user-guide/property-config/use-data-sync.md @@ -0,0 +1,378 @@ +--- +title: Data Synchronization Config +keywords: ["Data Synchronization"] +description: use different data-sync strategy +--- + +This document focuses on how to use different data synchronization strategies. Data synchronization refers to the strategy used to synchronize data to ShenYu gateway after shenyu-admin background operation data. ShenYu gateway currently supports ZooKeeper, WebSocket, HTTP Long Polling, Nacos, Etcd and Consul for data synchronization. + + + + +For details about the data synchronization principles, see [Data Synchronization Design](../../design/data-sync) in the design document. + +### WebSocket Synchronization Config(default strategy, recommend) + +* `Apache ShenYu` gateway config + + Add these dependencies in `pom.xml`: + +```xml + + + org.apache.shenyu + shenyu-spring-boot-starter-sync-data-websocket + ${project.version} + +``` + + + + +Add these config values in yaml file: + +```yaml +shenyu: + sync: + websocket : + # urls: address of shenyu-admin,multi-address will be separated with (,). + urls: ws://localhost:9095/websocket + allowOrigin: ws://localhost:9195 +``` + + + +* `shenyu-admin` config + + Add these config values in yaml file: + +```yml +shenyu: + sync: + websocket: + enabled: true +``` + + + +After the connection is established, the data will be fully obtained once, and the subsequent data will be updated and added increments, with good performance. It also supports disconnection (default: `30` seconds). This mode is recommended for data synchronization and is the default data synchronization strategy of ShenYu. + +### Zookeeper Synchronization Config + +> Please pay attention! From ShenYu 2.5.0, ShenYu will no longer support Zookeeper 3.4.x or below version. If you're already using Zookeeper, You need to use Zookeeper with a higher version and initialize the data. + +* `Apache ShenYu` gateway config + + Add these dependencies in `pom.xml`: + + ```xml + + + org.apache.shenyu + shenyu-spring-boot-starter-sync-data-zookeeper + ${project.version} + + ``` + + + + +Add these config values in yaml file: + + +```yaml +shenyu: + sync: + zookeeper: + url: localhost:2181 + #url: config with your zk address, used by the cluster environment, separated with (,). + sessionTimeout: 5000 + connectionTimeout: 2000 +``` + + + + +* `shenyu-admin` config + +Add these config values in yaml file: + + +```yaml +shenyu: + sync: + zookeeper: + url: localhost:2181 + #url: config with your zk address, used by the cluster environment, separated with (,). + sessionTimeout: 5000 + connectionTimeout: 2000 +``` + + + + + +It is a good idea to use ZooKeeper synchronization mechanism with high timeliness, but we also have to deal with the unstable environment of ZK, cluster brain splitting and other problems. + + + +### HTTP Long Polling Synchronization Config + +* `Apache ShenYu` gateway config + +Add these dependencies in `pom.xml`: + +```xml + + + org.apache.shenyu + shenyu-spring-boot-starter-sync-data-http + ${project.version} + +``` + + + + +Add these config values in yaml file: + +```yaml +shenyu: + sync: + http: + url: http://localhost:9095 + #url: config your shenyu-admin ip and port,cluster IP by split by (,) +``` + + + + +* `shenyu-admin` config + + Add these config values in yaml file: + +```yaml +shenyu: + sync: + http: + enabled: true +``` + + + + +HTTP long-polling makes the gateway lightweight, but less time-sensitive. It pulls according to the group key, if the data is too large, it will have some influences, a small change under a group will pull the entire group. + + + +### Nacos Synchronization Config + +* `Apache ShenYu` gateway config + + +Add these dependencies in `pom.xml`: + +```xml + + + org.apache.shenyu + shenyu-spring-boot-starter-sync-data-nacos + ${project.version} + +``` + + + + +Add these config values in yaml file: + +```yaml +shenyu: + sync: + nacos: + url: localhost:8848 + # url: config with your nacos address, please use (,) to split your cluster environment. + namespace: 1c10d748-af86-43b9-8265-75f487d20c6c + username: + password: + acm: + enabled: false + endpoint: acm.aliyun.com + namespace: + accessKey: + secretKey: + # other configure,please refer to the naocs website. +``` + + + + +* `shenyu-admin` config + + Add these config values in yaml file: + +```yaml +shenyu: + sync: + nacos: + url: localhost:8848 + namespace: 1c10d748-af86-43b9-8265-75f487d20c6c + username: + password: + acm: + enabled: false + endpoint: acm.aliyun.com + namespace: + accessKey: + secretKey: + # url: config with your nacos address, pls use (,) to split your cluster environment. + # other configure,pls refer to the naocs website. +``` + + + + +### Etcd Synchronization Config + +* `Apache ShenYu` gateway config + + Add these dependencies in `pom.xml`: + +```xml + + + org.apache.shenyu + shenyu-spring-boot-starter-sync-data-etcd + ${project.version} + + + io.grpc + grpc-grpclb + + + io.grpc + grpc-netty + + + +``` + + + +Add these config values in yaml file: + +```yaml +shenyu: + sync: + etcd: + url: http://localhost:2379 + #url: config with your etcd address, used by the cluster environment, separated with (,). +``` + + + + +* `shenyu-admin` config + + Add these config values in yaml file: + +```yaml +shenyu: + sync: + etcd: + url: http://localhost:2379 + #url: config with your etcd address, used by the cluster environment, separated with (,). +``` + + + + +### Consul Synchronization Config + +* `Apache ShenYu` gateway config + +Add these dependencies in `pom.xml`: + +```xml + + + org.apache.shenyu + shenyu-spring-boot-starter-sync-data-consul + ${project.version} + +``` + + + + +Add these config values in yaml file: + +```yaml +shenyu: + sync: + consul: + url: http://localhost:8500 + waitTime: 1000 # query wait time + watchDelay: 1000 # Data synchronization interval +``` + + + + +* `shenyu-admin` config + + Add these config values in yaml file: + +```yaml +shenyu: + sync: + consul: + url: http://localhost:8500 +``` + + + +### Apollo Synchronization Config + +Apollo just support Java [8,17), if you want to use apollo as data sync center, please make sure your JDK version is between [8,17). + +* `Apache ShenYu` gateway config + +Download the corresponding version of the jar package from `https://repo1.maven.org/maven2/org/apache/shenyu/shenyu-spring-boot-starter-sync-data-apollo/`, and then put the jar package into the `/lib` directory. + +Add these config values in yaml file: + +```yaml +shenyu: + sync: + apollo: + appId: shenyu + meta: http://localhost:8080 + env: dev + clusterName: test + namespace: application +``` + +* `Apache ShenYu Admin` config + +Download the corresponding version of the jar package from `https://repo1.maven.org/maven2/org/apache/shenyu/shenyu-admin-listener-apollo/`, and then put the jar package into the `/lib` directory. + + +```yaml +shenyu: + sync: + apollo: + meta: http://localhost:8080 + appId: shenyu + portalUrl: http://localhost:8070 + env: dev + clusterName: test + namespace: application + token: 0fff5645fc74ee5e0d63a6389433c8c8afc0beea31eed0279ecc1c8961d12da9 +``` + + + + +> After the data synchronization strategy of Apache ShenYu gateway and shenyu-admin is reconfigured, the microservice needs to be restarted. +> the Apache ShenYu gateway and shenyu-admin must use the same synchronization strategy. diff --git a/versioned_docs/version-2.6.1/user-guide/proxy/_category_.json b/versioned_docs/version-2.6.1/user-guide/proxy/_category_.json new file mode 100644 index 00000000000..fce38607773 --- /dev/null +++ b/versioned_docs/version-2.6.1/user-guide/proxy/_category_.json @@ -0,0 +1,4 @@ +{ + "label": "Quick Connect to Your Service", + "position": 4 +} diff --git a/versioned_docs/version-2.6.1/user-guide/proxy/dubbo-proxy.md b/versioned_docs/version-2.6.1/user-guide/proxy/dubbo-proxy.md new file mode 100644 index 00000000000..2af957035f7 --- /dev/null +++ b/versioned_docs/version-2.6.1/user-guide/proxy/dubbo-proxy.md @@ -0,0 +1,437 @@ +--- +title: Dubbo Proxy +keywords: ["Dubbo"] +description: Dubbo Client Access +--- + +This document is intended to help the `Dubbo` service access the `Apache ShenYu` gateway. The `Apache ShenYu` gateway uses the `Dubbo` plugin to handle `dubbo` service. + +Support Alibaba Dubbo(< 2.7.x) and Apache Dubbo (>=2.7.x). + +Before the connection, start `shenyu-admin` correctly, start `Dubbo` plugin, and add related dependencies on the gateway and `Dubbo` application client. Refer to the previous [Quick start with Dubbo](../../quick-start/quick-start-dubbo) . + +For details about client access configuration, see [Application Client Access Config](../property-config/register-center-access.md) . + +For details about data synchronization configurations, see [Data Synchronization Config](../property-config/use-data-sync.md) . + +## Add dubbo plugin in gateway + +Add these dependencies in gateway's `pom.xml`. + +Alibaba dubbo user, configure the dubbo version and registry center with yours. + +```xml + + + org.apache.shenyu + shenyu-spring-boot-starter-client-alibaba-dubbo + ${project.version} + + + + com.alibaba + dubbo + 2.6.5 + + + org.apache.curator + curator-client + 4.0.1 + + + org.apache.curator + curator-framework + 4.0.1 + + + org.apache.curator + curator-recipes + 4.0.1 + +``` + +Apache dubbo user, configure the dubbo version and registry center with yours. + +```xml + + + org.apache.shenyu + shenyu-spring-boot-starter-client-apache-dubbo + ${project.version} + + + + + org.apache.dubbo + dubbo + 2.7.5 + + + + org.apache.dubbo + dubbo-registry-nacos + 2.7.5 + + + com.alibaba.nacos + nacos-client + 1.1.4 + + + + + + org.apache.curator + curator-client + 4.0.1 + + + org.apache.curator + curator-framework + 4.0.1 + + + org.apache.curator + curator-recipes + 4.0.1 + + +``` + +* restart gateway service. + +## Dubbo service access gateway + +Dubbo integration with gateway, please refer to : [shenyu-examples-dubbo](https://github.com/apache/shenyu/tree/master/shenyu-examples/shenyu-examples-dubbo) . + +* Alibaba Dubbo User + * SpringBoot + + Add these dependencies: + + ```xml + + org.apache.shenyu + shenyu-spring-boot-starter-client-alibaba-dubbo + ${shenyu.version} + + ``` + + * Spring + + Add these dependencies: + + ```xml + + org.apache.shenyu + shenyu-client-alibaba-dubbo + ${shenyu.version} + + ``` + + Inject these properties into your Spring beans XML file: + + ```xml + + + + + + + + + + + + + + + + + + + + + + + ``` + +* Apache Dubbo User + + * SpringBoot + + Add these dependencies: + + ```xml + + org.apache.shenyu + shenyu-spring-boot-starter-client-apache-dubbo + ${shenyu.version} + + ``` + + Add these in your client project's application.yml: + + ```yml + dubbo: + registry: + address: dubbo register address + port: dubbo service port + + shenyu: + register: + registerType: shenyu service register type #http #zookeeper #etcd #nacos #consul + serverLists: shenyu service register address #http://localhost:9095 #localhost:2181 #http://localhost:2379 #localhost:8848 + client: + dubbo: + props: + contextPath: /your contextPath + appName: your app name + ``` + + * Spring + + Add these dependencies: + + ```xml + + org.apache.shenyu + shenyu-client-apache-dubbo + ${shenyu.version} + + ``` + + Injecct these properties into your Spring beans XML file: + + ```xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ``` + + Add these in your client project's application.yml: + + ```yml + dubbo: + registry: + address: dubbo register address + port: dubbo service port + ``` + +## Dubbo configuration + +* Enable `dubbo` option in `shenyu-admin`. +* Configure your registry address in `dubbo`. + +```yaml +{"register":"zookeeper://localhost:2181"} or {"register":"nacos://localhost:8848"} +``` + +### Configure the interface with gateway + +* you can add the annotation `@ShenyuDubboClient` to your dubbo service implementation class, so that the interface method will be configured with gateway. + +* Start your provider. After successful startup, go to PluginList -> rpc Proxy -> dubbo in the backend management system. You will see auto-registered selectors and rules information. + +### Dubbo user request and parameter explanation. + +* Communicate with dubbo service through Http transport protocol. +* Apache ShenYu gateway need a route prefix which configured when accessing the project. + +```yaml +# for example: you have an order service and it has a interface, registry address: /order/test/save + +# now we can communicate with gateway through POST request http://localhost:9195/order/test/save + +# localhost:9195 is gateway's ip port,default port is 9195 ,/order is the contextPath you set through gateway. +``` + +* parameter deliver: + * communicate with gateway through body or json of http post request. + * more parameter types, please refer to the interface definition in [shenyu-examples-dubbo](https://github.com/apache/shenyu/tree/master/shenyu-examples/shenyu-examples-dubbo) and parameter passing + method. +* Single java bean parameter type (`default`). +* Multi-parameter type support, add this config value in gateway's yaml file: + +```yaml +shenyu: + dubbo: + parameter: multi +``` + +* Support for customized multi-parameter type +* Create a new implementation class `MyDubboParamResolveService` in your gateway project of `org.apache.shenyu.web.dubbo.DubboParamResolveService`. + +```java +public interface DubboParamResolveService { + + /** + * Build parameter pair. + * this is Resolve http body to get dubbo param. + * + * @param body the body + * @param parameterTypes the parameter types + * @return the pair + */ + Pair buildParameter(String body, String parameterTypes); +} +``` + +* `body` is the json string in http request. +* `parameterTypes`: the list of method parameter types that are matched,split with `,`. +* in Pair,left is parmeter type,right is parameter value, it's the standard of dubbo generalization calls. +* Inject your class into Spring bean, cover the default implementation. + +```java +@Bean +public DubboParamResolveService myDubboParamResolveService() { + return new MyDubboParamResolveService(); +} +``` + +## Service governance + +* Tag route + * Add `Dubbo_Tag_Route` when send request, the current request will be routed to the provider of the specified tag, which is only valid for the current request. +* Explicit Target + * Set the `url` property in the annotation `@ShenyuDubboClient`. + * Update the configuration in Admin. + * It's valid for all request. +* Param valid and ShenyuException + * Set `validation="shenyuValidation"`. + * When `ShenyuException` is thrown in the interface, exception information will be returned. It should be noted that `ShenyuException` is thrown explicitly. + + ```java + @Service(validation = "shenyuValidation") + public class TestServiceImpl implements TestService { + + @Override + @ShenyuDubboClient(path = "/test", desc = "test method") + public String test(@Valid HelloServiceRequest name) throws ShenyuException { + if (true){ + throw new ShenyuException("Param binding error."); + } + return "Hello " + name.getName(); + } + } + ``` + + * Request param + + ```java + public class HelloServiceRequest implements Serializable { + + private static final long serialVersionUID = -5968745817846710197L; + + @NotEmpty(message = "name cannot be empty") + private String name; + + @NotNull(message = "age cannot be null") + private Integer age; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Integer getAge() { + return age; + } + + public void setAge(Integer age) { + this.age = age; + } + } + ``` + + * Send request + + ```json + { + "name": "" + } + ``` + + * Response + + ```json + { + "code": 500, + "message": "Internal Server Error", + "data": "name cannot be empty,age cannot be null" + } + ``` + + * Error message + + ```json + { + "code": 500, + "message": "Internal Server Error", + "data": "Param binding error." + } + ``` + + +## Http --> Gateway --> Dubbo Provider + +It basically switches from HTTP request to Dubbo protocol, then invoke Dubbo service and return to the result. +Two things need to notice after intgeration with gateway, one is the added annoation `@ShenyuDubboClient`, another is a path used to speicify the request path. +And you added a config value of `contextPath`. + +If you have a function like this, the config value in contextPath is `/dubbo` + +```java + @Override + @ShenyuDubboClient(path = "/insert", desc = "insert data") + public DubboTest insert(final DubboTest dubboTest) { + return dubboTest; + } +``` + +So our request path is: http://localhost:9195/dubbo/insert, localhost:9195 is the gateway's domain name,if you changed before,so does with yours here.. + +`DubboTest` is a java bean object,has 2 parameters, id and name, so we can transfer the value's json type through request body. + +``` +{"id":"1234","name":"XIAO5y"} +``` + +If your interface has no parameter, then the value is: + +``` +{} +``` + +If the interface has multiple parameters, refer to the multi-parameter type support described above. diff --git a/versioned_docs/version-2.6.1/user-guide/proxy/grpc-proxy.md b/versioned_docs/version-2.6.1/user-guide/proxy/grpc-proxy.md new file mode 100644 index 00000000000..6a05c604c18 --- /dev/null +++ b/versioned_docs/version-2.6.1/user-guide/proxy/grpc-proxy.md @@ -0,0 +1,197 @@ +--- +title: gRPC Proxy +keywords: ["gRPC"] +description: gRPC access shenyu gateway +--- + +This document is intended to help the `gRPC` service access the `Apache ShenYu` gateway. The `Apache ShenYu` gateway uses the `gRPC` plugin to handle `gRPC` service. + +Before the connection, start `shenyu-admin` correctly, start `gRPC` plugin, and add related dependencies on the gateway and `gRPC` application client. Refer to the previous [Quick start with gRPC](../quick-start/quick-start-grpc) . + +For details about client access configuration, see [Application Client Access Config](../property-config/register-center-access.md) . + +For details about data synchronization configurations, see [Data Synchronization Config](../property-config/use-data-sync.md) . + +## Add gRPC plugin in gateway + +Add the following dependencies in the gateway's `pom.xml` file: + +```xml + + + org.apache.shenyu + shenyu-spring-boot-starter-plugin-grpc + ${project.version} + + +``` + +* Restart the gateway service. + +## gRPC service access gateway + +You can refer to:[shenyu-examples-grpc](https://github.com/apache/shenyu/tree/master/shenyu-examples/shenyu-examples-grpc) . + +1. In the microservice built by `gRPC`, add the following dependencies: + + +```xml + + org.apache.shenyu + shenyu-spring-boot-starter-client-grpc + ${shenyu.version} + + + guava + com.google.guava + + + +``` + +Execute command to generate java code in `shenyu-examples-grpc` project. + +```shell +mvn protobuf:compile +mvn protobuf:compile-custom +``` + +2. Add the following configuration to application.yaml: + +```yaml +shenyu: + register: + registerType: http #zookeeper #etcd #nacos #consul + serverLists: http://localhost:9095 #localhost:2181 #http://localhost:2379 #localhost:8848 + props: + username: admin + password: 123456 + client: + grpc: + props: + contextPath: /grpc + appName: grpc + ipAndPort: 127.0.0.1:38080 + port: 38080 +``` + +3. Add `@ShenyuGrpcClient` Annotation on the `gRPC` service interface implementation class. Start your service provider, after successful registration, in the background management system go to PluginList -> rpc proxy -> gRPC, you will see automatic registration of selectors and rules information. + +Example: + +```java + @Override + @ShenyuGrpcClient(path = "/echo", desc = "echo") + public void echo(EchoRequest request, StreamObserver responseObserver) { + System.out.println("Received: " + request.getMessage()); + EchoResponse.Builder response = EchoResponse.newBuilder() + .setMessage("ReceivedHELLO") + .addTraces(Trace.newBuilder().setHost(getHostname()).build()); + responseObserver.onNext(response.build()); + responseObserver.onCompleted(); + } + +``` + +## User Request + +You can request your gRPC service by Http. The `Apache ShenYu` gateway needs to have a route prefix that you access to configure `contextPath`. + + + +If your `proto` file is defined as follows: + + +```protobuf +message EchoRequest { + string message = 1; +} +``` + +So the request parameters look like this: + +```json +{ + "data": [ + { + "message": "hello grpc" + } + ] +} +``` + +The parameters are currently passed in `json` format, and the name of `key` defaults to `data`, which you can reset in `GrpcConstants.JSON_DESCRIPTOR_PROTO_FIELD_NAME`; The `value` is passed in according to the `proto` file you define. + + +the Apache ShenYu can support streaming calls to `gRPC` service, passing multiple arguments in the form of an array. + +If your `proto` file is defined as follows: + +```protobuf +message RequestData { + string text = 1; +} +``` + +The corresponding method call request parameters are as follows: + +- `UNARY` + +```json +{ + "data": [ + { + "text": "hello grpc" + } + ] +} +``` + +- `CLIENT_STREAMING` + +```json +{ + "data": [ + { + "text": "hello grpc" + }, + { + "text": "hello grpc" + }, + { + "text": "hello grpc" + } + ] +} +``` + +- `SERVER_STREAMING` + + +```json +{ + "data": [ + { + "text": "hello grpc" + } + ] +} +``` + +- `BIDI_STREAMING` + +```json +{ + "data": [ + { + "text": "hello grpc" + }, + { + "text": "hello grpc" + }, + { + "text": "hello grpc" + } + ] +} +``` diff --git a/versioned_docs/version-2.6.1/user-guide/proxy/http-proxy.md b/versioned_docs/version-2.6.1/user-guide/proxy/http-proxy.md new file mode 100644 index 00000000000..9dc9783e685 --- /dev/null +++ b/versioned_docs/version-2.6.1/user-guide/proxy/http-proxy.md @@ -0,0 +1,262 @@ +--- +title: Http Proxy +keywords: ["Http"] +description: Integrate Http with shenyu gateway +--- + + +This document is intended to help the `Http` service access the `Apache ShenYu` gateway. The `Apache ShenYu` gateway uses the `Divide` plugin to handle `Http` requests. + +Before the connection, start `shenyu-admin` correctly, start `Divide` plugin, and add related dependencies on the gateway and `Http` application client. Refer to the previous [Quick start with Http](../../quick-start/quick-start-http) . + +For details about client access configuration, see [Application Client Access Config](../property-config/register-center-access.md) . + +For details about data synchronization configurations, see [Data Synchronization Config](../property-config/use-data-sync.md) . + +## Add divide plugin in gateway + +* Add the following dependencies to the gateway's `pom.xml` file: + + ```xml + + org.apache.shenyu + shenyu-spring-boot-starter-plugin-divide + ${project.version} + + + + org.apache.shenyu + shenyu-spring-boot-starter-plugin-httpclient + ${project.version} + + ``` + +## Http request access gateway (for springMvc) + +* SpringBoot + + Please refer this:[shenyu-examples-http](https://github.com/apache/shenyu/tree/master/shenyu-examples/shenyu-examples-http) + + 1. Add the following dependencies to the `pom.xml` file in your `Http` service: + + ```xml + + org.apache.shenyu + shenyu-spring-boot-starter-client-springmvc + ${shenyu.version} + + ``` + + 2. Add the following configuration to application.yaml: + + ```yaml + shenyu: + register: + registerType: http #zookeeper #etcd #nacos #consul + serverLists: http://localhost:9095 #localhost:2181 #http://localhost:2379 #localhost:8848 + props: + username: admin + password: 123456 + client: + http: + props: + contextPath: /http + appName: http + # port: 8189 + ``` + +* SpringMvc + + Please refer this:[shenyu-examples-springmvc](https://github.com/apache/shenyu/tree/master/shenyu-examples/shenyu-examples-springmvc) + + Add the following dependencies to the `pom.xml` file in your `Http` service: + + ```xml + + org.apache.shenyu + shenyu-client-springmvc + ${shenyu.version} + + ``` + + Add the following to the `XML` file defined by your `bean` : + + ```xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ``` + + Add this annotation `@ShenyuSpringMvcClient` in your `controller` interface. + + You can apply the annotation to class-level in a controller. The name of the `path` variable is prefix and `/**` will apply proxy for entire interfaces. + + +Example(1) + +The following indicates that `/test/payment`, `/test/findByUserId` will be proxy by the gateway. + +```java + @RestController + @RequestMapping("/test") + @ShenyuSpringMvcClient(path = "/test/**") + public class HttpTestController { + + @PostMapping("/payment") + public UserDTO post(@RequestBody final UserDTO userDTO) { + return userDTO; + } + + @GetMapping("/findByUserId") + public UserDTO findByUserId(@RequestParam("userId") final String userId) { + UserDTO userDTO = new UserDTO(); + userDTO.setUserId(userId); + userDTO.setUserName("hello world"); + return userDTO; + } + } +``` + + + +Example(2) + + +The following indicates that `/order/save` is proxied by the gateway, while `/order/findById` is not. + + +```java + @RestController + @RequestMapping("/order") + @ShenyuSpringMvcClient(path = "/order") + public class OrderController { + + @PostMapping("/save") + @ShenyuSpringMvcClient(path = "/save") + public OrderDTO save(@RequestBody final OrderDTO orderDTO) { + orderDTO.setName("hello world save order"); + return orderDTO; + } + + @GetMapping("/findById") + public OrderDTO findById(@RequestParam("id") final String id) { + OrderDTO orderDTO = new OrderDTO(); + orderDTO.setId(id); + orderDTO.setName("hello world findById"); + return orderDTO; + } + } +``` + +example (3):This is a simplified way to use it, just need a simple annotation to register to the gateway using metadata. +Special note: currently only supports `@RequestMapping, @GetMapping, @PostMapping, @DeleteMapping, @PutMapping` annotations, and only valid for the first path in `@XXXMapping` + +```java + @RestController + @RequestMapping("new/feature") + public class NewFeatureController { + + /** + * no support gateway access api. + * + * @return result + */ + @RequestMapping("/gateway/not") + public EntityResult noSupportGateway() { + return new EntityResult(200, "no support gateway access"); + } + + /** + * Do not use shenyu annotation path. used request mapping path. + * + * @return result + */ + @RequestMapping("/requst/mapping/path") + @ShenyuSpringCloudClient + public EntityResult requestMappingUrl() { + return new EntityResult(200, "Do not use shenyu annotation path. used request mapping path"); + } + + /** + * Do not use shenyu annotation path. used post mapping path. + * + * @return result + */ + @PostMapping("/post/mapping/path") + @ShenyuSpringCloudClient + public EntityResult postMappingUrl() { + return new EntityResult(200, "Do not use shenyu annotation path. used post mapping path"); + } + + /** + * Do not use shenyu annotation path. used post mapping path. + * + * @return result + */ + @GetMapping("/get/mapping/path") + @ShenyuSpringCloudClient + public EntityResult getMappingUrl() { + return new EntityResult(200, "Do not use shenyu annotation path. used get mapping path"); + } + } + +``` + +* Start your project, your service interface is connected to the gateway, go to the `shenyu-admin` management system plugin list `->` HTTP process `->` Divide, see automatically created selectors and rules. + + +## Http request access gateway(other framework) + +* First, find `divide` plugin in `shenyu-admin`, add selector, and rules, and filter traffic matching. +* If you don't know how to configure, please refer to [Selector Detailed Explanation](../admin-usage/selector-and-rule). +* You can also develop your customized http-client,refer to [multi-language Http client development](../../developer/developer-shenyu-client)。 + +## User request + +* Send the request as before, only two points need to notice. +* Firstly, the domain name that requested before in your service, now need to replace with gateway's domain name. +* Secondly, `Apache ShenYu` Gateway needs a route prefix which comes from `contextPath`, it configured during the integration with gateway, you can change it freely in `divide` plugin of `shenyu-admin`, if you are familiar with it. + * for example, if you have an `order` service, and it has an interface, the request url: `http://localhost:8080/test/save` + + * Now need to change to: `http://localhost:9195/order/test/save` + + * We can see `localhost:9195` is your gateway's `ip` port,default port number is `9195` ,`/order` is your `contextPath` which you configured with gateway. + + * Other parameters doesn't change in request method. + + +* Then you can visit, very easy and simple. diff --git a/versioned_docs/version-2.6.1/user-guide/proxy/motan-proxy.md b/versioned_docs/version-2.6.1/user-guide/proxy/motan-proxy.md new file mode 100644 index 00000000000..d1bf0cadd54 --- /dev/null +++ b/versioned_docs/version-2.6.1/user-guide/proxy/motan-proxy.md @@ -0,0 +1,107 @@ +--- +title: Motan Proxy +description: Motan Proxy +--- + +This document is intended to help the `Motan` service access the `Apache ShenYu` gateway. The `Apache ShenYu` gateway uses the `Motan` plugin to handle `motan` service. + +Before the connection, start `shenyu-admin` correctly, start `Motan` plugin, and add related dependencies on the gateway and `Motan` application client. Refer to the previous [Quick start with Motan](../quick-start/quick-start-motan) . + +For details about client access configuration, see [Application Client Access Config](../property-config/register-center-access.md) . + +For details about data synchronization configurations, see [Data Synchronization Config](../property-config/use-data-sync.md) . + +## Add motan plugin in gateway + +Add the following dependencies to the gateway's `pom.xml` file: + +```xml + + + org.apache.shenyu + shenyu-spring-boot-starter-plugin-motan + ${project.version} + + + com.weibo + motan-core + 1.1.9 + + + com.weibo + motan-registry-zookeeper + 1.1.9 + + + com.weibo + motan-transport-netty4 + 1.1.9 + + + com.weibo + motan-springsupport + 1.1.9 + +``` + +* Restart your gateway service. + +## Motan service access gateway + +Please refer to: [shenyu-examples-motan](https://github.com/apache/shenyu/tree/master/shenyu-examples/shenyu-examples-motan) + +1. In the microservice built by `Motan`, add the following dependencies: + +```xml + + org.apache.shenyu + shenyu-spring-boot-starter-client-motan + ${shenyu.version} + +``` + +2. Add the following configuration to the `application.yaml` configuration file: + +```yaml +shenyu: + register: + registerType: http #zookeeper #etcd #nacos #consul + serverLists: http://localhost:9095 #localhost:2181 #http://localhost:2379 #localhost:8848 + props: + username: admin + password: 123456 + client: + motan: + props: + contextPath: /motan + ipAndPort: motan + appName: motan + port: 8081 + package-path: org.apache.shenyu.examples.motan.service + basicServiceConfig: + exportPort: 8002 +motan: + registry: + protocol: zookeeper + address: 127.0.0.1:2181 +``` + + +3. Add `@ShenyuMotanClient` annotation to the method of `Motan` service interface implementation class, start your service provider, after successful registration, go to PluginList -> rpc proxy -> motan in the background management system, you will see automatic registration of selectors and rules information. + +Example: + +```java +@MotanService(export = "demoMotan:8002") +public class MotanDemoServiceImpl implements MotanDemoService { + @Override + @ShenyuMotanClient(path = "/hello") + public String hello(String name) { + return "hello " + name; + } +} +``` + +## User Request + +You can request your `motan` service by Http. The `Apache ShenYu` gateway needs to have a route prefix which is the `contextPath` configured by the access gateway. For example: `http://localhost:9195/motan/hello` . diff --git a/versioned_docs/version-2.6.1/user-guide/proxy/sofa-rpc-proxy.md b/versioned_docs/version-2.6.1/user-guide/proxy/sofa-rpc-proxy.md new file mode 100644 index 00000000000..e9494c921c9 --- /dev/null +++ b/versioned_docs/version-2.6.1/user-guide/proxy/sofa-rpc-proxy.md @@ -0,0 +1,187 @@ +--- +title: Sofa Proxy +keywords: ["Sofa"] +description: sofa access shenyu gateway +--- + +This document is intended to help the `Sofa` service access the `Apache ShenYu` gateway. The `Apache ShenYu` gateway uses the `Sofa` plugin to handle `sofa` service. + +Before the connection, start `shenyu-admin` correctly, start `Sofa` plugin, and add related dependencies on the gateway and `Sofa` application client. Refer to the previous [Quick start with Sofa](../quick-start/quick-start-sofa) . + +For the use of the plugin, see:[Sofa Plugin](../../plugin-center/proxy/sofa-plugin.md) + +For details about client access configuration, see [Application Client Access Config](../property-config/register-center-access.md) . + +For details about data synchronization configurations, see [Data Synchronization Config](../property-config/use-data-sync.md) . + +## Add sofa plugin in gateway + +> In the current version, this dependency has been introduced by default. + +1. Add the following dependencies in the gateway's `pom.xml` file: + + ```xml + + com.alipay.sofa + sofa-rpc-all + 5.7.6 + + + net.jcip + jcip-annotations + + + + + org.apache.curator + curator-client + 4.0.1 + + + org.apache.curator + curator-framework + 4.0.1 + + + org.apache.curator + curator-recipes + 4.0.1 + + + org.apache.shenyu + shenyu-spring-boot-starter-plugin-sofa + ${project.version} + + ``` + +2. Restart the gateway service. + +## Sofa service access gateway + +Please refer to:[shenyu-examples-sofa](https://github.com/apache/shenyu/tree/master/shenyu-examples/shenyu-examples-sofa) + +1. Based on the `springboot` project,Introduce the following dependencies: + + ```xml + + com.alipay.sofa + rpc-sofa-boot-starter + ${rpc-sofa-boot-starter.version} + + + org.apache.shenyu + shenyu-spring-boot-starter-client-sofa + ${shenyu.version} + + ``` + +2. Configure in application.yml + +```yaml +com: + alipay: + sofa: + rpc: + registry-address: zookeeper://127.0.0.1:2181 # consul # nacos + bolt-port: 8888 +shenyu: + register: + registerType: http #zookeeper #etcd #nacos #consul + serverLists: http://localhost:9095 #localhost:2181 #http://localhost:2379 #localhost:8848 + props: + username: admin + password: 123456 + client: + sofa: + props: + contextPath: /sofa + ipAndPort: sofa + appName: sofa + port: 8888 +``` + +3. Configure the service interface exposed by the sofa service in the xml file in the resources. + +```xml + + + + + + + + +``` + +4. Add the `@ShenyuSofaClient` annotation to the interface + +```java +@ShenyuSofaClient("/demo") +@Service +public class SofaClientMultiParamServiceImpl implements SofaClientMultiParamService { + + @Override + @ShenyuSofaClient("/findByIdsAndName") + public SofaSimpleTypeBean findByIdsAndName(final List ids, final String name) { + return new SofaSimpleTypeBean(ids.toString(), "hello world shenyu sofa param findByIdsAndName :" + name); + } +} +``` + +5. Start the `sofa` service, and after successful registration: +- Go to `PluginList -> Proxy -> Sofa` in the backend management system, you will see the information of auto-registered selectors and rules. +- Go to `BasicConfig -> Metadata` and search by app name . You will see the metadata of sofa, each `sofa` interface method, will correspond to a metadata. + +## User request and parameter description + +- The gateway can be requested by means of `http` to request your `sofa` service. + - ShenYu gateway needs to have a routing prefix, this routing prefix is for you to access the project for configuration `contextPath` . + +> For example, if you have an `order` service, it has an interface and its registration path `/order/test/save` +> +> Now it's to request the gateway via post:`http://localhost:9195/order/test/save` +> +> Where `localhost:9195` is the IP port of the gateway, default port is `9195`, `/order` is the `contextPath` of your sofa access gateway configuration. + + +* Parameter passing: + - Access the gateway through http post,and pass through body and json. + - For more parameter type transfer, please refer to the interface definition in [shenyu-examples-sofa](https://github.com/apache/shenyu/tree/master/shenyu-examples/shenyu-examples-sofa) and the parameter transfer method. + +* Single java bean parameter type (default) +* Customize multi-parameter support: +* In the gateway project you built, add a new class `MySofaParamResolveService`, implements `org.apache.shenyu.plugin.api.sofa.SofaParamResolveService` . + + ```java + public interface SofaParamResolveService { + + /** + * Build parameter pair. + * this is Resolve http body to get sofa param. + * + * @param body the body + * @param parameterTypes the parameter types + * @return the pair + */ + Pair buildParameter(String body, String parameterTypes); + } + ``` + +* `body` is the json string passed by body in http. +* `parameterTypes`: list of matched method parameter types, If there are multiple, use `,` to separate. +* In Pair,left is the parameter type,and right is the parameter value. This is the standard for sofa generalization calls. +* Register your class as a String bean and override the default implementation. + + ```java + @Bean + public SofaParamResolveService mySofaParamResolveService() { + return new MySofaParamResolveService(); + } + ``` + + diff --git a/versioned_docs/version-2.6.1/user-guide/proxy/spring-cloud-proxy.md b/versioned_docs/version-2.6.1/user-guide/proxy/spring-cloud-proxy.md new file mode 100644 index 00000000000..62e5bf93871 --- /dev/null +++ b/versioned_docs/version-2.6.1/user-guide/proxy/spring-cloud-proxy.md @@ -0,0 +1,300 @@ +--- +title: Spring Cloud Proxy +keywords: ["Spring Cloud"] +description: springCloud with shenyu gateway +--- + +This document is intended to help the `Spring Cloud` service access the `Apache ShenYu` gateway. The `Apache ShenYu` gateway uses the `springCloud` plugin to handle `Spring Cloud` service. + +Before the connection, start `shenyu-admin` correctly, start `springCloud` plugin, and add related dependencies on the gateway and `springCloud` application client. Refer to the previous [Quick start with Spring Cloud](../quick-start/quick-start-springcloud) . + +For details about client access configuration, see [Application Client Access Config](../property-config/register-center-access.md) . + +For details about data synchronization configurations, see [Data Synchronization Config](../property-config/use-data-sync.md) . + + +## Add springcloud plugin in gateway + +* add these dependencies in gateway's pom.xml: + + +```xml + + + org.apache.shenyu + shenyu-spring-boot-starter-plugin-springcloud + ${project.version} + + + + org.apache.shenyu + shenyu-spring-boot-starter-plugin-httpclient + ${project.version} + + + + + org.springframework.cloud + spring-cloud-commons + 2.2.0.RELEASE + +``` + +* If you use `eureka` as SpringCloud registry center. + + add these dependencies: + + ```xml + + org.springframework.cloud + spring-cloud-starter-netflix-eureka-client + 2.2.0.RELEASE + + ``` + +add these config values in gateway's yaml file: + + ```yaml + eureka: + client: + serviceUrl: + defaultZone: http://localhost:8761/eureka/ #your eureka address + instance: + prefer-ip-address: true + ``` + +* if you use `nacos` as Spring Cloud registry center. + + add these dependencies: + + ```xml + + com.alibaba.cloud + spring-cloud-starter-alibaba-nacos-discovery + 2.1.0.RELEASE + + ``` + +add these config values in gateway's yaml file: + + ```yaml + spring: + cloud: + nacos: + discovery: + server-addr: 127.0.0.1:8848 # your nacos address + ``` + +Special note: Please ensure that the spring Cloud registry service discovery configuration is enabled + +* Configuration method + +```yml +spring: + cloud: + discovery: + enabled: true +``` + +* code method + +```java +@SpringBootApplication +@EnableDiscoveryClient +public class ShenyuBootstrapApplication { + + /** + * Main Entrance. + * + * @param args startup arguments + */ + public static void main(final String[] args) { + SpringApplication.run(ShenyuBootstrapApplication.class, args); + } +} +``` + +* restart your gateway service. + +## SpringCloud service access gateway + +Please refer to [shenyu-examples-springcloud](https://github.com/apache/shenyu/tree/master/shenyu-examples/shenyu-examples-springcloud) + +* Add the following dependencies to your `Spring Cloud` microservice : + +```xml + + org.apache.shenyu + shenyu-spring-boot-starter-client-springcloud + ${shenyu.version} + +``` + +* Add the annotation `@ShenyuSpringCloudClient` in your `controller` interface. you can apply the annotation to class-level in a controller.the name of the path variable is prefix and '/**' will apply proxy for entire interfaces. + +* example (1):both `/test/payment` and `/test/findByUserId` will be handled by gateway. + + ```java + @RestController + @RequestMapping("/test") + @ShenyuSpringCloudClient(path = "/test/**") + public class HttpTestController { + + @PostMapping("/payment") + public UserDTO post(@RequestBody final UserDTO userDTO) { + return userDTO; + } + + @GetMapping("/findByUserId") + public UserDTO findByUserId(@RequestParam("userId") final String userId) { + UserDTO userDTO = new UserDTO(); + userDTO.setUserId(userId); + userDTO.setUserName("hello world"); + return userDTO; + } + } +``` + +example (2):`/order/save` will be handled by gateway, and `/order/findById` won't. + + ```java + @RestController + @RequestMapping("/order") + @ShenyuSpringCloudClient(path = "/order") + public class OrderController { + + @PostMapping("/save") + @ShenyuSpringMvcClient(path = "/save") + public OrderDTO save(@RequestBody final OrderDTO orderDTO) { + orderDTO.setName("hello world save order"); + return orderDTO; + } + + @GetMapping("/findById") + public OrderDTO findById(@RequestParam("id") final String id) { + OrderDTO orderDTO = new OrderDTO(); + orderDTO.setId(id); + orderDTO.setName("hello world findById"); + return orderDTO; + } + } +``` + +example (3): `isFull`:`true` represents that all service will be represented by the gateway. + +```yaml +shenyu: + register: + registerType: http #zookeeper #etcd #nacos #consul + serverLists: http://localhost:9095 #localhost:2181 #http://localhost:2379 #localhost:8848 + props: + username: admin + password: 123456 + client: + springCloud: + props: + contextPath: /springcloud + isFull: true +# port: 8884 +# registerType : service registre type, see the application client access document +# serverList: server list, see the application client access document +# contextPath: route prefix for your project in ShenYu gateway. +# isFull: set true to proxy your all service and false to proxy some of your controllers +``` + + ```java + @RestController + @RequestMapping("/order") + public class OrderController { + + @PostMapping("/save") + @ShenyuSpringMvcClient(path = "/save") + public OrderDTO save(@RequestBody final OrderDTO orderDTO) { + orderDTO.setName("hello world save order"); + return orderDTO; + } + + @GetMapping("/findById") + public OrderDTO findById(@RequestParam("id") final String id) { + OrderDTO orderDTO = new OrderDTO(); + orderDTO.setId(id); + orderDTO.setName("hello world findById"); + return orderDTO; + } + } +``` + +example (4):This is a simplified way to use it, just need a simple annotation to register to the gateway using metadata. +Special note: currently only supports `@RequestMapping, @GetMapping, @PostMapping, @DeleteMapping, @PutMapping` annotations, and only valid for the first path in `@XXXMapping`. + +```java + @RestController + @RequestMapping("new/feature") + public class NewFeatureController { + + /** + * no support gateway access api. + * + * @return result + */ + @RequestMapping("/gateway/not") + public EntityResult noSupportGateway() { + return new EntityResult(200, "no support gateway access"); + } + + /** + * Do not use shenyu annotation path. used request mapping path. + * + * @return result + */ + @RequestMapping("/requst/mapping/path") + @ShenyuSpringCloudClient + public EntityResult requestMappingUrl() { + return new EntityResult(200, "Do not use shenyu annotation path. used request mapping path"); + } + + /** + * Do not use shenyu annotation path. used post mapping path. + * + * @return result + */ + @PostMapping("/post/mapping/path") + @ShenyuSpringCloudClient + public EntityResult postMappingUrl() { + return new EntityResult(200, "Do not use shenyu annotation path. used post mapping path"); + } + + /** + * Do not use shenyu annotation path. used post mapping path. + * + * @return result + */ + @GetMapping("/get/mapping/path") + @ShenyuSpringCloudClient + public EntityResult getMappingUrl() { + return new EntityResult(200, "Do not use shenyu annotation path. used get mapping path"); + } + } + +``` + +* After successfully registering your service, go to the backend management system PluginList -> rpc proxy -> springCloud ', you will see the automatic registration of selectors and rules information. + + + +## User Request + +* Send the request as before, only two points need to notice. + +* firstly,the domain name that requested before in your service, now need to replace with gateway's domain name. + +* secondly, Apache ShenYu gateway needs a route prefix which comes from `contextPath`, it configured during the integration with gateway, you can change it freely in divide plugin of `shenyu-admin`, if your familiar with it. + +> For example, your have an `order` service and it has a interface, the request url: `http://localhost:8080/test/save` . +> +> Now need to change to:`http://localhost:9195/order/test/save` . +> +> We can see `localhost:9195` is the gateway's ip port, default port number is `9195` , `/order` is the `contextPath` in your config yaml file. +> +> The request of other parameters doesn't change. Then you can visit, very easy and simple. + diff --git a/versioned_docs/version-2.6.1/user-guide/proxy/tars-proxy.md b/versioned_docs/version-2.6.1/user-guide/proxy/tars-proxy.md new file mode 100644 index 00000000000..8f1fec4853b --- /dev/null +++ b/versioned_docs/version-2.6.1/user-guide/proxy/tars-proxy.md @@ -0,0 +1,98 @@ +--- +title: Tars Proxy +description: Tars Proxy +--- + +This document is intended to help the `Tars` service access the `Apache ShenYu` gateway. The `Apache ShenYu` gateway uses the `tars` plugin to handle `tars` service. + +Before the connection, start `shenyu-admin` correctly, start `tars` plugin, and add related dependencies on the gateway and `tars` application client. Refer to the previous [Quick start with Tars](../quick-start/quick-start-tars) . + +For details about client access configuration, see [Application Client Access Config](../property-config/register-center-access.md) . + +For details about data synchronization configurations, see [Data Synchronization Config](../property-config/use-data-sync.md)). + + +## Add tars plugin in gateway + + +Add the following dependencies to the gateway's `pom.xml` file: + + +```xml + + + org.apache.shenyu + shenyu-spring-boot-starter-plugin-tars + ${project.version} + + + + com.tencent.tars + tars-client + 1.7.2 + + +``` + +* Restart your gateway service. + +## Tars service access gateway + +Please refer to: [shenyu-examples-tars](https://github.com/apache/shenyu/tree/master/shenyu-examples/shenyu-examples-tars) + +1. In the microservice built by `Tars`, add the following dependencies: + +```xml + + org.apache.shenyu + shenyu-spring-boot-starter-client-tars + ${shenyu.version} + +``` + +2. Add the following configuration to the `application.yaml` configuration file: + +```yaml +shenyu: + register: + registerType: http #zookeeper #etcd #nacos #consul + serverLists: http://localhost:9095 #localhost:2181 #http://localhost:2379 #localhost:8848 + props: + username: admin + password: 123456 + client: + tars: + props: + contextPath: /tars + appName: tars + port: 21715 + host: 192.168.41.103 +``` + +3. Add `@ShenyuTarsService` Annotation on the tars service interface implementation class and `@ShenyuTarsClient` on the method, start your service provider, and register successfully. In the background management system, enter PluginList -> rpc proxy -> tars, you will see the automatic registration of selectors and rules information. + +Example: + +```java + @TarsServant("HelloObj") + @ShenyuTarsService(serviceName = "ShenyuExampleServer.ShenyuExampleApp.HelloObj") + public class HelloServantImpl implements HelloServant { + @Override + @ShenyuTarsClient(path = "/hello", desc = "hello") + public String hello(int no, String name) { + return String.format("hello no=%s, name=%s, time=%s", no, name, System.currentTimeMillis()); + } + + @Override + @ShenyuTarsClient(path = "/helloInt", desc = "helloInt") + public int helloInt(int no, String name) { + return 1; + } + } + +``` + +## User Request + +You can request your tars service by Http. The `Apache ShenYu` gateway needs to have a route prefix which is the `contextPath` configured by the access gateway. For example: `http://localhost:9195/tars/hello` . + diff --git a/versioned_docs/version-2.6.1/user-guide/proxy/websocket-proxy.md b/versioned_docs/version-2.6.1/user-guide/proxy/websocket-proxy.md new file mode 100644 index 00000000000..b91592c755a --- /dev/null +++ b/versioned_docs/version-2.6.1/user-guide/proxy/websocket-proxy.md @@ -0,0 +1,89 @@ +--- +title: Websocket Proxy +description: Websocket Proxy +--- + +This document is intended to help the `Websocket` service access the `Apache ShenYu` gateway. The `Apache ShenYu` gateway uses the `Websocket` plugin to handle `Websocket` service. + +Before the connection, start `shenyu-admin` correctly, start `Websocket` plugin, and add related dependencies on the gateway and `Websocket` application client. Refer to the previous [Quick start with Websocket](../quick-start/quick-start-websocket) . + +For details about client access configuration, see [Application Client Access Config](../property-config/register-center-access.md) . + +For details about data synchronization configurations, see [Data Synchronization Config](../property-config/use-data-sync.md)). + +## Add Websocket plugin in gateway + +Add the following dependencies to the gateway's `pom.xml` file , which is introduced by default: + +```xml + + + org.apache.shenyu + shenyu-spring-boot-starter-plugin-websocket + ${project.version} + +``` + +* Restart your gateway service. + +## Websocket service access gateway + +> Please refer to: [shenyu-examples-websocket](https://github.com/apache/shenyu/tree/master/shenyu-examples/shenyu-examples-websocket), Contains examples of the three implementations of `annotation websocket`、`spring native websocket`、`spring reactive websocket` + +1. In the `Websocket` service, add the following dependencies: + +```xml + + org.apache.shenyu + shenyu-spring-boot-starter-client-websocket + ${shenyu.version} + +``` + +2. Add the following configuration to the `application.yaml` configuration file: + +```yaml +shenyu: + register: + registerType: http + serverLists: http://localhost:9095 # shenyu-admin ip and port + props: + username: admin + password: 123456 + client: + websocket: + props: + contextPath: /ws-annotation + appName: ws-annotation + port: 8001 # need to be consistent with the service port +``` + +3. Add `@ShenyuSpringWebSocketClient` annotation to the `Websocket` service interface implementation class, start your service and after successful registration, go to `Client List -> Proxy -> Websocket` in the `shenyu-admin` management system and you will see the auto-registered selector and rule information. + +示例: + +```java +@ShenyuSpringWebSocketClient("/myWs") +@ServerEndpoint("/myWs") +public class WsServerEndpoint { + @OnOpen + public void onOpen(final Session session) { + LOG.info("connect successful"); + } + + @OnClose + public void onClose(final Session session) { + LOG.info("connect closed"); + } + + @OnMessage + public String onMsg(final String text) { + return "server send message:" + text; + } +} +``` + +## User Request + +You need to request your `Websocket` service via the `ws` protocol. The `Apache ShenYu` gateway will configure a routing prefix which is the `contextPath` in the access gateway configuration file. For example: `ws://localhost:9195/ws-annotation/myWs`, after which you can establish a connection to send and receive messages normally. + diff --git a/versioned_docs/version-2.6.1/user-guide/sdk-usage/_category_.json b/versioned_docs/version-2.6.1/user-guide/sdk-usage/_category_.json new file mode 100644 index 00000000000..f2539153751 --- /dev/null +++ b/versioned_docs/version-2.6.1/user-guide/sdk-usage/_category_.json @@ -0,0 +1,4 @@ +{ + "label": "Shenyu-Sdk Usage", + "position": 3 +} diff --git a/versioned_docs/version-2.6.1/user-guide/sdk-usage/shenyu-sdk-consul.md b/versioned_docs/version-2.6.1/user-guide/sdk-usage/shenyu-sdk-consul.md new file mode 100644 index 00000000000..f98f156c38d --- /dev/null +++ b/versioned_docs/version-2.6.1/user-guide/sdk-usage/shenyu-sdk-consul.md @@ -0,0 +1,204 @@ +--- +title: Using Consul with Shenyu-SDK +keywords: ["Using Shenyu-Sdk", "Consul"] +description: Using Shenyu-Sdk +--- + +## Background explanation + +Shenyu offers Shenyu-Sdk to make it easy for services to quickly integrate with the Shenyu gateway. By simply depending on the SDK and doing some simple configuration, client services can call the gateway's exposed APIs as if they were calling local interfaces. + + + +The registration center supported by the gateway for client access includes (nacos, eureka, etcd, zookeeper, consul), and the following is the relevant guide for using **Zookeeper** registration center when `shenyu-bootstrap` and `application client` are used. + +## Environment preparation + +Refer to `Deployment` guide, and choose a way to start `shenyu-admin` and `shenyu-bootstrap`. + +## shenyu-bootstrap + +### Maven dependency + +In the gateway's `pom.xml` file, introduce the following dependencies. + +```xml + + org.apache.shenyu + shenyu-spring-boot-starter-registry + ${project.version} + +``` + +### Edit the configuration file + +Add the following configuration to the gateway's `yml` configuration file. + +```yaml +shenyu: + register: + enabled: true + registerType: consul + serverLists: localhost + props: + delay: 1 + wait-time: 55 + instanceId: shenyu-gateway + hostName: localhost + tags: test1,test2 + preferAgentAddress: false + enableTagOverride: false + +# registerType: service registration type, fill in consul +# serverLists: consul client agent address (sidecar deployment mode (single machine or cluster), can also be the address of consul server agent (can only connect to one consul server agent node, if it is a cluster, then there will be a single point of failure problem)) +# delay: the polling interval of each metadata monitoring, unit: second, default 1 second +# wait-time: the waiting time of a single request for metadata monitoring (long polling mechanism), unit: second, default 55 seconds +# instanceId: required for consul service, consul needs to find specific services through instance-id +# name: the group name where the service is registered to consul +# hostName: for consul registration type, fill in the address of the registered service instance, the address of the registered service instance in this registration center will not be used for client calls, so this configuration can be omitted, port, preferAgentAddress similarly +# port: for consul registration type, fill in the port of the registered service instance +# tags: corresponding to the tags configuration in consul configuration +# preferAgentAddress: use the address of the agent on the consul client side as the address of the registered service instance, which will override the manual configuration of hostName +# enableTagOverride: corresponding to the enableTagOverride configuration in consul configuration for detailed reference, please see the user guide> attribute configuration> client access configuration document + +# for detailed reference, please see the `user-guide> Property Config> Register Center Instance Config` configuration document. +``` + +## Client Application + +### Maven dependency + +In the `pom.xml` file of the application client, introduce the following dependencies. + +- Shenyu-Sdk Core + +```xml + + + org.apache.shenyu + shenyu-sdk-core + 2.5.1-SNAPSHOT + + + + org.apache.shenyu + shenyu-spring-boot-starter-sdk + 2.5.1-SNAPSHOT + + +``` + +- Shenyu-Sdk http implementation + +> HTTP client implementation, offering okhttp and httpclient as implementation options. Other implementations can be created by extending the `AbstractShenyuSdkClient` class. + +```xml + + + org.apache.shenyu + shenyu-sdk-httpclient + 2.5.1-SNAPSHOT + + + + +``` + +### Edit the configuration file + +Add the following configuration in the application client's `yml` configuration file. + +```yaml +shenyu: + sdk: + enabled: true + register-type: consul + server-lists: localhost + props: + checkTtl: 5 + token: "" + waitTime: 30 + watchDelay: 5 + tags: "" + port: 8500 + retry: + enable: true + period: 100 + maxPeriod: 1000 + maxAttempts: 5 + algorithm: roundRobin + scheme: http + +# registerType: service registration type, fill in consul. +# serverLists: consul client agent address (sidecar deployment mode (single machine or cluster), can also be the address of consul server agent (can only connect to one consul server agent node, if it is a cluster, then there will be a single point of failure problem)). +# checkTtl: TTL, Default 5 seconds. +# token: "" +# waitTime: The waiting time for a single request for monitoring metadata (long polling mechanism), in seconds, with a default value of 55 seconds. +# watchDelay: The interval duration for each polling of metadata monitoring, in seconds, with a default value of 1 second. +# tags: tags for consul configure. +# port: consul server port. +# scheme: Request protocol. + +# retry Configuration related to failure retries +# retry.period: Retry waiting time. +# retry.maxPeriod: Maximum retry waiting time . +# retry.maxAttempts: Maximum retry count. +``` + +## Writing the local interface for the SDK + +1. In the project startup class, annotate `@EnableShenyuClients(basePackages = "org.apache.shenyu.examples.sdk.http.api")`, where `basePackages` maintains the package location of Shenyu-Sdk's corresponding maintained gateway API interface. + +2. Create an interface and use the `@ShenyuClient(name = "xxx", contextId = "ShenyuSdkApiName")` annotation to mark it, where `name` represents the gateway service name. If you need to define multiple beans to maintain the gateway's API, you can use `contextId` as the corresponding bean alias. + +3. In the defined interface, add the methods of the interface to be mapped to the shenyu gateway, where the `value` of `@xxMapping` corresponds to the path of the corresponding request in the gateway. + +**Example** + +Project startup class + +```java +import org.apache.shenyu.sdk.spring.EnableShenyuClients; + +@SpringBootApplication +@EnableShenyuClients(basePackages = "org.apache.shenyu.examples.sdk.http.api") +public class ShenyuSdkHttpExampleApplication { + + /** + * main. + * + * @param args args + */ + public static void main(final String[] args) { + SpringApplication.run(ShenyuSdkHttpExampleApplication.class, args); + } +} +``` + +Shenyu-SDK interface + +```java +import org.apache.shenyu.sdk.spring.ShenyuClient; + +@ShenyuClient(name = "shenyu-gateway", contextId = "ShenyuSdkApiName") +public interface ShenyuHttpClientApi { + + /** + * findById. + * test Get. + * + * @param id id + * @return SdkTestDto + */ + @GetMapping("/http/shenyu/client/findById") + SdkTestDto findById(@RequestParam("id") String id); +} +``` + +For more information, refer to the sample project [shenyu-examples-sdk](https://github.com/apache/shenyu/tree/master/shenyu-examples/shenyu-examples-sdk) diff --git a/versioned_docs/version-2.6.1/user-guide/sdk-usage/shenyu-sdk-etcd.md b/versioned_docs/version-2.6.1/user-guide/sdk-usage/shenyu-sdk-etcd.md new file mode 100644 index 00000000000..0837668ef56 --- /dev/null +++ b/versioned_docs/version-2.6.1/user-guide/sdk-usage/shenyu-sdk-etcd.md @@ -0,0 +1,184 @@ +--- +title: Using Etcd with Shenyu-SDK +keywords: ["Using Shenyu-Sdk", "Etcd"] +description: Using Shenyu-Sdk +--- + +## Background explanation + +Shenyu offers Shenyu-Sdk to make it easy for services to quickly integrate with the Shenyu gateway. By simply depending on the SDK and doing some simple configuration, client services can call the gateway's exposed APIs as if they were calling local interfaces. + + + +The registration center supported by the gateway for client access includes (nacos, eureka, etcd, zookeeper, consul), and the following is the relevant guide for using **etcd** registration center when `shenyu-bootstrap` and `application client` are used. + +## Environment preparation + +Refer to `Deployment` guide, and choose a way to start `shenyu-admin` and `shenyu-bootstrap`. + +## shenyu-bootstrap + +### Maven dependency + +In the gateway's `pom.xml` file, introduce the following dependencies. + +```xml + + org.apache.shenyu + shenyu-spring-boot-starter-registry + ${project.version} + +``` + +### Edit the configuration file + +Add the following configuration to the gateway's `yml` configuration file. + +```yaml +shenyu: + register: + enabled: true + registerType: etcd + serverLists: http://localhost:2379 + props: + appName: http + port: xx + +# registerType: service registration type, fill in etcd. +# serverList: Enter the etcd address(es), separated by commas in English. +# appName:Your application name. If not configured, the default value will be taken from spring.application.name. +# port: Your project's startup port, currently springmvc/tars/grpc needs to be filled in. + +# for detailed reference, please see the `user-guide> Property Config> Register Center Instance Config` configuration document. +``` + +## Client Application + +### Maven dependency + +In the `pom.xml` file of the application client, introduce the following dependencies. + +- Shenyu-Sdk Core + +```xml + + + org.apache.shenyu + shenyu-sdk-core + 2.5.1-SNAPSHOT + + + + org.apache.shenyu + shenyu-spring-boot-starter-sdk + 2.5.1-SNAPSHOT + + +``` + +- Shenyu-Sdk http implementation + +> HTTP client implementation, offering okhttp and httpclient as implementation options. Other implementations can be created by extending the `AbstractShenyuSdkClient` class. + +```xml + + + org.apache.shenyu + shenyu-sdk-httpclient + 2.5.1-SNAPSHOT + + + + +``` + +### Edit the configuration file + +Add the following configuration in the application client's `yml` configuration file. + +```yaml +shenyu: + sdk: + enabled: true + register-type: etcd + server-lists: http://localhost:2379 + props: + etcdTimeout: 3000 + etcdTTL: 5 + retry: + enable: true + period: 100 + maxPeriod: 1000 + maxAttempts: 5 + algorithm: roundRobin + scheme: http + +# register-type: service registration type, fill in etcd. +# server-lists: Enter the etcd address(es), separated by commas in English. +# etcdTimeout: Request timeout time, in milliseconds, default 3000 +# etcdTTL: Lease TTL, default 5 seconds. +# scheme: Request protocol. + +# retry: Configuration related to failure retries. +# retry.period: Retry waiting time. +# retry.maxPeriod: Maximum retry waiting time . +# retry.maxAttempts: Maximum retry count. +``` + +## Writing the local interface for the SDK + +1. In the project startup class, annotate `@EnableShenyuClients(basePackages = "org.apache.shenyu.examples.sdk.http.api")`, where `basePackages` maintains the package location of Shenyu-Sdk's corresponding maintained gateway API interface. + +2. Create an interface and use the `@ShenyuClient(name = "xxx", contextId = "ShenyuSdkApiName")` annotation to mark it, where `name` represents the gateway service name. If you need to define multiple beans to maintain the gateway's API, you can use `contextId` as the corresponding bean alias. + +3. In the defined interface, add the methods of the interface to be mapped to the shenyu gateway, where the `value` of `@xxMapping` corresponds to the path of the corresponding request in the gateway. + +**Example** + +Project startup class + +```java +import org.apache.shenyu.sdk.spring.EnableShenyuClients; + +@SpringBootApplication +@EnableShenyuClients(basePackages = "org.apache.shenyu.examples.sdk.http.api") +public class ShenyuSdkHttpExampleApplication { + + /** + * main. + * + * @param args args + */ + public static void main(final String[] args) { + SpringApplication.run(ShenyuSdkHttpExampleApplication.class, args); + } +} +``` + +Shenyu-SDK interface + +```java +import org.apache.shenyu.sdk.spring.ShenyuClient; + +@ShenyuClient(name = "shenyu-gateway", contextId = "ShenyuSdkApiName") +public interface ShenyuHttpClientApi { + + /** + * findById. + * test Get. + * + * @param id id + * @return SdkTestDto + */ + @GetMapping("/http/shenyu/client/findById") + SdkTestDto findById(@RequestParam("id") String id); +} +``` + +For more information, refer to the sample project [shenyu-examples-sdk](https://github.com/apache/shenyu/tree/master/shenyu-examples/shenyu-examples-sdk) diff --git a/versioned_docs/version-2.6.1/user-guide/sdk-usage/shenyu-sdk-eureka.md b/versioned_docs/version-2.6.1/user-guide/sdk-usage/shenyu-sdk-eureka.md new file mode 100644 index 00000000000..dfcd9c39a61 --- /dev/null +++ b/versioned_docs/version-2.6.1/user-guide/sdk-usage/shenyu-sdk-eureka.md @@ -0,0 +1,184 @@ +--- +title: Using Eureka with Shenyu-SDK +keywords: ["Using Shenyu-Sdk", "Eureka"] +description: Using Shenyu-Sdk +--- + +## Background explanation + +Shenyu offers Shenyu-Sdk to make it easy for services to quickly integrate with the Shenyu gateway. By simply depending on the SDK and doing some simple configuration, client services can call the gateway's exposed APIs as if they were calling local interfaces. + + + +The registration center supported by the gateway for client access includes (nacos, eureka, etcd, zookeeper, consul), and the following is the relevant guide for using **eureka** registration center when `shenyu-bootstrap` and `application client` are used. + +## Environment preparation + +Refer to `Deployment` guide, and choose a way to start `shenyu-admin` and `shenyu-bootstrap`. + +## shenyu-bootstrap + +### Maven dependency + +In the gateway's `pom.xml` file, introduce the following dependencies. + +```xml + + org.springframework.cloud + spring-cloud-starter-netflix-eureka-client + ${eureka-client.version} + + + org.springframework.cloud + spring-cloud-starter-loadbalancer + + + +``` + +### Edit the configuration file + +Add the following configuration to the gateway's `yml` configuration file. + +```yaml +spring: + cloud: + discovery: + enabled: true # Enable service discovery + +eureka: + client: + enabled: true + serviceUrl: + defaultZone: http://localhost:8761/eureka/ # Enter your eureka registry center address here + instance: + prefer-ip-address: true +``` + +## Client Application + +### Maven dependency + +In the `pom.xml` file of the application client, introduce the following dependencies. + +- Shenyu-Sdk Core + +```xml + + + org.apache.shenyu + shenyu-sdk-core + 2.5.1-SNAPSHOT + + + + org.apache.shenyu + shenyu-spring-boot-starter-sdk + 2.5.1-SNAPSHOT + + +``` + +- Shenyu-Sdk http implementation + +> HTTP client implementation, offering okhttp and httpclient as implementation options. Other implementations can be created by extending the `AbstractShenyuSdkClient` class. + +```xml + + + org.apache.shenyu + shenyu-sdk-httpclient + 2.5.1-SNAPSHOT + + + + +``` + +### Edit the configuration file + +Add the following configuration in the application client's `yml` configuration file. + +```yaml +shenyu: + sdk: + enabled: true + register-type: eureka + server-lists: http://localhost:8761/eureka/ + props: + retry: + enable: true + period: 100 + maxPeriod: 1000 + maxAttempts: 5 + algorithm: roundRobin + scheme: http + +# registerType: service registration type, fill in eureka +# serverList: Enter the eureka server address(es), separated by commas in English. +# scheme: Request protocol. + +# retry: Configuration related to failure retries. +# retry.period: Retry waiting time. +# retry.maxPeriod: Maximum retry waiting time . +# retry.maxAttempts: Maximum retry count. +``` + + +## Writing the local interface for the SDK + +1. In the project startup class, annotate `@EnableShenyuClients(basePackages = "org.apache.shenyu.examples.sdk.http.api")`, where `basePackages` maintains the package location of Shenyu-Sdk's corresponding maintained gateway API interface. + +2. Create an interface and use the `@ShenyuClient(name = "xxx", contextId = "ShenyuSdkApiName")` annotation to mark it, where `name` represents the gateway service name. If you need to define multiple beans to maintain the gateway's API, you can use `contextId` as the corresponding bean alias. + +3. In the defined interface, add the methods of the interface to be mapped to the shenyu gateway, where the `value` of `@xxMapping` corresponds to the path of the corresponding request in the gateway. + +**Example** + +Project startup class + +```java +import org.apache.shenyu.sdk.spring.EnableShenyuClients; + +@SpringBootApplication +@EnableShenyuClients(basePackages = "org.apache.shenyu.examples.sdk.http.api") +public class ShenyuSdkHttpExampleApplication { + + /** + * main. + * + * @param args args + */ + public static void main(final String[] args) { + SpringApplication.run(ShenyuSdkHttpExampleApplication.class, args); + } +} +``` + +Shenyu-SDK interface + +```java +import org.apache.shenyu.sdk.spring.ShenyuClient; + +@ShenyuClient(name = "shenyu-bootstrap", contextId = "ShenyuSdkApiName") +public interface ShenyuHttpClientApi { + + /** + * findById. + * test Get. + * + * @param id id + * @return SdkTestDto + */ + @GetMapping("/http/shenyu/client/findById") + SdkTestDto findById(@RequestParam("id") String id); +} +``` + +For more information, refer to the sample project [shenyu-examples-sdk](https://github.com/apache/shenyu/tree/master/shenyu-examples/shenyu-examples-sdk) diff --git a/versioned_docs/version-2.6.1/user-guide/sdk-usage/shenyu-sdk-feign.md b/versioned_docs/version-2.6.1/user-guide/sdk-usage/shenyu-sdk-feign.md new file mode 100644 index 00000000000..20cfe2df822 --- /dev/null +++ b/versioned_docs/version-2.6.1/user-guide/sdk-usage/shenyu-sdk-feign.md @@ -0,0 +1,130 @@ +--- +title: Using Shenyu-SDK-Feign +keywords: ["Using Shenyu-Sdk", "feign"] +description: Using Shenyu-Sdk-Feign +--- + +## Shenyu sdk-feign + +> Integrate `open Feign` to implement declarative SDK call gateway API. +> Like 'shenyu sdk', 'shenyu sdk feign' is another option; +> for more information see : +> * please refer to: [shenyu-sdk-consul](../../user-guide/sdk-usage/shenyu-sdk-consul) +> * please refer to: [shenyu-sdk-etcd](../../user-guide/sdk-usage/shenyu-sdk-etcd) +> * please refer to: [shenyu-sdk-eureka](../../user-guide/sdk-usage/shenyu-sdk-eureka) +> * please refer to: [shenyu-sdk-nacos](../../user-guide/sdk-usage/shenyu-sdk-nacos) +> * please refer to: [shenyu-sdk-zookeeper](../../user-guide/sdk-usage/shenyu-sdk-zookeeper) + +### Maven dependency + +In the `pom.xml` file of the application client, introduce the following dependencies(Compatible with `FeignClient`). + +```xml + + + org.springframework.cloud + spring-cloud-starter-openfeign + ${spring-cloud.version} + + + + org.apache.shenyu + shenyu-spring-boot-starter-sdk-feign + 2.6.1-SNAPSHOT + + +``` + + +### Edit the configuration file + +Add the following configuration in the application client's `yml` configuration file. + +```yaml +shenyu: + sdk: + enabled: true + register-type: consul + server-lists: localhost + props: + algorithm: roundRobin + scheme: http + +# if not use openFeign and springCloud-loadBalance, feign client options must be enabled. +feign: + client: + httpclient: + enabled: true + +# registerType: service registration type, fill in consul. +# serverLists: consul client agent address (sidecar deployment mode (single machine or cluster), can also be the address of consul server agent (can only connect to one consul server agent node, if it is a cluster, then there will be a single point of failure problem)). + +# algorithm: load balance algorithm. +# scheme: Request protocol. + +``` + +## Writing the local interface for the SDK + +1. In the project startup class, annotate `@EnableShenyuClients(basePackages = "org.apache.shenyu.examples.sdk.http.api")`, where `basePackages` maintains the package location of Shenyu-Sdk's corresponding maintained gateway API interface. + +2. Create an interface and use the `@ShenyuClient(name = "xxx", contextId = "ShenyuSdkApiName")` annotation to mark it, where `name` represents the gateway service name. If you need to define multiple beans to maintain the gateway's API, you can use `contextId` as the corresponding bean alias. + +3. In the defined interface, add the methods of the interface to be mapped to the shenyu gateway, where the `value` of `@xxMapping` corresponds to the path of the corresponding request in the gateway. + +**Example** + +Project startup class + +```java +import org.apache.shenyu.sdk.feign.EnableShenyuClients; + +@SpringBootApplication +@EnableShenyuClients(basePackages = "org.apache.shenyu.examples.sdk.feign.api") +public class ShenyuSdkHttpExampleApplication { + + /** + * main. + * + * @param args args + */ + public static void main(final String[] args) { + SpringApplication.run(ShenyuSdkHttpExampleApplication.class, args); + } +} +``` + +Shenyu-SDK interface + +```java +import org.apache.shenyu.sdk.feign.ShenyuClient; + +@ShenyuClient(name = "shenyu-gateway", contextId = "ShenyuSdkApiName", path = "/feign/shenyu/client") +public interface ShenyuFeignClientApi { + + /** + * findById. + * test Get. + * + * @param id id + * @return SdkTestDto + */ + @GetMapping("/findById") + SdkTestDto findById(@RequestParam("id") String id); + + /** + * annoTest. + * + * @param cookie cookie + * @param header header + * @param id id + * @param requestDto requestDto + * @return sdkTestDto + */ + @PostMapping("/{id}/anno") + SdkTestDto annoTest(@CookieValue("cookie") String cookie, @RequestHeader("header") String header, @PathVariable("id") String id, @RequestBody SdkTestDto requestDto); + +} +``` + +For more information, refer to the sample project [shenyu-examples-sdk-feign](https://github.com/apache/shenyu/tree/master/shenyu-examples/shenyu-examples-sdk/shenyu-examples-sdk-feign) diff --git a/versioned_docs/version-2.6.1/user-guide/sdk-usage/shenyu-sdk-nacos.md b/versioned_docs/version-2.6.1/user-guide/sdk-usage/shenyu-sdk-nacos.md new file mode 100644 index 00000000000..e8226285644 --- /dev/null +++ b/versioned_docs/version-2.6.1/user-guide/sdk-usage/shenyu-sdk-nacos.md @@ -0,0 +1,185 @@ +--- +title: Using Nacos with Shenyu-SDK +keywords: ["Using Shenyu-Sdk", "Nacos"] +description: Using Shenyu-Sdk +--- + +## Background explanation + +Shenyu offers Shenyu-Sdk to make it easy for services to quickly integrate with the Shenyu gateway. By simply depending on the SDK and doing some simple configuration, client services can call the gateway's exposed APIs as if they were calling local interfaces. + + + +The registration center supported by the gateway for client access includes (nacos, eureka, etcd, zookeeper, consul), and the following is the relevant guide for using **nacos** registration center when `shenyu-bootstrap` and `application client` are used. + +## Environment preparation + +Refer to `Deployment` guide, and choose a way to start `shenyu-admin` and `shenyu-bootstrap`. + +## shenyu-bootstrap + +### Maven dependency + +In the gateway's `pom.xml` file, introduce the following dependencies. + +```xml + + org.apache.shenyu + shenyu-spring-boot-starter-registry + ${project.version} + +``` + +### Edit the configuration file + +Add the following configuration to the gateway's `yml` configuration file. + +```yaml +spring: + application: + name: shenyu-bootstrap + cloud: + discovery: + enabled: true + nacos: + discovery: + server-addr: 127.0.0.1:8848 # Enter the nacos address(es), separated by commas in English. + enabled: true + namespace: ShenyuRegisterCenter # nacos namespace ID + # if nacos authentication is enabled, the following parameters must be configured + username: nacos # Authentication username + password: nacos # Authentication password +``` + +## Client Application + +### Maven dependency + +In the `pom.xml` file of the application client, introduce the following dependencies. + +- Shenyu-Sdk Core + +```xml + + + org.apache.shenyu + shenyu-sdk-core + 2.5.1-SNAPSHOT + + + + org.apache.shenyu + shenyu-spring-boot-starter-sdk + 2.5.1-SNAPSHOT + + +``` + +- Shenyu-Sdk http implementation + +> HTTP client implementation, offering okhttp and httpclient as implementation options. Other implementations can be created by extending the `AbstractShenyuSdkClient` class. + +```xml + + + org.apache.shenyu + shenyu-sdk-httpclient + 2.5.1-SNAPSHOT + + + + +``` + +### Edit the configuration file + +Add the following configuration in the application client's `yml` configuration file. + +```yaml +shenyu: + sdk: + enabled: true + register-type: nacos + server-lists: localhost:2181 + props: + nacosNameSpace: ShenyuRegisterCenter + username: nacos + password: nacos + retry: + enable: true + period: 100 + maxPeriod: 1000 + maxAttempts: 5 + algorithm: roundRobin + scheme: http + +# registerType: service registration type, fill in nacos. +# serverList: Enter the nacos address(es), separated by commas in English. +# nacosNameSpace: nacos namespace ID +# username: Authentication username +# password: Authentication password +# scheme: Request protocol. + +# retry: Configuration related to failure retries. +# retry.period: Retry waiting time. +# retry.maxPeriod: Maximum retry waiting time . +# retry.maxAttempts: Maximum retry count. +``` + +## Writing the local interface for the SDK + +1. In the project startup class, annotate `@EnableShenyuClients(basePackages = "org.apache.shenyu.examples.sdk.http.api")`, where `basePackages` maintains the package location of Shenyu-Sdk's corresponding maintained gateway API interface. + +2. Create an interface and use the `@ShenyuClient(name = "xxx", contextId = "ShenyuSdkApiName")` annotation to mark it, where `name` represents the gateway service name. If you need to define multiple beans to maintain the gateway's API, you can use `contextId` as the corresponding bean alias. + +3. In the defined interface, add the methods of the interface to be mapped to the shenyu gateway, where the `value` of `@xxMapping` corresponds to the path of the corresponding request in the gateway. + +**Example** + +Project startup class + +```java +import org.apache.shenyu.sdk.spring.EnableShenyuClients; + +@SpringBootApplication +@EnableShenyuClients(basePackages = "org.apache.shenyu.examples.sdk.http.api") +public class ShenyuSdkHttpExampleApplication { + + /** + * main. + * + * @param args args + */ + public static void main(final String[] args) { + SpringApplication.run(ShenyuSdkHttpExampleApplication.class, args); + } +} +``` + +Shenyu-SDK interface + +```java +import org.apache.shenyu.sdk.spring.ShenyuClient; + +@ShenyuClient(name = "shenyu-bootstrap", contextId = "ShenyuSdkApiName") +public interface ShenyuHttpClientApi { + + /** + * findById. + * test Get. + * + * @param id id + * @return SdkTestDto + */ + @GetMapping("/http/shenyu/client/findById") + SdkTestDto findById(@RequestParam("id") String id); +} +``` + +For more information, refer to the sample project [shenyu-examples-sdk](https://github.com/apache/shenyu/tree/master/shenyu-examples/shenyu-examples-sdk) diff --git a/versioned_docs/version-2.6.1/user-guide/sdk-usage/shenyu-sdk-zookeeper.md b/versioned_docs/version-2.6.1/user-guide/sdk-usage/shenyu-sdk-zookeeper.md new file mode 100644 index 00000000000..4c546574022 --- /dev/null +++ b/versioned_docs/version-2.6.1/user-guide/sdk-usage/shenyu-sdk-zookeeper.md @@ -0,0 +1,179 @@ +--- +title: Using Zookeeper with Shenyu-SDK +keywords: ["Using Shenyu-Sdk", "zookeeper"] +description: Using Shenyu-Sdk +--- + +## Background explanation + +Shenyu offers Shenyu-Sdk to make it easy for services to quickly integrate with the Shenyu gateway. By simply depending on the SDK and doing some simple configuration, client services can call the gateway's exposed APIs as if they were calling local interfaces. + + + +The registration center supported by the gateway for client access includes (nacos, eureka, etcd, zookeeper, consul), and the following is the relevant guide for using **Zookeeper** registration center when `shenyu-bootstrap` and `application client` are used. + +## Environment preparation + +Refer to `Deployment` guide, and choose a way to start `shenyu-admin` and `shenyu-bootstrap`. + +## shenyu-bootstrap + +### Maven dependency + +In the gateway's `pom.xml` file, introduce the following dependencies. + +```xml + + org.apache.shenyu + shenyu-spring-boot-starter-registry + ${project.version} + +``` + +### Edit the configuration file + +Add the following configuration to the gateway's `yml` configuration file. + +```yaml +shenyu: + register: + enabled: true + registerType: zookeeper + serverLists: localhost:2181 + props: + appName: http + port: xx +# registerType: service registration type, fill in zookeeper. +# serverList: Enter the zookeeper address(es), separated by commas in English. +# appName:Your application name. If not configured, the default value will be taken from spring.application.name. +# port: Your project's startup port, currently springmvc/tars/grpc needs to be filled in. + +# for detailed reference, please see the `user-guide> Property Config> Register Center Instance Config` configuration document. +``` + +## Client Application + +### Maven dependency + +In the `pom.xml` file of the application client, introduce the following dependencies. + +- Shenyu-Sdk Core + +```xml + + + org.apache.shenyu + shenyu-sdk-core + 2.5.1-SNAPSHOT + + + + org.apache.shenyu + shenyu-spring-boot-starter-sdk + 2.5.1-SNAPSHOT + + +``` + +- Shenyu-Sdk http implementation + +> HTTP client implementation, offering okhttp and httpclient as implementation options. Other implementations can be created by extending the `AbstractShenyuSdkClient` class. + +```xml + + + org.apache.shenyu + shenyu-sdk-httpclient + 2.5.1-SNAPSHOT + + + + +``` + +### Edit the configuration file + +Add the following configuration in the application client's `yml` configuration file. + +```yaml +shenyu: + sdk: + enabled: true + register-type: zookeeper + server-lists: localhost:2181 + props: + retry: + enable: true + period: 100 + maxPeriod: 1000 + maxAttempts: 5 + algorithm: roundRobin + scheme: http + +# register-type: service registration type, fill in zookeeper. +# server-lists: Enter the zookeeper address(es), separated by commas in English. +# scheme: Request protocol. + +# retry: Configuration related to failure retries. +# retry.period: Retry waiting time. +# retry.maxPeriod: Maximum retry waiting time . +# retry.maxAttempts: Maximum retry count. +``` + +## Writing the local interface for the SDK + +1. In the project startup class, annotate `@EnableShenyuClients(basePackages = "org.apache.shenyu.examples.sdk.http.api")`, where `basePackages` maintains the package location of Shenyu-Sdk's corresponding maintained gateway API interface. + +2. Create an interface and use the `@ShenyuClient(name = "xxx", contextId = "ShenyuSdkApiName")` annotation to mark it, where `name` represents the gateway service name. If you need to define multiple beans to maintain the gateway's API, you can use `contextId` as the corresponding bean alias. + +3. In the defined interface, add the methods of the interface to be mapped to the shenyu gateway, where the `value` of `@xxMapping` corresponds to the path of the corresponding request in the gateway. + +**Example** + +Project startup class + +```java +import org.apache.shenyu.sdk.spring.EnableShenyuClients; + +@SpringBootApplication +@EnableShenyuClients(basePackages = "org.apache.shenyu.examples.sdk.http.api") +public class ShenyuSdkHttpExampleApplication { + + /** + * main. + * + * @param args args + */ + public static void main(final String[] args) { + SpringApplication.run(ShenyuSdkHttpExampleApplication.class, args); + } +} +``` + +Shenyu-SDK interface + +```java +import org.apache.shenyu.sdk.spring.ShenyuClient; + +@ShenyuClient(name = "shenyu-gateway", contextId = "ShenyuSdkApiName") +public interface ShenyuHttpClientApi { + + /** + * findById. + * test Get. + * + * @param id id + * @return SdkTestDto + */ + @GetMapping("/http/shenyu/client/findById") + SdkTestDto findById(@RequestParam("id") String id); +} +``` + +For more information, refer to the sample project [shenyu-examples-sdk](https://github.com/apache/shenyu/tree/master/shenyu-examples/shenyu-examples-sdk) diff --git a/versioned_sidebars/version-2.6.1-sidebars.json b/versioned_sidebars/version-2.6.1-sidebars.json new file mode 100644 index 00000000000..7ef4ca95ab0 --- /dev/null +++ b/versioned_sidebars/version-2.6.1-sidebars.json @@ -0,0 +1,8 @@ +{ + "version-2.6.0/tutorialSidebar": [ + { + "type": "autogenerated", + "dirName": "." + } + ] +} diff --git a/versions.json b/versions.json index 0973190fa61..da31d6447a6 100755 --- a/versions.json +++ b/versions.json @@ -1,4 +1,5 @@ [ + "2.6.1", "2.6.0", "2.5.1", "2.5.0",