dengsixing 3 tahun lalu
melakukan
c2362ef52c
100 mengubah file dengan 6649 tambahan dan 0 penghapusan
  1. 8 0
      .codecov.yml
  2. 27 0
      .gitignore
  3. 24 0
      .travis.yml
  4. 73 0
      CODE_OF_CONDUCT.md
  5. 80 0
      CONTRIBUTING.md
  6. 201 0
      LICENSE
  7. 167 0
      README.md
  8. 3 0
      doc/README.md
  9. 52 0
      doc/awesome-sentinel.md
  10. TEMPAT SAMPAH
      doc/image/sentinel-features-overview-en.png
  11. TEMPAT SAMPAH
      doc/image/sentinel-opensource-eco-landscape-en.png
  12. TEMPAT SAMPAH
      doc/image/slots.gif
  13. 368 0
      pom.xml
  14. 71 0
      sentinel-adapter/pom.xml
  15. 68 0
      sentinel-adapter/sentinel-apache-dubbo-adapter/README.md
  16. 50 0
      sentinel-adapter/sentinel-apache-dubbo-adapter/pom.xml
  17. 43 0
      sentinel-adapter/sentinel-apache-dubbo-adapter/src/main/java/com/alibaba/csp/sentinel/adapter/dubbo/DubboAppContextFilter.java
  18. 54 0
      sentinel-adapter/sentinel-apache-dubbo-adapter/src/main/java/com/alibaba/csp/sentinel/adapter/dubbo/DubboUtils.java
  19. 83 0
      sentinel-adapter/sentinel-apache-dubbo-adapter/src/main/java/com/alibaba/csp/sentinel/adapter/dubbo/SentinelDubboConsumerFilter.java
  20. 93 0
      sentinel-adapter/sentinel-apache-dubbo-adapter/src/main/java/com/alibaba/csp/sentinel/adapter/dubbo/SentinelDubboProviderFilter.java
  21. 35 0
      sentinel-adapter/sentinel-apache-dubbo-adapter/src/main/java/com/alibaba/csp/sentinel/adapter/dubbo/fallback/DefaultDubboFallback.java
  22. 41 0
      sentinel-adapter/sentinel-apache-dubbo-adapter/src/main/java/com/alibaba/csp/sentinel/adapter/dubbo/fallback/DubboFallback.java
  23. 54 0
      sentinel-adapter/sentinel-apache-dubbo-adapter/src/main/java/com/alibaba/csp/sentinel/adapter/dubbo/fallback/DubboFallbackRegistry.java
  24. 3 0
      sentinel-adapter/sentinel-apache-dubbo-adapter/src/main/resources/META-INF/dubbo/org.apache.dubbo.rpc.Filter
  25. 40 0
      sentinel-adapter/sentinel-apache-dubbo-adapter/src/test/java/com/alibaba/csp/sentinel/BaseTest.java
  26. 75 0
      sentinel-adapter/sentinel-apache-dubbo-adapter/src/test/java/com/alibaba/csp/sentinel/adapter/dubbo/DubboAppContextFilterTest.java
  27. 75 0
      sentinel-adapter/sentinel-apache-dubbo-adapter/src/test/java/com/alibaba/csp/sentinel/adapter/dubbo/DubboUtilsTest.java
  28. 142 0
      sentinel-adapter/sentinel-apache-dubbo-adapter/src/test/java/com/alibaba/csp/sentinel/adapter/dubbo/SentinelDubboConsumerFilterTest.java
  29. 145 0
      sentinel-adapter/sentinel-apache-dubbo-adapter/src/test/java/com/alibaba/csp/sentinel/adapter/dubbo/SentinelDubboProviderFilterTest.java
  30. 50 0
      sentinel-adapter/sentinel-apache-dubbo-adapter/src/test/java/com/alibaba/csp/sentinel/adapter/dubbo/fallback/DubboFallbackRegistryTest.java
  31. 23 0
      sentinel-adapter/sentinel-apache-dubbo-adapter/src/test/java/com/alibaba/csp/sentinel/adapter/dubbo/provider/DemoService.java
  32. 27 0
      sentinel-adapter/sentinel-apache-dubbo-adapter/src/test/java/com/alibaba/csp/sentinel/adapter/dubbo/provider/impl/DemoServiceImpl.java
  33. 18 0
      sentinel-adapter/sentinel-apache-dubbo-adapter/src/test/resources/spring-dubbo-consumer-filter.xml
  34. 18 0
      sentinel-adapter/sentinel-apache-dubbo-adapter/src/test/resources/spring-dubbo-provider-filter.xml
  35. 8 0
      sentinel-adapter/sentinel-api-gateway-adapter-common/README.md
  36. 51 0
      sentinel-adapter/sentinel-api-gateway-adapter-common/pom.xml
  37. 52 0
      sentinel-adapter/sentinel-api-gateway-adapter-common/src/main/java/com/alibaba/csp/sentinel/adapter/gateway/common/SentinelGatewayConstants.java
  38. 81 0
      sentinel-adapter/sentinel-api-gateway-adapter-common/src/main/java/com/alibaba/csp/sentinel/adapter/gateway/common/api/ApiDefinition.java
  39. 32 0
      sentinel-adapter/sentinel-api-gateway-adapter-common/src/main/java/com/alibaba/csp/sentinel/adapter/gateway/common/api/ApiDefinitionChangeObserver.java
  40. 74 0
      sentinel-adapter/sentinel-api-gateway-adapter-common/src/main/java/com/alibaba/csp/sentinel/adapter/gateway/common/api/ApiPathPredicateItem.java
  41. 46 0
      sentinel-adapter/sentinel-api-gateway-adapter-common/src/main/java/com/alibaba/csp/sentinel/adapter/gateway/common/api/ApiPredicateGroupItem.java
  42. 37 0
      sentinel-adapter/sentinel-api-gateway-adapter-common/src/main/java/com/alibaba/csp/sentinel/adapter/gateway/common/api/ApiPredicateItem.java
  43. 162 0
      sentinel-adapter/sentinel-api-gateway-adapter-common/src/main/java/com/alibaba/csp/sentinel/adapter/gateway/common/api/GatewayApiDefinitionManager.java
  44. 74 0
      sentinel-adapter/sentinel-api-gateway-adapter-common/src/main/java/com/alibaba/csp/sentinel/adapter/gateway/common/api/matcher/AbstractApiMatcher.java
  45. 36 0
      sentinel-adapter/sentinel-api-gateway-adapter-common/src/main/java/com/alibaba/csp/sentinel/adapter/gateway/common/command/GetGatewayApiDefinitionGroupCommandHandler.java
  46. 36 0
      sentinel-adapter/sentinel-api-gateway-adapter-common/src/main/java/com/alibaba/csp/sentinel/adapter/gateway/common/command/GetGatewayRuleCommandHandler.java
  47. 61 0
      sentinel-adapter/sentinel-api-gateway-adapter-common/src/main/java/com/alibaba/csp/sentinel/adapter/gateway/common/command/UpdateGatewayApiDefinitionGroupCommandHandler.java
  48. 61 0
      sentinel-adapter/sentinel-api-gateway-adapter-common/src/main/java/com/alibaba/csp/sentinel/adapter/gateway/common/command/UpdateGatewayRuleCommandHandler.java
  49. 175 0
      sentinel-adapter/sentinel-api-gateway-adapter-common/src/main/java/com/alibaba/csp/sentinel/adapter/gateway/common/param/GatewayParamParser.java
  50. 58 0
      sentinel-adapter/sentinel-api-gateway-adapter-common/src/main/java/com/alibaba/csp/sentinel/adapter/gateway/common/param/GatewayRegexCache.java
  51. 67 0
      sentinel-adapter/sentinel-api-gateway-adapter-common/src/main/java/com/alibaba/csp/sentinel/adapter/gateway/common/param/RequestItemParser.java
  52. 186 0
      sentinel-adapter/sentinel-api-gateway-adapter-common/src/main/java/com/alibaba/csp/sentinel/adapter/gateway/common/rule/GatewayFlowRule.java
  53. 103 0
      sentinel-adapter/sentinel-api-gateway-adapter-common/src/main/java/com/alibaba/csp/sentinel/adapter/gateway/common/rule/GatewayParamFlowItem.java
  54. 89 0
      sentinel-adapter/sentinel-api-gateway-adapter-common/src/main/java/com/alibaba/csp/sentinel/adapter/gateway/common/rule/GatewayRuleConverter.java
  55. 272 0
      sentinel-adapter/sentinel-api-gateway-adapter-common/src/main/java/com/alibaba/csp/sentinel/adapter/gateway/common/rule/GatewayRuleManager.java
  56. 75 0
      sentinel-adapter/sentinel-api-gateway-adapter-common/src/main/java/com/alibaba/csp/sentinel/adapter/gateway/common/slot/GatewayFlowSlot.java
  57. 57 0
      sentinel-adapter/sentinel-api-gateway-adapter-common/src/main/java/com/alibaba/csp/sentinel/adapter/gateway/common/slot/GatewaySlotChainBuilder.java
  58. 4 0
      sentinel-adapter/sentinel-api-gateway-adapter-common/src/main/resources/META-INF/services/com.alibaba.csp.sentinel.command.CommandHandler
  59. 1 0
      sentinel-adapter/sentinel-api-gateway-adapter-common/src/main/resources/META-INF/services/com.alibaba.csp.sentinel.slotchain.SlotChainBuilder
  60. 27 0
      sentinel-adapter/sentinel-api-gateway-adapter-common/src/test/java/com/alibaba/csp/sentinel/adapter/gateway/common/api/GatewayApiDefinitionManagerTest.java
  61. 320 0
      sentinel-adapter/sentinel-api-gateway-adapter-common/src/test/java/com/alibaba/csp/sentinel/adapter/gateway/common/param/GatewayParamParserTest.java
  62. 49 0
      sentinel-adapter/sentinel-api-gateway-adapter-common/src/test/java/com/alibaba/csp/sentinel/adapter/gateway/common/param/GatewayRegexCacheTest.java
  63. 64 0
      sentinel-adapter/sentinel-api-gateway-adapter-common/src/test/java/com/alibaba/csp/sentinel/adapter/gateway/common/rule/GatewayRuleConverterTest.java
  64. 115 0
      sentinel-adapter/sentinel-api-gateway-adapter-common/src/test/java/com/alibaba/csp/sentinel/adapter/gateway/common/rule/GatewayRuleManagerTest.java
  65. 68 0
      sentinel-adapter/sentinel-dubbo-adapter/README.md
  66. 48 0
      sentinel-adapter/sentinel-dubbo-adapter/pom.xml
  67. 44 0
      sentinel-adapter/sentinel-dubbo-adapter/src/main/java/com/alibaba/csp/sentinel/adapter/dubbo/AbstractDubboFilter.java
  68. 43 0
      sentinel-adapter/sentinel-dubbo-adapter/src/main/java/com/alibaba/csp/sentinel/adapter/dubbo/DubboAppContextFilter.java
  69. 35 0
      sentinel-adapter/sentinel-dubbo-adapter/src/main/java/com/alibaba/csp/sentinel/adapter/dubbo/DubboUtils.java
  70. 80 0
      sentinel-adapter/sentinel-dubbo-adapter/src/main/java/com/alibaba/csp/sentinel/adapter/dubbo/SentinelDubboConsumerFilter.java
  71. 86 0
      sentinel-adapter/sentinel-dubbo-adapter/src/main/java/com/alibaba/csp/sentinel/adapter/dubbo/SentinelDubboProviderFilter.java
  72. 34 0
      sentinel-adapter/sentinel-dubbo-adapter/src/main/java/com/alibaba/csp/sentinel/adapter/dubbo/fallback/DefaultDubboFallback.java
  73. 39 0
      sentinel-adapter/sentinel-dubbo-adapter/src/main/java/com/alibaba/csp/sentinel/adapter/dubbo/fallback/DubboFallback.java
  74. 48 0
      sentinel-adapter/sentinel-dubbo-adapter/src/main/java/com/alibaba/csp/sentinel/adapter/dubbo/fallback/DubboFallbackRegistry.java
  75. 3 0
      sentinel-adapter/sentinel-dubbo-adapter/src/main/resources/META-INF/dubbo/com.alibaba.dubbo.rpc.Filter
  76. 24 0
      sentinel-adapter/sentinel-dubbo-adapter/src/test/java/com/alibaba/csp/sentinel/BaseTest.java
  77. 41 0
      sentinel-adapter/sentinel-dubbo-adapter/src/test/java/com/alibaba/csp/sentinel/adapter/dubbo/AbstractDubboFilterTest.java
  78. 59 0
      sentinel-adapter/sentinel-dubbo-adapter/src/test/java/com/alibaba/csp/sentinel/adapter/dubbo/DubboAppContextFilterTest.java
  79. 39 0
      sentinel-adapter/sentinel-dubbo-adapter/src/test/java/com/alibaba/csp/sentinel/adapter/dubbo/DubboUtilsTest.java
  80. 131 0
      sentinel-adapter/sentinel-dubbo-adapter/src/test/java/com/alibaba/csp/sentinel/adapter/dubbo/SentinelDubboConsumerFilterTest.java
  81. 133 0
      sentinel-adapter/sentinel-dubbo-adapter/src/test/java/com/alibaba/csp/sentinel/adapter/dubbo/SentinelDubboProviderFilterTest.java
  82. 56 0
      sentinel-adapter/sentinel-dubbo-adapter/src/test/java/com/alibaba/csp/sentinel/adapter/dubbo/fallback/DubboFallbackRegistryTest.java
  83. 23 0
      sentinel-adapter/sentinel-dubbo-adapter/src/test/java/com/alibaba/csp/sentinel/adapter/dubbo/provider/DemoService.java
  84. 27 0
      sentinel-adapter/sentinel-dubbo-adapter/src/test/java/com/alibaba/csp/sentinel/adapter/dubbo/provider/impl/DemoServiceImpl.java
  85. 18 0
      sentinel-adapter/sentinel-dubbo-adapter/src/test/resources/spring-dubbo-consumer-filter.xml
  86. 18 0
      sentinel-adapter/sentinel-dubbo-adapter/src/test/resources/spring-dubbo-provider-filter.xml
  87. 38 0
      sentinel-adapter/sentinel-grpc-adapter/README.md
  88. 98 0
      sentinel-adapter/sentinel-grpc-adapter/pom.xml
  89. 139 0
      sentinel-adapter/sentinel-grpc-adapter/src/main/java/com/alibaba/csp/sentinel/adapter/grpc/SentinelGrpcClientInterceptor.java
  90. 90 0
      sentinel-adapter/sentinel-grpc-adapter/src/main/java/com/alibaba/csp/sentinel/adapter/grpc/SentinelGrpcServerInterceptor.java
  91. 70 0
      sentinel-adapter/sentinel-grpc-adapter/src/test/java/com/alibaba/csp/sentinel/adapter/grpc/FooServiceClient.java
  92. 44 0
      sentinel-adapter/sentinel-grpc-adapter/src/test/java/com/alibaba/csp/sentinel/adapter/grpc/FooServiceImpl.java
  93. 48 0
      sentinel-adapter/sentinel-grpc-adapter/src/test/java/com/alibaba/csp/sentinel/adapter/grpc/GrpcTestServer.java
  94. 96 0
      sentinel-adapter/sentinel-grpc-adapter/src/test/java/com/alibaba/csp/sentinel/adapter/grpc/SentinelGrpcClientInterceptorTest.java
  95. 98 0
      sentinel-adapter/sentinel-grpc-adapter/src/test/java/com/alibaba/csp/sentinel/adapter/grpc/SentinelGrpcServerInterceptorTest.java
  96. 23 0
      sentinel-adapter/sentinel-grpc-adapter/src/test/proto/example.proto
  97. 23 0
      sentinel-adapter/sentinel-reactor-adapter/README.md
  98. 44 0
      sentinel-adapter/sentinel-reactor-adapter/pom.xml
  99. 57 0
      sentinel-adapter/sentinel-reactor-adapter/src/main/java/com/alibaba/csp/sentinel/adapter/reactor/ContextConfig.java
  100. 0 0
      sentinel-adapter/sentinel-reactor-adapter/src/main/java/com/alibaba/csp/sentinel/adapter/reactor/EntryConfig.java

+ 8 - 0
.codecov.yml

@@ -0,0 +1,8 @@
+ignore:
+  - "sentinel-demo/.*"
+  - "sentinel-dashboard/.*"
+  - "sentinel-benchmark/.*"
+  - "sentinel-transport/.*"
+  - "sentinel-core/src/main/java/com/alibaba/csp/sentinel/slots/statistic/base/LongAdder.java"
+  - "sentinel-core/src/main/java/com/alibaba/csp/sentinel/slots/statistic/base/Striped64.java"
+  - "sentinel-core/src/main/java/com/alibaba/csp/sentinel/eagleeye/*"

+ 27 - 0
.gitignore

@@ -0,0 +1,27 @@
+# IntelliJ project files
+.idea/
+*.iml
+out
+gen
+
+# Maven
+target/
+pom.xml.tag
+pom.xml.releaseBackup
+pom.xml.versionsBackup
+pom.xml.next
+release.properties
+dependency-reduced-pom.xml
+buildNumber.properties
+.mvn/timing.properties
+!/.mvn/wrapper/maven-wrapper.jar
+
+# Eclipse
+.classpath
+.settings/
+.project
+bin/
+
+# System related
+*.DS_Store
+Thumbs.db

+ 24 - 0
.travis.yml

@@ -0,0 +1,24 @@
+language: java
+
+sudo: required
+dist: trusty
+
+matrix:
+  include:
+  - jdk: oraclejdk8
+    env: BUILD_JDK=ORACLE_JDK_8
+  - jdk: oraclejdk11
+    env: BUILD_JDK=ORACLE_JDK_11
+  allow_failures:
+  - env: BUILD_JDK=ORACLE_JDK_11
+
+# https://docs.travis-ci.com/user/languages/java/#maven-dependency-management
+install:
+  - mvn install -DskipTests=true -Dmaven.javadoc.skip=true -B -V -DminimumPriority=1
+
+after_success:
+  - bash <(curl -s https://codecov.io/bash)
+
+cache:
+  directories:
+  - $HOME/.m2/

+ 73 - 0
CODE_OF_CONDUCT.md

@@ -0,0 +1,73 @@
+# Contributor Covenant Code of Conduct
+
+## Our Pledge
+
+In the interest of fostering an open and welcoming environment, we as
+contributors and maintainers pledge to making participation in our project and
+our community a harassment-free experience for everyone, regardless of age, body
+size, disability, ethnicity, gender identity and expression, level of experience,
+education, socio-economic status, nationality, personal appearance, race,
+religion, or sexual identity and orientation.
+
+## Our Standards
+
+Examples of behavior that contributes to creating a positive environment
+include:
+
+* Using welcoming and inclusive language
+* Being respectful of differing viewpoints and experiences
+* Gracefully accepting constructive criticism
+* Focusing on what is best for the community
+* Showing empathy towards other community members
+
+Examples of unacceptable behavior by participants include:
+
+* The use of sexualized language or imagery and unwelcome sexual attention or
+  advances
+* Trolling, insulting/derogatory comments, and personal or political attacks
+* Public or private harassment
+* Publishing others' private information, such as a physical or electronic
+  address, without explicit permission
+* Other conduct which could reasonably be considered inappropriate in a
+  professional setting
+
+## Our Responsibilities
+
+Project maintainers are responsible for clarifying the standards of acceptable
+behavior and are expected to take appropriate and fair corrective action in
+response to any instances of unacceptable behavior.
+
+Project maintainers have the right and responsibility to remove, edit, or
+reject comments, commits, code, wiki edits, issues, and other contributions
+that are not aligned to this Code of Conduct, or to ban temporarily or
+permanently any contributor for other behaviors that they deem inappropriate,
+threatening, offensive, or harmful.
+
+## Scope
+
+This Code of Conduct applies both within project spaces and in public spaces
+when an individual is representing the project or its community. Examples of
+representing a project or community include using an official project e-mail
+address, posting via an official social media account, or acting as an appointed
+representative at an online or offline event. Representation of a project may be
+further defined and clarified by project maintainers.
+
+## Enforcement
+
+Instances of abusive, harassing, or otherwise unacceptable behavior may be
+reported by contacting the project team at sentinel@linux.alibaba.com. All
+complaints will be reviewed and investigated and will result in a response that
+is deemed necessary and appropriate to the circumstances. The project team is
+obligated to maintain confidentiality with regard to the reporter of an incident.
+Further details of specific enforcement policies may be posted separately.
+
+Project maintainers who do not follow or enforce the Code of Conduct in good
+faith may face temporary or permanent repercussions as determined by other
+members of the project's leadership.
+
+## Attribution
+
+This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
+available at [https://www.contributor-covenant.org/version/1/4/code-of-conduct.html](https://www.contributor-covenant.org/version/1/4/code-of-conduct.html)
+
+[homepage]: https://www.contributor-covenant.org

+ 80 - 0
CONTRIBUTING.md

@@ -0,0 +1,80 @@
+# Contributing to Sentinel
+
+Welcome to Sentinel! This document is a guideline about how to contribute to Sentinel.
+If you find something incorrect or missing, please leave comments / suggestions.
+
+## Before you get started
+
+### Code of Conduct
+
+Please make sure to read and observe our [Code of Conduct](./CODE_OF_CONDUCT.md).
+
+### Setting up your development environment
+
+You should have JDK 1.8 or later installed in your system.
+
+## Contributing
+
+We are always very happy to have contributions, whether for typo fix, bug fix or big new features.
+Please do not ever hesitate to ask a question or send a pull request.
+
+We strongly value documentation and integration with other projects.
+We are very glad to accept improvements for these aspects.
+
+### GitHub workflow
+
+We use the `master` branch as the development branch, which indicates that this is a unstable branch.
+
+Here are the workflow for contributors:
+
+1. Fork to your own
+2. Clone fork to local repository
+3. Create a new branch and work on it
+4. Keep your branch in sync
+5. Commit your changes (make sure your commit message concise)
+6. Push your commits to your forked repository
+7. Create a pull request
+
+Please follow [the pull request template](./.github/PULL_REQUEST_TEMPLATE.md).
+Please make sure the PR has a corresponding issue.
+
+After creating a PR, one or more reviewers will be assigned to the pull request.
+The reviewers will review the code.
+
+Before merging a PR, squash any fix review feedback, typo, merged, and rebased sorts of commits.
+The final commit message should be clear and concise.
+
+### Open an issue / PR
+
+We use [GitHub Issues](https://github.com/alibaba/Sentinel/issues) and [Pull Requests](https://github.com/alibaba/Sentinel/pulls) for trackers.
+
+If you find a typo in document, find a bug in code, or want new features, or want to give suggestions,
+you can [open an issue on GitHub](https://github.com/alibaba/Sentinel/issues/new) to report it.
+Please follow the guideline message in the issue template.
+
+If you want to contribute, please follow the [contribution workflow](#github-workflow) and create a new pull request.
+If your PR contains large changes, e.g. component refactor or new components, please write detailed documents
+about its design and usage.
+
+Note that a single PR should not be too large. If heavy changes are required, it's better to separate the changes
+to a few individual PRs.
+
+### Code review
+
+All code should be well reviewed by one or more committers. Some principles:
+
+- Readability: Important code should be well-documented. Comply with our code style.
+- Elegance: New functions, classes or components should be well designed.
+- Testability: Important code should be well-tested (high unit test coverage).
+
+## Community
+
+### Contact us
+
+#### Mailing list
+
+If you have any questions or advice, please contact sentinel@linux.alibaba.com.
+
+#### Gitter
+
+Our Gitter room: [https://gitter.im/alibaba/Sentinel](https://gitter.im/alibaba/Sentinel).

+ 201 - 0
LICENSE

@@ -0,0 +1,201 @@
+                                 Apache License
+                           Version 2.0, January 2004
+                        http://www.apache.org/licenses/
+
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+   1. Definitions.
+
+      "License" shall mean the terms and conditions for use, reproduction,
+      and distribution as defined by Sections 1 through 9 of this document.
+
+      "Licensor" shall mean the copyright owner or entity authorized by
+      the copyright owner that is granting the License.
+
+      "Legal Entity" shall mean the union of the acting entity and all
+      other entities that control, are controlled by, or are under common
+      control with that entity. For the purposes of this definition,
+      "control" means (i) the power, direct or indirect, to cause the
+      direction or management of such entity, whether by contract or
+      otherwise, or (ii) ownership of fifty percent (50%) or more of the
+      outstanding shares, or (iii) beneficial ownership of such entity.
+
+      "You" (or "Your") shall mean an individual or Legal Entity
+      exercising permissions granted by this License.
+
+      "Source" form shall mean the preferred form for making modifications,
+      including but not limited to software source code, documentation
+      source, and configuration files.
+
+      "Object" form shall mean any form resulting from mechanical
+      transformation or translation of a Source form, including but
+      not limited to compiled object code, generated documentation,
+      and conversions to other media types.
+
+      "Work" shall mean the work of authorship, whether in Source or
+      Object form, made available under the License, as indicated by a
+      copyright notice that is included in or attached to the work
+      (an example is provided in the Appendix below).
+
+      "Derivative Works" shall mean any work, whether in Source or Object
+      form, that is based on (or derived from) the Work and for which the
+      editorial revisions, annotations, elaborations, or other modifications
+      represent, as a whole, an original work of authorship. For the purposes
+      of this License, Derivative Works shall not include works that remain
+      separable from, or merely link (or bind by name) to the interfaces of,
+      the Work and Derivative Works thereof.
+
+      "Contribution" shall mean any work of authorship, including
+      the original version of the Work and any modifications or additions
+      to that Work or Derivative Works thereof, that is intentionally
+      submitted to Licensor for inclusion in the Work by the copyright owner
+      or by an individual or Legal Entity authorized to submit on behalf of
+      the copyright owner. For the purposes of this definition, "submitted"
+      means any form of electronic, verbal, or written communication sent
+      to the Licensor or its representatives, including but not limited to
+      communication on electronic mailing lists, source code control systems,
+      and issue tracking systems that are managed by, or on behalf of, the
+      Licensor for the purpose of discussing and improving the Work, but
+      excluding communication that is conspicuously marked or otherwise
+      designated in writing by the copyright owner as "Not a Contribution."
+
+      "Contributor" shall mean Licensor and any individual or Legal Entity
+      on behalf of whom a Contribution has been received by Licensor and
+      subsequently incorporated within the Work.
+
+   2. Grant of Copyright License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      copyright license to reproduce, prepare Derivative Works of,
+      publicly display, publicly perform, sublicense, and distribute the
+      Work and such Derivative Works in Source or Object form.
+
+   3. Grant of Patent License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      (except as stated in this section) patent license to make, have made,
+      use, offer to sell, sell, import, and otherwise transfer the Work,
+      where such license applies only to those patent claims licensable
+      by such Contributor that are necessarily infringed by their
+      Contribution(s) alone or by combination of their Contribution(s)
+      with the Work to which such Contribution(s) was submitted. If You
+      institute patent litigation against any entity (including a
+      cross-claim or counterclaim in a lawsuit) alleging that the Work
+      or a Contribution incorporated within the Work constitutes direct
+      or contributory patent infringement, then any patent licenses
+      granted to You under this License for that Work shall terminate
+      as of the date such litigation is filed.
+
+   4. Redistribution. You may reproduce and distribute copies of the
+      Work or Derivative Works thereof in any medium, with or without
+      modifications, and in Source or Object form, provided that You
+      meet the following conditions:
+
+      (a) You must give any other recipients of the Work or
+          Derivative Works a copy of this License; and
+
+      (b) You must cause any modified files to carry prominent notices
+          stating that You changed the files; and
+
+      (c) You must retain, in the Source form of any Derivative Works
+          that You distribute, all copyright, patent, trademark, and
+          attribution notices from the Source form of the Work,
+          excluding those notices that do not pertain to any part of
+          the Derivative Works; and
+
+      (d) If the Work includes a "NOTICE" text file as part of its
+          distribution, then any Derivative Works that You distribute must
+          include a readable copy of the attribution notices contained
+          within such NOTICE file, excluding those notices that do not
+          pertain to any part of the Derivative Works, in at least one
+          of the following places: within a NOTICE text file distributed
+          as part of the Derivative Works; within the Source form or
+          documentation, if provided along with the Derivative Works; or,
+          within a display generated by the Derivative Works, if and
+          wherever such third-party notices normally appear. The contents
+          of the NOTICE file are for informational purposes only and
+          do not modify the License. You may add Your own attribution
+          notices within Derivative Works that You distribute, alongside
+          or as an addendum to the NOTICE text from the Work, provided
+          that such additional attribution notices cannot be construed
+          as modifying the License.
+
+      You may add Your own copyright statement to Your modifications and
+      may provide additional or different license terms and conditions
+      for use, reproduction, or distribution of Your modifications, or
+      for any such Derivative Works as a whole, provided Your use,
+      reproduction, and distribution of the Work otherwise complies with
+      the conditions stated in this License.
+
+   5. Submission of Contributions. Unless You explicitly state otherwise,
+      any Contribution intentionally submitted for inclusion in the Work
+      by You to the Licensor shall be under the terms and conditions of
+      this License, without any additional terms or conditions.
+      Notwithstanding the above, nothing herein shall supersede or modify
+      the terms of any separate license agreement you may have executed
+      with Licensor regarding such Contributions.
+
+   6. Trademarks. This License does not grant permission to use the trade
+      names, trademarks, service marks, or product names of the Licensor,
+      except as required for reasonable and customary use in describing the
+      origin of the Work and reproducing the content of the NOTICE file.
+
+   7. Disclaimer of Warranty. Unless required by applicable law or
+      agreed to in writing, Licensor provides the Work (and each
+      Contributor provides its Contributions) on an "AS IS" BASIS,
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+      implied, including, without limitation, any warranties or conditions
+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+      PARTICULAR PURPOSE. You are solely responsible for determining the
+      appropriateness of using or redistributing the Work and assume any
+      risks associated with Your exercise of permissions under this License.
+
+   8. Limitation of Liability. In no event and under no legal theory,
+      whether in tort (including negligence), contract, or otherwise,
+      unless required by applicable law (such as deliberate and grossly
+      negligent acts) or agreed to in writing, shall any Contributor be
+      liable to You for damages, including any direct, indirect, special,
+      incidental, or consequential damages of any character arising as a
+      result of this License or out of the use or inability to use the
+      Work (including but not limited to damages for loss of goodwill,
+      work stoppage, computer failure or malfunction, or any and all
+      other commercial damages or losses), even if such Contributor
+      has been advised of the possibility of such damages.
+
+   9. Accepting Warranty or Additional Liability. While redistributing
+      the Work or Derivative Works thereof, You may choose to offer,
+      and charge a fee for, acceptance of support, warranty, indemnity,
+      or other liability obligations and/or rights consistent with this
+      License. However, in accepting such obligations, You may act only
+      on Your own behalf and on Your sole responsibility, not on behalf
+      of any other Contributor, and only if You agree to indemnify,
+      defend, and hold each Contributor harmless for any liability
+      incurred by, or claims asserted against, such Contributor by reason
+      of your accepting any such warranty or additional liability.
+
+   END OF TERMS AND CONDITIONS
+
+   APPENDIX: How to apply the Apache License to your work.
+
+      To apply the Apache License to your work, attach the following
+      boilerplate notice, with the fields enclosed by brackets "[]"
+      replaced with your own identifying information. (Don't include
+      the brackets!)  The text should be enclosed in the appropriate
+      comment syntax for the file format. We also recommend that a
+      file or class name and description of purpose be included on the
+      same "printed page" as the copyright notice for easier
+      identification within third-party archives.
+
+   Copyright [yyyy] [name of copyright owner]
+
+   Licensed under the Apache License, Version 2.0 (the "License");
+   you may not use this file except in compliance with the License.
+   You may obtain a copy of the License at
+
+       http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.

+ 167 - 0
README.md

@@ -0,0 +1,167 @@
+<img src="https://user-images.githubusercontent.com/9434884/43697219-3cb4ef3a-9975-11e8-9a9c-73f4f537442d.png" alt="Sentinel Logo" width="50%">
+
+# Sentinel: Sentinel of Your Application
+
+[![Travis Build Status](https://travis-ci.org/alibaba/Sentinel.svg?branch=master)](https://travis-ci.org/alibaba/Sentinel)
+[![Codecov](https://codecov.io/gh/alibaba/Sentinel/branch/master/graph/badge.svg)](https://codecov.io/gh/alibaba/Sentinel)
+[![Maven Central](https://img.shields.io/maven-central/v/com.alibaba.csp/sentinel-core.svg?label=Maven%20Central)](https://search.maven.org/search?q=g:com.alibaba.csp%20AND%20a:sentinel-core)
+[![License](https://img.shields.io/badge/license-Apache%202-4EB1BA.svg)](https://www.apache.org/licenses/LICENSE-2.0.html)
+[![Gitter](https://badges.gitter.im/alibaba/Sentinel.svg)](https://gitter.im/alibaba/Sentinel)
+
+## Introduction
+
+As distributed systems become increasingly popular, the reliability between services is becoming more important than ever before.
+Sentinel takes "flow" as breakthrough point, and works on multiple fields including **flow control**, **circuit breaking** and **system adaptive protection**, to guarantee reliability of microservices.
+
+Sentinel has the following features:
+
+- **Rich applicable scenarios**: Sentinel has been wildly used in Alibaba, and has covered almost all the core-scenarios in Double-11 (11.11) Shopping Festivals in the past 10 years, such as “Second Kill” which needs to limit burst flow traffic to meet the system capacity, message peak clipping and valley fills, circuit breaking for unreliable downstream services, cluster flow control, etc.
+- **Real-time monitoring**: Sentinel also provides real-time monitoring ability. You can see the runtime information of a single machine in real-time, and the aggregated runtime info of a cluster with less than 500 nodes.
+- **Widespread open-source ecosystem**: Sentinel provides out-of-box integrations with commonly-used frameworks and libraries such as Spring Cloud, Dubbo and gRPC. You can easily use Sentinel by simply add the adapter dependency to your services.
+- **Various SPI extensions**: Sentinel provides easy-to-use SPI extension interfaces that allow you to quickly customize your logic, for example, custom rule management, adapting data sources, and so on.
+
+Features overview:
+
+![features-of-sentinel](./doc/image/sentinel-features-overview-en.png)
+
+## Documentation
+
+See the [中文文档](https://github.com/alibaba/Sentinel/wiki/%E4%BB%8B%E7%BB%8D) for document in Chinese.
+
+See the [Wiki](https://github.com/alibaba/Sentinel/wiki) for full documentation, examples, blog posts, operational details and other information.
+
+Sentinel provides integration module for various open-source frameworks and libraries
+(e.g. Spring Cloud, Apache Dubbo, gRPC, Spring WebFlux, Reactor). You can refer to [the document](https://github.com/alibaba/Sentinel/wiki/Adapters-to-Popular-Framework) for more information.
+
+If you are using Sentinel, please [**leave a comment here**](https://github.com/alibaba/Sentinel/issues/18) to tell us your scenario to make Sentinel better.
+It's also encouraged to add the link of your blog post, tutorial, demo or customized components to [**Awesome Sentinel**](./doc/awesome-sentinel.md).
+
+## Ecosystem Landscape
+
+![ecosystem-landscape](./doc/image/sentinel-opensource-eco-landscape-en.png)
+
+## Quick Start
+
+Below is a simple demo that guides new users to use Sentinel in just 3 steps. It also shows how to monitor this demo using the dashboard.
+
+### 1. Add Dependency
+
+**Note:** Sentinel requires Java 7 or later.
+
+If your application is build in Maven, just add the following dependency in `pom.xml`.
+
+```xml
+<!-- replace here with the latest version -->
+<dependency>
+    <groupId>com.alibaba.csp</groupId>
+    <artifactId>sentinel-core</artifactId>
+    <version>1.6.2</version>
+</dependency>
+```
+
+If not, you can download JAR in [Maven Center Repository](https://mvnrepository.com/artifact/com.alibaba.csp/sentinel-core).
+
+### 2. Define Resource
+
+Wrap your code snippet via Sentinel API: `SphU.entry(resourceName)`.
+In below example, it is `System.out.println("hello world");`:
+
+```java
+try (Entry entry = SphU.entry("HelloWorld")) {
+    // Your business logic here.
+    System.out.println("hello world");
+} catch (BlockException e) {
+    // Handle rejected request.
+    e.printStackTrace();
+}
+```
+
+So far the code modification is done. We also provide [annotation support module](https://github.com/alibaba/Sentinel/blob/master/sentinel-extension/sentinel-annotation-aspectj/README.md) to define resource easier.
+
+### 3. Define Rules
+
+If we want to limit the access times of the resource, we can **set rules to the resource**.
+The following code defines a rule that limits access to the resource to 20 times per second at the maximum.
+
+```java
+List<FlowRule> rules = new ArrayList<>();
+FlowRule rule = new FlowRule();
+rule.setResource("HelloWorld");
+// set limit qps to 20
+rule.setCount(20);
+rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
+rules.add(rule);
+FlowRuleManager.loadRules(rules);
+```
+
+For more information, please refer to [How To Use](https://github.com/alibaba/Sentinel/wiki/How-to-Use).
+
+### 4. Check the Result
+
+After running the demo for a while, you can see the following records in `~/logs/csp/${appName}-metrics.log.{date}` (When using the default `DateFileLogHandler`).
+
+```
+|--timestamp-|------date time----|-resource-|p |block|s |e|rt  |occupied
+1529998904000|2018-06-26 15:41:44|HelloWorld|20|0    |20|0|0   |0
+1529998905000|2018-06-26 15:41:45|HelloWorld|20|5579 |20|0|728 |0
+1529998906000|2018-06-26 15:41:46|HelloWorld|20|15698|20|0|0   |0
+1529998907000|2018-06-26 15:41:47|HelloWorld|20|19262|20|0|0   |0
+1529998908000|2018-06-26 15:41:48|HelloWorld|20|19502|20|0|0   |0
+1529998909000|2018-06-26 15:41:49|HelloWorld|20|18386|20|0|0   |0
+
+p stands for incoming request, block for blocked by rules, success for success handled by Sentinel, e for exception count, rt for average response time (ms), occupied stands for occupiedPassQps since 1.5.0 which enable us booking more than 1 shot when entering.
+```
+
+This shows that the demo can print "hello world" 20 times per second.
+
+More examples and information can be found in the [How To Use](https://github.com/alibaba/Sentinel/wiki/How-to-Use) section.
+
+The working principles of Sentinel can be found in [How it works](https://github.com/alibaba/Sentinel/wiki/How-it-works) section.
+
+Samples can be found in the [sentinel-demo](https://github.com/alibaba/Sentinel/tree/master/sentinel-demo) module.
+
+### 5. Start Dashboard
+
+Sentinel also provides a simple dashboard application, on which you can monitor the clients and configure the rules in real time.
+
+For details please refer to [Dashboard](https://github.com/alibaba/Sentinel/wiki/Dashboard).
+
+## Trouble Shooting and Logs
+
+Sentinel will generate logs for troubleshooting. All the information can be found in [logs](https://github.com/alibaba/Sentinel/wiki/Logs).
+
+## Bugs and Feedback
+
+For bug report, questions and discussions please submit [GitHub Issues](https://github.com/alibaba/sentinel/issues).
+
+Contact us: sentinel@linux.alibaba.com
+
+## Contributing
+
+Contributions are always welcomed! Please see [CONTRIBUTING](./CONTRIBUTING.md) for detailed guidelines.
+
+You can start with the issues labeled with [`good first issue`](https://github.com/alibaba/Sentinel/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22).
+
+## Credits
+
+Thanks [Guava](https://github.com/google/guava), which provides some inspiration on rate limiting.
+
+And thanks for all [contributors](https://github.com/alibaba/Sentinel/graphs/contributors) of Sentinel!
+
+## Who is using
+
+These are only part of the companies using Sentinel, for reference only. If you are using Sentinel, please [add your company here](https://github.com/alibaba/Sentinel/issues/18) to tell us your scenario to make Sentinel better :)
+
+![Alibaba Group](https://docs.alibabagroup.com/assets2/images/en/global/logo_header.png)
+![Taiping Renshou](http://www.cntaiping.com/tplresource/cms/www/taiping/img/home_new/tp_logo_img.png)
+![Shunfeng Technology](https://user-images.githubusercontent.com/9434884/48463502-2f48eb80-e817-11e8-984f-2f9b1b789e2d.png)
+![Mandao](https://user-images.githubusercontent.com/9434884/48463559-6cad7900-e817-11e8-87e4-42952b074837.png)
+![每日优鲜](https://home.missfresh.cn/statics/img/logo.png)
+![二维火](https://user-images.githubusercontent.com/9434884/49358468-bc43de00-f70d-11e8-97fe-0bf05865f29f.png)
+![文轩在线](http://static.winxuancdn.com/css/v2/images/logo.png)
+![客如云](https://www.keruyun.com/static/krynew/images/logo.png)
+![亲宝宝](https://stlib.qbb6.com/wclt/img/home_hd/version1/title_logo.png)
+![杭州光云科技](https://www.raycloud.com/images/logo.png)
+![金汇金融](https://res.jinhui365.com/r/images/logo2.png?v=1.527)
+![闪电购](http://cdn.52shangou.com/shandianbang/official-source/3.1.1/build/images/logo.png)
+![拼多多](http://cdn.pinduoduo.com/assets/img/pdd_logo_v3.png)

+ 3 - 0
doc/README.md

@@ -0,0 +1,3 @@
+# Sentinel related documents
+
+- [Awesome Sentinel](./awesome-sentinel.md)

+ 52 - 0
doc/awesome-sentinel.md

@@ -0,0 +1,52 @@
+# Awesome Sentinel
+
+[![Awesome](https://awesome.re/badge-flat.svg)](https://awesome.re)
+
+A curated list of awesome things (e.g. sample, extensions, blogs) for [Sentinel](https://github.com/alibaba/Sentinel).
+
+If you want your component to appear here, send a pull request to this repository to add it.
+You can refer to the [awesome contribution guidelines](https://github.com/sentinel-group/sentinel-awesome/blob/master/CONTRIBUTING.md).
+
+You can also add to [sentinel-group/sentinel-awesome](https://github.com/sentinel-group/sentinel-awesome).
+
+## Contents
+
+- [Tutorials](#tutorials)
+- [Samples / Demos](#samples--demos)
+- [Extensions / Integrations](#extensions--integrations)
+- [Blogs](#blogs)
+
+## Tutorials
+
+## Samples / Demos
+
+- [sentinel-zuul-example](https://github.com/tigerMoon/sentinel-zuul-sample): A simple project integration Sentinel to Spring Cloud Zuul which provide Service and API Path level flow control management by [tiger](https://github.com/tigerMoon)
+
+## Extensions / Integrations
+
+- [sentinel-support](https://github.com/cdfive/sentinel-support): A support project for convenient Sentinel integration including properties file configuration, ActiveMQ integration and a JdbcDataSource implementation by [cdfive](https://github.com/cdfive)
+
+## Blogs
+
+- [Sentinel 为 Dubbo 服务保驾护航](http://dubbo.apache.org/zh-cn/blog/sentinel-introduction-for-dubbo.html) by [Eric Zhao](https://github.com/sczyh30)
+- [Sentinel 与 Hystrix 的对比](https://github.com/alibaba/Sentinel/wiki/Sentinel-%E4%B8%8E-Hystrix-%E7%9A%84%E5%AF%B9%E6%AF%94) by [Eric Zhao](https://github.com/sczyh30)
+- [Guideline: 从 Hystrix 迁移到 Sentinel](https://github.com/alibaba/Sentinel/wiki/Guideline:-%E4%BB%8E-Hystrix-%E8%BF%81%E7%A7%BB%E5%88%B0-Sentinel) by [Eric Zhao](https://github.com/sczyh30)
+- [Sentinel 控制台监控数据持久化【MySQL】(Spring Data JPA)](https://www.cnblogs.com/cdfive2018/p/9838577.html) by [cdfive](https://github.com/cdfive)
+- [Sentinel 控制台监控数据持久化【InfluxDB】](https://www.cnblogs.com/cdfive2018/p/9914838.html) by [cdfive](https://github.com/cdfive)
+- [Sentinel一体化监控解决方案 CrateDB+Grafana](https://blog.csdn.net/huyong1990/article/details/82392386) by [Young Hu](https://github.com/YoungHu)
+- [Sentinel 原理-全解析](https://mp.weixin.qq.com/s/7_pCkamNv0269e5l9_Wz7w) by [houyi](https://github.com/all4you)
+- [Sentinel 原理-调用链](https://mp.weixin.qq.com/s/UEzwD22YC6jpp02foNSXnw) by [houyi](https://github.com/all4you)
+- [Sentinel 原理-滑动窗口](https://mp.weixin.qq.com/s/B1_7Kb_CxeKEAv43kdCWOA) by [houyi](https://github.com/all4you)
+- [Sentinel 实战-限流](https://mp.weixin.qq.com/s/rjyU37Dm-sxNln7GUD8tOw) by [houyi](https://github.com/all4you)
+- [Sentinel 实战-控制台](https://mp.weixin.qq.com/s/23EDFHMXLwsDqw-4O5dR5A) by [houyi](https://github.com/all4you)
+- [Sentinel 实战-规则持久化](https://mp.weixin.qq.com/s/twMFiBfRawKLR-1-N-f1yw) by [houyi](https://github.com/all4you)
+- [sentinel 深入浅出之原理篇SlotChain](https://www.jianshu.com/p/a7a405de3a12) by [shxz130](https://github.com/shxz130)
+- [sentinel 深入浅出之原理篇Context初始化&Entry初始化](https://www.jianshu.com/p/e39ac47cd893) by [shxz130](https://github.com/shxz130)
+- [sentinel 深入浅出之原理篇NodeSelectorSlot](https://www.jianshu.com/p/9a380ba188ab) by [shxz130](https://github.com/shxz130)
+- [sentinel 深入浅出之原理篇ClusterBuilderSlot](https://www.jianshu.com/p/0b0b5d8888a2) by [shxz130](https://github.com/shxz130)
+- [sentinel 深入浅出之原理篇StatisticSlot&滑动窗口](https://www.jianshu.com/p/9620298fd15a) by [shxz130](https://github.com/shxz130)
+- [sentinel 深入浅出之原理篇SystemSlot](https://www.jianshu.com/p/bfad1b7d0cde) by [shxz130](https://github.com/shxz130)
+- [sentinel 深入浅出之原理篇AuthoritySlot](https://www.jianshu.com/p/c5312c2242b3) by [shxz130](https://github.com/shxz130)
+- [sentinel 深入浅出之原理篇FlowSlot](https://www.jianshu.com/p/53218d0d273e) by [shxz130](https://github.com/shxz130)
+- [sentinel 深入浅出之原理篇DegradeSlot](https://www.jianshu.com/p/e910d4840e4a) by [shxz130](https://github.com/shxz130)
+- [sentinel 深入浅出之原理篇协议拓展dubbo,grpc,web-servlet](https://www.jianshu.com/p/579bff0f34be) by [shxz130](https://github.com/shxz130)

TEMPAT SAMPAH
doc/image/sentinel-features-overview-en.png


TEMPAT SAMPAH
doc/image/sentinel-opensource-eco-landscape-en.png


TEMPAT SAMPAH
doc/image/slots.gif


+ 368 - 0
pom.xml

@@ -0,0 +1,368 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+    <modelVersion>4.0.0</modelVersion>
+
+    <groupId>com.alibaba.csp</groupId>
+    <artifactId>sentinel-parent</artifactId>
+    <version>1.6.2</version>
+    <packaging>pom</packaging>
+
+    <name>${project.artifactId}</name>
+    <description>The parent project of Sentinel</description>
+    <url>https://github.com/alibaba/Sentinel</url>
+    <licenses>
+        <license>
+            <name>Apache License, Version 2.0</name>
+            <url>http://www.apache.org/licenses/LICENSE-2.0</url>
+            <distribution>repo</distribution>
+        </license>
+    </licenses>
+    <scm>
+        <url>https://github.com/alibaba/Sentinel</url>
+        <connection>scm:git:https://github.com/alibaba/Sentinel.git</connection>
+        <developerConnection>scm:git:https://github.com/alibaba/Sentinel.git</developerConnection>
+    </scm>
+    <developers>
+        <developer>
+            <name>The Sentinel Project Contributors</name>
+            <email>sentinel-dev@linux.alibaba.com</email>
+            <url>https://github.com/alibaba/Sentinel</url>
+        </developer>
+    </developers>
+    <organization>
+        <name>Alibaba Group</name>
+        <url>https://github.com/alibaba</url>
+    </organization>
+    <issueManagement>
+        <system>github</system>
+        <url>https://github.com/alibaba/Sentinel/issues</url>
+    </issueManagement>
+
+    <properties>
+        <!-- Compile libs -->
+        <fastjson.version>1.2.56</fastjson.version>
+
+        <!-- Test libs -->
+        <junit.version>4.12</junit.version>
+        <mockito.version>2.21.0</mockito.version>
+        <assertj.version>3.12.1</assertj.version>
+        <awaitility.version>3.1.5</awaitility.version>
+        <powermock.version>2.0.0</powermock.version>
+
+        <!-- Build -->
+        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+        <java.source.version>1.7</java.source.version>
+        <java.target.version>1.7</java.target.version>
+        <java.encoding>UTF-8</java.encoding>
+        <maven.compiler.version>3.8.0</maven.compiler.version>
+        <maven.surefire.version>2.22.1</maven.surefire.version>
+        <maven.source.version>3.0.1</maven.source.version>
+        <maven.javadoc.version>3.0.1</maven.javadoc.version>
+        <maven.deploy.version>2.8.2</maven.deploy.version>
+        <maven.gpg.version>1.6</maven.gpg.version>
+        <maven.jacoco.version>0.8.3</maven.jacoco.version>
+        <maven.jar.version>3.1.0</maven.jar.version>
+        <maven.pmd.version>3.8</maven.pmd.version>
+    </properties>
+
+    <modules>
+        <module>sentinel-core</module>
+        <module>sentinel-extension</module>
+        <module>sentinel-transport</module>
+        <module>sentinel-adapter</module>
+        <module>sentinel-dashboard</module>
+
+        <module>sentinel-demo</module>
+        <module>sentinel-benchmark</module>
+        <module>sentinel-cluster</module>
+    </modules>
+
+    <dependencyManagement>
+        <dependencies>
+            <dependency>
+                <groupId>com.alibaba.csp</groupId>
+                <artifactId>sentinel-core</artifactId>
+                <version>${project.version}</version>
+            </dependency>
+            <dependency>
+                <groupId>com.alibaba.csp</groupId>
+                <artifactId>sentinel-extension</artifactId>
+                <version>${project.version}</version>
+            </dependency>
+            <dependency>
+                <groupId>com.alibaba.csp</groupId>
+                <artifactId>sentinel-annotation-aspectj</artifactId>
+                <version>${project.version}</version>
+            </dependency>
+            <dependency>
+                <groupId>com.alibaba.csp</groupId>
+                <artifactId>sentinel-parameter-flow-control</artifactId>
+                <version>${project.version}</version>
+            </dependency>
+            <dependency>
+                <groupId>com.alibaba.csp</groupId>
+                <artifactId>sentinel-datasource-extension</artifactId>
+                <version>${project.version}</version>
+            </dependency>
+            <dependency>
+                <groupId>com.alibaba.csp</groupId>
+                <artifactId>sentinel-datasource-nacos</artifactId>
+                <version>${project.version}</version>
+            </dependency>
+            <dependency>
+                <groupId>com.alibaba.csp</groupId>
+                <artifactId>sentinel-datasource-zookeeper</artifactId>
+                <version>${project.version}</version>
+            </dependency>
+            <dependency>
+                <groupId>com.alibaba.csp</groupId>
+                <artifactId>sentinel-datasource-apollo</artifactId>
+                <version>${project.version}</version>
+            </dependency>
+            <dependency>
+                <groupId>com.alibaba.csp</groupId>
+                <artifactId>sentinel-transport-simple-http</artifactId>
+                <version>${project.version}</version>
+            </dependency>
+            <dependency>
+                <groupId>com.alibaba.csp</groupId>
+                <artifactId>sentinel-transport-netty-http</artifactId>
+                <version>${project.version}</version>
+            </dependency>
+            <dependency>
+                <groupId>com.alibaba.csp</groupId>
+                <artifactId>sentinel-transport-common</artifactId>
+                <version>${project.version}</version>
+            </dependency>
+            <dependency>
+                <groupId>com.alibaba.csp</groupId>
+                <artifactId>sentinel-cluster-common-default</artifactId>
+                <version>${project.version}</version>
+            </dependency>
+            <dependency>
+                <groupId>com.alibaba.csp</groupId>
+                <artifactId>sentinel-adapter</artifactId>
+                <version>${project.version}</version>
+            </dependency>
+
+            <dependency>
+                <groupId>com.alibaba</groupId>
+                <artifactId>fastjson</artifactId>
+                <version>${fastjson.version}</version>
+            </dependency>
+
+            <dependency>
+                <groupId>junit</groupId>
+                <artifactId>junit</artifactId>
+                <version>${junit.version}</version>
+                <scope>test</scope>
+            </dependency>
+            <dependency>
+                <groupId>org.mockito</groupId>
+                <artifactId>mockito-core</artifactId>
+                <version>${mockito.version}</version>
+                <scope>test</scope>
+            </dependency>
+            <dependency>
+                <groupId>org.assertj</groupId>
+                <artifactId>assertj-core</artifactId>
+                <version>${assertj.version}</version>
+                <scope>test</scope>
+            </dependency>
+            <dependency>
+                <groupId>org.awaitility</groupId>
+                <artifactId>awaitility</artifactId>
+                <version>${awaitility.version}</version>
+                <scope>test</scope>
+            </dependency>
+            <dependency>
+                <groupId>org.hamcrest</groupId>
+                <artifactId>java-hamcrest</artifactId>
+                <version>2.0.0.0</version>
+                <scope>test</scope>
+            </dependency>
+            <dependency>
+                <groupId>org.powermock</groupId>
+                <artifactId>powermock-module-junit4</artifactId>
+                <version>${powermock.version}</version>
+                <scope>test</scope>
+            </dependency>
+            <dependency>
+                <groupId>org.powermock</groupId>
+                <artifactId>powermock-api-mockito2</artifactId>
+                <version>${powermock.version}</version>
+                <scope>test</scope>
+            </dependency>
+        </dependencies>
+    </dependencyManagement>
+
+    <build>
+        <plugins>
+            <plugin>
+                <groupId>org.apache.maven.plugins</groupId>
+                <artifactId>maven-pmd-plugin</artifactId>
+                <version>${maven.pmd.version}</version>
+                <configuration>
+                    <sourceEncoding>${project.build.sourceEncoding}</sourceEncoding>
+                    <minimumPriority>1</minimumPriority>
+                    <excludeRoots>
+                        <excludeRoot>com/alibaba/csp/sentinel/benchmark</excludeRoot>
+                    </excludeRoots>
+                    <excludes>
+                        <exclude>**/*_jmhTest.java</exclude>
+                    </excludes>
+                    <printFailingErrors>true</printFailingErrors>
+                    <rulesets>
+                        <ruleset>rulesets/java/ali-comment.xml</ruleset>
+                        <ruleset>rulesets/java/ali-concurrent.xml</ruleset>
+                        <ruleset>rulesets/java/ali-constant.xml</ruleset>
+                        <ruleset>rulesets/java/ali-exception.xml</ruleset>
+                        <ruleset>rulesets/java/ali-flowcontrol.xml</ruleset>
+                        <ruleset>rulesets/java/ali-naming.xml</ruleset>
+                        <ruleset>rulesets/java/ali-oop.xml</ruleset>
+                        <ruleset>rulesets/java/ali-orm.xml</ruleset>
+                        <ruleset>rulesets/java/ali-other.xml</ruleset>
+                        <ruleset>rulesets/java/ali-set.xml</ruleset>
+                    </rulesets>
+                </configuration>
+                <executions>
+                    <execution>
+                        <phase>verify</phase>
+                        <goals>
+                            <goal>check</goal>
+                        </goals>
+                    </execution>
+                </executions>
+                <dependencies>
+                    <dependency>
+                        <groupId>com.alibaba.p3c</groupId>
+                        <artifactId>p3c-pmd</artifactId>
+                        <version>1.3.6</version>
+                    </dependency>
+                </dependencies>
+            </plugin>
+            <plugin>
+                <groupId>org.apache.maven.plugins</groupId>
+                <artifactId>maven-compiler-plugin</artifactId>
+                <version>${maven.compiler.version}</version>
+                <configuration>
+                    <source>${java.source.version}</source>
+                    <target>${java.target.version}</target>
+                    <encoding>${java.encoding}</encoding>
+                </configuration>
+            </plugin>
+            <plugin>
+                <groupId>org.apache.maven.plugins</groupId>
+                <artifactId>maven-surefire-plugin</artifactId>
+                <configuration>
+                    <!-- CircleCI build workaround -->
+                    <argLine>@{argLine} -Xms1024m -Xmx2048m</argLine>
+                    <useSystemClassLoader>false</useSystemClassLoader>
+                </configuration>
+            </plugin>
+            <plugin>
+                <groupId>org.jacoco</groupId>
+                <artifactId>jacoco-maven-plugin</artifactId>
+                <version>${maven.jacoco.version}</version>
+                <executions>
+                    <execution>
+                        <goals>
+                            <goal>prepare-agent</goal>
+                        </goals>
+                    </execution>
+                    <execution>
+                        <id>report</id>
+                        <phase>test</phase>
+                        <goals>
+                            <goal>report</goal>
+                        </goals>
+                    </execution>
+                </executions>
+            </plugin>
+        </plugins>
+        <pluginManagement>
+            <plugins>
+                <plugin>
+                    <groupId>org.apache.maven.plugins</groupId>
+                    <artifactId>maven-surefire-plugin</artifactId>
+                    <version>${maven.surefire.version}</version>
+                </plugin>
+                <plugin>
+                    <groupId>org.apache.maven.plugins</groupId>
+                    <artifactId>maven-jar-plugin</artifactId>
+                    <version>${maven.jar.version}</version>
+                </plugin>
+            </plugins>
+        </pluginManagement>
+    </build>
+
+    <profiles>
+        <profile>
+            <id>oss</id>
+            <build>
+                <plugins>
+                    <!-- Source -->
+                    <plugin>
+                        <groupId>org.apache.maven.plugins</groupId>
+                        <artifactId>maven-source-plugin</artifactId>
+                        <version>${maven.source.version}</version>
+                        <executions>
+                            <execution>
+                                <phase>package</phase>
+                                <goals>
+                                    <goal>jar-no-fork</goal>
+                                </goals>
+                            </execution>
+                        </executions>
+                    </plugin>
+                    <!-- Javadoc -->
+                    <plugin>
+                        <groupId>org.apache.maven.plugins</groupId>
+                        <artifactId>maven-javadoc-plugin</artifactId>
+                        <version>${maven.javadoc.version}</version>
+                        <executions>
+                            <execution>
+                                <phase>package</phase>
+                                <goals>
+                                    <goal>jar</goal>
+                                </goals>
+                                <configuration>
+                                    <locale>en_US</locale>
+                                    <encoding>UTF-8</encoding>
+                                    <charset>UTF-8</charset>
+                                    <doclint>none</doclint>
+                                </configuration>
+                            </execution>
+                        </executions>
+                    </plugin>
+                    <!-- GPG -->
+                    <plugin>
+                        <groupId>org.apache.maven.plugins</groupId>
+                        <artifactId>maven-gpg-plugin</artifactId>
+                        <version>${maven.gpg.version}</version>
+                        <executions>
+                            <execution>
+                                <phase>verify</phase>
+                                <goals>
+                                    <goal>sign</goal>
+                                </goals>
+                            </execution>
+                        </executions>
+                    </plugin>
+                </plugins>
+            </build>
+            <distributionManagement>
+                <snapshotRepository>
+                    <id>oss</id>
+                    <url>https://oss.sonatype.org/content/repositories/snapshots/</url>
+                </snapshotRepository>
+                <repository>
+                    <id>oss</id>
+                    <url>https://oss.sonatype.org/service/local/staging/deploy/maven2/</url>
+                </repository>
+            </distributionManagement>
+        </profile>
+    </profiles>
+
+</project>

+ 71 - 0
sentinel-adapter/pom.xml

@@ -0,0 +1,71 @@
+<?xml version="1.0" encoding="utf-8"?>
+
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+    <modelVersion>4.0.0</modelVersion>
+
+    <parent>
+        <groupId>com.alibaba.csp</groupId>
+        <artifactId>sentinel-parent</artifactId>
+        <version>1.6.2</version>
+    </parent>
+    <artifactId>sentinel-adapter</artifactId>
+    <packaging>pom</packaging>
+    <name>sentinel-adapter</name>
+    <description>The adapters of Sentinel</description>
+
+    <modules>
+        <module>sentinel-web-servlet</module>
+        <module>sentinel-dubbo-adapter</module>
+        <module>sentinel-apache-dubbo-adapter</module>
+        <module>sentinel-grpc-adapter</module>
+        <module>sentinel-zuul-adapter</module>
+        <module>sentinel-reactor-adapter</module>
+        <module>sentinel-spring-webflux-adapter</module>
+        <module>sentinel-api-gateway-adapter-common</module>
+        <module>sentinel-spring-cloud-gateway-adapter</module>
+    </modules>
+
+    <dependencyManagement>
+        <dependencies>
+            <dependency>
+                <groupId>com.alibaba.csp</groupId>
+                <artifactId>sentinel-core</artifactId>
+                <version>${project.version}</version>
+            </dependency>
+            <dependency>
+                <groupId>com.alibaba.csp</groupId>
+                <artifactId>sentinel-extension</artifactId>
+                <version>${project.version}</version>
+            </dependency>
+            <dependency>
+                <groupId>com.alibaba.csp</groupId>
+                <artifactId>sentinel-web-servlet</artifactId>
+                <version>${project.version}</version>
+            </dependency>
+            <dependency>
+                <groupId>com.alibaba.csp</groupId>
+                <artifactId>sentinel-reactor-adapter</artifactId>
+                <version>${project.version}</version>
+            </dependency>
+            <dependency>
+                <groupId>com.alibaba.csp</groupId>
+                <artifactId>sentinel-api-gateway-adapter-common</artifactId>
+                <version>${project.version}</version>
+            </dependency>
+
+            <dependency>
+                <groupId>junit</groupId>
+                <artifactId>junit</artifactId>
+                <version>${junit.version}</version>
+                <scope>test</scope>
+            </dependency>
+            <dependency>
+                <groupId>org.mockito</groupId>
+                <artifactId>mockito-core</artifactId>
+                <version>${mockito.version}</version>
+                <scope>test</scope>
+            </dependency>
+        </dependencies>
+    </dependencyManagement>
+</project>

+ 68 - 0
sentinel-adapter/sentinel-apache-dubbo-adapter/README.md

@@ -0,0 +1,68 @@
+# Sentinel Apache Dubbo Adapter
+
+> Note: 中文文档请见[此处](https://github.com/alibaba/Sentinel/wiki/主流框架的适配#dubbo)。
+
+Sentinel Dubbo Adapter provides service consumer filter and provider filter
+for [Apache Dubbo](https://dubbo.apache.org/en-us/) services.
+
+**Note: This adapter only supports Apache Dubbo 2.7.x and above.** For legacy `com.alibaba:dubbo` 2.6.x,
+please use `sentinel-dubbo-adapter` module instead.
+
+To use Sentinel Dubbo Adapter, you can simply add the following dependency to your `pom.xml`:
+
+```xml
+<dependency>
+    <groupId>com.alibaba.csp</groupId>
+    <artifactId>sentinel-apache-dubbo-adapter</artifactId>
+    <version>x.y.z</version>
+</dependency>
+```
+
+The Sentinel filters are **enabled by default**. Once you add the dependency,
+the Dubbo services and methods will become protected resources in Sentinel,
+which can leverage Sentinel's flow control and guard ability when rules are configured.
+Demos can be found in [sentinel-demo-dubbo](https://github.com/alibaba/Sentinel/tree/master/sentinel-demo/sentinel-demo-dubbo).
+
+If you don't want the filters enabled, you can manually disable them. For example:
+
+```xml
+<dubbo:consumer filter="-sentinel.dubbo.consumer.filter"/>
+
+<dubbo:provider filter="-sentinel.dubbo.provider.filter"/>
+```
+
+For more details of Dubbo filter, see [here](http://dubbo.apache.org/en-us/docs/dev/impls/filter.html).
+
+## Dubbo resources
+
+The resource for Dubbo services has two granularities: service interface and service method.
+
+- Service interface:resourceName format is `interfaceName`,e.g. `com.alibaba.csp.sentinel.demo.dubbo.FooService`
+- Service method:resourceName format is `interfaceName:methodSignature`,e.g. `com.alibaba.csp.sentinel.demo.dubbo.FooService:sayHello(java.lang.String)`
+
+## Flow control based on caller
+
+In many circumstances, it's also significant to control traffic flow based on the **caller**.
+For example, assuming that there are two services A and B, both of them initiate remote call requests to the service provider.
+If we want to limit the calls from service B only, we can set the `limitApp` of flow rule as the identifier of service B (e.g. service name).
+
+Sentinel Dubbo Adapter will automatically resolve the Dubbo consumer's *application name* as the caller's name (`origin`),
+and will bring the caller's name when doing resource protection.
+If `limitApp` of flow rules is not configured (`default`), flow control will take effects on all callers.
+If `limitApp` of a flow rule is configured with a caller, then the corresponding flow rule will only take effect on the specific caller.
+
+> Note: Dubbo consumer does not provide its Dubbo application name when doing RPC,
+so developers should manually put the application name into *attachment* at consumer side,
+then extract it at provider side. Sentinel Dubbo Adapter has implemented a filter (`DubboAppContextFilter`)
+where consumer can carry application name information to provider automatically.
+If the consumer does not use Sentinel Dubbo Adapter but requires flow control based on caller, developers can manually put the application name into attachment with the key `dubboApplication`.
+
+## Global fallback
+
+Sentinel Dubbo Adapter supports global fallback configuration.
+The global fallback will handle exceptions and give replacement result when blocked by
+flow control, degrade or system load protection. You can implement your own `DubboFallback` interface
+and then register to `DubboFallbackRegistry`. If no fallback is configured, Sentinel will wrap the `BlockException`
+then directly throw it out.
+
+Besides, we can also leverage [Dubbo mock mechanism](http://dubbo.apache.org/en-us/docs/user/demos/local-mock.html) to provide fallback implementation of degraded Dubbo services.

+ 50 - 0
sentinel-adapter/sentinel-apache-dubbo-adapter/pom.xml

@@ -0,0 +1,50 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+    <parent>
+        <artifactId>sentinel-adapter</artifactId>
+        <groupId>com.alibaba.csp</groupId>
+        <version>1.6.2</version>
+    </parent>
+    <modelVersion>4.0.0</modelVersion>
+
+    <artifactId>sentinel-apache-dubbo-adapter</artifactId>
+    <packaging>jar</packaging>
+
+    <properties>
+        <java.source.version>1.8</java.source.version>
+        <java.target.version>1.8</java.target.version>
+        <apache.dubbo.version>2.7.1</apache.dubbo.version>
+    </properties>
+
+    <dependencies>
+        <dependency>
+            <groupId>com.alibaba.csp</groupId>
+            <artifactId>sentinel-core</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.dubbo</groupId>
+            <artifactId>dubbo</artifactId>
+            <version>${apache.dubbo.version}</version>
+            <scope>provided</scope>
+        </dependency>
+
+        <dependency>
+            <groupId>junit</groupId>
+            <artifactId>junit</artifactId>
+            <scope>test</scope>
+        </dependency>
+
+        <dependency>
+            <groupId>org.mockito</groupId>
+            <artifactId>mockito-core</artifactId>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>com.alibaba</groupId>
+            <artifactId>fastjson</artifactId>
+            <scope>test</scope>
+        </dependency>
+    </dependencies>
+</project>

+ 43 - 0
sentinel-adapter/sentinel-apache-dubbo-adapter/src/main/java/com/alibaba/csp/sentinel/adapter/dubbo/DubboAppContextFilter.java

@@ -0,0 +1,43 @@
+/*
+ * Copyright 1999-2018 Alibaba Group Holding Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.alibaba.csp.sentinel.adapter.dubbo;
+
+import org.apache.dubbo.common.Constants;
+import org.apache.dubbo.common.extension.Activate;
+import org.apache.dubbo.rpc.Filter;
+import org.apache.dubbo.rpc.Invocation;
+import org.apache.dubbo.rpc.Invoker;
+import org.apache.dubbo.rpc.Result;
+import org.apache.dubbo.rpc.RpcContext;
+import org.apache.dubbo.rpc.RpcException;
+
+/**
+ * Puts current consumer's application name in the attachment of each invocation.
+ *
+ * @author Eric Zhao
+ */
+@Activate(group = "consumer")
+public class DubboAppContextFilter implements Filter {
+
+    @Override
+    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
+        String application = invoker.getUrl().getParameter(Constants.APPLICATION_KEY);
+        if (application != null) {
+            RpcContext.getContext().setAttachment(DubboUtils.SENTINEL_DUBBO_APPLICATION_KEY, application);
+        }
+        return invoker.invoke(invocation);
+    }
+}

+ 54 - 0
sentinel-adapter/sentinel-apache-dubbo-adapter/src/main/java/com/alibaba/csp/sentinel/adapter/dubbo/DubboUtils.java

@@ -0,0 +1,54 @@
+/*
+ * Copyright 1999-2018 Alibaba Group Holding Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.alibaba.csp.sentinel.adapter.dubbo;
+
+import org.apache.dubbo.rpc.Invocation;
+import org.apache.dubbo.rpc.Invoker;
+
+/**
+ * @author Eric Zhao
+ */
+public final class DubboUtils {
+
+    public static final String SENTINEL_DUBBO_APPLICATION_KEY = "dubboApplication";
+
+    public static String getApplication(Invocation invocation, String defaultValue) {
+        if (invocation == null || invocation.getAttachments() == null) {
+            throw new IllegalArgumentException("Bad invocation instance");
+        }
+        return invocation.getAttachment(SENTINEL_DUBBO_APPLICATION_KEY, defaultValue);
+    }
+
+    public static String getResourceName(Invoker<?> invoker, Invocation invocation) {
+        StringBuilder buf = new StringBuilder(64);
+        buf.append(invoker.getInterface().getName())
+            .append(":")
+            .append(invocation.getMethodName())
+            .append("(");
+        boolean isFirst = true;
+        for (Class<?> clazz : invocation.getParameterTypes()) {
+            if (!isFirst) {
+                buf.append(",");
+            }
+            buf.append(clazz.getName());
+            isFirst = false;
+        }
+        buf.append(")");
+        return buf.toString();
+    }
+
+    private DubboUtils() {}
+}

+ 83 - 0
sentinel-adapter/sentinel-apache-dubbo-adapter/src/main/java/com/alibaba/csp/sentinel/adapter/dubbo/SentinelDubboConsumerFilter.java

@@ -0,0 +1,83 @@
+/*
+ * Copyright 1999-2018 Alibaba Group Holding Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.alibaba.csp.sentinel.adapter.dubbo;
+
+import com.alibaba.csp.sentinel.Entry;
+import com.alibaba.csp.sentinel.EntryType;
+import com.alibaba.csp.sentinel.SphU;
+import com.alibaba.csp.sentinel.Tracer;
+import com.alibaba.csp.sentinel.log.RecordLog;
+import com.alibaba.csp.sentinel.slots.block.BlockException;
+
+import com.alibaba.csp.sentinel.adapter.dubbo.fallback.DubboFallbackRegistry;
+import org.apache.dubbo.common.extension.Activate;
+import org.apache.dubbo.rpc.Filter;
+import org.apache.dubbo.rpc.Invocation;
+import org.apache.dubbo.rpc.Invoker;
+import org.apache.dubbo.rpc.Result;
+import org.apache.dubbo.rpc.RpcException;
+
+/**
+ * <p>Dubbo service consumer filter for Sentinel. Auto activated by default.</p>
+ *
+ * If you want to disable the consumer filter, you can configure:
+ * <pre>
+ * &lt;dubbo:consumer filter="-sentinel.dubbo.consumer.filter"/&gt;
+ * </pre>
+ *
+ * @author Carpenter Lee
+ * @author Eric Zhao
+ */
+@Activate(group = "consumer")
+public class SentinelDubboConsumerFilter implements Filter {
+
+    public SentinelDubboConsumerFilter() {
+        RecordLog.info("Sentinel Apache Dubbo consumer filter initialized");
+    }
+
+    @Override
+    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
+        Entry interfaceEntry = null;
+        Entry methodEntry = null;
+        try {
+            String resourceName = DubboUtils.getResourceName(invoker, invocation);
+            interfaceEntry = SphU.entry(invoker.getInterface().getName(), EntryType.OUT);
+            methodEntry = SphU.entry(resourceName, EntryType.OUT);
+
+            Result result = invoker.invoke(invocation);
+            if (result.hasException()) {
+                Throwable e = result.getException();
+                // Record common exception.
+                Tracer.traceEntry(e, interfaceEntry);
+                Tracer.traceEntry(e, methodEntry);
+            }
+            return result;
+        } catch (BlockException e) {
+            return DubboFallbackRegistry.getConsumerFallback().handle(invoker, invocation, e);
+        } catch (RpcException e) {
+            Tracer.traceEntry(e, interfaceEntry);
+            Tracer.traceEntry(e, methodEntry);
+            throw e;
+        } finally {
+            if (methodEntry != null) {
+                methodEntry.exit();
+            }
+            if (interfaceEntry != null) {
+                interfaceEntry.exit();
+            }
+        }
+    }
+}

+ 93 - 0
sentinel-adapter/sentinel-apache-dubbo-adapter/src/main/java/com/alibaba/csp/sentinel/adapter/dubbo/SentinelDubboProviderFilter.java

@@ -0,0 +1,93 @@
+/*
+ * Copyright 1999-2018 Alibaba Group Holding Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.alibaba.csp.sentinel.adapter.dubbo;
+
+import com.alibaba.csp.sentinel.Entry;
+import com.alibaba.csp.sentinel.EntryType;
+import com.alibaba.csp.sentinel.SphU;
+import com.alibaba.csp.sentinel.Tracer;
+import com.alibaba.csp.sentinel.adapter.dubbo.fallback.DubboFallbackRegistry;
+import com.alibaba.csp.sentinel.context.ContextUtil;
+import com.alibaba.csp.sentinel.log.RecordLog;
+import com.alibaba.csp.sentinel.slots.block.BlockException;
+
+import org.apache.dubbo.common.extension.Activate;
+import org.apache.dubbo.rpc.Filter;
+import org.apache.dubbo.rpc.Invocation;
+import org.apache.dubbo.rpc.Invoker;
+import org.apache.dubbo.rpc.Result;
+import org.apache.dubbo.rpc.RpcException;
+
+/**
+ * <p>Apache Dubbo service provider filter that enables integration with Sentinel. Auto activated by default.</p>
+ * <p>Note: this only works for Apache Dubbo 2.7.x or above version.</p>
+ *
+ * If you want to disable the provider filter, you can configure:
+ * <pre>
+ * &lt;dubbo:provider filter="-sentinel.dubbo.provider.filter"/&gt;
+ * </pre>
+ *
+ * @author Carpenter Lee
+ * @author Eric Zhao
+ */
+@Activate(group = "provider")
+public class SentinelDubboProviderFilter implements Filter {
+
+    public SentinelDubboProviderFilter() {
+        RecordLog.info("Sentinel Apache Dubbo provider filter initialized");
+    }
+
+    @Override
+    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
+        // Get origin caller.
+        String application = DubboUtils.getApplication(invocation, "");
+
+        Entry interfaceEntry = null;
+        Entry methodEntry = null;
+        try {
+            String resourceName = DubboUtils.getResourceName(invoker, invocation);
+            String interfaceName = invoker.getInterface().getName();
+            // Only need to create entrance context at provider side, as context will take effect
+            // at entrance of invocation chain only (for inbound traffic).
+            ContextUtil.enter(resourceName, application);
+            interfaceEntry = SphU.entry(interfaceName, EntryType.IN);
+            methodEntry = SphU.entry(resourceName, EntryType.IN, 1, invocation.getArguments());
+
+            Result result = invoker.invoke(invocation);
+            if (result.hasException()) {
+                Throwable e = result.getException();
+                // Record common exception.
+                Tracer.traceEntry(e, interfaceEntry);
+                Tracer.traceEntry(e, methodEntry);
+            }
+            return result;
+        } catch (BlockException e) {
+            return DubboFallbackRegistry.getProviderFallback().handle(invoker, invocation, e);
+        } catch (RpcException e) {
+            Tracer.traceEntry(e, interfaceEntry);
+            Tracer.traceEntry(e, methodEntry);
+            throw e;
+        } finally {
+            if (methodEntry != null) {
+                methodEntry.exit(1, invocation.getArguments());
+            }
+            if (interfaceEntry != null) {
+                interfaceEntry.exit();
+            }
+            ContextUtil.exit();
+        }
+    }
+}

+ 35 - 0
sentinel-adapter/sentinel-apache-dubbo-adapter/src/main/java/com/alibaba/csp/sentinel/adapter/dubbo/fallback/DefaultDubboFallback.java

@@ -0,0 +1,35 @@
+/*
+ * Copyright 1999-2018 Alibaba Group Holding Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.alibaba.csp.sentinel.adapter.dubbo.fallback;
+
+import com.alibaba.csp.sentinel.slots.block.BlockException;
+import com.alibaba.csp.sentinel.slots.block.SentinelRpcException;
+
+import org.apache.dubbo.rpc.Invocation;
+import org.apache.dubbo.rpc.Invoker;
+import org.apache.dubbo.rpc.Result;
+
+/**
+ * @author Eric Zhao
+ */
+public class DefaultDubboFallback implements DubboFallback {
+
+    @Override
+    public Result handle(Invoker<?> invoker, Invocation invocation, BlockException ex) {
+        // Just wrap and throw the exception.
+        throw new SentinelRpcException(ex);
+    }
+}

+ 41 - 0
sentinel-adapter/sentinel-apache-dubbo-adapter/src/main/java/com/alibaba/csp/sentinel/adapter/dubbo/fallback/DubboFallback.java

@@ -0,0 +1,41 @@
+/*
+ * Copyright 1999-2018 Alibaba Group Holding Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.alibaba.csp.sentinel.adapter.dubbo.fallback;
+
+import com.alibaba.csp.sentinel.slots.block.BlockException;
+
+import org.apache.dubbo.rpc.Invocation;
+import org.apache.dubbo.rpc.Invoker;
+import org.apache.dubbo.rpc.Result;
+
+/**
+ * Fallback handler for Dubbo services.
+ *
+ * @author Eric Zhao
+ */
+@FunctionalInterface
+public interface DubboFallback {
+
+    /**
+     * Handle the block exception and provide fallback result.
+     *
+     * @param invoker Dubbo invoker
+     * @param invocation Dubbo invocation
+     * @param ex block exception
+     * @return fallback result
+     */
+    Result handle(Invoker<?> invoker, Invocation invocation, BlockException ex);
+}

+ 54 - 0
sentinel-adapter/sentinel-apache-dubbo-adapter/src/main/java/com/alibaba/csp/sentinel/adapter/dubbo/fallback/DubboFallbackRegistry.java

@@ -0,0 +1,54 @@
+/*
+ * Copyright 1999-2018 Alibaba Group Holding Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.alibaba.csp.sentinel.adapter.dubbo.fallback;
+
+import com.alibaba.csp.sentinel.util.AssertUtil;
+
+/**
+ * <p>Global fallback registry for Dubbo.</p>
+ *
+ * <p>
+ * Note: Circuit breaking is mainly designed for consumer. The provider should not
+ * give fallback result in most circumstances.
+ * </p>
+ *
+ * @author Eric Zhao
+ */
+public final class DubboFallbackRegistry {
+
+    private static volatile DubboFallback consumerFallback = new DefaultDubboFallback();
+    private static volatile DubboFallback providerFallback = new DefaultDubboFallback();
+
+    public static DubboFallback getConsumerFallback() {
+        return consumerFallback;
+    }
+
+    public static void setConsumerFallback(DubboFallback consumerFallback) {
+        AssertUtil.notNull(consumerFallback, "consumerFallback cannot be null");
+        DubboFallbackRegistry.consumerFallback = consumerFallback;
+    }
+
+    public static DubboFallback getProviderFallback() {
+        return providerFallback;
+    }
+
+    public static void setProviderFallback(DubboFallback providerFallback) {
+        AssertUtil.notNull(providerFallback, "providerFallback cannot be null");
+        DubboFallbackRegistry.providerFallback = providerFallback;
+    }
+
+    private DubboFallbackRegistry() {}
+}

+ 3 - 0
sentinel-adapter/sentinel-apache-dubbo-adapter/src/main/resources/META-INF/dubbo/org.apache.dubbo.rpc.Filter

@@ -0,0 +1,3 @@
+sentinel.dubbo.provider.filter=com.alibaba.csp.sentinel.adapter.dubbo.SentinelDubboProviderFilter
+sentinel.dubbo.consumer.filter=com.alibaba.csp.sentinel.adapter.dubbo.SentinelDubboConsumerFilter
+dubbo.application.context.name.filter=com.alibaba.csp.sentinel.adapter.dubbo.DubboAppContextFilter

+ 40 - 0
sentinel-adapter/sentinel-apache-dubbo-adapter/src/test/java/com/alibaba/csp/sentinel/BaseTest.java

@@ -0,0 +1,40 @@
+/*
+ * Copyright 1999-2018 Alibaba Group Holding Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.alibaba.csp.sentinel;
+
+import com.alibaba.csp.sentinel.slots.clusterbuilder.ClusterBuilderSlot;
+
+import org.apache.dubbo.rpc.RpcContext;
+
+/**
+ * Base test class, provide common methods for subClass
+ * The package is same as CtSph, to call CtSph.resetChainMap() method for test
+ *
+ * Note: Only for test. DO NOT USE IN PRODUCTION!
+ *
+ * @author cdfive
+ */
+public class BaseTest {
+
+    /**
+     * Clean up resources for context, clusterNodeMap, processorSlotChainMap
+     */
+    protected static void cleanUpAll() {
+        RpcContext.removeContext();
+        ClusterBuilderSlot.getClusterNodeMap().clear();
+        CtSph.resetChainMap();
+    }
+}

+ 75 - 0
sentinel-adapter/sentinel-apache-dubbo-adapter/src/test/java/com/alibaba/csp/sentinel/adapter/dubbo/DubboAppContextFilterTest.java

@@ -0,0 +1,75 @@
+/*
+ * Copyright 1999-2018 Alibaba Group Holding Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.alibaba.csp.sentinel.adapter.dubbo;
+
+import com.alibaba.csp.sentinel.BaseTest;
+
+import org.apache.dubbo.common.URL;
+import org.apache.dubbo.rpc.Invocation;
+import org.apache.dubbo.rpc.Invoker;
+import org.apache.dubbo.rpc.RpcContext;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+import static org.junit.Assert.*;
+import static org.mockito.Mockito.*;
+
+/**
+ * @author cdfive
+ */
+public class DubboAppContextFilterTest extends BaseTest {
+
+    private DubboAppContextFilter filter = new DubboAppContextFilter();
+
+    @Before
+    public void setUp() {
+        cleanUpAll();
+    }
+
+    @After
+    public void cleanUp() {
+        cleanUpAll();
+    }
+
+    @Test
+    public void testInvokeApplicationKey() {
+        Invoker invoker = mock(Invoker.class);
+        Invocation invocation = mock(Invocation.class);
+        URL url = URL.valueOf("test://test:111/test?application=serviceA");
+        when(invoker.getUrl()).thenReturn(url);
+
+        filter.invoke(invoker, invocation);
+        verify(invoker).invoke(invocation);
+
+        String application = RpcContext.getContext().getAttachment(DubboUtils.SENTINEL_DUBBO_APPLICATION_KEY);
+        assertEquals("serviceA", application);
+    }
+
+    @Test
+    public void testInvokeNullApplicationKey() {
+        Invoker invoker = mock(Invoker.class);
+        Invocation invocation = mock(Invocation.class);
+        URL url = URL.valueOf("test://test:111/test?application=");
+        when(invoker.getUrl()).thenReturn(url);
+
+        filter.invoke(invoker, invocation);
+        verify(invoker).invoke(invocation);
+
+        String application = RpcContext.getContext().getAttachment(DubboUtils.SENTINEL_DUBBO_APPLICATION_KEY);
+        assertNull(application);
+    }
+}

+ 75 - 0
sentinel-adapter/sentinel-apache-dubbo-adapter/src/test/java/com/alibaba/csp/sentinel/adapter/dubbo/DubboUtilsTest.java

@@ -0,0 +1,75 @@
+/*
+ * Copyright 1999-2018 Alibaba Group Holding Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.alibaba.csp.sentinel.adapter.dubbo;
+
+import org.apache.dubbo.rpc.Invocation;
+import org.apache.dubbo.rpc.Invoker;
+import org.junit.Test;
+
+import java.lang.reflect.Method;
+import java.util.HashMap;
+
+import com.alibaba.csp.sentinel.adapter.dubbo.provider.DemoService;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
+import static org.mockito.Mockito.*;
+
+/**
+ * @author cdfive
+ */
+public class DubboUtilsTest {
+
+    @Test
+    public void testGetApplication() {
+        Invocation invocation = mock(Invocation.class);
+        when(invocation.getAttachments()).thenReturn(new HashMap<>());
+        when(invocation.getAttachment(DubboUtils.SENTINEL_DUBBO_APPLICATION_KEY, ""))
+            .thenReturn("consumerA");
+
+        String application = DubboUtils.getApplication(invocation, "");
+        verify(invocation).getAttachment(DubboUtils.SENTINEL_DUBBO_APPLICATION_KEY, "");
+
+        assertEquals("consumerA", application);
+    }
+
+    @Test(expected = IllegalArgumentException.class)
+    public void testGetApplicationNoAttachments() {
+        Invocation invocation = mock(Invocation.class);
+        when(invocation.getAttachments()).thenReturn(null);
+        when(invocation.getAttachment(DubboUtils.SENTINEL_DUBBO_APPLICATION_KEY, ""))
+            .thenReturn("consumerA");
+
+        DubboUtils.getApplication(invocation, "");
+
+        fail("No attachments in invocation, IllegalArgumentException should be thrown!");
+    }
+
+    @Test
+    public void testGetResourceName() {
+        Invoker invoker = mock(Invoker.class);
+        when(invoker.getInterface()).thenReturn(DemoService.class);
+
+        Invocation invocation = mock(Invocation.class);
+        Method method = DemoService.class.getMethods()[0];
+        when(invocation.getMethodName()).thenReturn(method.getName());
+        when(invocation.getParameterTypes()).thenReturn(method.getParameterTypes());
+
+        String resourceName = DubboUtils.getResourceName(invoker, invocation);
+
+        assertEquals("com.alibaba.csp.sentinel.adapter.dubbo.provider.DemoService:sayHello(java.lang.String,int)", resourceName);
+    }
+}

+ 142 - 0
sentinel-adapter/sentinel-apache-dubbo-adapter/src/test/java/com/alibaba/csp/sentinel/adapter/dubbo/SentinelDubboConsumerFilterTest.java

@@ -0,0 +1,142 @@
+/*
+ * Copyright 1999-2018 Alibaba Group Holding Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.alibaba.csp.sentinel.adapter.dubbo;
+
+import com.alibaba.csp.sentinel.BaseTest;
+import com.alibaba.csp.sentinel.Constants;
+import com.alibaba.csp.sentinel.Entry;
+import com.alibaba.csp.sentinel.EntryType;
+import com.alibaba.csp.sentinel.adapter.dubbo.provider.DemoService;
+import com.alibaba.csp.sentinel.context.Context;
+import com.alibaba.csp.sentinel.context.ContextUtil;
+import com.alibaba.csp.sentinel.node.ClusterNode;
+import com.alibaba.csp.sentinel.node.DefaultNode;
+import com.alibaba.csp.sentinel.node.Node;
+import com.alibaba.csp.sentinel.node.StatisticNode;
+import com.alibaba.csp.sentinel.slotchain.ResourceWrapper;
+
+import org.apache.dubbo.rpc.Invocation;
+import org.apache.dubbo.rpc.Invoker;
+import org.apache.dubbo.rpc.Result;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+import java.lang.reflect.Method;
+import java.util.Map;
+import java.util.Set;
+
+import static org.junit.Assert.*;
+import static org.mockito.Mockito.*;
+
+/**
+ * @author cdfive
+ */
+public class SentinelDubboConsumerFilterTest extends BaseTest {
+
+    private SentinelDubboConsumerFilter filter = new SentinelDubboConsumerFilter();
+
+    @Before
+    public void setUp() {
+        cleanUpAll();
+    }
+
+    @After
+    public void cleanUp() {
+        cleanUpAll();
+    }
+
+    @Test
+    public void testInvoke() {
+        final Invoker invoker = mock(Invoker.class);
+        when(invoker.getInterface()).thenReturn(DemoService.class);
+
+        final Invocation invocation = mock(Invocation.class);
+        Method method = DemoService.class.getMethods()[0];
+        when(invocation.getMethodName()).thenReturn(method.getName());
+        when(invocation.getParameterTypes()).thenReturn(method.getParameterTypes());
+
+        final Result result = mock(Result.class);
+        when(result.hasException()).thenReturn(false);
+        when(invoker.invoke(invocation)).thenAnswer(invocationOnMock -> {
+            verifyInvocationStructure(invoker, invocation);
+            return result;
+        });
+
+        filter.invoke(invoker, invocation);
+        verify(invoker).invoke(invocation);
+
+        Context context = ContextUtil.getContext();
+        assertNull(context);
+    }
+
+    /**
+     * Simply verify invocation structure in memory:
+     * EntranceNode(defaultContextName)
+     * --InterfaceNode(interfaceName)
+     * ----MethodNode(resourceName)
+     */
+    private void verifyInvocationStructure(Invoker invoker, Invocation invocation) {
+        Context context = ContextUtil.getContext();
+        assertNotNull(context);
+
+        // As not call ContextUtil.enter(resourceName, application) in SentinelDubboConsumerFilter, use default context
+        // In actual project, a consumer is usually also a provider, the context will be created by SentinelDubboProviderFilter
+        // If consumer is on the top of Dubbo RPC invocation chain, use default context
+        String resourceName = DubboUtils.getResourceName(invoker, invocation);
+        assertEquals(Constants.CONTEXT_DEFAULT_NAME, context.getName());
+        assertEquals("", context.getOrigin());
+
+        DefaultNode entranceNode = context.getEntranceNode();
+        ResourceWrapper entranceResource = entranceNode.getId();
+        assertEquals(Constants.CONTEXT_DEFAULT_NAME, entranceResource.getName());
+        assertSame(EntryType.IN, entranceResource.getType());
+
+        // As SphU.entry(interfaceName, EntryType.OUT);
+        Set<Node> childList = entranceNode.getChildList();
+        assertEquals(1, childList.size());
+        DefaultNode interfaceNode = (DefaultNode) childList.iterator().next();
+        ResourceWrapper interfaceResource = interfaceNode.getId();
+        assertEquals(DemoService.class.getName(), interfaceResource.getName());
+        assertSame(EntryType.OUT, interfaceResource.getType());
+
+        // As SphU.entry(resourceName, EntryType.OUT);
+        childList = interfaceNode.getChildList();
+        assertEquals(1, childList.size());
+        DefaultNode methodNode = (DefaultNode) childList.iterator().next();
+        ResourceWrapper methodResource = methodNode.getId();
+        assertEquals(resourceName, methodResource.getName());
+        assertSame(EntryType.OUT, methodResource.getType());
+
+        // Verify curEntry
+        Entry curEntry = context.getCurEntry();
+        assertSame(methodNode, curEntry.getCurNode());
+        assertSame(interfaceNode, curEntry.getLastNode());
+        assertNull(curEntry.getOriginNode());// As context origin is not "", no originNode should be created in curEntry
+
+        // Verify clusterNode
+        ClusterNode methodClusterNode = methodNode.getClusterNode();
+        ClusterNode interfaceClusterNode = interfaceNode.getClusterNode();
+        assertNotSame(methodClusterNode, interfaceClusterNode);// Different resource->Different ProcessorSlot->Different ClusterNode
+
+        // As context origin is "", the StatisticNode should not be created in originCountMap of ClusterNode
+        Map<String, StatisticNode> methodOriginCountMap = methodClusterNode.getOriginCountMap();
+        assertEquals(0, methodOriginCountMap.size());
+
+        Map<String, StatisticNode> interfaceOriginCountMap = interfaceClusterNode.getOriginCountMap();
+        assertEquals(0, interfaceOriginCountMap.size());
+    }
+}

+ 145 - 0
sentinel-adapter/sentinel-apache-dubbo-adapter/src/test/java/com/alibaba/csp/sentinel/adapter/dubbo/SentinelDubboProviderFilterTest.java

@@ -0,0 +1,145 @@
+/*
+ * Copyright 1999-2018 Alibaba Group Holding Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.alibaba.csp.sentinel.adapter.dubbo;
+
+import com.alibaba.csp.sentinel.BaseTest;
+import com.alibaba.csp.sentinel.Entry;
+import com.alibaba.csp.sentinel.EntryType;
+import com.alibaba.csp.sentinel.adapter.dubbo.provider.DemoService;
+import com.alibaba.csp.sentinel.context.Context;
+import com.alibaba.csp.sentinel.context.ContextUtil;
+import com.alibaba.csp.sentinel.node.ClusterNode;
+import com.alibaba.csp.sentinel.node.DefaultNode;
+import com.alibaba.csp.sentinel.node.Node;
+import com.alibaba.csp.sentinel.node.StatisticNode;
+import com.alibaba.csp.sentinel.slotchain.ResourceWrapper;
+
+import org.apache.dubbo.rpc.Invocation;
+import org.apache.dubbo.rpc.Invoker;
+import org.apache.dubbo.rpc.Result;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+import java.lang.reflect.Method;
+import java.util.Map;
+import java.util.Set;
+
+import static org.junit.Assert.*;
+import static org.mockito.Mockito.*;
+
+/**
+ * @author cdfive
+ */
+public class SentinelDubboProviderFilterTest extends BaseTest {
+
+    private SentinelDubboProviderFilter filter = new SentinelDubboProviderFilter();
+
+    @Before
+    public void setUp() {
+        cleanUpAll();
+    }
+
+    @After
+    public void cleanUp() {
+        cleanUpAll();
+    }
+
+    @Test
+    public void testInvoke() {
+        final String originApplication = "consumerA";
+
+        final Invoker invoker = mock(Invoker.class);
+        when(invoker.getInterface()).thenReturn(DemoService.class);
+
+        final Invocation invocation = mock(Invocation.class);
+        Method method = DemoService.class.getMethods()[0];
+        when(invocation.getMethodName()).thenReturn(method.getName());
+        when(invocation.getParameterTypes()).thenReturn(method.getParameterTypes());
+        when(invocation.getAttachment(DubboUtils.SENTINEL_DUBBO_APPLICATION_KEY, ""))
+            .thenReturn(originApplication);
+
+        final Result result = mock(Result.class);
+        when(result.hasException()).thenReturn(false);
+        when(invoker.invoke(invocation)).thenAnswer(invocationOnMock -> {
+            verifyInvocationStructure(originApplication, invoker, invocation);
+            return result;
+        });
+
+        filter.invoke(invoker, invocation);
+        verify(invoker).invoke(invocation);
+
+        Context context = ContextUtil.getContext();
+        assertNull(context);
+    }
+
+    /**
+     * Simply verify invocation structure in memory:
+     * EntranceNode(resourceName)
+     * --InterfaceNode(interfaceName)
+     * ----MethodNode(resourceName)
+     */
+    private void verifyInvocationStructure(String originApplication, Invoker invoker, Invocation invocation) {
+        Context context = ContextUtil.getContext();
+        assertNotNull(context);
+
+        // As ContextUtil.enter(resourceName, application) in SentinelDubboProviderFilter
+        String resourceName = DubboUtils.getResourceName(invoker, invocation);
+        assertEquals(resourceName, context.getName());
+        assertEquals(originApplication, context.getOrigin());
+
+        DefaultNode entranceNode = context.getEntranceNode();
+        ResourceWrapper entranceResource = entranceNode.getId();
+        assertEquals(resourceName, entranceResource.getName());
+        assertSame(EntryType.IN, entranceResource.getType());
+
+        // As SphU.entry(interfaceName, EntryType.IN);
+        Set<Node> childList = entranceNode.getChildList();
+        assertEquals(1, childList.size());
+        DefaultNode interfaceNode = (DefaultNode) childList.iterator().next();
+        ResourceWrapper interfaceResource = interfaceNode.getId();
+        assertEquals(DemoService.class.getName(), interfaceResource.getName());
+        assertSame(EntryType.IN, interfaceResource.getType());
+
+        // As SphU.entry(resourceName, EntryType.IN, 1, invocation.getArguments());
+        childList = interfaceNode.getChildList();
+        assertEquals(1, childList.size());
+        DefaultNode methodNode = (DefaultNode) childList.iterator().next();
+        ResourceWrapper methodResource = methodNode.getId();
+        assertEquals(resourceName, methodResource.getName());
+        assertSame(EntryType.IN, methodResource.getType());
+
+        // Verify curEntry
+        Entry curEntry = context.getCurEntry();
+        assertSame(methodNode, curEntry.getCurNode());
+        assertSame(interfaceNode, curEntry.getLastNode());
+        assertNotNull(curEntry.getOriginNode());// As context origin is not "", originNode should be created
+
+        // Verify clusterNode
+        ClusterNode methodClusterNode = methodNode.getClusterNode();
+        ClusterNode interfaceClusterNode = interfaceNode.getClusterNode();
+        assertNotSame(methodClusterNode, interfaceClusterNode);// Different resource->Different ProcessorSlot->Different ClusterNode
+
+        // As context origin is not "", the StatisticNode should be created in originCountMap of ClusterNode
+        Map<String, StatisticNode> methodOriginCountMap = methodClusterNode.getOriginCountMap();
+        assertEquals(1, methodOriginCountMap.size());
+        assertTrue(methodOriginCountMap.containsKey(originApplication));
+
+        Map<String, StatisticNode> interfaceOriginCountMap = interfaceClusterNode.getOriginCountMap();
+        assertEquals(1, interfaceOriginCountMap.size());
+        assertTrue(interfaceOriginCountMap.containsKey(originApplication));
+    }
+}

+ 50 - 0
sentinel-adapter/sentinel-apache-dubbo-adapter/src/test/java/com/alibaba/csp/sentinel/adapter/dubbo/fallback/DubboFallbackRegistryTest.java

@@ -0,0 +1,50 @@
+/*
+ * Copyright 1999-2018 Alibaba Group Holding Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.alibaba.csp.sentinel.adapter.dubbo.fallback;
+
+import com.alibaba.csp.sentinel.slots.block.BlockException;
+import com.alibaba.csp.sentinel.slots.block.SentinelRpcException;
+import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
+
+import org.apache.dubbo.rpc.Result;
+import org.apache.dubbo.rpc.RpcResult;
+import org.junit.Assert;
+import org.junit.Test;
+
+/**
+ * @author Eric Zhao
+ */
+public class DubboFallbackRegistryTest {
+
+    @Test(expected = SentinelRpcException.class)
+    public void testDefaultFallback() {
+        // Test for default.
+        BlockException ex = new FlowException("xxx");
+        DubboFallbackRegistry.getConsumerFallback()
+            .handle(null, null, ex);
+    }
+
+    @Test
+    public void testCustomFallback() {
+        BlockException ex = new FlowException("xxx");
+        DubboFallbackRegistry.setConsumerFallback(
+            (invoker, invocation, e) -> new RpcResult("Error: " + e.getClass().getName()));
+        Result result = DubboFallbackRegistry.getConsumerFallback()
+            .handle(null, null, ex);
+        Assert.assertFalse("The invocation should not fail", result.hasException());
+        Assert.assertEquals("Error: " + ex.getClass().getName(), result.getValue());
+    }
+}

+ 23 - 0
sentinel-adapter/sentinel-apache-dubbo-adapter/src/test/java/com/alibaba/csp/sentinel/adapter/dubbo/provider/DemoService.java

@@ -0,0 +1,23 @@
+/*
+ * Copyright 1999-2018 Alibaba Group Holding Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.alibaba.csp.sentinel.adapter.dubbo.provider;
+
+/**
+ * @author leyou
+ */
+public interface DemoService {
+    String sayHello(String name, int n);
+}

+ 27 - 0
sentinel-adapter/sentinel-apache-dubbo-adapter/src/test/java/com/alibaba/csp/sentinel/adapter/dubbo/provider/impl/DemoServiceImpl.java

@@ -0,0 +1,27 @@
+/*
+ * Copyright 1999-2018 Alibaba Group Holding Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.alibaba.csp.sentinel.adapter.dubbo.provider.impl;
+
+import com.alibaba.csp.sentinel.adapter.dubbo.provider.DemoService;
+
+/**
+ * @author leyou
+ */
+public class DemoServiceImpl implements DemoService {
+    public String sayHello(String name, int n) {
+        return "Hello " + name + ", " + n;
+    }
+}

+ 18 - 0
sentinel-adapter/sentinel-apache-dubbo-adapter/src/test/resources/spring-dubbo-consumer-filter.xml

@@ -0,0 +1,18 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<beans xmlns="http://www.springframework.org/schema/beans"
+       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+       xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"
+       xsi:schemaLocation="http://www.springframework.org/schema/beans
+       http://www.springframework.org/schema/beans/spring-beans.xsd
+       http://code.alibabatech.com/schema/dubbo
+       http://code.alibabatech.com/schema/dubbo/dubbo.xsd">
+
+    <dubbo:application name="demo-consumer"/>
+    <dubbo:registry address="multicast://224.5.6.7:1234"/>
+    <dubbo:protocol name="dubbo" port="20880"/>
+    <dubbo:service interface="com.alibaba.csp.sentinel.adapter.dubbo.provider.DemoService" ref="demoServiceImp" />
+    <bean id="demoServiceImp" class="com.alibaba.csp.sentinel.adapter.dubbo.provider.impl.DemoServiceImpl"/>
+
+    <dubbo:reference id="demoService" interface="com.alibaba.csp.sentinel.adapter.dubbo.provider.DemoService"/>
+
+</beans>

+ 18 - 0
sentinel-adapter/sentinel-apache-dubbo-adapter/src/test/resources/spring-dubbo-provider-filter.xml

@@ -0,0 +1,18 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<beans xmlns="http://www.springframework.org/schema/beans"
+       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+       xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"
+       xsi:schemaLocation="http://www.springframework.org/schema/beans
+       http://www.springframework.org/schema/beans/spring-beans.xsd
+       http://code.alibabatech.com/schema/dubbo
+       http://code.alibabatech.com/schema/dubbo/dubbo.xsd">
+
+    <dubbo:application name="demo-provider"/>
+    <dubbo:registry address="multicast://224.5.6.7:1234"/>
+    <dubbo:protocol name="dubbo" port="20880"/>
+    <dubbo:service interface="com.alibaba.csp.sentinel.adapter.dubbo.provider.DemoService" ref="demoServiceImp" />
+    <bean id="demoServiceImp" class="com.alibaba.csp.sentinel.adapter.dubbo.provider.impl.DemoServiceImpl"/>
+
+    <dubbo:reference id="demoService" interface="com.alibaba.csp.sentinel.adapter.dubbo.provider.DemoService"/>
+
+</beans>

+ 8 - 0
sentinel-adapter/sentinel-api-gateway-adapter-common/README.md

@@ -0,0 +1,8 @@
+# Sentinel API Gateway Adapter Common
+
+The `sentinel-api-gateway-adapter-common` module provides common abstraction for
+API gateway flow control:
+
+- `GatewayFlowRule`: flow control rule specific for route or API defined in API gateway.
+This can be automatically converted to `FlowRule` or `ParamFlowRule`.
+- `ApiDefinition`: gateway API definition with a group of predicates

+ 51 - 0
sentinel-adapter/sentinel-api-gateway-adapter-common/pom.xml

@@ -0,0 +1,51 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+    <parent>
+        <artifactId>sentinel-adapter</artifactId>
+        <groupId>com.alibaba.csp</groupId>
+        <version>1.6.2</version>
+    </parent>
+    <modelVersion>4.0.0</modelVersion>
+
+    <artifactId>sentinel-api-gateway-adapter-common</artifactId>
+    <packaging>jar</packaging>
+
+    <properties>
+        <java.source.version>1.7</java.source.version>
+        <java.target.version>1.7</java.target.version>
+    </properties>
+
+    <dependencies>
+        <dependency>
+            <groupId>com.alibaba.csp</groupId>
+            <artifactId>sentinel-core</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>com.alibaba.csp</groupId>
+            <artifactId>sentinel-parameter-flow-control</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>com.alibaba.csp</groupId>
+            <artifactId>sentinel-transport-common</artifactId>
+            <scope>provided</scope>
+        </dependency>
+
+        <dependency>
+            <groupId>junit</groupId>
+            <artifactId>junit</artifactId>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.assertj</groupId>
+            <artifactId>assertj-core</artifactId>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.mockito</groupId>
+            <artifactId>mockito-core</artifactId>
+            <scope>test</scope>
+        </dependency>
+    </dependencies>
+</project>

+ 52 - 0
sentinel-adapter/sentinel-api-gateway-adapter-common/src/main/java/com/alibaba/csp/sentinel/adapter/gateway/common/SentinelGatewayConstants.java

@@ -0,0 +1,52 @@
+/*
+ * Copyright 1999-2019 Alibaba Group Holding Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.alibaba.csp.sentinel.adapter.gateway.common;
+
+/**
+ * @author Eric Zhao
+ * @since 1.6.0
+ */
+public final class SentinelGatewayConstants {
+
+    public static final int APP_TYPE_GATEWAY = 1;
+
+    public static final int RESOURCE_MODE_ROUTE_ID = 0;
+    public static final int RESOURCE_MODE_CUSTOM_API_NAME = 1;
+
+    public static final int PARAM_PARSE_STRATEGY_CLIENT_IP = 0;
+    public static final int PARAM_PARSE_STRATEGY_HOST = 1;
+    public static final int PARAM_PARSE_STRATEGY_HEADER = 2;
+    public static final int PARAM_PARSE_STRATEGY_URL_PARAM = 3;
+    public static final int PARAM_PARSE_STRATEGY_COOKIE = 4;
+
+    public static final int URL_MATCH_STRATEGY_EXACT = 0;
+    public static final int URL_MATCH_STRATEGY_PREFIX = 1;
+    public static final int URL_MATCH_STRATEGY_REGEX = 2;
+
+    public static final int PARAM_MATCH_STRATEGY_EXACT = 0;
+    public static final int PARAM_MATCH_STRATEGY_PREFIX = 1;
+    public static final int PARAM_MATCH_STRATEGY_REGEX = 2;
+    public static final int PARAM_MATCH_STRATEGY_CONTAINS = 3;
+
+    public static final String GATEWAY_CONTEXT_DEFAULT = "sentinel_gateway_context_default";
+    public static final String GATEWAY_CONTEXT_PREFIX = "sentinel_gateway_context$$";
+    public static final String GATEWAY_CONTEXT_ROUTE_PREFIX = "sentinel_gateway_context$$route$$";
+
+    public static final String GATEWAY_NOT_MATCH_PARAM = "$NM";
+    public static final String GATEWAY_DEFAULT_PARAM = "$D";
+
+    private SentinelGatewayConstants() {}
+}

+ 81 - 0
sentinel-adapter/sentinel-api-gateway-adapter-common/src/main/java/com/alibaba/csp/sentinel/adapter/gateway/common/api/ApiDefinition.java

@@ -0,0 +1,81 @@
+/*
+ * Copyright 1999-2019 Alibaba Group Holding Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.alibaba.csp.sentinel.adapter.gateway.common.api;
+
+import java.util.Objects;
+import java.util.Set;
+
+/**
+ * A group of HTTP API patterns.
+ *
+ * @author Eric Zhao
+ * @since 1.6.0
+ */
+public class ApiDefinition {
+
+    private String apiName;
+    private Set<ApiPredicateItem> predicateItems;
+
+    public ApiDefinition() {}
+
+    public ApiDefinition(String apiName) {
+        this.apiName = apiName;
+    }
+
+    public String getApiName() {
+        return apiName;
+    }
+
+    public ApiDefinition setApiName(String apiName) {
+        this.apiName = apiName;
+        return this;
+    }
+
+    public Set<ApiPredicateItem> getPredicateItems() {
+        return predicateItems;
+    }
+
+    public ApiDefinition setPredicateItems(Set<ApiPredicateItem> predicateItems) {
+        this.predicateItems = predicateItems;
+        return this;
+    }
+
+    @Override
+    public boolean equals(Object o) {
+        if (this == o) { return true; }
+        if (o == null || getClass() != o.getClass()) { return false; }
+
+        ApiDefinition that = (ApiDefinition)o;
+
+        if (!Objects.equals(apiName, that.apiName)) { return false; }
+        return Objects.equals(predicateItems, that.predicateItems);
+    }
+
+    @Override
+    public int hashCode() {
+        int result = apiName != null ? apiName.hashCode() : 0;
+        result = 31 * result + (predicateItems != null ? predicateItems.hashCode() : 0);
+        return result;
+    }
+
+    @Override
+    public String toString() {
+        return "ApiDefinition{" +
+            "apiName='" + apiName + '\'' +
+            ", predicateItems=" + predicateItems +
+            '}';
+    }
+}

+ 32 - 0
sentinel-adapter/sentinel-api-gateway-adapter-common/src/main/java/com/alibaba/csp/sentinel/adapter/gateway/common/api/ApiDefinitionChangeObserver.java

@@ -0,0 +1,32 @@
+/*
+ * Copyright 1999-2019 Alibaba Group Holding Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.alibaba.csp.sentinel.adapter.gateway.common.api;
+
+import java.util.Set;
+
+/**
+ * @author Eric Zhao
+ * @since 1.6.0
+ */
+public interface ApiDefinitionChangeObserver {
+
+    /**
+     * Notify the observer about the new gateway API definitions.
+     *
+     * @param apiDefinitions new set of gateway API definition
+     */
+    void onChange(Set<ApiDefinition> apiDefinitions);
+}

+ 74 - 0
sentinel-adapter/sentinel-api-gateway-adapter-common/src/main/java/com/alibaba/csp/sentinel/adapter/gateway/common/api/ApiPathPredicateItem.java

@@ -0,0 +1,74 @@
+/*
+ * Copyright 1999-2019 Alibaba Group Holding Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.alibaba.csp.sentinel.adapter.gateway.common.api;
+
+import java.util.Objects;
+
+import com.alibaba.csp.sentinel.adapter.gateway.common.SentinelGatewayConstants;
+
+/**
+ * @author Eric Zhao
+ * @since 1.6.0
+ */
+public class ApiPathPredicateItem implements ApiPredicateItem {
+
+    private String pattern;
+    private int matchStrategy = SentinelGatewayConstants.URL_MATCH_STRATEGY_EXACT;
+
+    public ApiPathPredicateItem setPattern(String pattern) {
+        this.pattern = pattern;
+        return this;
+    }
+
+    public ApiPathPredicateItem setMatchStrategy(int matchStrategy) {
+        this.matchStrategy = matchStrategy;
+        return this;
+    }
+
+    public String getPattern() {
+        return pattern;
+    }
+
+    public int getMatchStrategy() {
+        return matchStrategy;
+    }
+
+    @Override
+    public boolean equals(Object o) {
+        if (this == o) { return true; }
+        if (o == null || getClass() != o.getClass()) { return false; }
+
+        ApiPathPredicateItem that = (ApiPathPredicateItem)o;
+
+        if (matchStrategy != that.matchStrategy) { return false; }
+        return Objects.equals(pattern, that.pattern);
+    }
+
+    @Override
+    public int hashCode() {
+        int result = pattern != null ? pattern.hashCode() : 0;
+        result = 31 * result + matchStrategy;
+        return result;
+    }
+
+    @Override
+    public String toString() {
+        return "ApiPathPredicateItem{" +
+            "pattern='" + pattern + '\'' +
+            ", matchStrategy=" + matchStrategy +
+            '}';
+    }
+}

+ 46 - 0
sentinel-adapter/sentinel-api-gateway-adapter-common/src/main/java/com/alibaba/csp/sentinel/adapter/gateway/common/api/ApiPredicateGroupItem.java

@@ -0,0 +1,46 @@
+/*
+ * Copyright 1999-2019 Alibaba Group Holding Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.alibaba.csp.sentinel.adapter.gateway.common.api;
+
+import java.util.HashSet;
+import java.util.Set;
+
+import com.alibaba.csp.sentinel.util.AssertUtil;
+
+/**
+ * @author Eric Zhao
+ * @since 1.6.0
+ */
+public class ApiPredicateGroupItem implements ApiPredicateItem {
+
+    private final Set<ApiPredicateItem> items = new HashSet<>();
+
+    public ApiPredicateGroupItem addItem(ApiPredicateItem item) {
+        AssertUtil.notNull(item, "item cannot be null");
+        items.add(item);
+        return this;
+    }
+
+    public Set<ApiPredicateItem> getItems() {
+        return items;
+    }
+
+    /*@Override
+    public ApiPredicateItem and(ApiPredicateItem item) {
+        AssertUtil.notNull(item, "item cannot be null");
+        return this.addItem(item);
+    }*/
+}

+ 37 - 0
sentinel-adapter/sentinel-api-gateway-adapter-common/src/main/java/com/alibaba/csp/sentinel/adapter/gateway/common/api/ApiPredicateItem.java

@@ -0,0 +1,37 @@
+/*
+ * Copyright 1999-2019 Alibaba Group Holding Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.alibaba.csp.sentinel.adapter.gateway.common.api;
+
+import com.alibaba.csp.sentinel.util.AssertUtil;
+
+/**
+ * @author Eric Zhao
+ * @since 1.6.0
+ */
+public interface ApiPredicateItem {
+
+    /**
+     * Combine two {@link ApiPredicateItem}.
+     *
+     * @param item another predicate item
+     * @return combined predicate group item
+     */
+    /*default ApiPredicateItem and(ApiPredicateItem item) {
+        AssertUtil.notNull(item, "item cannot be null");
+        return new ApiPredicateGroupItem()
+            .addItem(this).addItem(item);
+    }*/
+}

+ 162 - 0
sentinel-adapter/sentinel-api-gateway-adapter-common/src/main/java/com/alibaba/csp/sentinel/adapter/gateway/common/api/GatewayApiDefinitionManager.java

@@ -0,0 +1,162 @@
+/*
+ * Copyright 1999-2019 Alibaba Group Holding Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.alibaba.csp.sentinel.adapter.gateway.common.api;
+
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+
+import com.alibaba.csp.sentinel.log.RecordLog;
+import com.alibaba.csp.sentinel.property.DynamicSentinelProperty;
+import com.alibaba.csp.sentinel.property.PropertyListener;
+import com.alibaba.csp.sentinel.property.SentinelProperty;
+import com.alibaba.csp.sentinel.util.AssertUtil;
+import com.alibaba.csp.sentinel.util.SpiLoader;
+import com.alibaba.csp.sentinel.util.StringUtil;
+
+/**
+ * Manager for gateway API definitions.
+ *
+ * @author Eric Zhao
+ * @since 1.6.0
+ */
+public final class GatewayApiDefinitionManager {
+
+    private static final Map<String, ApiDefinition> API_MAP = new ConcurrentHashMap<>();
+
+    private static final ApiDefinitionPropertyListener LISTENER = new ApiDefinitionPropertyListener();
+    private static SentinelProperty<Set<ApiDefinition>> currentProperty = new DynamicSentinelProperty<>();
+
+    /**
+     * The map keeps all found ApiDefinitionChangeObserver (class name as key).
+     */
+    private static final Map<String, ApiDefinitionChangeObserver> API_CHANGE_OBSERVERS = new ConcurrentHashMap<>();
+
+    static {
+        try {
+            currentProperty.addListener(LISTENER);
+            initializeApiChangeObserverSpi();
+        } catch (Throwable ex) {
+            RecordLog.warn("[GatewayApiDefinitionManager] Failed to initialize", ex);
+            ex.printStackTrace();
+        }
+    }
+
+    private static void initializeApiChangeObserverSpi() {
+        List<ApiDefinitionChangeObserver> listeners = SpiLoader.loadInstanceList(ApiDefinitionChangeObserver.class);
+        for (ApiDefinitionChangeObserver e : listeners) {
+            API_CHANGE_OBSERVERS.put(e.getClass().getCanonicalName(), e);
+            RecordLog.info("[GatewayApiDefinitionManager] ApiDefinitionChangeObserver added: {0}",
+                e.getClass().getCanonicalName());
+        }
+    }
+
+    public static void register2Property(SentinelProperty<Set<ApiDefinition>> property) {
+        AssertUtil.notNull(property, "property cannot be null");
+        synchronized (LISTENER) {
+            RecordLog.info("[GatewayApiDefinitionManager] Registering new property to gateway API definition manager");
+            currentProperty.removeListener(LISTENER);
+            property.addListener(LISTENER);
+            currentProperty = property;
+        }
+    }
+
+    /**
+     * Load given gateway API definitions and apply to downstream observers.
+     *
+     * @param apiDefinitions set of gateway API definitions
+     * @return true if updated, or else false
+     */
+    public static boolean loadApiDefinitions(Set<ApiDefinition> apiDefinitions) {
+        return currentProperty.updateValue(apiDefinitions);
+    }
+
+    public static ApiDefinition getApiDefinition(final String apiName) {
+        if (apiName == null) {
+            return null;
+        }
+        return API_MAP.get(apiName);
+    }
+
+    public static Set<ApiDefinition> getApiDefinitions() {
+        return new HashSet<>(API_MAP.values());
+    }
+
+    private static final class ApiDefinitionPropertyListener implements PropertyListener<Set<ApiDefinition>> {
+
+        @Override
+        public void configUpdate(Set<ApiDefinition> set) {
+            applyApiUpdateInternal(set);
+            RecordLog.info("[GatewayApiDefinitionManager] Api definition updated: " + API_MAP);
+        }
+
+        @Override
+        public void configLoad(Set<ApiDefinition> set) {
+            applyApiUpdateInternal(set);
+            RecordLog.info("[GatewayApiDefinitionManager] Api definition loaded: " + API_MAP);
+        }
+
+        private static synchronized void applyApiUpdateInternal(Set<ApiDefinition> set) {
+            if (set == null || set.isEmpty()) {
+                API_MAP.clear();
+                notifyDownstreamListeners(new HashSet<ApiDefinition>());
+                return;
+            }
+            Map<String, ApiDefinition> map = new HashMap<>(set.size());
+            Set<ApiDefinition> validSet = new HashSet<>();
+            for (ApiDefinition definition : set) {
+                if (isValidApi(definition)) {
+                    map.put(definition.getApiName(), definition);
+                    validSet.add(definition);
+                }
+            }
+
+            API_MAP.clear();
+            API_MAP.putAll(map);
+
+            // propagate to downstream.
+            notifyDownstreamListeners(validSet);
+        }
+    }
+
+    private static void notifyDownstreamListeners(/*@Valid*/ final Set<ApiDefinition> definitions) {
+        try {
+            for (Map.Entry<?, ApiDefinitionChangeObserver> entry : API_CHANGE_OBSERVERS.entrySet()) {
+                entry.getValue().onChange(definitions);
+            }
+        } catch (Exception ex) {
+            RecordLog.warn("[GatewayApiDefinitionManager] WARN: failed to notify downstream api listeners", ex);
+        }
+    }
+
+    public static boolean isValidApi(ApiDefinition apiDefinition) {
+        return apiDefinition != null && StringUtil.isNotBlank(apiDefinition.getApiName())
+            && apiDefinition.getPredicateItems() != null;
+    }
+
+    static void addApiChangeListener(ApiDefinitionChangeObserver listener) {
+        AssertUtil.notNull(listener, "listener cannot be null");
+        API_CHANGE_OBSERVERS.put(listener.getClass().getCanonicalName(), listener);
+    }
+
+    static void removeApiChangeListener(Class<?> clazz) {
+        AssertUtil.notNull(clazz, "class cannot be null");
+        API_CHANGE_OBSERVERS.remove(clazz.getCanonicalName());
+    }
+}

+ 74 - 0
sentinel-adapter/sentinel-api-gateway-adapter-common/src/main/java/com/alibaba/csp/sentinel/adapter/gateway/common/api/matcher/AbstractApiMatcher.java

@@ -0,0 +1,74 @@
+/*
+ * Copyright 1999-2019 Alibaba Group Holding Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.alibaba.csp.sentinel.adapter.gateway.common.api.matcher;
+
+import java.util.HashSet;
+import java.util.Set;
+
+import com.alibaba.csp.sentinel.adapter.gateway.common.api.ApiDefinition;
+import com.alibaba.csp.sentinel.log.RecordLog;
+import com.alibaba.csp.sentinel.util.AssertUtil;
+import com.alibaba.csp.sentinel.util.function.Predicate;
+
+/**
+ * @author Eric Zhao
+ * @since 1.6.0
+ */
+public abstract class AbstractApiMatcher<T> implements Predicate<T> {
+
+    protected final String apiName;
+    protected final ApiDefinition apiDefinition;
+    /**
+     * We use {@link com.alibaba.csp.sentinel.util.function.Predicate} here as the min JDK version is 1.7.
+     */
+    protected final Set<Predicate<T>> matchers = new HashSet<>();
+
+    public AbstractApiMatcher(ApiDefinition apiDefinition) {
+        AssertUtil.notNull(apiDefinition, "apiDefinition cannot be null");
+        AssertUtil.assertNotBlank(apiDefinition.getApiName(), "apiName cannot be empty");
+        this.apiName = apiDefinition.getApiName();
+        this.apiDefinition = apiDefinition;
+
+        try {
+            initializeMatchers();
+        } catch (Exception ex) {
+            RecordLog.warn("[GatewayApiMatcher] Failed to initialize internal matchers", ex);
+        }
+    }
+
+    /**
+     * Initialize the matchers.
+     */
+    protected abstract void initializeMatchers();
+
+    @Override
+    public boolean test(T t) {
+        for (Predicate<T> matcher : matchers) {
+            if (matcher.test(t)) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    public String getApiName() {
+        return apiName;
+    }
+
+    public ApiDefinition getApiDefinition() {
+        return apiDefinition;
+    }
+}

+ 36 - 0
sentinel-adapter/sentinel-api-gateway-adapter-common/src/main/java/com/alibaba/csp/sentinel/adapter/gateway/common/command/GetGatewayApiDefinitionGroupCommandHandler.java

@@ -0,0 +1,36 @@
+/*
+ * Copyright 1999-2019 Alibaba Group Holding Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.alibaba.csp.sentinel.adapter.gateway.common.command;
+
+import com.alibaba.csp.sentinel.adapter.gateway.common.api.GatewayApiDefinitionManager;
+import com.alibaba.csp.sentinel.command.CommandHandler;
+import com.alibaba.csp.sentinel.command.CommandRequest;
+import com.alibaba.csp.sentinel.command.CommandResponse;
+import com.alibaba.csp.sentinel.command.annotation.CommandMapping;
+import com.alibaba.fastjson.JSON;
+
+/**
+ * @author Eric Zhao
+ * @since 1.6.0
+ */
+@CommandMapping(name = "gateway/getApiDefinitions", desc = "Fetch all customized gateway API groups")
+public class GetGatewayApiDefinitionGroupCommandHandler implements CommandHandler<String> {
+
+    @Override
+    public CommandResponse<String> handle(CommandRequest request) {
+        return CommandResponse.ofSuccess(JSON.toJSONString(GatewayApiDefinitionManager.getApiDefinitions()));
+    }
+}

+ 36 - 0
sentinel-adapter/sentinel-api-gateway-adapter-common/src/main/java/com/alibaba/csp/sentinel/adapter/gateway/common/command/GetGatewayRuleCommandHandler.java

@@ -0,0 +1,36 @@
+/*
+ * Copyright 1999-2019 Alibaba Group Holding Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.alibaba.csp.sentinel.adapter.gateway.common.command;
+
+import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayRuleManager;
+import com.alibaba.csp.sentinel.command.CommandHandler;
+import com.alibaba.csp.sentinel.command.CommandRequest;
+import com.alibaba.csp.sentinel.command.CommandResponse;
+import com.alibaba.csp.sentinel.command.annotation.CommandMapping;
+import com.alibaba.fastjson.JSON;
+
+/**
+ * @author Eric Zhao
+ * @since 1.6.0
+ */
+@CommandMapping(name = "gateway/getRules", desc = "Fetch all gateway rules")
+public class GetGatewayRuleCommandHandler implements CommandHandler<String> {
+
+    @Override
+    public CommandResponse<String> handle(CommandRequest request) {
+        return CommandResponse.ofSuccess(JSON.toJSONString(GatewayRuleManager.getRules()));
+    }
+}

+ 61 - 0
sentinel-adapter/sentinel-api-gateway-adapter-common/src/main/java/com/alibaba/csp/sentinel/adapter/gateway/common/command/UpdateGatewayApiDefinitionGroupCommandHandler.java

@@ -0,0 +1,61 @@
+/*
+ * Copyright 1999-2019 Alibaba Group Holding Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.alibaba.csp.sentinel.adapter.gateway.common.command;
+
+import java.net.URLDecoder;
+import java.util.HashSet;
+import java.util.List;
+
+import com.alibaba.csp.sentinel.adapter.gateway.common.api.ApiDefinition;
+import com.alibaba.csp.sentinel.adapter.gateway.common.api.GatewayApiDefinitionManager;
+import com.alibaba.csp.sentinel.command.CommandHandler;
+import com.alibaba.csp.sentinel.command.CommandRequest;
+import com.alibaba.csp.sentinel.command.CommandResponse;
+import com.alibaba.csp.sentinel.command.annotation.CommandMapping;
+import com.alibaba.csp.sentinel.log.RecordLog;
+import com.alibaba.csp.sentinel.util.StringUtil;
+import com.alibaba.fastjson.JSONArray;
+
+/**
+ * @author Eric Zhao
+ * @since 1.6.0
+ */
+@CommandMapping(name = "gateway/updateApiDefinitions", desc = "")
+public class UpdateGatewayApiDefinitionGroupCommandHandler implements CommandHandler<String> {
+
+    @Override
+    public CommandResponse<String> handle(CommandRequest request) {
+        String data = request.getParam("data");
+        if (StringUtil.isBlank(data)) {
+            return CommandResponse.ofFailure(new IllegalArgumentException("Bad data"));
+        }
+        try {
+            data = URLDecoder.decode(data, "utf-8");
+        } catch (Exception e) {
+            RecordLog.info("Decode gateway API definition data error", e);
+            return CommandResponse.ofFailure(e, "decode gateway API definition data error");
+        }
+
+        RecordLog.info("[API Server] Receiving data change (type: gateway API definition): {0}", data);
+
+        String result = SUCCESS_MSG;
+        List<ApiDefinition> apiDefinitions = JSONArray.parseArray(data, ApiDefinition.class);
+        GatewayApiDefinitionManager.loadApiDefinitions(new HashSet<>(apiDefinitions));
+        return CommandResponse.ofSuccess(result);
+    }
+
+    private static final String SUCCESS_MSG = "success";
+}

+ 61 - 0
sentinel-adapter/sentinel-api-gateway-adapter-common/src/main/java/com/alibaba/csp/sentinel/adapter/gateway/common/command/UpdateGatewayRuleCommandHandler.java

@@ -0,0 +1,61 @@
+/*
+ * Copyright 1999-2019 Alibaba Group Holding Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.alibaba.csp.sentinel.adapter.gateway.common.command;
+
+import java.net.URLDecoder;
+import java.util.HashSet;
+import java.util.List;
+
+import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayFlowRule;
+import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayRuleManager;
+import com.alibaba.csp.sentinel.command.CommandHandler;
+import com.alibaba.csp.sentinel.command.CommandRequest;
+import com.alibaba.csp.sentinel.command.CommandResponse;
+import com.alibaba.csp.sentinel.command.annotation.CommandMapping;
+import com.alibaba.csp.sentinel.log.RecordLog;
+import com.alibaba.csp.sentinel.util.StringUtil;
+import com.alibaba.fastjson.JSONArray;
+
+/**
+ * @author Eric Zhao
+ * @since 1.6.0
+ */
+@CommandMapping(name = "gateway/updateRules", desc = "Update gateway rules")
+public class UpdateGatewayRuleCommandHandler implements CommandHandler<String> {
+
+    @Override
+    public CommandResponse<String> handle(CommandRequest request) {
+        String data = request.getParam("data");
+        if (StringUtil.isBlank(data)) {
+            return CommandResponse.ofFailure(new IllegalArgumentException("Bad data"));
+        }
+        try {
+            data = URLDecoder.decode(data, "utf-8");
+        } catch (Exception e) {
+            RecordLog.info("Decode gateway rule data error", e);
+            return CommandResponse.ofFailure(e, "decode gateway rule data error");
+        }
+
+        RecordLog.info(String.format("[API Server] Receiving rule change (type: gateway rule): %s", data));
+
+        String result = SUCCESS_MSG;
+        List<GatewayFlowRule> flowRules = JSONArray.parseArray(data, GatewayFlowRule.class);
+        GatewayRuleManager.loadRules(new HashSet<>(flowRules));
+        return CommandResponse.ofSuccess(result);
+    }
+
+    private static final String SUCCESS_MSG = "success";
+}

+ 175 - 0
sentinel-adapter/sentinel-api-gateway-adapter-common/src/main/java/com/alibaba/csp/sentinel/adapter/gateway/common/param/GatewayParamParser.java

@@ -0,0 +1,175 @@
+/*
+ * Copyright 1999-2019 Alibaba Group Holding Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.alibaba.csp.sentinel.adapter.gateway.common.param;
+
+import java.util.HashSet;
+import java.util.Set;
+import java.util.regex.Pattern;
+
+import com.alibaba.csp.sentinel.adapter.gateway.common.SentinelGatewayConstants;
+import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayFlowRule;
+import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayParamFlowItem;
+import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayRuleManager;
+import com.alibaba.csp.sentinel.util.AssertUtil;
+import com.alibaba.csp.sentinel.util.StringUtil;
+import com.alibaba.csp.sentinel.util.function.Predicate;
+
+/**
+ * @author Eric Zhao
+ * @since 1.6.0
+ */
+public class GatewayParamParser<T> {
+
+    private final RequestItemParser<T> requestItemParser;
+
+    public GatewayParamParser(RequestItemParser<T> requestItemParser) {
+        AssertUtil.notNull(requestItemParser, "requestItemParser cannot be null");
+        this.requestItemParser = requestItemParser;
+    }
+
+    /**
+     * Parse parameters for given resource from the request entity on condition of the rule predicate.
+     *
+     * @param resource      valid resource name
+     * @param request       valid request
+     * @param rulePredicate rule predicate indicating the rules to refer
+     * @return the parameter array
+     */
+    public Object[] parseParameterFor(String resource, T request, Predicate<GatewayFlowRule> rulePredicate) {
+        if (StringUtil.isEmpty(resource) || request == null || rulePredicate == null) {
+            return new Object[0];
+        }
+        Set<GatewayFlowRule> gatewayRules = new HashSet<>();
+        Set<Boolean> predSet = new HashSet<>();
+        boolean hasNonParamRule = false;
+        for (GatewayFlowRule rule : GatewayRuleManager.getRulesForResource(resource)) {
+            if (rule.getParamItem() != null) {
+                gatewayRules.add(rule);
+                predSet.add(rulePredicate.test(rule));
+            } else {
+                hasNonParamRule = true;
+            }
+        }
+        if (!hasNonParamRule && gatewayRules.isEmpty()) {
+            return new Object[0];
+        }
+        if (predSet.size() > 1 || predSet.contains(false)) {
+            return new Object[0];
+        }
+        int size = hasNonParamRule ? gatewayRules.size() + 1 : gatewayRules.size();
+        Object[] arr = new Object[size];
+        for (GatewayFlowRule rule : gatewayRules) {
+            GatewayParamFlowItem paramItem = rule.getParamItem();
+            int idx = paramItem.getIndex();
+            String param = parseInternal(paramItem, request);
+            arr[idx] = param;
+        }
+        if (hasNonParamRule) {
+            arr[size - 1] = SentinelGatewayConstants.GATEWAY_DEFAULT_PARAM;
+        }
+        return arr;
+    }
+
+    private String parseInternal(GatewayParamFlowItem item, T request) {
+        switch (item.getParseStrategy()) {
+            case SentinelGatewayConstants.PARAM_PARSE_STRATEGY_CLIENT_IP:
+                return parseClientIp(item, request);
+            case SentinelGatewayConstants.PARAM_PARSE_STRATEGY_HOST:
+                return parseHost(item, request);
+            case SentinelGatewayConstants.PARAM_PARSE_STRATEGY_HEADER:
+                return parseHeader(item, request);
+            case SentinelGatewayConstants.PARAM_PARSE_STRATEGY_URL_PARAM:
+                return parseUrlParameter(item, request);
+            case SentinelGatewayConstants.PARAM_PARSE_STRATEGY_COOKIE:
+                return parseCookie(item, request);
+            default:
+                return null;
+        }
+    }
+
+    private String parseClientIp(/*@Valid*/ GatewayParamFlowItem item, T request) {
+        String clientIp = requestItemParser.getRemoteAddress(request);
+        String pattern = item.getPattern();
+        if (pattern == null) {
+            return clientIp;
+        }
+        return parseWithMatchStrategyInternal(item.getMatchStrategy(), clientIp, pattern);
+    }
+
+    private String parseHeader(/*@Valid*/ GatewayParamFlowItem item, T request) {
+        String headerKey = item.getFieldName();
+        String pattern = item.getPattern();
+        // TODO: what if the header has multiple values?
+        String headerValue = requestItemParser.getHeader(request, headerKey);
+        if (pattern == null) {
+            return headerValue;
+        }
+        // Match value according to regex pattern or exact mode.
+        return parseWithMatchStrategyInternal(item.getMatchStrategy(), headerValue, pattern);
+    }
+
+    private String parseHost(/*@Valid*/ GatewayParamFlowItem item, T request) {
+        String pattern = item.getPattern();
+        String host = requestItemParser.getHeader(request, "Host");
+        if (pattern == null) {
+            return host;
+        }
+        // Match value according to regex pattern or exact mode.
+        return parseWithMatchStrategyInternal(item.getMatchStrategy(), host, pattern);
+    }
+
+    private String parseUrlParameter(/*@Valid*/ GatewayParamFlowItem item, T request) {
+        String paramName = item.getFieldName();
+        String pattern = item.getPattern();
+        String param = requestItemParser.getUrlParam(request, paramName);
+        if (pattern == null) {
+            return param;
+        }
+        // Match value according to regex pattern or exact mode.
+        return parseWithMatchStrategyInternal(item.getMatchStrategy(), param, pattern);
+    }
+
+    private String parseCookie(/*@Valid*/ GatewayParamFlowItem item, T request) {
+        String cookieName = item.getFieldName();
+        String pattern = item.getPattern();
+        String param = requestItemParser.getCookieValue(request, cookieName);
+        if (pattern == null) {
+            return param;
+        }
+        // Match value according to regex pattern or exact mode.
+        return parseWithMatchStrategyInternal(item.getMatchStrategy(), param, pattern);
+    }
+
+    private String parseWithMatchStrategyInternal(int matchStrategy, String value, String pattern) {
+        if (value == null) {
+            return null;
+        }
+        switch (matchStrategy) {
+            case SentinelGatewayConstants.PARAM_MATCH_STRATEGY_EXACT:
+                return value.equals(pattern) ? value : SentinelGatewayConstants.GATEWAY_NOT_MATCH_PARAM;
+            case SentinelGatewayConstants.PARAM_MATCH_STRATEGY_CONTAINS:
+                return value.contains(pattern) ? value : SentinelGatewayConstants.GATEWAY_NOT_MATCH_PARAM;
+            case SentinelGatewayConstants.PARAM_MATCH_STRATEGY_REGEX:
+                Pattern regex = GatewayRegexCache.getRegexPattern(pattern);
+                if (regex == null) {
+                    return value;
+                }
+                return regex.matcher(value).matches() ? value : SentinelGatewayConstants.GATEWAY_NOT_MATCH_PARAM;
+            default:
+                return value;
+        }
+    }
+}

+ 58 - 0
sentinel-adapter/sentinel-api-gateway-adapter-common/src/main/java/com/alibaba/csp/sentinel/adapter/gateway/common/param/GatewayRegexCache.java

@@ -0,0 +1,58 @@
+/*
+ * Copyright 1999-2019 Alibaba Group Holding Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.alibaba.csp.sentinel.adapter.gateway.common.param;
+
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.regex.Pattern;
+
+import com.alibaba.csp.sentinel.log.RecordLog;
+
+/**
+ * @author Eric Zhao
+ * @since 1.6.2
+ */
+public final class GatewayRegexCache {
+
+    private static final Map<String, Pattern> REGEX_CACHE = new ConcurrentHashMap<>();
+
+    public static Pattern getRegexPattern(String pattern) {
+        if (pattern == null) {
+            return null;
+        }
+        return REGEX_CACHE.get(pattern);
+    }
+
+    public static boolean addRegexPattern(String pattern) {
+        if (pattern == null) {
+            return false;
+        }
+        try {
+            Pattern regex = Pattern.compile(pattern);
+            REGEX_CACHE.put(pattern, regex);
+            return true;
+        } catch (Exception ex) {
+            RecordLog.warn("[GatewayRegexCache] Failed to compile the regex: " + pattern, ex);
+            return false;
+        }
+    }
+
+    public static void clear() {
+        REGEX_CACHE.clear();
+    }
+
+    private GatewayRegexCache() {}
+}

+ 67 - 0
sentinel-adapter/sentinel-api-gateway-adapter-common/src/main/java/com/alibaba/csp/sentinel/adapter/gateway/common/param/RequestItemParser.java

@@ -0,0 +1,67 @@
+/*
+ * Copyright 1999-2019 Alibaba Group Holding Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.alibaba.csp.sentinel.adapter.gateway.common.param;
+
+/**
+ * @author Eric Zhao
+ * @since 1.6.0
+ */
+public interface RequestItemParser<T> {
+
+    /**
+     * Get API path from the request.
+     *
+     * @param request valid request
+     * @return API path
+     */
+    String getPath(T request);
+
+    /**
+     * Get remote address from the request.
+     *
+     * @param request valid request
+     * @return remote address
+     */
+    String getRemoteAddress(T request);
+
+    /**
+     * Get the header associated with the header key.
+     *
+     * @param request valid request
+     * @param key     valid header key
+     * @return the header
+     */
+    String getHeader(T request, String key);
+
+    /**
+     * Get the parameter value associated with the parameter name.
+     *
+     * @param request   valid request
+     * @param paramName valid parameter name
+     * @return the parameter value
+     */
+    String getUrlParam(T request, String paramName);
+
+    /**
+     * Get the cookie value associated with the cookie name.
+     *
+     * @param request    valid request
+     * @param cookieName valid cookie name
+     * @return the cookie value
+     * @since 1.7.0
+     */
+    String getCookieValue(T request, String cookieName);
+}

+ 186 - 0
sentinel-adapter/sentinel-api-gateway-adapter-common/src/main/java/com/alibaba/csp/sentinel/adapter/gateway/common/rule/GatewayFlowRule.java

@@ -0,0 +1,186 @@
+/*
+ * Copyright 1999-2019 Alibaba Group Holding Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.alibaba.csp.sentinel.adapter.gateway.common.rule;
+
+import java.util.Objects;
+
+import com.alibaba.csp.sentinel.adapter.gateway.common.SentinelGatewayConstants;
+import com.alibaba.csp.sentinel.slots.block.RuleConstant;
+
+/**
+ * @author Eric Zhao
+ * @since 1.6.0
+ */
+public class GatewayFlowRule {
+
+    private String resource;
+    private int resourceMode = SentinelGatewayConstants.RESOURCE_MODE_ROUTE_ID;
+
+    private int grade = RuleConstant.FLOW_GRADE_QPS;
+    private double count;
+    private long intervalSec = 1;
+
+    private int controlBehavior = RuleConstant.CONTROL_BEHAVIOR_DEFAULT;
+    private int burst;
+    /**
+     * For throttle (rate limiting with queueing).
+     */
+    private int maxQueueingTimeoutMs = 500;
+
+    /**
+     * For parameter flow control. If not set, the gateway rule will be
+     * converted to normal flow rule.
+     */
+    private GatewayParamFlowItem paramItem;
+
+    public GatewayFlowRule() {}
+
+    public GatewayFlowRule(String resource) {
+        this.resource = resource;
+    }
+
+    public String getResource() {
+        return resource;
+    }
+
+    public GatewayFlowRule setResource(String resource) {
+        this.resource = resource;
+        return this;
+    }
+
+    public int getResourceMode() {
+        return resourceMode;
+    }
+
+    public GatewayFlowRule setResourceMode(int resourceMode) {
+        this.resourceMode = resourceMode;
+        return this;
+    }
+
+    public int getGrade() {
+        return grade;
+    }
+
+    public GatewayFlowRule setGrade(int grade) {
+        this.grade = grade;
+        return this;
+    }
+
+    public int getControlBehavior() {
+        return controlBehavior;
+    }
+
+    public GatewayFlowRule setControlBehavior(int controlBehavior) {
+        this.controlBehavior = controlBehavior;
+        return this;
+    }
+
+    public double getCount() {
+        return count;
+    }
+
+    public GatewayFlowRule setCount(double count) {
+        this.count = count;
+        return this;
+    }
+
+    public long getIntervalSec() {
+        return intervalSec;
+    }
+
+    public GatewayFlowRule setIntervalSec(long intervalSec) {
+        this.intervalSec = intervalSec;
+        return this;
+    }
+
+    public int getBurst() {
+        return burst;
+    }
+
+    public GatewayFlowRule setBurst(int burst) {
+        this.burst = burst;
+        return this;
+    }
+
+    public GatewayParamFlowItem getParamItem() {
+        return paramItem;
+    }
+
+    public GatewayFlowRule setParamItem(GatewayParamFlowItem paramItem) {
+        this.paramItem = paramItem;
+        return this;
+    }
+
+    public int getMaxQueueingTimeoutMs() {
+        return maxQueueingTimeoutMs;
+    }
+
+    public GatewayFlowRule setMaxQueueingTimeoutMs(int maxQueueingTimeoutMs) {
+        this.maxQueueingTimeoutMs = maxQueueingTimeoutMs;
+        return this;
+    }
+
+    @Override
+    public boolean equals(Object o) {
+        if (this == o) { return true; }
+        if (o == null || getClass() != o.getClass()) { return false; }
+
+        GatewayFlowRule rule = (GatewayFlowRule)o;
+
+        if (resourceMode != rule.resourceMode) { return false; }
+        if (grade != rule.grade) { return false; }
+        if (Double.compare(rule.count, count) != 0) { return false; }
+        if (intervalSec != rule.intervalSec) { return false; }
+        if (controlBehavior != rule.controlBehavior) { return false; }
+        if (burst != rule.burst) { return false; }
+        if (maxQueueingTimeoutMs != rule.maxQueueingTimeoutMs) { return false; }
+        if (!Objects.equals(resource, rule.resource)) { return false; }
+        return Objects.equals(paramItem, rule.paramItem);
+
+    }
+
+    @Override
+    public int hashCode() {
+        int result;
+        long temp;
+        result = resource != null ? resource.hashCode() : 0;
+        result = 31 * result + resourceMode;
+        result = 31 * result + grade;
+        temp = Double.doubleToLongBits(count);
+        result = 31 * result + (int)(temp ^ (temp >>> 32));
+        result = 31 * result + (int)(intervalSec ^ (intervalSec >>> 32));
+        result = 31 * result + controlBehavior;
+        result = 31 * result + burst;
+        result = 31 * result + maxQueueingTimeoutMs;
+        result = 31 * result + (paramItem != null ? paramItem.hashCode() : 0);
+        return result;
+    }
+
+    @Override
+    public String toString() {
+        return "GatewayFlowRule{" +
+            "resource='" + resource + '\'' +
+            ", resourceMode=" + resourceMode +
+            ", grade=" + grade +
+            ", count=" + count +
+            ", intervalSec=" + intervalSec +
+            ", controlBehavior=" + controlBehavior +
+            ", burst=" + burst +
+            ", maxQueueingTimeoutMs=" + maxQueueingTimeoutMs +
+            ", paramItem=" + paramItem +
+            '}';
+    }
+}

+ 103 - 0
sentinel-adapter/sentinel-api-gateway-adapter-common/src/main/java/com/alibaba/csp/sentinel/adapter/gateway/common/rule/GatewayParamFlowItem.java

@@ -0,0 +1,103 @@
+/*
+ * Copyright 1999-2019 Alibaba Group Holding Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.alibaba.csp.sentinel.adapter.gateway.common.rule;
+
+import com.alibaba.csp.sentinel.adapter.gateway.common.SentinelGatewayConstants;
+
+/**
+ * @author Eric Zhao
+ * @since 1.6.0
+ */
+public class GatewayParamFlowItem {
+
+    /**
+     * Should be set when applying to parameter flow rules.
+     */
+    private Integer index;
+
+    /**
+     * Strategy for parsing item (e.g. client IP, arbitrary headers and URL parameters).
+     */
+    private int parseStrategy;
+    /**
+     * Field to get (only required for arbitrary headers or URL parameters mode).
+     */
+    private String fieldName;
+    /**
+     * Matching pattern. If not set, all values will be kept in LRU map.
+     */
+    private String pattern;
+    /**
+     * Matching strategy for item value.
+     */
+    private int matchStrategy = SentinelGatewayConstants.PARAM_MATCH_STRATEGY_EXACT;
+
+    public Integer getIndex() {
+        return index;
+    }
+
+    GatewayParamFlowItem setIndex(Integer index) {
+        this.index = index;
+        return this;
+    }
+
+    public int getParseStrategy() {
+        return parseStrategy;
+    }
+
+    public GatewayParamFlowItem setParseStrategy(int parseStrategy) {
+        this.parseStrategy = parseStrategy;
+        return this;
+    }
+
+    public String getFieldName() {
+        return fieldName;
+    }
+
+    public GatewayParamFlowItem setFieldName(String fieldName) {
+        this.fieldName = fieldName;
+        return this;
+    }
+
+    public String getPattern() {
+        return pattern;
+    }
+
+    public GatewayParamFlowItem setPattern(String pattern) {
+        this.pattern = pattern;
+        return this;
+    }
+
+    public int getMatchStrategy() {
+        return matchStrategy;
+    }
+
+    public GatewayParamFlowItem setMatchStrategy(int matchStrategy) {
+        this.matchStrategy = matchStrategy;
+        return this;
+    }
+
+    @Override
+    public String toString() {
+        return "GatewayParamFlowItem{" +
+            "index=" + index +
+            ", parseStrategy=" + parseStrategy +
+            ", fieldName='" + fieldName + '\'' +
+            ", pattern='" + pattern + '\'' +
+            ", matchStrategy=" + matchStrategy +
+            '}';
+    }
+}

+ 89 - 0
sentinel-adapter/sentinel-api-gateway-adapter-common/src/main/java/com/alibaba/csp/sentinel/adapter/gateway/common/rule/GatewayRuleConverter.java

@@ -0,0 +1,89 @@
+/*
+ * Copyright 1999-2019 Alibaba Group Holding Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.alibaba.csp.sentinel.adapter.gateway.common.rule;
+
+import com.alibaba.csp.sentinel.adapter.gateway.common.SentinelGatewayConstants;
+import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
+import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowItem;
+import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowRule;
+
+/**
+ * @author Eric Zhao
+ * @since 1.6.0
+ */
+final class GatewayRuleConverter {
+
+    static FlowRule toFlowRule(/*@Valid*/ GatewayFlowRule rule) {
+        return new FlowRule(rule.getResource())
+            .setControlBehavior(rule.getControlBehavior())
+            .setCount(rule.getCount())
+            .setGrade(rule.getGrade())
+            .setMaxQueueingTimeMs(rule.getMaxQueueingTimeoutMs());
+    }
+
+    static ParamFlowItem generateNonMatchPassParamItem() {
+        return new ParamFlowItem().setClassType(String.class.getName())
+            .setCount(1000_0000)
+            .setObject(SentinelGatewayConstants.GATEWAY_NOT_MATCH_PARAM);
+    }
+
+    static ParamFlowItem generateNonMatchBlockParamItem() {
+        return new ParamFlowItem().setClassType(String.class.getName())
+            .setCount(0)
+            .setObject(SentinelGatewayConstants.GATEWAY_NOT_MATCH_PARAM);
+    }
+
+    static ParamFlowRule applyNonParamToParamRule(/*@Valid*/ GatewayFlowRule gatewayRule, int idx) {
+        return new ParamFlowRule(gatewayRule.getResource())
+            .setCount(gatewayRule.getCount())
+            .setGrade(gatewayRule.getGrade())
+            .setDurationInSec(gatewayRule.getIntervalSec())
+            .setBurstCount(gatewayRule.getBurst())
+            .setControlBehavior(gatewayRule.getControlBehavior())
+            .setMaxQueueingTimeMs(gatewayRule.getMaxQueueingTimeoutMs())
+            .setParamIdx(idx);
+    }
+
+    /**
+     * Convert a gateway rule to parameter flow rule, then apply the generated
+     * parameter index to {@link GatewayParamFlowItem} of the rule.
+     *
+     * @param gatewayRule a valid gateway rule that should contain valid parameter items
+     * @param idx generated parameter index (callers should guarantee it's unique and incremental)
+     * @return converted parameter flow rule
+     */
+    static ParamFlowRule applyToParamRule(/*@Valid*/ GatewayFlowRule gatewayRule, int idx) {
+        ParamFlowRule paramRule = new ParamFlowRule(gatewayRule.getResource())
+            .setCount(gatewayRule.getCount())
+            .setGrade(gatewayRule.getGrade())
+            .setDurationInSec(gatewayRule.getIntervalSec())
+            .setBurstCount(gatewayRule.getBurst())
+            .setControlBehavior(gatewayRule.getControlBehavior())
+            .setMaxQueueingTimeMs(gatewayRule.getMaxQueueingTimeoutMs())
+            .setParamIdx(idx);
+        GatewayParamFlowItem gatewayItem = gatewayRule.getParamItem();
+        // Apply the current idx to gateway rule item.
+        gatewayItem.setIndex(idx);
+        // Apply for pattern-based parameters.
+        String valuePattern = gatewayItem.getPattern();
+        if (valuePattern != null) {
+            paramRule.getParamFlowItemList().add(generateNonMatchPassParamItem());
+        }
+        return paramRule;
+    }
+
+    private GatewayRuleConverter() {}
+}

+ 272 - 0
sentinel-adapter/sentinel-api-gateway-adapter-common/src/main/java/com/alibaba/csp/sentinel/adapter/gateway/common/rule/GatewayRuleManager.java

@@ -0,0 +1,272 @@
+/*
+ * Copyright 1999-2019 Alibaba Group Holding Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.alibaba.csp.sentinel.adapter.gateway.common.rule;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+
+import com.alibaba.csp.sentinel.adapter.gateway.common.SentinelGatewayConstants;
+import com.alibaba.csp.sentinel.adapter.gateway.common.param.GatewayRegexCache;
+import com.alibaba.csp.sentinel.log.RecordLog;
+import com.alibaba.csp.sentinel.property.DynamicSentinelProperty;
+import com.alibaba.csp.sentinel.property.PropertyListener;
+import com.alibaba.csp.sentinel.property.SentinelProperty;
+import com.alibaba.csp.sentinel.slots.block.RuleConstant;
+import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowRule;
+import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowRuleUtil;
+import com.alibaba.csp.sentinel.slots.block.flow.param.ParameterMetricStorage;
+import com.alibaba.csp.sentinel.util.AssertUtil;
+import com.alibaba.csp.sentinel.util.StringUtil;
+
+/**
+ * @author Eric Zhao
+ * @since 1.6.0
+ */
+public final class GatewayRuleManager {
+
+    /**
+     * Gateway flow rule map: (resource, [rules...])
+     */
+    private static final Map<String, Set<GatewayFlowRule>> GATEWAY_RULE_MAP = new ConcurrentHashMap<>();
+
+    private static final Map<String, List<ParamFlowRule>> CONVERTED_PARAM_RULE_MAP = new ConcurrentHashMap<>();
+
+    private static final GatewayRulePropertyListener LISTENER = new GatewayRulePropertyListener();
+    private static SentinelProperty<Set<GatewayFlowRule>> currentProperty = new DynamicSentinelProperty<>();
+
+    static {
+        currentProperty.addListener(LISTENER);
+    }
+
+    public static void register2Property(SentinelProperty<Set<GatewayFlowRule>> property) {
+        AssertUtil.notNull(property, "property cannot be null");
+        synchronized (LISTENER) {
+            RecordLog.info("[GatewayRuleManager] Registering new property to gateway flow rule manager");
+            currentProperty.removeListener(LISTENER);
+            property.addListener(LISTENER);
+            currentProperty = property;
+        }
+    }
+
+    /**
+     * Load all provided gateway rules into memory, while
+     * previous rules will be replaced.
+     *
+     * @param rules rule set
+     * @return true if updated, otherwise false
+     */
+    public static boolean loadRules(Set<GatewayFlowRule> rules) {
+        return currentProperty.updateValue(rules);
+    }
+
+    public static Set<GatewayFlowRule> getRules() {
+        Set<GatewayFlowRule> rules = new HashSet<>();
+        for (Set<GatewayFlowRule> ruleSet : GATEWAY_RULE_MAP.values()) {
+            rules.addAll(ruleSet);
+        }
+        return rules;
+    }
+
+    public static Set<GatewayFlowRule> getRulesForResource(String resourceName) {
+        if (StringUtil.isBlank(resourceName)) {
+            return new HashSet<>();
+        }
+        Set<GatewayFlowRule> set = GATEWAY_RULE_MAP.get(resourceName);
+        if (set == null) {
+            return new HashSet<>();
+        }
+        return new HashSet<>(set);
+    }
+
+    /**
+     * <p>Get all converted parameter rules.</p>
+     * <p>Note: caller SHOULD NOT modify the list and rules.</p>
+     *
+     * @param resourceName valid resource name
+     * @return converted parameter rules
+     */
+    public static List<ParamFlowRule> getConvertedParamRules(String resourceName) {
+        if (StringUtil.isBlank(resourceName)) {
+            return new ArrayList<>();
+        }
+        return CONVERTED_PARAM_RULE_MAP.get(resourceName);
+    }
+
+    private static final class GatewayRulePropertyListener implements PropertyListener<Set<GatewayFlowRule>> {
+
+        @Override
+        public void configUpdate(Set<GatewayFlowRule> conf) {
+            applyGatewayRuleInternal(conf);
+            RecordLog.info("[GatewayRuleManager] Gateway flow rules received: " + GATEWAY_RULE_MAP);
+        }
+
+        @Override
+        public void configLoad(Set<GatewayFlowRule> conf) {
+            applyGatewayRuleInternal(conf);
+            RecordLog.info("[GatewayRuleManager] Gateway flow rules loaded: " + GATEWAY_RULE_MAP);
+        }
+
+        private int getIdxInternal(Map<String, Integer> idxMap, String resourceName) {
+            // Prepare index map.
+            if (!idxMap.containsKey(resourceName)) {
+                idxMap.put(resourceName, 0);
+            }
+            return idxMap.get(resourceName);
+        }
+
+        private void cacheRegexPattern(/*@NonNull*/ GatewayParamFlowItem item) {
+            String pattern = item.getPattern();
+            if (StringUtil.isNotEmpty(pattern) &&
+                item.getMatchStrategy() == SentinelGatewayConstants.PARAM_MATCH_STRATEGY_REGEX) {
+                if (GatewayRegexCache.getRegexPattern(pattern) == null) {
+                    GatewayRegexCache.addRegexPattern(pattern);
+                }
+            }
+        }
+
+        private synchronized void applyGatewayRuleInternal(Set<GatewayFlowRule> conf) {
+            if (conf == null || conf.isEmpty()) {
+                applyToConvertedParamMap(new HashSet<ParamFlowRule>());
+                GATEWAY_RULE_MAP.clear();
+                return;
+            }
+            Map<String, Set<GatewayFlowRule>> gatewayRuleMap = new ConcurrentHashMap<>();
+            Map<String, Integer> idxMap = new HashMap<>();
+            Set<ParamFlowRule> paramFlowRules = new HashSet<>();
+            Map<String, List<GatewayFlowRule>> noParamMap = new HashMap<>();
+
+            for (GatewayFlowRule rule : conf) {
+                if (!isValidRule(rule)) {
+                    RecordLog.warn("[GatewayRuleManager] Ignoring invalid rule when loading new rules: " + rule);
+                    continue;
+                }
+                String resourceName = rule.getResource();
+                if (rule.getParamItem() == null) {
+                    // Cache the rules with no parameter config, then skip.
+                    List<GatewayFlowRule> noParamList = noParamMap.get(resourceName);
+                    if (noParamList == null) {
+                        noParamList = new ArrayList<>();
+                        noParamMap.put(resourceName, noParamList);
+                    }
+                    noParamList.add(rule);
+                } else {
+                    int idx = getIdxInternal(idxMap, resourceName);
+                    // Convert to parameter flow rule.
+                    if (paramFlowRules.add(GatewayRuleConverter.applyToParamRule(rule, idx))) {
+                        idxMap.put(rule.getResource(), idx + 1);
+                    }
+                    cacheRegexPattern(rule.getParamItem());
+                }
+                // Apply to the gateway rule map.
+                Set<GatewayFlowRule> ruleSet = gatewayRuleMap.get(resourceName);
+                if (ruleSet == null) {
+                    ruleSet = new HashSet<>();
+                    gatewayRuleMap.put(resourceName, ruleSet);
+                }
+                ruleSet.add(rule);
+            }
+            // Handle non-param mode rules.
+            for (Map.Entry<String, List<GatewayFlowRule>> e : noParamMap.entrySet()) {
+                List<GatewayFlowRule> rules = e.getValue();
+                if (rules == null || rules.isEmpty()) {
+                    continue;
+                }
+                for (GatewayFlowRule rule : rules) {
+                    int idx = getIdxInternal(idxMap, e.getKey());
+                    // Always use the same index (the last position).
+                    paramFlowRules.add(GatewayRuleConverter.applyNonParamToParamRule(rule, idx));
+                }
+            }
+
+            applyToConvertedParamMap(paramFlowRules);
+
+            GATEWAY_RULE_MAP.clear();
+            GATEWAY_RULE_MAP.putAll(gatewayRuleMap);
+        }
+
+        private void applyToConvertedParamMap(Set<ParamFlowRule> paramFlowRules) {
+            Map<String, List<ParamFlowRule>> newRuleMap = ParamFlowRuleUtil.buildParamRuleMap(
+                new ArrayList<>(paramFlowRules));
+            if (newRuleMap == null || newRuleMap.isEmpty()) {
+                // No parameter flow rules, so clear all the metrics.
+                for (String resource : CONVERTED_PARAM_RULE_MAP.keySet()) {
+                    ParameterMetricStorage.clearParamMetricForResource(resource);
+                }
+                RecordLog.info("[GatewayRuleManager] No gateway rules, clearing parameter metrics of previous rules");
+                CONVERTED_PARAM_RULE_MAP.clear();
+                return;
+            }
+
+            // Clear unused parameter metrics.
+            Set<String> previousResources = CONVERTED_PARAM_RULE_MAP.keySet();
+            for (String resource : previousResources) {
+                if (!newRuleMap.containsKey(resource)) {
+                    ParameterMetricStorage.clearParamMetricForResource(resource);
+                }
+            }
+
+            // Apply to converted rule map.
+            CONVERTED_PARAM_RULE_MAP.clear();
+            CONVERTED_PARAM_RULE_MAP.putAll(newRuleMap);
+
+            RecordLog.info("[GatewayRuleManager] Converted internal param rules: " + CONVERTED_PARAM_RULE_MAP);
+        }
+    }
+
+    public static boolean isValidRule(GatewayFlowRule rule) {
+        if (rule == null || StringUtil.isBlank(rule.getResource()) || rule.getResourceMode() < 0
+            || rule.getGrade() < 0 || rule.getCount() < 0 || rule.getBurst() < 0 || rule.getControlBehavior() < 0) {
+            return false;
+        }
+        if (rule.getGrade() == RuleConstant.CONTROL_BEHAVIOR_RATE_LIMITER
+            && rule.getMaxQueueingTimeoutMs() < 0) {
+            return false;
+        }
+        if (rule.getIntervalSec() <= 0) {
+            return false;
+        }
+        GatewayParamFlowItem item = rule.getParamItem();
+        if (item != null) {
+            return isValidParamItem(item);
+        }
+        return true;
+    }
+
+    static boolean isValidParamItem(/*@NonNull*/ GatewayParamFlowItem item) {
+        if (item.getParseStrategy() < 0) {
+            return false;
+        }
+        // Check required field name for item types.
+        if (FIELD_REQUIRED_SET.contains(item.getParseStrategy()) && StringUtil.isBlank(item.getFieldName())) {
+            return false;
+        }
+        return StringUtil.isEmpty(item.getPattern()) || item.getMatchStrategy() >= 0;
+    }
+
+    private static final Set<Integer> FIELD_REQUIRED_SET = new HashSet<>(
+        Arrays.asList(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_URL_PARAM,
+            SentinelGatewayConstants.PARAM_PARSE_STRATEGY_HEADER,
+            SentinelGatewayConstants.PARAM_PARSE_STRATEGY_COOKIE)
+    );
+
+    private GatewayRuleManager() {}
+}

+ 75 - 0
sentinel-adapter/sentinel-api-gateway-adapter-common/src/main/java/com/alibaba/csp/sentinel/adapter/gateway/common/slot/GatewayFlowSlot.java

@@ -0,0 +1,75 @@
+/*
+ * Copyright 1999-2019 Alibaba Group Holding Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.alibaba.csp.sentinel.adapter.gateway.common.slot;
+
+import java.util.List;
+
+import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayRuleManager;
+import com.alibaba.csp.sentinel.context.Context;
+import com.alibaba.csp.sentinel.node.DefaultNode;
+import com.alibaba.csp.sentinel.slotchain.AbstractLinkedProcessorSlot;
+import com.alibaba.csp.sentinel.slotchain.ResourceWrapper;
+import com.alibaba.csp.sentinel.slots.block.BlockException;
+import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowChecker;
+import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
+import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowRule;
+import com.alibaba.csp.sentinel.slots.block.flow.param.ParameterMetricStorage;
+
+/**
+ * @author Eric Zhao
+ * @since 1.6.1
+ */
+public class GatewayFlowSlot extends AbstractLinkedProcessorSlot<DefaultNode> {
+
+    @Override
+    public void entry(Context context, ResourceWrapper resource, DefaultNode node, int count,
+                      boolean prioritized, Object... args) throws Throwable {
+        checkGatewayParamFlow(resource, count, args);
+
+        fireEntry(context, resource, node, count, prioritized, args);
+    }
+
+    private void checkGatewayParamFlow(ResourceWrapper resourceWrapper, int count, Object... args)
+        throws BlockException {
+        if (args == null) {
+            return;
+        }
+
+        List<ParamFlowRule> rules = GatewayRuleManager.getConvertedParamRules(resourceWrapper.getName());
+        if (rules == null || rules.isEmpty()) {
+            return;
+        }
+
+        for (ParamFlowRule rule : rules) {
+            // Initialize the parameter metrics.
+            ParameterMetricStorage.initParamMetricsFor(resourceWrapper, rule);
+
+            if (!ParamFlowChecker.passCheck(resourceWrapper, rule, count, args)) {
+                String triggeredParam = "";
+                if (args.length > rule.getParamIdx()) {
+                    Object value = args[rule.getParamIdx()];
+                    triggeredParam = String.valueOf(value);
+                }
+                throw new ParamFlowException(resourceWrapper.getName(), triggeredParam, rule);
+            }
+        }
+    }
+
+    @Override
+    public void exit(Context context, ResourceWrapper resourceWrapper, int count, Object... args) {
+        fireExit(context, resourceWrapper, count, args);
+    }
+}

+ 57 - 0
sentinel-adapter/sentinel-api-gateway-adapter-common/src/main/java/com/alibaba/csp/sentinel/adapter/gateway/common/slot/GatewaySlotChainBuilder.java

@@ -0,0 +1,57 @@
+/*
+ * Copyright 1999-2019 Alibaba Group Holding Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.alibaba.csp.sentinel.adapter.gateway.common.slot;
+
+import com.alibaba.csp.sentinel.slotchain.DefaultProcessorSlotChain;
+import com.alibaba.csp.sentinel.slotchain.ProcessorSlotChain;
+import com.alibaba.csp.sentinel.slotchain.SlotChainBuilder;
+import com.alibaba.csp.sentinel.slots.block.authority.AuthoritySlot;
+import com.alibaba.csp.sentinel.slots.block.degrade.DegradeSlot;
+import com.alibaba.csp.sentinel.slots.block.flow.FlowSlot;
+import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowSlot;
+import com.alibaba.csp.sentinel.slots.clusterbuilder.ClusterBuilderSlot;
+import com.alibaba.csp.sentinel.slots.logger.LogSlot;
+import com.alibaba.csp.sentinel.slots.nodeselector.NodeSelectorSlot;
+import com.alibaba.csp.sentinel.slots.statistic.StatisticSlot;
+import com.alibaba.csp.sentinel.slots.system.SystemSlot;
+
+/**
+ * @author Eric Zhao
+ * @since 1.6.1
+ */
+public class GatewaySlotChainBuilder implements SlotChainBuilder {
+
+    @Override
+    public ProcessorSlotChain build() {
+        ProcessorSlotChain chain = new DefaultProcessorSlotChain();
+        // Prepare slot
+        chain.addLast(new NodeSelectorSlot());
+        chain.addLast(new ClusterBuilderSlot());
+        // Stat slot
+        chain.addLast(new LogSlot());
+        chain.addLast(new StatisticSlot());
+        // Rule checking slot
+        chain.addLast(new AuthoritySlot());
+        chain.addLast(new SystemSlot());
+        chain.addLast(new GatewayFlowSlot());
+
+        chain.addLast(new ParamFlowSlot());
+        chain.addLast(new FlowSlot());
+        chain.addLast(new DegradeSlot());
+
+        return chain;
+    }
+}

+ 4 - 0
sentinel-adapter/sentinel-api-gateway-adapter-common/src/main/resources/META-INF/services/com.alibaba.csp.sentinel.command.CommandHandler

@@ -0,0 +1,4 @@
+com.alibaba.csp.sentinel.adapter.gateway.common.command.UpdateGatewayApiDefinitionGroupCommandHandler
+com.alibaba.csp.sentinel.adapter.gateway.common.command.UpdateGatewayRuleCommandHandler
+com.alibaba.csp.sentinel.adapter.gateway.common.command.GetGatewayApiDefinitionGroupCommandHandler
+com.alibaba.csp.sentinel.adapter.gateway.common.command.GetGatewayRuleCommandHandler

+ 1 - 0
sentinel-adapter/sentinel-api-gateway-adapter-common/src/main/resources/META-INF/services/com.alibaba.csp.sentinel.slotchain.SlotChainBuilder

@@ -0,0 +1 @@
+com.alibaba.csp.sentinel.adapter.gateway.common.slot.GatewaySlotChainBuilder

+ 27 - 0
sentinel-adapter/sentinel-api-gateway-adapter-common/src/test/java/com/alibaba/csp/sentinel/adapter/gateway/common/api/GatewayApiDefinitionManagerTest.java

@@ -0,0 +1,27 @@
+package com.alibaba.csp.sentinel.adapter.gateway.common.api;
+
+import java.util.Collections;
+
+import org.junit.Test;
+
+import static org.junit.Assert.*;
+
+/**
+ * @author Eric Zhao
+ */
+public class GatewayApiDefinitionManagerTest {
+
+    @Test
+    public void testIsValidApi() {
+        ApiDefinition bad1 = new ApiDefinition();
+        ApiDefinition bad2 = new ApiDefinition("foo");
+        ApiDefinition good1 = new ApiDefinition("foo")
+            .setPredicateItems(Collections.<ApiPredicateItem>singleton(new ApiPathPredicateItem()
+                .setPattern("/abc")
+            ));
+
+        assertFalse(GatewayApiDefinitionManager.isValidApi(bad1));
+        assertFalse(GatewayApiDefinitionManager.isValidApi(bad2));
+        assertTrue(GatewayApiDefinitionManager.isValidApi(good1));
+    }
+}

+ 320 - 0
sentinel-adapter/sentinel-api-gateway-adapter-common/src/test/java/com/alibaba/csp/sentinel/adapter/gateway/common/param/GatewayParamParserTest.java

@@ -0,0 +1,320 @@
+/*
+ * Copyright 1999-2019 Alibaba Group Holding Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.alibaba.csp.sentinel.adapter.gateway.common.param;
+
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+
+import com.alibaba.csp.sentinel.adapter.gateway.common.SentinelGatewayConstants;
+import com.alibaba.csp.sentinel.adapter.gateway.common.api.ApiDefinition;
+import com.alibaba.csp.sentinel.adapter.gateway.common.api.GatewayApiDefinitionManager;
+import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayFlowRule;
+import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayParamFlowItem;
+import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayRuleManager;
+import com.alibaba.csp.sentinel.slots.block.RuleConstant;
+import com.alibaba.csp.sentinel.util.function.Predicate;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.ArgumentMatchers.*;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+/**
+ * @author Eric Zhao
+ */
+@SuppressWarnings("unchecked")
+public class GatewayParamParserTest {
+
+    private final Predicate<GatewayFlowRule> routeIdPredicate = new Predicate<GatewayFlowRule>() {
+        @Override
+        public boolean test(GatewayFlowRule e) {
+            return e.getResourceMode() == SentinelGatewayConstants.RESOURCE_MODE_ROUTE_ID;
+        }
+    };
+    private final Predicate<GatewayFlowRule> apiNamePredicate = new Predicate<GatewayFlowRule>() {
+        @Override
+        public boolean test(GatewayFlowRule e) {
+            return e.getResourceMode() == SentinelGatewayConstants.RESOURCE_MODE_CUSTOM_API_NAME;
+        }
+    };
+
+    @Test
+    public void testParseParametersNoParamItem() {
+        RequestItemParser<Object> itemParser = mock(RequestItemParser.class);
+        GatewayParamParser<Object> parser = new GatewayParamParser<>(itemParser);
+        // Create a fake request.
+        Object request = new Object();
+        // Prepare gateway rules.
+        Set<GatewayFlowRule> rules = new HashSet<>();
+        String routeId1 = "my_test_route_A";
+        rules.add(new GatewayFlowRule(routeId1)
+            .setCount(5)
+            .setIntervalSec(1)
+        );
+        rules.add(new GatewayFlowRule(routeId1)
+            .setCount(10)
+            .setControlBehavior(2)
+            .setMaxQueueingTimeoutMs(1000)
+        );
+        GatewayRuleManager.loadRules(rules);
+
+        Object[] params = parser.parseParameterFor(routeId1, request, routeIdPredicate);
+        assertThat(params.length).isEqualTo(1);
+    }
+
+    @Test
+    public void testParseParametersWithItems() {
+        RequestItemParser<Object> itemParser = mock(RequestItemParser.class);
+        GatewayParamParser<Object> paramParser = new GatewayParamParser<>(itemParser);
+        // Create a fake request.
+        Object request = new Object();
+
+        // Prepare gateway rules.
+        Set<GatewayFlowRule> rules = new HashSet<>();
+        final String routeId1 = "my_test_route_A";
+        final String api1 = "my_test_route_B";
+        final String headerName = "X-Sentinel-Flag";
+        final String paramName = "p";
+        final String cookieName = "myCookie";
+        GatewayFlowRule routeRuleNoParam = new GatewayFlowRule(routeId1)
+            .setCount(10)
+            .setIntervalSec(10);
+        GatewayFlowRule routeRule1 = new GatewayFlowRule(routeId1)
+            .setCount(2)
+            .setIntervalSec(2)
+            .setBurst(2)
+            .setParamItem(new GatewayParamFlowItem()
+                .setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_CLIENT_IP)
+            );
+        GatewayFlowRule routeRule2 = new GatewayFlowRule(routeId1)
+            .setCount(10)
+            .setIntervalSec(1)
+            .setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_RATE_LIMITER)
+            .setMaxQueueingTimeoutMs(600)
+            .setParamItem(new GatewayParamFlowItem()
+                .setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_HEADER)
+                .setFieldName(headerName)
+            );
+        GatewayFlowRule routeRule3 = new GatewayFlowRule(routeId1)
+            .setCount(20)
+            .setIntervalSec(1)
+            .setBurst(5)
+            .setParamItem(new GatewayParamFlowItem()
+                .setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_URL_PARAM)
+                .setFieldName(paramName)
+            );
+        GatewayFlowRule routeRule4 = new GatewayFlowRule(routeId1)
+            .setCount(120)
+            .setIntervalSec(10)
+            .setBurst(30)
+            .setParamItem(new GatewayParamFlowItem()
+                .setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_HOST)
+            );
+        GatewayFlowRule routeRule5 = new GatewayFlowRule(routeId1)
+            .setCount(50)
+            .setIntervalSec(30)
+            .setParamItem(new GatewayParamFlowItem()
+                .setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_COOKIE)
+                .setFieldName(cookieName)
+            );
+        GatewayFlowRule apiRule1 = new GatewayFlowRule(api1)
+            .setResourceMode(SentinelGatewayConstants.RESOURCE_MODE_CUSTOM_API_NAME)
+            .setCount(5)
+            .setIntervalSec(1)
+            .setParamItem(new GatewayParamFlowItem()
+                .setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_URL_PARAM)
+                .setFieldName(paramName)
+            );
+        rules.add(routeRule1);
+        rules.add(routeRule2);
+        rules.add(routeRule3);
+        rules.add(routeRule4);
+        rules.add(routeRule5);
+        rules.add(routeRuleNoParam);
+        rules.add(apiRule1);
+        GatewayRuleManager.loadRules(rules);
+
+        final String expectedHost = "hello.test.sentinel";
+        final String expectedAddress = "66.77.88.99";
+        final String expectedHeaderValue1 = "Sentinel";
+        final String expectedUrlParamValue1 = "17";
+        final String expectedCookieValue1 = "Sentinel-Foo";
+
+        mockClientHostAddress(itemParser, expectedAddress);
+        Map<String, String> expectedHeaders = new HashMap<String, String>() {{
+            put(headerName, expectedHeaderValue1); put("Host", expectedHost);
+        }};
+        mockHeaders(itemParser, expectedHeaders);
+        mockSingleUrlParam(itemParser, paramName, expectedUrlParamValue1);
+        mockSingleCookie(itemParser, cookieName, expectedCookieValue1);
+
+        Object[] params = paramParser.parseParameterFor(routeId1, request, routeIdPredicate);
+        // Param length should be 6 (5 with parameters, 1 normal flow with generated constant)
+        assertThat(params.length).isEqualTo(6);
+        assertThat(params[routeRule1.getParamItem().getIndex()]).isEqualTo(expectedAddress);
+        assertThat(params[routeRule2.getParamItem().getIndex()]).isEqualTo(expectedHeaderValue1);
+        assertThat(params[routeRule3.getParamItem().getIndex()]).isEqualTo(expectedUrlParamValue1);
+        assertThat(params[routeRule4.getParamItem().getIndex()]).isEqualTo(expectedHost);
+        assertThat(params[routeRule5.getParamItem().getIndex()]).isEqualTo(expectedCookieValue1);
+        assertThat(params[params.length - 1]).isEqualTo(SentinelGatewayConstants.GATEWAY_DEFAULT_PARAM);
+
+        assertThat(paramParser.parseParameterFor(api1, request, routeIdPredicate).length).isZero();
+
+        String expectedUrlParamValue2 = "fs";
+        mockSingleUrlParam(itemParser, paramName, expectedUrlParamValue2);
+        params = paramParser.parseParameterFor(api1, request, apiNamePredicate);
+        assertThat(params.length).isEqualTo(1);
+        assertThat(params[apiRule1.getParamItem().getIndex()]).isEqualTo(expectedUrlParamValue2);
+    }
+
+    @Test
+    public void testParseParametersWithItemPatternMatching() {
+        RequestItemParser<Object> itemParser = mock(RequestItemParser.class);
+        GatewayParamParser<Object> paramParser = new GatewayParamParser<>(itemParser);
+        // Create a fake request.
+        Object request = new Object();
+
+        // Prepare gateway rules.
+        Set<GatewayFlowRule> rules = new HashSet<>();
+        final String routeId1 = "my_test_route_F&@";
+        final String api1 = "my_test_route_E5K";
+        final String headerName = "X-Sentinel-Flag";
+        final String paramName = "p";
+
+        String nameEquals = "Wow";
+        String nameContains = "warn";
+        String valueRegex = "\\d+";
+        GatewayFlowRule routeRule1 = new GatewayFlowRule(routeId1)
+            .setCount(10)
+            .setIntervalSec(1)
+            .setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_RATE_LIMITER)
+            .setMaxQueueingTimeoutMs(600)
+            .setParamItem(new GatewayParamFlowItem()
+                .setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_HEADER)
+                .setFieldName(headerName)
+                .setPattern(nameEquals)
+                .setMatchStrategy(SentinelGatewayConstants.PARAM_MATCH_STRATEGY_EXACT)
+            );
+        GatewayFlowRule routeRule2 = new GatewayFlowRule(routeId1)
+            .setCount(20)
+            .setIntervalSec(1)
+            .setBurst(5)
+            .setParamItem(new GatewayParamFlowItem()
+                .setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_URL_PARAM)
+                .setFieldName(paramName)
+                .setPattern(nameContains)
+                .setMatchStrategy(SentinelGatewayConstants.PARAM_MATCH_STRATEGY_CONTAINS)
+            );
+        GatewayFlowRule apiRule1 = new GatewayFlowRule(api1)
+            .setResourceMode(SentinelGatewayConstants.RESOURCE_MODE_CUSTOM_API_NAME)
+            .setCount(5)
+            .setIntervalSec(1)
+            .setParamItem(new GatewayParamFlowItem()
+                .setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_URL_PARAM)
+                .setFieldName(paramName)
+                .setPattern(valueRegex)
+                .setMatchStrategy(SentinelGatewayConstants.PARAM_MATCH_STRATEGY_REGEX)
+            );
+        rules.add(routeRule1);
+        rules.add(routeRule2);
+        rules.add(apiRule1);
+        GatewayRuleManager.loadRules(rules);
+
+        mockSingleHeader(itemParser, headerName, nameEquals);
+        mockSingleUrlParam(itemParser, paramName, nameContains);
+        Object[] params = paramParser.parseParameterFor(routeId1, request, routeIdPredicate);
+        assertThat(params.length).isEqualTo(2);
+        assertThat(params[routeRule1.getParamItem().getIndex()]).isEqualTo(nameEquals);
+        assertThat(params[routeRule2.getParamItem().getIndex()]).isEqualTo(nameContains);
+
+        mockSingleHeader(itemParser, headerName, nameEquals + "_foo");
+        mockSingleUrlParam(itemParser, paramName, nameContains + "_foo");
+        params = paramParser.parseParameterFor(routeId1, request, routeIdPredicate);
+        assertThat(params.length).isEqualTo(2);
+        assertThat(params[routeRule1.getParamItem().getIndex()])
+            .isEqualTo(SentinelGatewayConstants.GATEWAY_NOT_MATCH_PARAM);
+        assertThat(params[routeRule2.getParamItem().getIndex()])
+            .isEqualTo(nameContains + "_foo");
+
+        mockSingleHeader(itemParser, headerName, "foo");
+        mockSingleUrlParam(itemParser, paramName, "foo");
+        params = paramParser.parseParameterFor(routeId1, request, routeIdPredicate);
+        assertThat(params.length).isEqualTo(2);
+        assertThat(params[routeRule1.getParamItem().getIndex()])
+            .isEqualTo(SentinelGatewayConstants.GATEWAY_NOT_MATCH_PARAM);
+        assertThat(params[routeRule2.getParamItem().getIndex()])
+            .isEqualTo(SentinelGatewayConstants.GATEWAY_NOT_MATCH_PARAM);
+
+        mockSingleUrlParam(itemParser, paramName, "23");
+        params = paramParser.parseParameterFor(api1, request, apiNamePredicate);
+        assertThat(params.length).isEqualTo(1);
+        assertThat(params[apiRule1.getParamItem().getIndex()]).isEqualTo("23");
+
+        mockSingleUrlParam(itemParser, paramName, "some233");
+        params = paramParser.parseParameterFor(api1, request, apiNamePredicate);
+        assertThat(params.length).isEqualTo(1);
+        assertThat(params[apiRule1.getParamItem().getIndex()])
+            .isEqualTo(SentinelGatewayConstants.GATEWAY_NOT_MATCH_PARAM);
+    }
+
+    private void mockClientHostAddress(/*@Mock*/ RequestItemParser parser, String address) {
+        when(parser.getRemoteAddress(any())).thenReturn(address);
+    }
+
+    private void mockHeaders(/*@Mock*/ RequestItemParser parser, Map<String, String> headerMap) {
+        for (Map.Entry<String, String> e : headerMap.entrySet()) {
+            when(parser.getHeader(any(), eq(e.getKey()))).thenReturn(e.getValue());
+        }
+    }
+
+    private void mockUrlParams(/*@Mock*/ RequestItemParser parser, Map<String, String> paramMap) {
+        for (Map.Entry<String, String> e : paramMap.entrySet()) {
+            when(parser.getUrlParam(any(), eq(e.getKey()))).thenReturn(e.getValue());
+        }
+    }
+
+    private void mockSingleUrlParam(/*@Mock*/ RequestItemParser parser, String key, String value) {
+        when(parser.getUrlParam(any(), eq(key))).thenReturn(value);
+    }
+
+    private void mockSingleHeader(/*@Mock*/ RequestItemParser parser, String key, String value) {
+        when(parser.getHeader(any(), eq(key))).thenReturn(value);
+    }
+
+    private void mockSingleCookie(/*@Mock*/ RequestItemParser parser, String key, String value) {
+        when(parser.getCookieValue(any(), eq(key))).thenReturn(value);
+    }
+
+    @Before
+    public void setUp() {
+        GatewayApiDefinitionManager.loadApiDefinitions(new HashSet<ApiDefinition>());
+        GatewayRuleManager.loadRules(new HashSet<GatewayFlowRule>());
+        GatewayRegexCache.clear();
+    }
+
+    @After
+    public void tearDown() {
+        GatewayApiDefinitionManager.loadApiDefinitions(new HashSet<ApiDefinition>());
+        GatewayRuleManager.loadRules(new HashSet<GatewayFlowRule>());
+        GatewayRegexCache.clear();
+    }
+}

+ 49 - 0
sentinel-adapter/sentinel-api-gateway-adapter-common/src/test/java/com/alibaba/csp/sentinel/adapter/gateway/common/param/GatewayRegexCacheTest.java

@@ -0,0 +1,49 @@
+/*
+ * Copyright 1999-2019 Alibaba Group Holding Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.alibaba.csp.sentinel.adapter.gateway.common.param;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+/**
+ * @author Eric Zhao
+ */
+public class GatewayRegexCacheTest {
+
+    @Before
+    public void setUp() {
+        GatewayRegexCache.clear();
+    }
+
+    @After
+    public void tearDown() {
+        GatewayRegexCache.clear();
+    }
+
+    @Test
+    public void testAddAndGetRegexPattern() {
+        // Test for invalid pattern.
+        assertThat(GatewayRegexCache.addRegexPattern("\\")).isFalse();
+        assertThat(GatewayRegexCache.addRegexPattern(null)).isFalse();
+        // Test for good pattern.
+        String goodPattern = "\\d+";
+        assertThat(GatewayRegexCache.addRegexPattern(goodPattern)).isTrue();
+        assertThat(GatewayRegexCache.getRegexPattern(goodPattern)).isNotNull();
+    }
+}

+ 64 - 0
sentinel-adapter/sentinel-api-gateway-adapter-common/src/test/java/com/alibaba/csp/sentinel/adapter/gateway/common/rule/GatewayRuleConverterTest.java

@@ -0,0 +1,64 @@
+/*
+ * Copyright 1999-2019 Alibaba Group Holding Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.alibaba.csp.sentinel.adapter.gateway.common.rule;
+
+import com.alibaba.csp.sentinel.adapter.gateway.common.SentinelGatewayConstants;
+import com.alibaba.csp.sentinel.slots.block.RuleConstant;
+import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
+import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowRule;
+
+import org.junit.Test;
+
+import static org.junit.Assert.*;
+
+/**
+ * @author Eric Zhao
+ */
+public class GatewayRuleConverterTest {
+
+    @Test
+    public void testConvertToFlowRule() {
+        GatewayFlowRule rule = new GatewayFlowRule("routeId1")
+            .setCount(10)
+            .setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_RATE_LIMITER)
+            .setMaxQueueingTimeoutMs(1000);
+        FlowRule flowRule = GatewayRuleConverter.toFlowRule(rule);
+        assertEquals(rule.getResource(), flowRule.getResource());
+        assertEquals(rule.getCount(), flowRule.getCount(), 0.01);
+        assertEquals(rule.getControlBehavior(), flowRule.getControlBehavior());
+        assertEquals(rule.getMaxQueueingTimeoutMs(), flowRule.getMaxQueueingTimeMs());
+    }
+
+    @Test
+    public void testConvertAndApplyToParamRule() {
+        GatewayFlowRule routeRule1 = new GatewayFlowRule("routeId1")
+            .setCount(2)
+            .setIntervalSec(2)
+            .setBurst(2)
+            .setParamItem(new GatewayParamFlowItem()
+                .setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_CLIENT_IP)
+            );
+        int idx = 1;
+        ParamFlowRule paramRule = GatewayRuleConverter.applyToParamRule(routeRule1, idx);
+        assertEquals(routeRule1.getResource(), paramRule.getResource());
+        assertEquals(routeRule1.getCount(), paramRule.getCount(), 0.01);
+        assertEquals(routeRule1.getControlBehavior(), paramRule.getControlBehavior());
+        assertEquals(routeRule1.getIntervalSec(), paramRule.getDurationInSec());
+        assertEquals(routeRule1.getBurst(), paramRule.getBurstCount());
+        assertEquals(idx, (int)paramRule.getParamIdx());
+        assertEquals(idx, (int)routeRule1.getParamItem().getIndex());
+    }
+}

+ 115 - 0
sentinel-adapter/sentinel-api-gateway-adapter-common/src/test/java/com/alibaba/csp/sentinel/adapter/gateway/common/rule/GatewayRuleManagerTest.java

@@ -0,0 +1,115 @@
+/*
+ * Copyright 1999-2019 Alibaba Group Holding Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.alibaba.csp.sentinel.adapter.gateway.common.rule;
+
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+import com.alibaba.csp.sentinel.adapter.gateway.common.SentinelGatewayConstants;
+import com.alibaba.csp.sentinel.slots.block.RuleConstant;
+import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowRule;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+import static org.junit.Assert.*;
+
+/**
+ * @author Eric Zhao
+ */
+public class GatewayRuleManagerTest {
+
+    @Test
+    public void testLoadAndGetGatewayRules() {
+        Set<GatewayFlowRule> rules = new HashSet<>();
+        String ahasRoute = "ahas_route";
+        GatewayFlowRule rule1 = new GatewayFlowRule(ahasRoute)
+            .setCount(500)
+            .setIntervalSec(1);
+        GatewayFlowRule rule2 = new GatewayFlowRule(ahasRoute)
+            .setCount(20)
+            .setIntervalSec(2)
+            .setBurst(5)
+            .setParamItem(new GatewayParamFlowItem()
+                .setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_CLIENT_IP)
+            );
+        GatewayFlowRule rule3 = new GatewayFlowRule("complex_route_ZZZ")
+            .setCount(10)
+            .setIntervalSec(1)
+            .setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_RATE_LIMITER)
+            .setMaxQueueingTimeoutMs(600)
+            .setParamItem(new GatewayParamFlowItem()
+                .setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_HEADER)
+                .setFieldName("X-Sentinel-Flag")
+            );
+        rules.add(rule1);
+        rules.add(rule2);
+        rules.add(rule3);
+        GatewayRuleManager.loadRules(rules);
+
+        List<ParamFlowRule> convertedRules = GatewayRuleManager.getConvertedParamRules(ahasRoute);
+        assertNotNull(convertedRules);
+        assertEquals(0, (int)rule2.getParamItem().getIndex());
+        assertEquals(0, (int)rule3.getParamItem().getIndex());
+        assertTrue(GatewayRuleManager.getRulesForResource(ahasRoute).contains(rule1));
+        assertTrue(GatewayRuleManager.getRulesForResource(ahasRoute).contains(rule2));
+    }
+
+    @Test
+    public void testIsValidRule() {
+        GatewayFlowRule bad1 = new GatewayFlowRule();
+        GatewayFlowRule bad2 = new GatewayFlowRule("abc")
+            .setIntervalSec(0);
+        GatewayFlowRule bad3 = new GatewayFlowRule("abc")
+            .setParamItem(new GatewayParamFlowItem()
+                .setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_URL_PARAM));
+        GatewayFlowRule bad4 = new GatewayFlowRule("abc")
+            .setParamItem(new GatewayParamFlowItem()
+                .setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_URL_PARAM)
+                .setFieldName("p")
+                .setPattern("def")
+                .setMatchStrategy(-1)
+            );
+        GatewayFlowRule good1 = new GatewayFlowRule("abc");
+        GatewayFlowRule good2 = new GatewayFlowRule("abc")
+            .setParamItem(new GatewayParamFlowItem().setParseStrategy(0));
+        GatewayFlowRule good3 = new GatewayFlowRule("abc")
+            .setParamItem(new GatewayParamFlowItem()
+                .setMatchStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_HEADER)
+                .setFieldName("Origin")
+                .setPattern("def"));
+        assertFalse(GatewayRuleManager.isValidRule(bad1));
+        assertFalse(GatewayRuleManager.isValidRule(bad2));
+        assertFalse(GatewayRuleManager.isValidRule(bad3));
+        assertFalse(GatewayRuleManager.isValidRule(bad4));
+
+        assertTrue(GatewayRuleManager.isValidRule(good1));
+        assertTrue(GatewayRuleManager.isValidRule(good2));
+        assertTrue(GatewayRuleManager.isValidRule(good3));
+    }
+
+    @Before
+    public void setUp() {
+        GatewayRuleManager.loadRules(new HashSet<GatewayFlowRule>());
+    }
+
+    @After
+    public void tearDown() {
+        GatewayRuleManager.loadRules(new HashSet<GatewayFlowRule>());
+    }
+}

+ 68 - 0
sentinel-adapter/sentinel-dubbo-adapter/README.md

@@ -0,0 +1,68 @@
+# Sentinel Dubbo Adapter
+
+> Note: 中文文档请见[此处](https://github.com/alibaba/Sentinel/wiki/%E4%B8%BB%E6%B5%81%E6%A1%86%E6%9E%B6%E7%9A%84%E9%80%82%E9%85%8D#dubbo)。
+
+Sentinel Dubbo Adapter provides service consumer filter and provider filter
+for [Dubbo](https://dubbo.apache.org/en-us/) services.
+
+**Note: This adapter only supports legacy Dubbo 2.6.x version and below.**
+For new Apache Dubbo 2.7.x or above version, please use `sentinel-apache-dubbo-adapter` module instead.
+
+To use Sentinel Dubbo Adapter, you can simply add the following dependency to your `pom.xml`:
+
+```xml
+<dependency>
+    <groupId>com.alibaba.csp</groupId>
+    <artifactId>sentinel-dubbo-adapter</artifactId>
+    <version>x.y.z</version>
+</dependency>
+```
+
+The Sentinel filters are **enabled by default**. Once you add the dependency,
+the Dubbo services and methods will become protected resources in Sentinel,
+which can leverage Sentinel's flow control and guard ability when rules are configured.
+Demos can be found in [sentinel-demo-dubbo](https://github.com/alibaba/Sentinel/tree/master/sentinel-demo/sentinel-demo-dubbo).
+
+If you don't want the filters enabled, you can manually disable them. For example:
+
+```xml
+<dubbo:consumer filter="-sentinel.dubbo.consumer.filter"/>
+
+<dubbo:provider filter="-sentinel.dubbo.provider.filter"/>
+```
+
+For more details of Dubbo filter, see [here](http://dubbo.apache.org/en-us/docs/dev/impls/filter.html).
+
+## Dubbo resources
+
+The resource for Dubbo services has two granularities: service interface and service method.
+
+- Service interface:resourceName format is `interfaceName`,e.g. `com.alibaba.csp.sentinel.demo.dubbo.FooService`
+- Service method:resourceName format is `interfaceName:methodSignature`,e.g. `com.alibaba.csp.sentinel.demo.dubbo.FooService:sayHello(java.lang.String)`
+
+## Flow control based on caller
+
+In many circumstances, it's also significant to control traffic flow based on the **caller**.
+For example, assuming that there are two services A and B, both of them initiate remote call requests to the service provider.
+If we want to limit the calls from service B only, we can set the `limitApp` of flow rule as the identifier of service B (e.g. service name).
+
+Sentinel Dubbo Adapter will automatically resolve the Dubbo consumer's *application name* as the caller's name (`origin`),
+and will bring the caller's name when doing resource protection.
+If `limitApp` of flow rules is not configured (`default`), flow control will take effects on all callers.
+If `limitApp` of a flow rule is configured with a caller, then the corresponding flow rule will only take effect on the specific caller.
+
+> Note: Dubbo consumer does not provide its Dubbo application name when doing RPC,
+so developers should manually put the application name into *attachment* at consumer side,
+then extract it at provider side. Sentinel Dubbo Adapter has implemented a filter (`DubboAppContextFilter`)
+where consumer can carry application name information to provider automatically.
+If the consumer does not use Sentinel Dubbo Adapter but requires flow control based on caller, developers can manually put the application name into attachment with the key `dubboApplication`.
+
+## Global fallback
+
+Sentinel Dubbo Adapter supports global fallback configuration.
+The global fallback will handle exceptions and give replacement result when blocked by
+flow control, degrade or system load protection. You can implement your own `DubboFallback` interface
+and then register to `DubboFallbackRegistry`. If no fallback is configured, Sentinel will wrap the `BlockException`
+then directly throw it out.
+
+Besides, we can also leverage [Dubbo mock mechanism](http://dubbo.apache.org/en-us/docs/user/demos/local-mock.html) to provide fallback implementation of degraded Dubbo services.

+ 48 - 0
sentinel-adapter/sentinel-dubbo-adapter/pom.xml

@@ -0,0 +1,48 @@
+<?xml version="1.0" encoding="utf-8"?>
+
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+
+    <parent>
+        <groupId>com.alibaba.csp</groupId>
+        <artifactId>sentinel-adapter</artifactId>
+        <version>1.6.2</version>
+    </parent>
+    <modelVersion>4.0.0</modelVersion>
+    <artifactId>sentinel-dubbo-adapter</artifactId>
+    <packaging>jar</packaging>
+
+    <properties>
+        <dubbo.version>2.6.6</dubbo.version>
+    </properties>
+
+    <dependencies>
+        <dependency>
+            <groupId>com.alibaba.csp</groupId>
+            <artifactId>sentinel-core</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>com.alibaba</groupId>
+            <artifactId>dubbo</artifactId>
+            <version>${dubbo.version}</version>
+            <scope>provided</scope>
+        </dependency>
+
+        <dependency>
+            <groupId>junit</groupId>
+            <artifactId>junit</artifactId>
+            <scope>test</scope>
+        </dependency>
+
+        <dependency>
+            <groupId>org.mockito</groupId>
+            <artifactId>mockito-core</artifactId>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>com.alibaba</groupId>
+            <artifactId>fastjson</artifactId>
+            <scope>test</scope>
+        </dependency>
+    </dependencies>
+</project>

+ 44 - 0
sentinel-adapter/sentinel-dubbo-adapter/src/main/java/com/alibaba/csp/sentinel/adapter/dubbo/AbstractDubboFilter.java

@@ -0,0 +1,44 @@
+/*
+ * Copyright 1999-2018 Alibaba Group Holding Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.alibaba.csp.sentinel.adapter.dubbo;
+
+import com.alibaba.dubbo.rpc.Filter;
+import com.alibaba.dubbo.rpc.Invocation;
+import com.alibaba.dubbo.rpc.Invoker;
+
+/**
+ * @author leyou
+ */
+abstract class AbstractDubboFilter implements Filter {
+
+    protected String getResourceName(Invoker<?> invoker, Invocation invocation) {
+        StringBuilder buf = new StringBuilder(64);
+        buf.append(invoker.getInterface().getName())
+            .append(":")
+            .append(invocation.getMethodName())
+            .append("(");
+        boolean isFirst = true;
+        for (Class<?> clazz : invocation.getParameterTypes()) {
+            if (!isFirst) {
+                buf.append(",");
+            }
+            buf.append(clazz.getName());
+            isFirst = false;
+        }
+        buf.append(")");
+        return buf.toString();
+    }
+}

+ 43 - 0
sentinel-adapter/sentinel-dubbo-adapter/src/main/java/com/alibaba/csp/sentinel/adapter/dubbo/DubboAppContextFilter.java

@@ -0,0 +1,43 @@
+/*
+ * Copyright 1999-2018 Alibaba Group Holding Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.alibaba.csp.sentinel.adapter.dubbo;
+
+import com.alibaba.dubbo.common.Constants;
+import com.alibaba.dubbo.common.extension.Activate;
+import com.alibaba.dubbo.rpc.Filter;
+import com.alibaba.dubbo.rpc.Invocation;
+import com.alibaba.dubbo.rpc.Invoker;
+import com.alibaba.dubbo.rpc.Result;
+import com.alibaba.dubbo.rpc.RpcContext;
+import com.alibaba.dubbo.rpc.RpcException;
+
+/**
+ * Puts current consumer's application name in the attachment of each invocation.
+ *
+ * @author Eric Zhao
+ */
+@Activate(group = "consumer")
+public class DubboAppContextFilter implements Filter {
+
+    @Override
+    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
+        String application = invoker.getUrl().getParameter(Constants.APPLICATION_KEY);
+        if (application != null) {
+            RpcContext.getContext().setAttachment(DubboUtils.DUBBO_APPLICATION_KEY, application);
+        }
+        return invoker.invoke(invocation);
+    }
+}

+ 35 - 0
sentinel-adapter/sentinel-dubbo-adapter/src/main/java/com/alibaba/csp/sentinel/adapter/dubbo/DubboUtils.java

@@ -0,0 +1,35 @@
+/*
+ * Copyright 1999-2018 Alibaba Group Holding Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.alibaba.csp.sentinel.adapter.dubbo;
+
+import com.alibaba.dubbo.rpc.Invocation;
+
+/**
+ * @author Eric Zhao
+ */
+public final class DubboUtils {
+
+    public static final String DUBBO_APPLICATION_KEY = "dubboApplication";
+
+    public static String getApplication(Invocation invocation, String defaultValue) {
+        if (invocation == null || invocation.getAttachments() == null) {
+            throw new IllegalArgumentException("Bad invocation instance");
+        }
+        return invocation.getAttachment(DUBBO_APPLICATION_KEY, defaultValue);
+    }
+
+    private DubboUtils() {}
+}

+ 80 - 0
sentinel-adapter/sentinel-dubbo-adapter/src/main/java/com/alibaba/csp/sentinel/adapter/dubbo/SentinelDubboConsumerFilter.java

@@ -0,0 +1,80 @@
+/*
+ * Copyright 1999-2018 Alibaba Group Holding Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.alibaba.csp.sentinel.adapter.dubbo;
+
+import com.alibaba.csp.sentinel.Entry;
+import com.alibaba.csp.sentinel.EntryType;
+import com.alibaba.csp.sentinel.SphU;
+import com.alibaba.csp.sentinel.Tracer;
+import com.alibaba.csp.sentinel.adapter.dubbo.fallback.DubboFallbackRegistry;
+import com.alibaba.csp.sentinel.context.ContextUtil;
+import com.alibaba.csp.sentinel.log.RecordLog;
+import com.alibaba.csp.sentinel.slots.block.BlockException;
+import com.alibaba.dubbo.common.extension.Activate;
+import com.alibaba.dubbo.rpc.Filter;
+import com.alibaba.dubbo.rpc.Invocation;
+import com.alibaba.dubbo.rpc.Invoker;
+import com.alibaba.dubbo.rpc.Result;
+import com.alibaba.dubbo.rpc.RpcException;
+
+/**
+ * <p>Dubbo service consumer filter for Sentinel. Auto activated by default.</p>
+ *
+ * If you want to disable the consumer filter, you can configure:
+ * <pre>
+ * &lt;dubbo:consumer filter="-sentinel.dubbo.consumer.filter"/&gt;
+ * </pre>
+ *
+ * @author leyou
+ * @author Eric Zhao
+ */
+@Activate(group = "consumer")
+public class SentinelDubboConsumerFilter extends AbstractDubboFilter implements Filter {
+
+    public SentinelDubboConsumerFilter() {
+        RecordLog.info("Sentinel Dubbo consumer filter initialized");
+    }
+
+    @Override
+    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
+        Entry interfaceEntry = null;
+        Entry methodEntry = null;
+        try {
+            String resourceName = getResourceName(invoker, invocation);
+            interfaceEntry = SphU.entry(invoker.getInterface().getName(), EntryType.OUT);
+            methodEntry = SphU.entry(resourceName, EntryType.OUT);
+
+            Result result = invoker.invoke(invocation);
+            if (result.hasException()) {
+                // Record common exception.
+                Tracer.trace(result.getException());
+            }
+            return result;
+        } catch (BlockException e) {
+            return DubboFallbackRegistry.getConsumerFallback().handle(invoker, invocation, e);
+        } catch (RpcException e) {
+            Tracer.trace(e);
+            throw e;
+        } finally {
+            if (methodEntry != null) {
+                methodEntry.exit();
+            }
+            if (interfaceEntry != null) {
+                interfaceEntry.exit();
+            }
+        }
+    }
+}

+ 86 - 0
sentinel-adapter/sentinel-dubbo-adapter/src/main/java/com/alibaba/csp/sentinel/adapter/dubbo/SentinelDubboProviderFilter.java

@@ -0,0 +1,86 @@
+/*
+ * Copyright 1999-2018 Alibaba Group Holding Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.alibaba.csp.sentinel.adapter.dubbo;
+
+import com.alibaba.csp.sentinel.Entry;
+import com.alibaba.csp.sentinel.EntryType;
+import com.alibaba.csp.sentinel.SphU;
+import com.alibaba.csp.sentinel.Tracer;
+import com.alibaba.csp.sentinel.adapter.dubbo.fallback.DubboFallbackRegistry;
+import com.alibaba.csp.sentinel.context.ContextUtil;
+import com.alibaba.csp.sentinel.log.RecordLog;
+import com.alibaba.csp.sentinel.slots.block.BlockException;
+import com.alibaba.csp.sentinel.slots.block.SentinelRpcException;
+import com.alibaba.dubbo.common.extension.Activate;
+import com.alibaba.dubbo.rpc.Filter;
+import com.alibaba.dubbo.rpc.Invocation;
+import com.alibaba.dubbo.rpc.Invoker;
+import com.alibaba.dubbo.rpc.Result;
+import com.alibaba.dubbo.rpc.RpcException;
+
+/**
+ * <p>Dubbo service provider filter for Sentinel. Auto activated by default.</p>
+ *
+ * If you want to disable the provider filter, you can configure:
+ * <pre>
+ * &lt;dubbo:provider filter="-sentinel.dubbo.provider.filter"/&gt;
+ * </pre>
+ *
+ * @author leyou
+ * @author Eric Zhao
+ */
+@Activate(group = "provider")
+public class SentinelDubboProviderFilter extends AbstractDubboFilter implements Filter {
+
+    public SentinelDubboProviderFilter() {
+        RecordLog.info("Sentinel Dubbo provider filter initialized");
+    }
+
+    @Override
+    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
+        // Get origin caller.
+        String application = DubboUtils.getApplication(invocation, "");
+
+        Entry interfaceEntry = null;
+        Entry methodEntry = null;
+        try {
+            String resourceName = getResourceName(invoker, invocation);
+            String interfaceName = invoker.getInterface().getName();
+            ContextUtil.enter(resourceName, application);
+            interfaceEntry = SphU.entry(interfaceName, EntryType.IN);
+            methodEntry = SphU.entry(resourceName, EntryType.IN, 1, invocation.getArguments());
+
+            Result result = invoker.invoke(invocation);
+            if (result.hasException()) {
+                Tracer.trace(result.getException());
+            }
+            return result;
+        } catch (BlockException e) {
+            return DubboFallbackRegistry.getProviderFallback().handle(invoker, invocation, e);
+        } catch (RpcException e) {
+            Tracer.trace(e);
+            throw e;
+        } finally {
+            if (methodEntry != null) {
+                methodEntry.exit(1, invocation.getArguments());
+            }
+            if (interfaceEntry != null) {
+                interfaceEntry.exit();
+            }
+            ContextUtil.exit();
+        }
+    }
+}

+ 34 - 0
sentinel-adapter/sentinel-dubbo-adapter/src/main/java/com/alibaba/csp/sentinel/adapter/dubbo/fallback/DefaultDubboFallback.java

@@ -0,0 +1,34 @@
+/*
+ * Copyright 1999-2018 Alibaba Group Holding Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.alibaba.csp.sentinel.adapter.dubbo.fallback;
+
+import com.alibaba.csp.sentinel.slots.block.BlockException;
+import com.alibaba.csp.sentinel.slots.block.SentinelRpcException;
+import com.alibaba.dubbo.rpc.Invocation;
+import com.alibaba.dubbo.rpc.Invoker;
+import com.alibaba.dubbo.rpc.Result;
+
+/**
+ * @author Eric Zhao
+ */
+public class DefaultDubboFallback implements DubboFallback {
+
+    @Override
+    public Result handle(Invoker<?> invoker, Invocation invocation, BlockException ex) {
+        // Just wrap and throw the exception.
+        throw new SentinelRpcException(ex);
+    }
+}

+ 39 - 0
sentinel-adapter/sentinel-dubbo-adapter/src/main/java/com/alibaba/csp/sentinel/adapter/dubbo/fallback/DubboFallback.java

@@ -0,0 +1,39 @@
+/*
+ * Copyright 1999-2018 Alibaba Group Holding Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.alibaba.csp.sentinel.adapter.dubbo.fallback;
+
+import com.alibaba.csp.sentinel.slots.block.BlockException;
+import com.alibaba.dubbo.rpc.Invocation;
+import com.alibaba.dubbo.rpc.Invoker;
+import com.alibaba.dubbo.rpc.Result;
+
+/**
+ * Fallback handler for Dubbo services.
+ *
+ * @author Eric Zhao
+ */
+public interface DubboFallback {
+
+    /**
+     * Handle the block exception and provide fallback result.
+     *
+     * @param invoker Dubbo invoker
+     * @param invocation Dubbo invocation
+     * @param ex block exception
+     * @return fallback result
+     */
+    Result handle(Invoker<?> invoker, Invocation invocation, BlockException ex);
+}

+ 48 - 0
sentinel-adapter/sentinel-dubbo-adapter/src/main/java/com/alibaba/csp/sentinel/adapter/dubbo/fallback/DubboFallbackRegistry.java

@@ -0,0 +1,48 @@
+/*
+ * Copyright 1999-2018 Alibaba Group Holding Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.alibaba.csp.sentinel.adapter.dubbo.fallback;
+
+/**
+ * Global fallback registry for Dubbo.
+ *
+ * Note: Degrading is mainly designed for consumer. The provider should not
+ * give fallback result in most circumstances.
+ *
+ * @author Eric Zhao
+ */
+public final class DubboFallbackRegistry {
+
+    private static volatile DubboFallback consumerFallback = new DefaultDubboFallback();
+    private static volatile DubboFallback providerFallback = new DefaultDubboFallback();
+
+    public static DubboFallback getConsumerFallback() {
+        return consumerFallback;
+    }
+
+    public static void setConsumerFallback(DubboFallback consumerFallback) {
+        DubboFallbackRegistry.consumerFallback = consumerFallback;
+    }
+
+    public static DubboFallback getProviderFallback() {
+        return providerFallback;
+    }
+
+    public static void setProviderFallback(DubboFallback providerFallback) {
+        DubboFallbackRegistry.providerFallback = providerFallback;
+    }
+
+    private DubboFallbackRegistry() {}
+}

+ 3 - 0
sentinel-adapter/sentinel-dubbo-adapter/src/main/resources/META-INF/dubbo/com.alibaba.dubbo.rpc.Filter

@@ -0,0 +1,3 @@
+sentinel.dubbo.provider.filter=com.alibaba.csp.sentinel.adapter.dubbo.SentinelDubboProviderFilter
+sentinel.dubbo.consumer.filter=com.alibaba.csp.sentinel.adapter.dubbo.SentinelDubboConsumerFilter
+dubbo.application.context.name.filter=com.alibaba.csp.sentinel.adapter.dubbo.DubboAppContextFilter

+ 24 - 0
sentinel-adapter/sentinel-dubbo-adapter/src/test/java/com/alibaba/csp/sentinel/BaseTest.java

@@ -0,0 +1,24 @@
+package com.alibaba.csp.sentinel;
+
+import com.alibaba.csp.sentinel.slots.clusterbuilder.ClusterBuilderSlot;
+import com.alibaba.dubbo.rpc.RpcContext;
+
+/**
+ * Base test class, provide common methods for subClass
+ * The package is same as CtSph, to call CtSph.resetChainMap() method for test
+ *
+ * Note: Only for test. DO NOT USE IN PRODUCTION!
+ *
+ * @author cdfive
+ */
+public class BaseTest {
+
+    /**
+     * Clean up resources for context, clusterNodeMap, processorSlotChainMap
+     */
+    protected static void cleanUpAll() {
+        RpcContext.removeContext();
+        ClusterBuilderSlot.getClusterNodeMap().clear();
+        CtSph.resetChainMap();
+    }
+}

+ 41 - 0
sentinel-adapter/sentinel-dubbo-adapter/src/test/java/com/alibaba/csp/sentinel/adapter/dubbo/AbstractDubboFilterTest.java

@@ -0,0 +1,41 @@
+package com.alibaba.csp.sentinel.adapter.dubbo;
+
+import com.alibaba.csp.sentinel.adapter.dubbo.provider.DemoService;
+import com.alibaba.dubbo.rpc.Invocation;
+import com.alibaba.dubbo.rpc.Invoker;
+import com.alibaba.dubbo.rpc.Result;
+import com.alibaba.dubbo.rpc.RpcException;
+import org.junit.Test;
+
+import java.lang.reflect.Method;
+
+import static org.junit.Assert.*;
+import static org.mockito.Mockito.*;
+
+/**
+ * @author cdfive
+ */
+public class AbstractDubboFilterTest {
+
+    private AbstractDubboFilter filter = new AbstractDubboFilter() {
+        @Override
+        public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
+            return null;
+        }
+    };
+
+    @Test
+    public void testGetResourceName() {
+        Invoker invoker = mock(Invoker.class);
+        when(invoker.getInterface()).thenReturn(DemoService.class);
+
+        Invocation invocation = mock(Invocation.class);
+        Method method = DemoService.class.getMethods()[0];
+        when(invocation.getMethodName()).thenReturn(method.getName());
+        when(invocation.getParameterTypes()).thenReturn(method.getParameterTypes());
+
+        String resourceName = filter.getResourceName(invoker, invocation);
+
+        assertEquals("com.alibaba.csp.sentinel.adapter.dubbo.provider.DemoService:sayHello(java.lang.String,int)", resourceName);
+    }
+}

+ 59 - 0
sentinel-adapter/sentinel-dubbo-adapter/src/test/java/com/alibaba/csp/sentinel/adapter/dubbo/DubboAppContextFilterTest.java

@@ -0,0 +1,59 @@
+package com.alibaba.csp.sentinel.adapter.dubbo;
+
+import com.alibaba.csp.sentinel.BaseTest;
+import com.alibaba.dubbo.common.URL;
+import com.alibaba.dubbo.rpc.Invocation;
+import com.alibaba.dubbo.rpc.Invoker;
+import com.alibaba.dubbo.rpc.RpcContext;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+import static org.junit.Assert.*;
+import static org.mockito.Mockito.*;
+
+/**
+ * @author cdfive
+ */
+public class DubboAppContextFilterTest extends BaseTest {
+
+    private DubboAppContextFilter filter = new DubboAppContextFilter();
+
+    @Before
+    public void setUp() {
+        cleanUpAll();
+    }
+
+    @After
+    public void cleanUp() {
+        cleanUpAll();
+    }
+
+    @Test
+    public void testInvokeApplicationKey() {
+        Invoker invoker = mock(Invoker.class);
+        Invocation invocation = mock(Invocation.class);
+        URL url = URL.valueOf("test://test:111/test?application=serviceA");
+        when(invoker.getUrl()).thenReturn(url);
+
+        filter.invoke(invoker, invocation);
+        verify(invoker).invoke(invocation);
+
+        String application = RpcContext.getContext().getAttachment(DubboUtils.DUBBO_APPLICATION_KEY);
+        assertEquals("serviceA", application);
+    }
+
+    @Test
+    public void testInvokeNullApplicationKey() {
+        Invoker invoker = mock(Invoker.class);
+        Invocation invocation = mock(Invocation.class);
+        URL url = URL.valueOf("test://test:111/test?application=");
+        when(invoker.getUrl()).thenReturn(url);
+
+        filter.invoke(invoker, invocation);
+        verify(invoker).invoke(invocation);
+
+        String application = RpcContext.getContext().getAttachment(DubboUtils.DUBBO_APPLICATION_KEY);
+        assertNull(application);
+    }
+}

+ 39 - 0
sentinel-adapter/sentinel-dubbo-adapter/src/test/java/com/alibaba/csp/sentinel/adapter/dubbo/DubboUtilsTest.java

@@ -0,0 +1,39 @@
+package com.alibaba.csp.sentinel.adapter.dubbo;
+
+import com.alibaba.dubbo.rpc.Invocation;
+import org.junit.Test;
+
+import java.util.HashMap;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
+import static org.mockito.Mockito.*;
+
+/**
+ * @author cdfive
+ */
+public class DubboUtilsTest {
+
+    @Test
+    public void testGetApplication() {
+        Invocation invocation = mock(Invocation.class);
+        when(invocation.getAttachments()).thenReturn(new HashMap<String, String>());
+        when(invocation.getAttachment(DubboUtils.DUBBO_APPLICATION_KEY, "")).thenReturn("consumerA");
+
+        String application = DubboUtils.getApplication(invocation, "");
+        verify(invocation).getAttachment(DubboUtils.DUBBO_APPLICATION_KEY, "");
+
+        assertEquals("consumerA", application);
+    }
+
+    @Test(expected = IllegalArgumentException.class)
+    public void testGetApplicationNoAttachments() {
+        Invocation invocation = mock(Invocation.class);
+        when(invocation.getAttachments()).thenReturn(null);
+        when(invocation.getAttachment(DubboUtils.DUBBO_APPLICATION_KEY, "")).thenReturn("consumerA");
+
+        DubboUtils.getApplication(invocation, "");
+
+        fail("No attachments in invocation, IllegalArgumentException should be thrown!");
+    }
+}

+ 131 - 0
sentinel-adapter/sentinel-dubbo-adapter/src/test/java/com/alibaba/csp/sentinel/adapter/dubbo/SentinelDubboConsumerFilterTest.java

@@ -0,0 +1,131 @@
+package com.alibaba.csp.sentinel.adapter.dubbo;
+
+import com.alibaba.csp.sentinel.BaseTest;
+import com.alibaba.csp.sentinel.Constants;
+import com.alibaba.csp.sentinel.Entry;
+import com.alibaba.csp.sentinel.EntryType;
+import com.alibaba.csp.sentinel.adapter.dubbo.provider.DemoService;
+import com.alibaba.csp.sentinel.context.Context;
+import com.alibaba.csp.sentinel.context.ContextUtil;
+import com.alibaba.csp.sentinel.node.ClusterNode;
+import com.alibaba.csp.sentinel.node.DefaultNode;
+import com.alibaba.csp.sentinel.node.Node;
+import com.alibaba.csp.sentinel.node.StatisticNode;
+import com.alibaba.csp.sentinel.slotchain.ResourceWrapper;
+import com.alibaba.dubbo.rpc.Invocation;
+import com.alibaba.dubbo.rpc.Invoker;
+import com.alibaba.dubbo.rpc.Result;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.invocation.InvocationOnMock;
+import org.mockito.stubbing.Answer;
+
+import java.lang.reflect.Method;
+import java.util.Map;
+import java.util.Set;
+
+import static org.junit.Assert.*;
+import static org.mockito.Mockito.*;
+
+/**
+ * @author cdfive
+ */
+public class SentinelDubboConsumerFilterTest extends BaseTest {
+
+    private SentinelDubboConsumerFilter filter = new SentinelDubboConsumerFilter();
+
+    @Before
+    public void setUp() {
+        cleanUpAll();
+    }
+
+    @After
+    public void cleanUp() {
+        cleanUpAll();
+    }
+
+    @Test
+    public void testInvoke() {
+        final Invoker invoker = mock(Invoker.class);
+        when(invoker.getInterface()).thenReturn(DemoService.class);
+
+        final Invocation invocation = mock(Invocation.class);
+        Method method = DemoService.class.getMethods()[0];
+        when(invocation.getMethodName()).thenReturn(method.getName());
+        when(invocation.getParameterTypes()).thenReturn(method.getParameterTypes());
+
+        final Result result = mock(Result.class);
+        when(result.hasException()).thenReturn(false);
+        when(invoker.invoke(invocation)).thenAnswer(new Answer<Object>() {
+            @Override
+            public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
+                verifyInvocationStructure(invoker, invocation);
+                return result;
+            }
+        });
+
+        filter.invoke(invoker, invocation);
+        verify(invoker).invoke(invocation);
+
+        Context context = ContextUtil.getContext();
+        assertNull(context);
+    }
+
+    /**
+     * Simply verify invocation structure in memory:
+     * EntranceNode(defaultContextName)
+     * --InterfaceNode(interfaceName)
+     * ----MethodNode(resourceName)
+     */
+    private void verifyInvocationStructure(Invoker invoker, Invocation invocation) {
+        Context context = ContextUtil.getContext();
+        assertNotNull(context);
+
+        // As not call ContextUtil.enter(resourceName, application) in SentinelDubboConsumerFilter, use default context
+        // In actual project, a consumer is usually also a provider, the context will be created by SentinelDubboProviderFilter
+        // If consumer is on the top of Dubbo RPC invocation chain, use default context
+        String resourceName = filter.getResourceName(invoker, invocation);
+        assertEquals(Constants.CONTEXT_DEFAULT_NAME, context.getName());
+        assertEquals("", context.getOrigin());
+
+        DefaultNode entranceNode = context.getEntranceNode();
+        ResourceWrapper entranceResource = entranceNode.getId();
+        assertEquals(Constants.CONTEXT_DEFAULT_NAME, entranceResource.getName());
+        assertSame(EntryType.IN, entranceResource.getType());
+
+        // As SphU.entry(interfaceName, EntryType.OUT);
+        Set<Node> childList = entranceNode.getChildList();
+        assertEquals(1, childList.size());
+        DefaultNode interfaceNode = (DefaultNode) childList.iterator().next();
+        ResourceWrapper interfaceResource = interfaceNode.getId();
+        assertEquals(DemoService.class.getName(), interfaceResource.getName());
+        assertSame(EntryType.OUT, interfaceResource.getType());
+
+        // As SphU.entry(resourceName, EntryType.OUT);
+        childList = interfaceNode.getChildList();
+        assertEquals(1, childList.size());
+        DefaultNode methodNode = (DefaultNode) childList.iterator().next();
+        ResourceWrapper methodResource = methodNode.getId();
+        assertEquals(resourceName, methodResource.getName());
+        assertSame(EntryType.OUT, methodResource.getType());
+
+        // Verify curEntry
+        Entry curEntry = context.getCurEntry();
+        assertSame(methodNode, curEntry.getCurNode());
+        assertSame(interfaceNode, curEntry.getLastNode());
+        assertNull(curEntry.getOriginNode());// As context origin is not "", no originNode should be created in curEntry
+
+        // Verify clusterNode
+        ClusterNode methodClusterNode = methodNode.getClusterNode();
+        ClusterNode interfaceClusterNode = interfaceNode.getClusterNode();
+        assertNotSame(methodClusterNode, interfaceClusterNode);// Different resource->Different ProcessorSlot->Different ClusterNode
+
+        // As context origin is "", the StatisticNode should not be created in originCountMap of ClusterNode
+        Map<String, StatisticNode> methodOriginCountMap = methodClusterNode.getOriginCountMap();
+        assertEquals(0, methodOriginCountMap.size());
+
+        Map<String, StatisticNode> interfaceOriginCountMap = interfaceClusterNode.getOriginCountMap();
+        assertEquals(0, interfaceOriginCountMap.size());
+    }
+}

+ 133 - 0
sentinel-adapter/sentinel-dubbo-adapter/src/test/java/com/alibaba/csp/sentinel/adapter/dubbo/SentinelDubboProviderFilterTest.java

@@ -0,0 +1,133 @@
+package com.alibaba.csp.sentinel.adapter.dubbo;
+
+import com.alibaba.csp.sentinel.BaseTest;
+import com.alibaba.csp.sentinel.Entry;
+import com.alibaba.csp.sentinel.EntryType;
+import com.alibaba.csp.sentinel.adapter.dubbo.provider.DemoService;
+import com.alibaba.csp.sentinel.context.Context;
+import com.alibaba.csp.sentinel.context.ContextUtil;
+import com.alibaba.csp.sentinel.node.ClusterNode;
+import com.alibaba.csp.sentinel.node.DefaultNode;
+import com.alibaba.csp.sentinel.node.Node;
+import com.alibaba.csp.sentinel.node.StatisticNode;
+import com.alibaba.csp.sentinel.slotchain.ResourceWrapper;
+import com.alibaba.dubbo.rpc.Invocation;
+import com.alibaba.dubbo.rpc.Invoker;
+import com.alibaba.dubbo.rpc.Result;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.invocation.InvocationOnMock;
+import org.mockito.stubbing.Answer;
+
+import java.lang.reflect.Method;
+import java.util.Map;
+import java.util.Set;
+
+import static org.junit.Assert.*;
+import static org.mockito.Mockito.*;
+
+/**
+ * @author cdfive
+ */
+public class SentinelDubboProviderFilterTest extends BaseTest {
+
+    private SentinelDubboProviderFilter filter = new SentinelDubboProviderFilter();
+
+    @Before
+    public void setUp() {
+        cleanUpAll();
+    }
+
+    @After
+    public void cleanUp() {
+        cleanUpAll();
+    }
+
+    @Test
+    public void testInvoke() {
+        final String originApplication = "consumerA";
+
+        final Invoker invoker = mock(Invoker.class);
+        when(invoker.getInterface()).thenReturn(DemoService.class);
+
+        final Invocation invocation = mock(Invocation.class);
+        Method method = DemoService.class.getMethods()[0];
+        when(invocation.getMethodName()).thenReturn(method.getName());
+        when(invocation.getParameterTypes()).thenReturn(method.getParameterTypes());
+        when(invocation.getAttachment(DubboUtils.DUBBO_APPLICATION_KEY, "")).thenReturn(originApplication);
+
+        final Result result = mock(Result.class);
+        when(result.hasException()).thenReturn(false);
+        when(invoker.invoke(invocation)).thenAnswer(new Answer<Object>() {
+            @Override
+            public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
+                verifyInvocationStructure(originApplication, invoker, invocation);
+                return result;
+            }
+        });
+
+        filter.invoke(invoker, invocation);
+        verify(invoker).invoke(invocation);
+
+        Context context = ContextUtil.getContext();
+        assertNull(context);
+    }
+
+    /**
+     * Simply verify invocation structure in memory:
+     * EntranceNode(resourceName)
+     * --InterfaceNode(interfaceName)
+     * ----MethodNode(resourceName)
+     */
+    private void verifyInvocationStructure(String originApplication, Invoker invoker, Invocation invocation) {
+        Context context = ContextUtil.getContext();
+        assertNotNull(context);
+
+        // As ContextUtil.enter(resourceName, application) in SentinelDubboProviderFilter
+        String resourceName = filter.getResourceName(invoker, invocation);
+        assertEquals(resourceName, context.getName());
+        assertEquals(originApplication, context.getOrigin());
+
+        DefaultNode entranceNode = context.getEntranceNode();
+        ResourceWrapper entranceResource = entranceNode.getId();
+        assertEquals(resourceName, entranceResource.getName());
+        assertSame(EntryType.IN, entranceResource.getType());
+
+        // As SphU.entry(interfaceName, EntryType.IN);
+        Set<Node> childList = entranceNode.getChildList();
+        assertEquals(1, childList.size());
+        DefaultNode interfaceNode = (DefaultNode) childList.iterator().next();
+        ResourceWrapper interfaceResource = interfaceNode.getId();
+        assertEquals(DemoService.class.getName(), interfaceResource.getName());
+        assertSame(EntryType.IN, interfaceResource.getType());
+
+        // As SphU.entry(resourceName, EntryType.IN, 1, invocation.getArguments());
+        childList = interfaceNode.getChildList();
+        assertEquals(1, childList.size());
+        DefaultNode methodNode = (DefaultNode) childList.iterator().next();
+        ResourceWrapper methodResource = methodNode.getId();
+        assertEquals(resourceName, methodResource.getName());
+        assertSame(EntryType.IN, methodResource.getType());
+
+        // Verify curEntry
+        Entry curEntry = context.getCurEntry();
+        assertSame(methodNode, curEntry.getCurNode());
+        assertSame(interfaceNode, curEntry.getLastNode());
+        assertNotNull(curEntry.getOriginNode());// As context origin is not "", originNode should be created
+
+        // Verify clusterNode
+        ClusterNode methodClusterNode = methodNode.getClusterNode();
+        ClusterNode interfaceClusterNode = interfaceNode.getClusterNode();
+        assertNotSame(methodClusterNode, interfaceClusterNode);// Different resource->Different ProcessorSlot->Different ClusterNode
+
+        // As context origin is not "", the StatisticNode should be created in originCountMap of ClusterNode
+        Map<String, StatisticNode> methodOriginCountMap = methodClusterNode.getOriginCountMap();
+        assertEquals(1, methodOriginCountMap.size());
+        assertTrue(methodOriginCountMap.containsKey(originApplication));
+
+        Map<String, StatisticNode> interfaceOriginCountMap = interfaceClusterNode.getOriginCountMap();
+        assertEquals(1, interfaceOriginCountMap.size());
+        assertTrue(interfaceOriginCountMap.containsKey(originApplication));
+    }
+}

+ 56 - 0
sentinel-adapter/sentinel-dubbo-adapter/src/test/java/com/alibaba/csp/sentinel/adapter/dubbo/fallback/DubboFallbackRegistryTest.java

@@ -0,0 +1,56 @@
+/*
+ * Copyright 1999-2018 Alibaba Group Holding Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.alibaba.csp.sentinel.adapter.dubbo.fallback;
+
+import com.alibaba.csp.sentinel.slots.block.BlockException;
+import com.alibaba.csp.sentinel.slots.block.SentinelRpcException;
+import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
+import com.alibaba.dubbo.rpc.Invocation;
+import com.alibaba.dubbo.rpc.Invoker;
+import com.alibaba.dubbo.rpc.Result;
+import com.alibaba.dubbo.rpc.RpcResult;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+/**
+ * @author Eric Zhao
+ */
+public class DubboFallbackRegistryTest {
+
+    @Test(expected = SentinelRpcException.class)
+    public void testDefaultFallback() {
+        // Test for default.
+        BlockException ex = new FlowException("xxx");
+        DubboFallbackRegistry.getConsumerFallback()
+            .handle(null, null, ex);
+    }
+
+    @Test
+    public void testCustomFallback() {
+        BlockException ex = new FlowException("xxx");
+        DubboFallbackRegistry.setConsumerFallback(new DubboFallback() {
+            @Override
+            public Result handle(Invoker<?> invoker, Invocation invocation, BlockException e) {
+                return new RpcResult("Error: " + e.getClass().getName());
+            }
+        });
+        Result result = DubboFallbackRegistry.getConsumerFallback()
+            .handle(null, null, ex);
+        Assert.assertFalse("The invocation should not fail", result.hasException());
+        Assert.assertEquals("Error: " + ex.getClass().getName(), result.getValue());
+    }
+}

+ 23 - 0
sentinel-adapter/sentinel-dubbo-adapter/src/test/java/com/alibaba/csp/sentinel/adapter/dubbo/provider/DemoService.java

@@ -0,0 +1,23 @@
+/*
+ * Copyright 1999-2018 Alibaba Group Holding Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.alibaba.csp.sentinel.adapter.dubbo.provider;
+
+/**
+ * @author leyou
+ */
+public interface DemoService {
+    String sayHello(String name, int n);
+}

+ 27 - 0
sentinel-adapter/sentinel-dubbo-adapter/src/test/java/com/alibaba/csp/sentinel/adapter/dubbo/provider/impl/DemoServiceImpl.java

@@ -0,0 +1,27 @@
+/*
+ * Copyright 1999-2018 Alibaba Group Holding Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.alibaba.csp.sentinel.adapter.dubbo.provider.impl;
+
+import com.alibaba.csp.sentinel.adapter.dubbo.provider.DemoService;
+
+/**
+ * @author leyou
+ */
+public class DemoServiceImpl implements DemoService {
+    public String sayHello(String name, int n) {
+        return "Hello " + name + ", " + n;
+    }
+}

+ 18 - 0
sentinel-adapter/sentinel-dubbo-adapter/src/test/resources/spring-dubbo-consumer-filter.xml

@@ -0,0 +1,18 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<beans xmlns="http://www.springframework.org/schema/beans"
+       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+       xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"
+       xsi:schemaLocation="http://www.springframework.org/schema/beans
+       http://www.springframework.org/schema/beans/spring-beans.xsd
+       http://code.alibabatech.com/schema/dubbo
+       http://code.alibabatech.com/schema/dubbo/dubbo.xsd">
+
+    <dubbo:application name="demo-consumer"/>
+    <dubbo:registry address="multicast://224.5.6.7:1234"/>
+    <dubbo:protocol name="dubbo" port="20880"/>
+    <dubbo:service interface="com.alibaba.csp.sentinel.adapter.dubbo.provider.DemoService" ref="demoServiceImp" />
+    <bean id="demoServiceImp" class="com.alibaba.csp.sentinel.adapter.dubbo.provider.impl.DemoServiceImpl"/>
+
+    <dubbo:reference id="demoService" interface="com.alibaba.csp.sentinel.adapter.dubbo.provider.DemoService"/>
+
+</beans>

+ 18 - 0
sentinel-adapter/sentinel-dubbo-adapter/src/test/resources/spring-dubbo-provider-filter.xml

@@ -0,0 +1,18 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<beans xmlns="http://www.springframework.org/schema/beans"
+       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+       xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"
+       xsi:schemaLocation="http://www.springframework.org/schema/beans
+       http://www.springframework.org/schema/beans/spring-beans.xsd
+       http://code.alibabatech.com/schema/dubbo
+       http://code.alibabatech.com/schema/dubbo/dubbo.xsd">
+
+    <dubbo:application name="demo-provider"/>
+    <dubbo:registry address="multicast://224.5.6.7:1234"/>
+    <dubbo:protocol name="dubbo" port="20880"/>
+    <dubbo:service interface="com.alibaba.csp.sentinel.adapter.dubbo.provider.DemoService" ref="demoServiceImp" />
+    <bean id="demoServiceImp" class="com.alibaba.csp.sentinel.adapter.dubbo.provider.impl.DemoServiceImpl"/>
+
+    <dubbo:reference id="demoService" interface="com.alibaba.csp.sentinel.adapter.dubbo.provider.DemoService"/>
+
+</beans>

+ 38 - 0
sentinel-adapter/sentinel-grpc-adapter/README.md

@@ -0,0 +1,38 @@
+# Sentinel gRPC Adapter
+
+Sentinel gRPC Adapter provides client and server interceptor for gRPC services.
+
+> Note that currently the interceptor only supports unary methods in gRPC.
+> In some circumstances (e.g. asynchronous call), the RT metrics might not be accurate.
+
+## Client Interceptor
+
+Example:
+
+```java
+public class ServiceClient {
+
+    private final ManagedChannel channel;
+
+    ServiceClient(String host, int port) {
+        this.channel = ManagedChannelBuilder.forAddress(host, port)
+            .intercept(new SentinelGrpcClientInterceptor()) // Add the client interceptor.
+            .build();
+        // Init your stub here.
+    }
+}
+```
+
+## Server Interceptor
+
+Example:
+
+```java
+import io.grpc.Server;
+
+Server server = ServerBuilder.forPort(port)
+     .addService(new MyServiceImpl()) // Add your service.
+     .intercept(new SentinelGrpcServerInterceptor()) // Add the server interceptor.
+     .build();
+```
+

+ 98 - 0
sentinel-adapter/sentinel-grpc-adapter/pom.xml

@@ -0,0 +1,98 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+    <parent>
+        <artifactId>sentinel-adapter</artifactId>
+        <groupId>com.alibaba.csp</groupId>
+        <version>1.6.2</version>
+    </parent>
+    <modelVersion>4.0.0</modelVersion>
+    <artifactId>sentinel-grpc-adapter</artifactId>
+    <packaging>jar</packaging>
+
+    <properties>
+        <grpc.version>1.13.1</grpc.version>
+    </properties>
+
+    <dependencies>
+        <dependency>
+            <groupId>com.alibaba.csp</groupId>
+            <artifactId>sentinel-core</artifactId>
+        </dependency>
+
+        <dependency>
+            <groupId>io.grpc</groupId>
+            <artifactId>grpc-netty</artifactId>
+            <version>${grpc.version}</version>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>io.grpc</groupId>
+            <artifactId>grpc-protobuf</artifactId>
+            <version>${grpc.version}</version>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>io.grpc</groupId>
+            <artifactId>grpc-stub</artifactId>
+            <version>${grpc.version}</version>
+            <scope>provided</scope>
+        </dependency>
+        <!-- workaround for compile in JDK 11 -->
+        <dependency>
+            <groupId>javax.annotation</groupId>
+            <artifactId>javax.annotation-api</artifactId>
+            <version>1.2</version>
+        </dependency>
+
+
+        <dependency>
+            <groupId>junit</groupId>
+            <artifactId>junit</artifactId>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.mockito</groupId>
+            <artifactId>mockito-core</artifactId>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>com.alibaba</groupId>
+            <artifactId>fastjson</artifactId>
+            <version>${fastjson.version}</version>
+            <scope>test</scope>
+        </dependency>
+    </dependencies>
+
+    <build>
+        <extensions>
+            <extension>
+                <groupId>kr.motd.maven</groupId>
+                <artifactId>os-maven-plugin</artifactId>
+                <version>1.5.0.Final</version>
+            </extension>
+        </extensions>
+        <plugins>
+            <plugin>
+                <groupId>org.xolstice.maven.plugins</groupId>
+                <artifactId>protobuf-maven-plugin</artifactId>
+                <version>0.5.1</version>
+                <configuration>
+                    <protocArtifact>com.google.protobuf:protoc:3.5.1-1:exe:${os.detected.classifier}</protocArtifact>
+                    <pluginId>grpc-java</pluginId>
+                    <pluginArtifact>io.grpc:protoc-gen-grpc-java:${grpc.version}:exe:${os.detected.classifier}
+                    </pluginArtifact>
+                </configuration>
+                <executions>
+                    <execution>
+                        <goals>
+                            <goal>test-compile</goal>
+                            <goal>test-compile-custom</goal>
+                        </goals>
+                    </execution>
+                </executions>
+            </plugin>
+        </plugins>
+    </build>
+</project>

+ 139 - 0
sentinel-adapter/sentinel-grpc-adapter/src/main/java/com/alibaba/csp/sentinel/adapter/grpc/SentinelGrpcClientInterceptor.java

@@ -0,0 +1,139 @@
+/*
+ * Copyright 1999-2018 Alibaba Group Holding Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.alibaba.csp.sentinel.adapter.grpc;
+
+import javax.annotation.Nullable;
+
+import com.alibaba.csp.sentinel.Entry;
+import com.alibaba.csp.sentinel.EntryType;
+import com.alibaba.csp.sentinel.SphU;
+import com.alibaba.csp.sentinel.Tracer;
+import com.alibaba.csp.sentinel.context.ContextUtil;
+import com.alibaba.csp.sentinel.slots.block.BlockException;
+
+import io.grpc.CallOptions;
+import io.grpc.Channel;
+import io.grpc.ClientCall;
+import io.grpc.ClientInterceptor;
+import io.grpc.ForwardingClientCall;
+import io.grpc.ForwardingClientCallListener.SimpleForwardingClientCallListener;
+import io.grpc.Metadata;
+import io.grpc.MethodDescriptor;
+import io.grpc.Status;
+
+/**
+ * <p>gRPC client interceptor for Sentinel. Currently it only works with unary methods.</p>
+ *
+ * Example code:
+ * <pre>
+ * public class ServiceClient {
+ *
+ *     private final ManagedChannel channel;
+ *
+ *     ServiceClient(String host, int port) {
+ *         this.channel = ManagedChannelBuilder.forAddress(host, port)
+ *             .intercept(new SentinelGrpcClientInterceptor()) // Add the client interceptor.
+ *             .build();
+ *         // Init your stub here.
+ *     }
+ *
+ * }
+ * </pre>
+ *
+ * For server interceptor, see {@link SentinelGrpcServerInterceptor}.
+ *
+ * @author Eric Zhao
+ */
+public class SentinelGrpcClientInterceptor implements ClientInterceptor {
+
+    private static final Status FLOW_CONTROL_BLOCK = Status.UNAVAILABLE.withDescription(
+        "Flow control limit exceeded (client side)");
+
+    @Override
+    public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(MethodDescriptor<ReqT, RespT> methodDescriptor,
+                                                               CallOptions callOptions, Channel channel) {
+        String resourceName = methodDescriptor.getFullMethodName();
+        Entry entry = null;
+        try {
+            entry = SphU.entry(resourceName, EntryType.OUT);
+            // Allow access, forward the call.
+            return new ForwardingClientCall.SimpleForwardingClientCall<ReqT, RespT>(
+                channel.newCall(methodDescriptor, callOptions)) {
+                @Override
+                public void start(Listener<RespT> responseListener, Metadata headers) {
+                    super.start(new SimpleForwardingClientCallListener<RespT>(responseListener) {
+                        @Override
+                        public void onReady() {
+                            super.onReady();
+                        }
+
+                        @Override
+                        public void onClose(Status status, Metadata trailers) {
+                            super.onClose(status, trailers);
+                            // Record the exception metrics.
+                            if (!status.isOk()) {
+                                recordException(status.asRuntimeException());
+                            }
+                        }
+                    }, headers);
+                }
+
+                @Override
+                public void cancel(@Nullable String message, @Nullable Throwable cause) {
+                    super.cancel(message, cause);
+                    // Record the exception metrics.
+                    recordException(cause);
+                }
+            };
+        } catch (BlockException e) {
+            // Flow control threshold exceeded, block the call.
+            return new ClientCall<ReqT, RespT>() {
+                @Override
+                public void start(Listener<RespT> responseListener, Metadata headers) {
+                    responseListener.onClose(FLOW_CONTROL_BLOCK, new Metadata());
+                }
+
+                @Override
+                public void request(int numMessages) {
+
+                }
+
+                @Override
+                public void cancel(@Nullable String message, @Nullable Throwable cause) {
+
+                }
+
+                @Override
+                public void halfClose() {
+
+                }
+
+                @Override
+                public void sendMessage(ReqT message) {
+
+                }
+            };
+        } finally {
+            if (entry != null) {
+                entry.exit();
+            }
+        }
+    }
+
+    private void recordException(Throwable t) {
+        Tracer.trace(t);
+    }
+}

+ 90 - 0
sentinel-adapter/sentinel-grpc-adapter/src/main/java/com/alibaba/csp/sentinel/adapter/grpc/SentinelGrpcServerInterceptor.java

@@ -0,0 +1,90 @@
+/*
+ * Copyright 1999-2018 Alibaba Group Holding Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.alibaba.csp.sentinel.adapter.grpc;
+
+import com.alibaba.csp.sentinel.Entry;
+import com.alibaba.csp.sentinel.EntryType;
+import com.alibaba.csp.sentinel.SphU;
+import com.alibaba.csp.sentinel.Tracer;
+import com.alibaba.csp.sentinel.context.ContextUtil;
+import com.alibaba.csp.sentinel.slots.block.BlockException;
+
+import io.grpc.ForwardingServerCall;
+import io.grpc.ForwardingServerCallListener;
+import io.grpc.Metadata;
+import io.grpc.ServerCall;
+import io.grpc.ServerCall.Listener;
+import io.grpc.ServerCallHandler;
+import io.grpc.ServerInterceptor;
+import io.grpc.Status;
+
+/**
+ * <p>gRPC server interceptor for Sentinel. Currently it only works with unary methods.</p>
+ *
+ * Example code:
+ * <pre>
+ * Server server = ServerBuilder.forPort(port)
+ *      .addService(new MyServiceImpl()) // Add your service.
+ *      .intercept(new SentinelGrpcServerInterceptor()) // Add the server interceptor.
+ *      .build();
+ * </pre>
+ *
+ * For client interceptor, see {@link SentinelGrpcClientInterceptor}.
+ *
+ * @author Eric Zhao
+ */
+public class SentinelGrpcServerInterceptor implements ServerInterceptor {
+
+    private static final Status FLOW_CONTROL_BLOCK = Status.UNAVAILABLE.withDescription(
+        "Flow control limit exceeded (server side)");
+
+    @Override
+    public <ReqT, RespT> Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> serverCall, Metadata metadata,
+                                                      ServerCallHandler<ReqT, RespT> serverCallHandler) {
+        String resourceName = serverCall.getMethodDescriptor().getFullMethodName();
+        // Remote address: serverCall.getAttributes().get(Grpc.TRANSPORT_ATTR_REMOTE_ADDR);
+        Entry entry = null;
+        try {
+            ContextUtil.enter(resourceName);
+            entry = SphU.entry(resourceName, EntryType.IN);
+            // Allow access, forward the call.
+            return new ForwardingServerCallListener.SimpleForwardingServerCallListener<ReqT>(
+                serverCallHandler.startCall(
+                    new ForwardingServerCall.SimpleForwardingServerCall<ReqT, RespT>(serverCall) {
+                        @Override
+                        public void close(Status status, Metadata trailers) {
+                            super.close(status, trailers);
+                            // Record the exception metrics.
+                            if (!status.isOk()) {
+                                recordException(status.asRuntimeException());
+                            }
+                        }
+                    }, metadata)) {};
+        } catch (BlockException e) {
+            serverCall.close(FLOW_CONTROL_BLOCK, new Metadata());
+            return new ServerCall.Listener<ReqT>() {};
+        } finally {
+            if (entry != null) {
+                entry.exit();
+            }
+            ContextUtil.exit();
+        }
+    }
+
+    private void recordException(Throwable t) {
+        Tracer.trace(t);
+    }
+}

+ 70 - 0
sentinel-adapter/sentinel-grpc-adapter/src/test/java/com/alibaba/csp/sentinel/adapter/grpc/FooServiceClient.java

@@ -0,0 +1,70 @@
+/*
+ * Copyright 1999-2018 Alibaba Group Holding Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.alibaba.csp.sentinel.adapter.grpc;
+
+import java.util.concurrent.TimeUnit;
+
+import com.alibaba.csp.sentinel.adapter.grpc.gen.FooRequest;
+import com.alibaba.csp.sentinel.adapter.grpc.gen.FooResponse;
+import com.alibaba.csp.sentinel.adapter.grpc.gen.FooServiceGrpc;
+
+import io.grpc.ClientInterceptor;
+import io.grpc.ManagedChannel;
+import io.grpc.ManagedChannelBuilder;
+
+/**
+ * A simple wrapped gRPC client for FooService.
+ *
+ * @author Eric Zhao
+ */
+final class FooServiceClient {
+
+    private final ManagedChannel channel;
+    private final FooServiceGrpc.FooServiceBlockingStub blockingStub;
+
+    FooServiceClient(String host, int port) {
+        this.channel = ManagedChannelBuilder.forAddress(host, port)
+            .usePlaintext()
+            .build();
+        this.blockingStub = FooServiceGrpc.newBlockingStub(this.channel);
+    }
+
+    FooServiceClient(String host, int port, ClientInterceptor interceptor) {
+        this.channel = ManagedChannelBuilder.forAddress(host, port)
+            .usePlaintext()
+            .intercept(interceptor)
+            .build();
+        this.blockingStub = FooServiceGrpc.newBlockingStub(this.channel);
+    }
+
+    FooResponse sayHello(FooRequest request) {
+        if (request == null) {
+            throw new IllegalArgumentException("Request cannot be null");
+        }
+        return blockingStub.sayHello(request);
+    }
+
+    FooResponse anotherHello(FooRequest request) {
+        if (request == null) {
+            throw new IllegalArgumentException("Request cannot be null");
+        }
+        return blockingStub.anotherHello(request);
+    }
+
+    void shutdown() throws InterruptedException {
+        channel.shutdown().awaitTermination(1, TimeUnit.SECONDS);
+    }
+}

+ 44 - 0
sentinel-adapter/sentinel-grpc-adapter/src/test/java/com/alibaba/csp/sentinel/adapter/grpc/FooServiceImpl.java

@@ -0,0 +1,44 @@
+/*
+ * Copyright 1999-2018 Alibaba Group Holding Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.alibaba.csp.sentinel.adapter.grpc;
+
+import com.alibaba.csp.sentinel.adapter.grpc.gen.FooRequest;
+import com.alibaba.csp.sentinel.adapter.grpc.gen.FooResponse;
+import com.alibaba.csp.sentinel.adapter.grpc.gen.FooServiceGrpc;
+
+import io.grpc.stub.StreamObserver;
+
+/**
+ * Implementation of FooService defined in proto.
+ */
+class FooServiceImpl extends FooServiceGrpc.FooServiceImplBase {
+
+    @Override
+    public void sayHello(FooRequest request, StreamObserver<FooResponse> responseObserver) {
+        String message = String.format("Hello %s! Your ID is %d.", request.getName(), request.getId());
+        FooResponse response = FooResponse.newBuilder().setMessage(message).build();
+        responseObserver.onNext(response);
+        responseObserver.onCompleted();
+    }
+
+    @Override
+    public void anotherHello(FooRequest request, StreamObserver<FooResponse> responseObserver) {
+        String message = String.format("Good day, %s (%d)", request.getName(), request.getId());
+        FooResponse response = FooResponse.newBuilder().setMessage(message).build();
+        responseObserver.onNext(response);
+        responseObserver.onCompleted();
+    }
+}

+ 48 - 0
sentinel-adapter/sentinel-grpc-adapter/src/test/java/com/alibaba/csp/sentinel/adapter/grpc/GrpcTestServer.java

@@ -0,0 +1,48 @@
+/*
+ * Copyright 1999-2018 Alibaba Group Holding Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.alibaba.csp.sentinel.adapter.grpc;
+
+import io.grpc.Server;
+import io.grpc.ServerBuilder;
+
+import java.io.IOException;
+
+class GrpcTestServer {
+
+    private Server server;
+
+    GrpcTestServer() {}
+
+    void start(int port, boolean shouldIntercept) throws IOException {
+        if (server != null) {
+            throw new IllegalStateException("Server already running!");
+        }
+        ServerBuilder<?> serverBuild = ServerBuilder.forPort(port)
+            .addService(new FooServiceImpl());
+        if (shouldIntercept) {
+            serverBuild.intercept(new SentinelGrpcServerInterceptor());
+        }
+        server = serverBuild.build();
+        server.start();
+    }
+
+    void stop() {
+        if (server != null) {
+            server.shutdown();
+            server = null;
+        }
+    }
+}

+ 96 - 0
sentinel-adapter/sentinel-grpc-adapter/src/test/java/com/alibaba/csp/sentinel/adapter/grpc/SentinelGrpcClientInterceptorTest.java

@@ -0,0 +1,96 @@
+/*
+ * Copyright 1999-2018 Alibaba Group Holding Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.alibaba.csp.sentinel.adapter.grpc;
+
+import java.util.Collections;
+
+import com.alibaba.csp.sentinel.EntryType;
+import com.alibaba.csp.sentinel.adapter.grpc.gen.FooRequest;
+import com.alibaba.csp.sentinel.adapter.grpc.gen.FooResponse;
+import com.alibaba.csp.sentinel.node.ClusterNode;
+import com.alibaba.csp.sentinel.slots.block.RuleConstant;
+import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
+import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
+import com.alibaba.csp.sentinel.slots.clusterbuilder.ClusterBuilderSlot;
+
+import io.grpc.StatusRuntimeException;
+import org.junit.After;
+import org.junit.Test;
+
+import static org.junit.Assert.*;
+
+/**
+ * Test cases for {@link SentinelGrpcClientInterceptor}.
+ *
+ * @author Eric Zhao
+ */
+public class SentinelGrpcClientInterceptorTest {
+
+    private final String resourceName = "com.alibaba.sentinel.examples.FooService/sayHello";
+    private final int threshold = 2;
+    private final GrpcTestServer server = new GrpcTestServer();
+
+    private void configureFlowRule(int count) {
+        FlowRule rule = new FlowRule()
+            .setCount(count)
+            .setGrade(RuleConstant.FLOW_GRADE_QPS)
+            .setResource(resourceName)
+            .setLimitApp("default")
+            .as(FlowRule.class);
+        FlowRuleManager.loadRules(Collections.singletonList(rule));
+    }
+
+    @Test
+    public void testGrpcClientInterceptor() throws Exception {
+        final int port = 19328;
+
+        configureFlowRule(threshold);
+        server.start(port, false);
+
+        FooServiceClient client = new FooServiceClient("localhost", port, new SentinelGrpcClientInterceptor());
+
+        assertTrue(sendRequest(client));
+        ClusterNode clusterNode = ClusterBuilderSlot.getClusterNode(resourceName, EntryType.OUT);
+        assertNotNull(clusterNode);
+        assertEquals(1, clusterNode.totalRequest() - clusterNode.blockRequest());
+
+        // Not allowed to pass.
+        configureFlowRule(0);
+
+        // The second request will be blocked.
+        assertFalse(sendRequest(client));
+        assertEquals(1, clusterNode.blockRequest());
+
+        server.stop();
+    }
+
+    private boolean sendRequest(FooServiceClient client) {
+        try {
+            FooResponse response = client.sayHello(FooRequest.newBuilder().setName("Sentinel").setId(666).build());
+            System.out.println("Response: " + response);
+            return true;
+        } catch (StatusRuntimeException ex) {
+            System.out.println("Blocked, cause: " + ex.getMessage());
+            return false;
+        }
+    }
+
+    @After
+    public void cleanUp() {
+        FlowRuleManager.loadRules(null);
+        ClusterBuilderSlot.getClusterNodeMap().clear();
+    }
+}

+ 98 - 0
sentinel-adapter/sentinel-grpc-adapter/src/test/java/com/alibaba/csp/sentinel/adapter/grpc/SentinelGrpcServerInterceptorTest.java

@@ -0,0 +1,98 @@
+/*
+ * Copyright 1999-2018 Alibaba Group Holding Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.alibaba.csp.sentinel.adapter.grpc;
+
+import java.util.Collections;
+
+import com.alibaba.csp.sentinel.EntryType;
+import com.alibaba.csp.sentinel.adapter.grpc.gen.FooRequest;
+import com.alibaba.csp.sentinel.adapter.grpc.gen.FooResponse;
+import com.alibaba.csp.sentinel.node.ClusterNode;
+import com.alibaba.csp.sentinel.slots.block.RuleConstant;
+import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
+import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
+import com.alibaba.csp.sentinel.slots.clusterbuilder.ClusterBuilderSlot;
+
+import io.grpc.StatusRuntimeException;
+import org.junit.After;
+import org.junit.Test;
+
+import static org.junit.Assert.*;
+
+/**
+ * Test cases for {@link SentinelGrpcServerInterceptor}.
+ *
+ * @author Eric Zhao
+ */
+public class SentinelGrpcServerInterceptorTest {
+
+    private final String resourceName = "com.alibaba.sentinel.examples.FooService/anotherHello";
+    private final int threshold = 4;
+    private final GrpcTestServer server = new GrpcTestServer();
+
+    private FooServiceClient client;
+
+    private void configureFlowRule(int count) {
+        FlowRule rule = new FlowRule()
+            .setCount(count)
+            .setGrade(RuleConstant.FLOW_GRADE_QPS)
+            .setResource(resourceName)
+            .setLimitApp("default")
+            .as(FlowRule.class);
+        FlowRuleManager.loadRules(Collections.singletonList(rule));
+    }
+
+    @Test
+    public void testGrpcServerInterceptor() throws Exception {
+        final int port = 19329;
+        client = new FooServiceClient("localhost", port);
+
+        configureFlowRule(threshold);
+        server.start(port, true);
+
+        assertTrue(sendRequest());
+        ClusterNode clusterNode = ClusterBuilderSlot.getClusterNode(resourceName, EntryType.IN);
+        assertNotNull(clusterNode);
+        assertEquals(1, clusterNode.totalRequest() - clusterNode.blockRequest());
+
+        // Not allowed to pass.
+        configureFlowRule(0);
+
+        // The second request will be blocked.
+        assertFalse(sendRequest());
+        assertEquals(1, clusterNode.blockRequest());
+
+        server.stop();
+    }
+
+    private boolean sendRequest() {
+        try {
+            FooResponse response = client.anotherHello(FooRequest.newBuilder().setName("Sentinel").setId(666).build());
+            System.out.println("Response: " + response);
+            return true;
+        } catch (StatusRuntimeException ex) {
+            System.out.println("Blocked, cause: " + ex.getMessage());
+            return false;
+        }
+    }
+
+
+    @After
+    public void cleanUp() {
+        FlowRuleManager.loadRules(null);
+        ClusterBuilderSlot.getClusterNodeMap().clear();
+    }
+}

+ 23 - 0
sentinel-adapter/sentinel-grpc-adapter/src/test/proto/example.proto

@@ -0,0 +1,23 @@
+syntax = "proto3";
+
+option java_multiple_files = true;
+option java_package = "com.alibaba.csp.sentinel.adapter.grpc.gen";
+option java_outer_classname = "FooProto";
+
+package com.alibaba.sentinel.examples;
+
+message FooRequest {
+    string name = 1;
+    int32 id = 2;
+}
+
+message FooResponse {
+    string message = 1;
+}
+
+// Example service definition.
+service FooService {
+    rpc sayHello(FooRequest) returns (FooResponse) {}
+
+    rpc anotherHello(FooRequest) returns (FooResponse) {}
+}

+ 23 - 0
sentinel-adapter/sentinel-reactor-adapter/README.md

@@ -0,0 +1,23 @@
+# Sentinel Reactor Adapter
+
+> Note: this module requires Java 8 or later version.
+
+Sentinel provides integration module for [Reactor](https://projectreactor.io/).
+
+Add the following dependency in `pom.xml` (if you are using Maven):
+
+```xml
+<dependency>
+    <groupId>com.alibaba.csp</groupId>
+    <artifactId>sentinel-reactor-adapter</artifactId>
+    <version>x.y.z</version>
+</dependency>
+```
+
+Example:
+
+```java
+someService.doSomething() // return type: Mono<T> or Flux<T>
+   .transform(new SentinelReactorTransformer<>(resourceName)) // transform here
+   .subscribe();
+```

+ 44 - 0
sentinel-adapter/sentinel-reactor-adapter/pom.xml

@@ -0,0 +1,44 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+    <parent>
+        <artifactId>sentinel-adapter</artifactId>
+        <groupId>com.alibaba.csp</groupId>
+        <version>1.6.2</version>
+    </parent>
+    <modelVersion>4.0.0</modelVersion>
+
+    <artifactId>sentinel-reactor-adapter</artifactId>
+
+    <properties>
+        <java.source.version>1.8</java.source.version>
+        <java.target.version>1.8</java.target.version>
+        <reactor.version>3.2.6.RELEASE</reactor.version>
+    </properties>
+
+    <dependencies>
+        <dependency>
+            <groupId>com.alibaba.csp</groupId>
+            <artifactId>sentinel-core</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>io.projectreactor</groupId>
+            <artifactId>reactor-core</artifactId>
+            <version>${reactor.version}</version>
+            <scope>provided</scope>
+        </dependency>
+
+        <dependency>
+            <groupId>junit</groupId>
+            <artifactId>junit</artifactId>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>io.projectreactor</groupId>
+            <artifactId>reactor-test</artifactId>
+            <version>${reactor.version}</version>
+            <scope>test</scope>
+        </dependency>
+    </dependencies>
+</project>

+ 57 - 0
sentinel-adapter/sentinel-reactor-adapter/src/main/java/com/alibaba/csp/sentinel/adapter/reactor/ContextConfig.java

@@ -0,0 +1,57 @@
+/*
+ * Copyright 1999-2019 Alibaba Group Holding Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.alibaba.csp.sentinel.adapter.reactor;
+
+import com.alibaba.csp.sentinel.util.AssertUtil;
+import com.alibaba.csp.sentinel.util.StringUtil;
+
+/**
+ * @author Eric Zhao
+ */
+public class ContextConfig {
+
+    private final String contextName;
+    private final String origin;
+
+    public ContextConfig(String contextName) {
+        this(contextName, "");
+    }
+
+    public ContextConfig(String contextName, String origin) {
+        AssertUtil.assertNotBlank(contextName, "contextName cannot be blank");
+        this.contextName = contextName;
+        if (StringUtil.isBlank(origin)) {
+            origin = "";
+        }
+        this.origin = origin;
+    }
+
+    public String getContextName() {
+        return contextName;
+    }
+
+    public String getOrigin() {
+        return origin;
+    }
+
+    @Override
+    public String toString() {
+        return "ContextConfig{" +
+            "contextName='" + contextName + '\'' +
+            ", origin='" + origin + '\'' +
+            '}';
+    }
+}

+ 0 - 0
sentinel-adapter/sentinel-reactor-adapter/src/main/java/com/alibaba/csp/sentinel/adapter/reactor/EntryConfig.java


Beberapa file tidak ditampilkan karena terlalu banyak file yang berubah dalam diff ini