diff --git a/.github/stale.yml b/.github/stale.yml new file mode 100644 index 0000000000..29bb6a3cb3 --- /dev/null +++ b/.github/stale.yml @@ -0,0 +1,61 @@ +# General configuration +# Number of days of inactivity before an issue becomes stale +daysUntilStale: 60 +# Issues with these labels will never be considered stale +exemptLabels: + - good first issue + - contribution welcome + - bug + - discussion + - enhancement + - feature + - feature request + - help wanted + - info + - need investigation + - tips + +# Set to true to ignore issues in a project (defaults to false) +exemptProjects: true +# Set to true to ignore issues in a milestone (defaults to false) +exemptMilestones: true +# Set to true to ignore issues with an assignee (defaults to false) +exemptAssignees: true +# Label to use when marking an issue as stale +staleLabel: stale + +# Pull request specific configuration +pulls: + # Number of days of inactivity before a stale Issue or Pull Request is closed. + # Set to false to disable. If disabled, issues still need to be closed manually, but will remain marked as stale. + daysUntilClose: 30 + # Comment to post when marking as stale. Set to `false` to disable + markComment: > + This pull request has been automatically marked as stale because it has not had activity + in the last 90 days. It will be closed in 30 days if no further activity occurs. Please + feel free to give a status update now, ping for review, or re-open when it's ready. + Thank you for your contributions! + # Comment to post when closing a stale Issue or Pull Request. + closeComment: > + This pull request has been automatically closed because it has not had + activity in the last 30 days. Please feel free to give a status update now, ping for review, or re-open when it's ready. + Thank you for your contributions! + # Limit the number of actions per hour, from 1-30. Default is 30 + limitPerRun: 1 + +# Issue specific configuration +issues: + # Number of days of inactivity before a stale Issue or Pull Request is closed. + daysUntilClose: 14 + # Comment to post when marking as stale. Set to `false` to disable + markComment: > + This issue has been automatically marked as stale because it has not had activity in the + last 90 days. It will be closed in 14 days unless it is tagged "help wanted" or other activity + occurs. Thank you for your contributions. + # Comment to post when closing a stale Issue or Pull Request. + closeComment: > + This issue has been automatically closed because it has not had activity in the + last 14 days. If this issue is still valid, please ping a maintainer and ask them to label it as "help wanted". + Thank you for your contributions. + # Limit the number of actions per hour, from 1-30. Default is 30 + limitPerRun: 1 \ No newline at end of file diff --git a/.github/workflows/maven.yml b/.github/workflows/maven.yml new file mode 100644 index 0000000000..e9cae0ab63 --- /dev/null +++ b/.github/workflows/maven.yml @@ -0,0 +1,25 @@ +# This workflow will build a Java project with Maven +# For more information see: https://help.github.com/actions/language-and-framework-guides/building-and-testing-java-with-maven + +name: build + +on: + push: + branches: [ 6.x.x ] + pull_request: + branches: [ 6.x.x ] + +jobs: + build: + + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v2 + - name: Set up JDK 8 + uses: actions/setup-java@v2 + with: + java-version: '8' + distribution: 'adopt' + - name: Build with Maven + run: mvn -B package --file pom.xml \ No newline at end of file diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 9e54ddd3c5..0000000000 --- a/.travis.yml +++ /dev/null @@ -1,4 +0,0 @@ -language: java - -jdk: - - openjdk8 \ No newline at end of file diff --git a/README.md b/README.md index fea82906f8..d5c7791dea 100644 --- a/README.md +++ b/README.md @@ -1,1042 +1,561 @@ -# Nepxion Discovery -[![Total lines](https://tokei.rs/b1/github/Nepxion/Discovery?category=lines)](https://tokei.rs/b1/github/Nepxion/Discovery?category=lines) -[![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg?label=license)](https://github.com/Nepxion/Discovery/blob/master/LICENSE) -[![Maven Central](https://img.shields.io/maven-central/v/com.nepxion/discovery.svg?label=maven%20central)](http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.nepxion%22%20AND%20discovery) -[![Javadocs](http://www.javadoc.io/badge/com.nepxion/discovery-plugin-framework.svg)](http://www.javadoc.io/doc/com.nepxion/discovery-plugin-framework) -[![Build Status](https://travis-ci.org/Nepxion/Discovery.svg?branch=master)](https://travis-ci.org/Nepxion/Discovery) -[![Codacy Badge](https://api.codacy.com/project/badge/Grade/8e39a24e1be740c58b83fb81763ba317)](https://www.codacy.com/project/HaojunRen/Discovery/dashboard?utm_source=github.com&utm_medium=referral&utm_content=Nepxion/Discovery&utm_campaign=Badge_Grade_Dashboard) +![](https://nepxion.github.io/Discovery/docs/discovery-doc/Banner.png) -Nepxion Discovery是一款对Spring Cloud Discovery服务注册发现、Ribbon负载均衡、Feign和RestTemplate调用、Hystrix或者阿里巴巴Sentinel熔断隔离限流降级的增强中间件,其功能包括灰度发布(包括切换发布和平滑发布)、服务隔离、服务路由(包括多机房区域路由、多版本路由和多IP和端口路由)、服务权重、黑/白名单的IP地址过滤、限制注册、限制发现、灰度调用链等,支持Eureka、Consul、Zookeeper和阿里巴巴的Nacos为服务注册发现中间件,支持阿里巴巴的Nacos、携程的Apollo和Redis为远程配置中心,支持Spring Cloud Gateway、Zuul网关和微服务的灰度发布,支持用户自定义和编程”禁止注册“、”禁止被发现“、”禁止被负载均衡“策略 ,支持用户自定义和编程灰度路由策略(包括RPC和REST两种调用方式),支持运维调度灰度发布和路由的元数据,支持多数据源的数据库灰度发布等客户特色化灰度发布,兼容Spring Cloud Edgware版、Finchley版和Greenwich版。现有的Spring Cloud微服务很方便引入该中间件,代码零侵入。鉴于Spring Cloud官方对Eureka和Hystrix不再做新功能的迭代,推荐用Nacos和Sentinel,它们对Spring Cloud灰度发布和路由更具出色的兼容性和友好性 +# Discovery【探索】云原生微服务解决方案 +![Total visits](https://visitor-badge.laobi.icu/badge?page_id=Nepxion&title=total%20visits) [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg?label=license)](https://github.com/Nepxion/Discovery/blob/6.x.x/LICENSE) [![Maven Central](https://img.shields.io/maven-central/v/com.nepxion/discovery.svg?label=maven)](https://search.maven.org/artifact/com.nepxion/discovery) [![Javadocs](http://www.javadoc.io/badge/com.nepxion/discovery-plugin-framework-starter.svg)](http://www.javadoc.io/doc/com.nepxion/discovery-plugin-framework-starter) [![Build Status](https://github.com/Nepxion/Discovery/workflows/build/badge.svg)](https://github.com/Nepxion/Discovery/actions) [![Codacy Badge](https://app.codacy.com/project/badge/Grade/5c42eb719ef64def9cad773abd877e8b)](https://www.codacy.com/gh/Nepxion/Discovery/dashboard?utm_source=github.com&utm_medium=referral&utm_content=Nepxion/Discovery&utm_campaign=Badge_Grade) [![Stars](https://img.shields.io/github/stars/Nepxion/Discovery.svg?label=Stars&style=flat&logo=GitHub)](https://github.com/Nepxion/Discovery/stargazers) [![Stars](https://gitee.com/Nepxion/Discovery/badge/star.svg?theme=gvp)](https://gitee.com/Nepxion/Discovery/stargazers) -:100:鸣谢 -- 感谢阿里巴巴中间件Nacos和Sentinel团队,尤其是Nacos负责人@于怀,Sentinel负责人@子衿,Spring Cloud Alibaba负责人@亦盏的技术支持 -- 感谢携程Apollo团队,尤其是@宋顺,特意开发OpenApi包和技术支持 -- 感谢代码贡献者@Esun,@JikaiSun,@HaoHuang,@Fan Yang,@Ankeway等同学,感谢为本框架提出宝贵意见和建议的同学 -- 感谢使用本框架的公司和企业 + -:100:建议 -- 强烈建议,先学习 [极简示例](https://github.com/Nepxion/DiscoveryGray) +[![Wiki](https://badgen.net/badge/icon/wiki?icon=wiki&label=GitHub)](https://github.com/Nepxion/Discovery/wiki) [![Wiki](https://badgen.net/badge/icon/wiki?icon=wiki&label=Gitee)](https://gitee.com/nepxion/Discovery/wikis/pages?sort_id=3993615&doc_id=1124387) [![Discovery PPT](https://img.shields.io/badge/Discovery%20-ppt-brightgreen?logo=Microsoft%20PowerPoint)](https://nepxion.github.io/Discovery/docs/link-doc/discovery-ppt.html) [![Discovery Page](https://img.shields.io/badge/Discovery%20-page-brightgreen?logo=Microsoft%20Edge)](https://nepxion.github.io/Discovery/) [![Discovery Platform Page](https://img.shields.io/badge/Discovery%20Platform%20-page-brightgreen?logo=Microsoft%20Edge)](https://nepxion.github.io/DiscoveryPlatform) [![Discovery Desktop Page](https://img.shields.io/badge/Discovery%20Desktop%20-page-brightgreen?logo=Microsoft%20Edge)](https://nepxion.github.io/DiscoveryDesktop) [![Polaris Page](https://img.shields.io/badge/Polaris%20-page-brightgreen?logo=Microsoft%20Edge)](https://polaris-paas.github.io/polaris-wiki) -:100:特性 -1. 使用方便。只需如下步骤: +            -- 引入相关依赖到pom.xml,参考 [依赖兼容](#依赖兼容) -- 操作配置文件,参考 [配置文件](#配置文件) - - 在元数据MetaData中,为微服务定义一个版本号(version),定义一个所属组名(group)或者应用名(application),定义一个所属区域(region)名 - - 根据项目实际情况,开启和关闭相关功能项或者属性值,达到最佳配置 -- 规则推送,参考 [规则定义](#规则定义) - - 通过远程配置中心推送规则 - - 通过控制平台界面推送规则 - - 通过客户端工具(例如Postman)推送 -- 导入Postman脚本 - - 为方便体验示例,把discovery-springcloud-postman/Nepxion.postman_collection.json导入到Postman运行即可 +如果您觉得本框架具有一定的参考价值和借鉴意义,请帮忙在页面右上角 [**Star**] -2. 兼容性强。支持如下版本: +## 简介 -| 框架版本 | 框架状态 | 适用Spring Cloud版本 | 适用Spring Boot版本 | 适用Spring Cloud Alibaba版本 | -| --- | --- | --- | --- | --- | -| 5.1.2 | 维护中,可用 | Greenwich | 2.1.x.RELEASE | 0.9.x.RELEASE | -| 4.9.2 | 维护中,可用 | Finchley | 2.0.x.RELEASE | 0.2.x.RELEASE | -| 3.9.2 | 维护中,可用 | Edgware | 1.5.x.RELEASE | 0.1.x.RELEASE | -| 2.0.x | 不维护,不可用 | Dalston | N/A | N/A | -| 1.0.x | 不维护,不可用 | Camden | N/A | N/A | - -:triangular_flag_on_post:由于Greenwich和Finchley版是兼容的,所以Nepxion Discovery版本对于Greenwich和Finchley版也是通用的,即Greenwich和Finchley版既可以使用5.x.x版,也可以使用4.x.x版;Edgware存在着不兼容性,必须使用3.x.x版 - -## 目录 -- [请联系我](#请联系我) -- [快速开始](#快速开始) -- [现有痛点](#现有痛点) -- [应用场景](#应用场景) -- [功能简介](#功能简介) -- [名词解释](#名词解释) -- [架构工程](#架构工程) - - [架构](#架构) - - [工程](#工程) -- [依赖兼容](#依赖兼容) - - [依赖](#依赖) - - [兼容](#兼容) -- [规则定义](#规则定义) - - [规则示例](#规则示例) - - [黑/白名单的IP地址注册的过滤规则](#黑/白名单的IP地址注册的过滤规则) - - [最大注册数的限制的过滤规则](#最大注册数的限制的过滤规则) - - [黑/白名单的IP地址发现的过滤规则](#黑/白名单的IP地址发现的过滤规则) - - [版本访问的灰度发布规则](#版本访问的灰度发布规则) - - [版本权重的灰度发布规则](#版本权重的灰度发布规则) - - [全局版本权重的灰度发布规则](#全局版本权重的灰度发布规则) - - [全局区域权重的灰度发布规则](#全局区域权重的灰度发布规则) - - [网关端全链路路由策略的灰度发布规则](#网关端全链路路由策略的灰度发布规则) - - [用户自定义的灰度发布规则](#用户自定义的灰度发布规则) - - [动态改变规则](#动态改变规则) - - [动态改变版本](#动态改变版本) -- [策略定义](#策略定义) - - [服务端的编程灰度路由策略](#服务端的编程灰度路由策略) - - [Zuul端的编程灰度路由策略](#Zuul端的编程灰度路由策略) - - [Gateway端的编程灰度路由策略](#Gateway端的编程灰度路由策略) - - [REST调用的内置多版本灰度路由策略](#REST调用的内置多版本灰度路由策略) - - [REST调用的内置多区域灰度路由策略](#REST调用的内置多区域灰度路由策略) - - [REST调用的内置多IP和端口灰度路由策略](#REST调用的内置多IP和端口灰度路由策略) - - [REST调用的内置版本权重灰度路由策略](#REST调用的内置版本权重灰度路由策略) - - [REST调用的内置区域权重灰度路由策略](#REST调用的内置区域权重灰度路由策略) - - [REST调用的编程灰度路由策略](#REST调用的编程灰度路由策略) - - [RPC调用的编程灰度路由策略](#RPC调用的编程灰度路由策略) -- [规则和策略](#规则和策略) - - [规则和策略的区别](#规则和策略的区别) - - [规则和策略的关系](#规则和策略的关系) -- [服务隔离](#服务隔离) - - [内置服务隔离](#内置服务隔离) - - [自定义服务隔离](#自定义服务隔离) -- [配置文件](#配置文件) - - [基础属性配置](#基础属性配置) - - [功能开关配置](#功能开关配置) - - [外部元数据配置](#外部元数据配置) -- [配置中心](#配置中心) -- [管理中心](#管理中心) -- [控制平台](#控制平台) -- [监控平台](#监控平台) -- [界面工具](#界面工具) - - [基于图形化桌面程序的灰度发布](#基于图形化桌面程序的灰度发布) - - [基于图形化Web程序的灰度发布](#基于图形化Web程序的灰度发布) - - [基于Apollo界面的灰度发布](#基于Apollo界面的灰度发布) - - [基于Nacos界面的灰度发布](#基于Nacos界面的灰度发布) - - [基于Rest方式的灰度发布](#基于Rest方式的灰度发布) -- [性能分析](#性能分析) -- [Star走势图](#Star走势图) - -## 快速开始 -- [极简示例](https://github.com/Nepxion/DiscoveryGray) -- [入门教程](https://github.com/Nepxion/Docs/raw/master/discovery-doc/README_QUICK_START.md) -- [示例演示](https://github.com/Nepxion/Docs/raw/master/discovery-doc/README_EXAMPLE.md) - -## 请联系我 -微信和公众号 - -![Alt text](https://github.com/Nepxion/Docs/raw/master/zxing-doc/微信-1.jpg) -![Alt text](https://github.com/Nepxion/Docs/raw/master/zxing-doc/公众号-1.jpg) - -## 界面展示 - -图形化灰度发布桌面程序 -![Alt text](https://github.com/Nepxion/Docs/raw/master/discovery-doc/Console1.jpg) -![Alt text](https://github.com/Nepxion/Docs/raw/master/discovery-doc/Console2.jpg) -![Alt text](https://github.com/Nepxion/Docs/raw/master/discovery-doc/Console.gif) -图形化灰度发布Web平台 -![Alt text](https://github.com/Nepxion/Docs/raw/master/discovery-doc/Console14.jpg) -集成规则配置的Apollo配置中心 -![Alt text](https://github.com/Nepxion/Docs/raw/master/discovery-doc/Apollo.jpg) -集成规则配置的Nacos配置中心 -![Alt text](https://github.com/Nepxion/Docs/raw/master/discovery-doc/Nacos1.jpg) -Nacos服务注册发现中心 -![Alt text](https://github.com/Nepxion/Docs/raw/master/discovery-doc/Nacos.jpg) -Spring Boot Admin监控平台 -![Alt text](https://github.com/Nepxion/Docs/raw/master/discovery-doc/Admin1.jpg) -集成Spring Boot Admin(F版或以上)监控平台,实现通过JMX向Endpoint推送规则和版本,实现灰度发布 -![Alt text](https://github.com/Nepxion/Docs/raw/master/discovery-doc/Admin2.jpg) -集成Spring Boot Admin(E版)监控平台,实现通过JMX向Endpoint推送规则和版本,实现灰度发布 -![Alt text](https://github.com/Nepxion/Docs/raw/master/discovery-doc/Admin3.jpg) -集成Sentinel熔断隔离限流降级平台 -![Alt text](https://github.com/Nepxion/Docs/raw/master/discovery-doc/Sentinel1.jpg) -![Alt text](https://github.com/Nepxion/Docs/raw/master/discovery-doc/Sentinel2.jpg) -集成健康检查的Consul界面 -![Alt text](https://github.com/Nepxion/Docs/raw/master/discovery-doc/Consul.jpg) - -## 现有痛点 -现有的Spring Cloud微服务痛点 -- 如果你是运维负责人,是否会经常发现,你掌管的测试环境中的服务注册中心,被一些不负责的开发人员把他本地开发环境注册上来,造成测试人员测试失败。你希望可以把本地开发环境注册给屏蔽掉,不让注册 -- 如果你是运维负责人,生产环境的某个微服务集群下的某个实例,暂时出了问题,但又不希望它下线。你希望可以把该实例给屏蔽掉,暂时不让它被调用 -- 如果你是业务负责人,鉴于业务服务的快速迭代性,微服务集群下的实例发布不同的版本。你希望根据版本管理策略进行路由,提供给下游微服务区别调用,例如访问控制快速基于版本的不同而切换,例如在不同的版本之间进行流量调拨 -- 如果你是业务负责人,希望灰度发布功能可以基于业务场景特色定制,例如根据用户手机号进行不同服务器的路由 -- 如果你是DBA负责人,希望灰度发布功能可以基于数据库切换上 -- 如果你是测试负责人,希望对微服务做A/B测试,那么通过动态改变版本达到该目的 - -## 应用场景 -- 黑/白名单的IP地址注册的过滤 - - 开发环境的本地微服务(例如IP地址为172.16.0.8)不希望被注册到测试环境的服务注册发现中心,那么可以在配置中心维护一个黑/白名单的IP地址过滤(支持全局和局部的过滤)的规则 - - 我们可以通过提供一份黑/白名单达到该效果 -- 最大注册数的限制的过滤 - - 当某个微服务注册数目已经达到上限(例如10个),那么后面起来的微服务,将再也不能注册上去 -- 黑/白名单的IP地址发现的过滤 - - 开发环境的本地微服务(例如IP地址为172.16.0.8)已经注册到测试环境的服务注册发现中心,那么可以在配置中心维护一个黑/白名单的IP地址过滤(支持全局和局部的过滤)的规则,该本地微服务不会被其他测试环境的微服务所调用 - - 我们可以通过推送一份黑/白名单达到该效果 -- 多版本访问的灰度控制 - - A服务调用B服务,而B服务有两个实例(B1、B2),虽然三者相同的服务名,但功能上有差异,需求是在某个时刻,A服务只能调用B1,禁止调用B2。在此场景下,我们在application.properties里为B1维护一个版本为1.0,为B2维护一个版本为1.1 - - 我们可以通过推送A服务调用某个版本的B服务对应关系的配置,达到某种意义上的灰度控制,改变版本的时候,我们只需要再次推送即可 -- 多版本权重的灰度控制 - - 上述场景中,我们也可以通过配给不同版本的权重(流量比例),根据需求,A访问B的流量在B1和B2进行调拨 -- 多区域权重的灰度控制 - - 上述场景中,我们也可以通过配给不同区域的权重(流量比例),根据需求,A访问B的流量在B1和B2(B1和B2所属不同区域)进行调拨 -- 多数据源的数据库灰度控制 - - 我们事先为微服务配置多套数据源,通过灰度发布实时切换数据源 -- 动态改变微服务版本 - - 在A/B测试中,通过动态改变版本,不重启微服务,达到访问版本的路径改变 -- 用户自定义和编程灰度路由策略,可以通过非常简单编程达到如下效果 - - 在业务REST调用上,在Header上传入服务名和版本对应关系的Json字符串,后端若干个服务会把请求路由到指定版本的服务器上 - - 在业务REST调用上,在Header上传入区域(region)名,后端若干个服务会把请求路由到指定区域(region)名的服务器上 - - 在业务REST调用上,在Header上传入Token,根据不同的Token查询到不同的用户,后端若干个服务会把请求路由到指定的服务器上 - - 在业务RPC调用上,根据不同的业务参数,例如手机号或者身份证号,后端若干个服务会把请求路由到指定的服务器上 - -## 功能简介 -- 基于Spring Cloud的微服务和Spring Cloud Gateway和Zuul网关实现下述功能,它具有几个特性 - - 具有极大的灵活性 - 支持在任何环节(微服务和两个网关),多种方式(REST和RPC)做过滤控制和灰度发布 - - 具有极小的限制性 - 只要开启了服务注册发现,程序入口加了@EnableDiscoveryClient注解 - - 具有极强的健壮性 - 当远程配置中心全部挂了,可以通过Rest方式进行灰度发布;当远程规则配置不规范,马上切换到本地规则来代替 - - 具有极简的易用性 - 只需要引入相关的包同时规则里含有了对应的配置,该功能将自然启动 -- 实现服务注册层面的控制 - - 基于黑/白名单的IP地址过滤机制禁止对相应的微服务进行注册 - - 基于最大注册数的限制微服务注册。一旦微服务集群下注册的实例数目已经达到上限,将禁止后续的微服务进行注册 -- 实现服务发现层面的控制 - - 基于黑/白名单的IP地址过滤机制禁止对相应的微服务被发现 - - 基于版本号配对,通过对消费端和提供端可访问版本对应关系的配置,在服务发现和负载均衡层面,进行多版本访问控制 - - 基于版本权重配对,通过对消费端和提供端版本权重(流量)对应关系的配置,在服务发现和负载均衡层面,进行多版本流量调拨访问控制 - - 基于区域权重配对,通过对消费端和提供端所属区域的权重(流量)对应关系的配置,在服务发现和负载均衡层面,进行多区域流量调拨访问控制 -- 实现用户业务层面的控制 - - 使用者可以通过订阅业务参数的变化,实现特色化的灰度发布,例如,多数据源的数据库切换的灰度发布 -- 实现灰度发布 - - 通过版本的动态改变,实现切换灰度发布 - - 通过版本访问规则的改变,实现切换灰度发布 - - 通过版本权重规则的改变,实现平滑灰度发布 - - 通过区域权重规则的改变,实现平滑灰度发布 -- 实现通过XML或者Json进行上述规则的定义 -- 实现通过事件总线机制(EventBus)的功能,实现发布/订阅功能 - - 对接远程配置中心,集成Nacos和Redis,异步接受远程配置中心主动推送规则信息,动态改变微服务的规则 - - 结合Spring Boot Actuator,异步接受Rest主动推送规则信息,动态改变微服务的规则,支持同步和异步推送两种方式 - - 结合Spring Boot Actuator,动态改变微服务的版本,支持同步和异步推送两种方式 - - 在服务注册层面的控制中,一旦禁止注册的条件触发,主动推送异步事件,以便使用者订阅 -- 实现通过Listener机制进行扩展 - - 使用者可以对服务注册发现核心事件进行监听 -- 实现通过策略扩展,用户自定义和编程灰度路由策略 - - 使用者可以实现跟业务有关的路由策略,根据业务参数的不同,负载均衡到不同的服务器 - - 使用者可以根据内置的版本路由策略+区域路由策略+IP和端口路由策略+自定义策略,随心所欲的达到需要的路由功能 -- 实现支持Spring Boot Actuator和Swagger集成 -- 实现支持Spring Boot Admin的集成 -- 实现支持Sentinel熔断隔离限流降级的集成 -- 实现支持未来扩展更多的服务注册中心 -- 实现控制平台微服务,支持对规则和版本集中管理、推送、更改和删除 -- 实现基于控制平台微服务的图形化的灰度发布功能 - -## 名词解释 -- E版和F版,即Spring Cloud的Edgware和Finchley的首字母,以此类推 -- 切换灰度发布(也叫刚性灰度发布)和平滑灰度发布(也叫柔性灰度发布),切换灰度发布即在灰度发布的时候,没有过渡过程,流量直接从旧版本切换到新版本;平滑灰度发布即在灰度发布的时候,有个过渡过程,可以根据实际情况,先给新版本分配低额流量,给旧版本分配高额流量,对新版本进行监测,如果没有问题,就继续把旧版的流量切换到新版本上 -- IP地址,即根据微服务上报的它所在机器的IP地址。本系统内部强制以IP地址上报,禁止HostName上报,杜绝Spring Cloud应用在Docker或者Kubernetes部署时候出现问题 -- 规则定义和策略定义,规则定义即通过XML或者Json定义既有格式的规则;策略定义即专指用户自定义和编程灰度路由的策略,属于编程方式的一种扩展 -- 本地版本,即初始化读取本地配置文件获取的版本,也可以是第一次读取远程配置中心获取的版本。本地版本和初始版本是同一个概念 -- 动态版本,即灰度发布时的版本。动态版本和灰度版本是同一个概念 -- 本地规则,即初始化读取本地配置文件获取的规则,也可以是第一次读取远程配置中心获取的规则。本地规则和初始规则是同一个概念 -- 动态规则,即灰度发布时的规则。动态规则和灰度规则是同一个概念 -- 事件总线,即基于Google Guava的EventBus构建的组件。通过事件总线可以推送动态版本和动态规则的更新和删除 -- 远程配置中心,即可以存储规则配置XML格式的配置中心,可以包括不限于Nacos,Redis,Apollo,DisConf,Spring Cloud Config -- 配置(Config)和规则(Rule),在本系统中属于同一个概念,例如更新配置,即更新规则;例如远程配置中心存储的配置,即规则XML -- 服务端口和管理端口,即服务端口指在配置文件的server.port值,管理端口指management.port(E版)值或者management.server.port(F版或以上)值 - -## 架构工程 -### 架构 -服务治理架构图 - -![Alt text](https://github.com/Nepxion/Docs/raw/master/discovery-doc/Govern.jpg) - -全局架构图 - -![Alt text](https://github.com/Nepxion/Docs/raw/master/discovery-doc/Architecture.jpg) - -从上图,可以分析出两种基于网关的灰度发布方案,您可以研究更多的灰度发布策略 - -:triangular_flag_on_post:基于网关版本权重的灰度发布 -- 灰度发布前 - - 网关不需要配置版本 - - 网关->服务A(V1.0),网关配给服务A(V1.0)的100%权重(流量) -- 灰度发布中 - - 上线服务A(V1.1) - - 在网关层调拨10%权重(流量)给A(V1.1),给A(V1.0)的权重(流量)减少到90% - - 通过观测确认灰度有效,把A(V1.0)的权重(流量)全部切换到A(V1.1) -- 灰度发布后 - - 下线服务A(V1.0),灰度成功 - -:triangular_flag_on_post:基于网关版本切换的灰度发布 -- 灰度发布前 - - 假设当前生产环境,调用路径为网关(V1.0)->服务A(V1.0) - - 运维将发布新的生产环境,部署新服务集群,服务A(V1.1) - - 由于网关(1.0)并未指向服务A(V1.1),所以它们是不能被调用的 -- 灰度发布中 - - 新增用作灰度发布的网关(V1.1),指向服务A(V1.1) - - 灰度网关(V1.1)发布到服务注册发现中心,但禁止被服务发现,网关外的调用进来无法负载均衡到网关(V1.1)上 - - 在灰度网关(V1.1)->服务A(V1.1)这条调用路径做灰度测试 - - 灰度测试成功后,把网关(V1.0)指向服务A(V1.1) -- 灰度发布后 - - 下线服务A(V1.0),灰度成功 - - 灰度网关(V1.1)可以不用下线,留作下次版本上线再次灰度发布 - - 如果您对新服务比较自信,可以更简化,可以不用灰度网关和灰度测试,当服务A(V1.1)上线后,原有网关直接指向服务A(V1.1),然后下线服务A(V1.0) - -模块结构图 - -![Alt text](https://github.com/Nepxion/Docs/raw/master/discovery-doc/Module.jpg) - -### 工程 - -| 工程名 | 描述 | -| --- | --- | -| discovery-common | 通用模块 | -| discovery-common-apollo | 封装Apollo通用操作逻辑 | -| discovery-common-nacos | 封装Nacos通用操作逻辑 | -| discovery-common-redis | 封装Redis通用操作逻辑 | -| discovery-plugin-framework | 核心框架 | -| discovery-plugin-framework-eureka | 核心框架服务注册发现的Eureka实现 | -| discovery-plugin-framework-consul | 核心框架服务注册发现的Consul实现 | -| discovery-plugin-framework-zookeeper | 核心框架服务注册发现的Zookeeper实现 | -| discovery-plugin-framework-nacos | 核心框架服务注册发现的Nacos实现 | -| discovery-plugin-config-center | 配置中心实现 | -| discovery-plugin-config-center-starter-apollo | 配置中心的Apollo Starter | -| discovery-plugin-config-center-starter-nacos | 配置中心的Nacos Starter | -| discovery-plugin-config-center-starter-redis | 配置中心的Redis Starter | -| discovery-plugin-admin-center | 管理中心实现 | -| discovery-plugin-starter-eureka | Eureka Starter | -| discovery-plugin-starter-consul | Consul Starter | -| discovery-plugin-starter-zookeeper | Zookeeper Starter | -| discovery-plugin-starter-nacos | Nacos Starter | -| discovery-plugin-strategy | 用户自定义和编程灰度路由策略 | -| discovery-plugin-strategy-starter-service | 用户自定义和编程灰度路由策略的Service Starter | -| discovery-plugin-strategy-starter-zuul | 用户自定义和编程灰度路由策略的Zuul Starter | -| discovery-plugin-strategy-starter-gateway | 用户自定义和编程灰度路由策略的Spring Cloud Gateway Starter | -| discovery-plugin-strategy-starter-hystrix | 用户自定义和编程灰度路由策略下,Hystrix做线程模式的服务隔离必须引入的插件 Starter | -| discovery-console | 控制平台,集成接口给UI | -| discovery-console-starter-apollo | 控制平台的Apollo Starter | -| discovery-console-starter-nacos | 控制平台的Nacos Starter | -| discovery-console-starter-redis | 控制平台的Redis Starter | -| discovery-console-desktop | 图形化灰度发布等桌面程序 | -| discovery-springcloud-example-admin | Spring Boot Admin服务台示例 | -| discovery-springcloud-example-console | 控制平台示例 | -| discovery-springcloud-example-eureka | Eureka服务器示例 | -| discovery-springcloud-example-service | 用于灰度发布的微服务示例 | -| discovery-springcloud-example-zuul | 用于灰度发布的Zuul示例 | -| discovery-springcloud-example-gateway | 用于灰度发布的Spring Cloud Gateway示例 | - -## 依赖兼容 -### 依赖 -:exclamation:下面标注[必须引入]是一定要引入的包,标注[选择引入]是可以选择一个引入,或者不引入 - -核心插件引入,支持微服务端、网关Zuul端和网关Spring Cloud Gateway端,包括核心灰度发布功能,管理中心,配置中心等 -```xml -[必须引入] 四个服务注册发现的中间件的增强插件,请任选一个引入 - - com.nepxion - discovery-plugin-starter-eureka - discovery-plugin-starter-consul - discovery-plugin-starter-zookeeper - discovery-plugin-starter-nacos - ${discovery.version} - - -[选择引入] 三个远程配置中心的中间件的扩展插件,如需要,请任选一个引入,或者也可以引入您自己的扩展 - - com.nepxion - discovery-plugin-config-center-starter-apollo - discovery-plugin-config-center-starter-nacos - discovery-plugin-config-center-starter-redis - ${discovery.version} - -``` - -扩展功能引入,支持微服务端、网关Zuul端和网关Spring Cloud Gateway端,包括内置版本路由、区域路由、用户自定义和编程灰度路由 -```xml -微服务端引入 -[选择引入] 用户自定义和编程灰度路由,如需要,请引入 - - com.nepxion - discovery-plugin-strategy-starter-service - ${discovery.version} - - -网关Zuul端引入 -[选择引入] 用户自定义和编程灰度路由,如需要,请引入 - - com.nepxion - discovery-plugin-strategy-starter-zuul - ${discovery.version} - - -网关Spring Cloud Gateway端引入 -[选择引入] 用户自定义和编程灰度路由,如需要,请引入 - - com.nepxion - discovery-plugin-strategy-starter-gateway - ${discovery.version} - -``` - -[选择引入] 用户自定义和编程灰度路由时候,Hystrix做线程模式的服务隔离必须引入的插件,信号量模式不需要引入 -```xml - - com.nepxion - discovery-plugin-strategy-starter-hystrix - ${discovery.version} - -``` - -控制平台引入 -```xml -[选择引入] 三个远程配置中心的中间件的扩展插件,如需要,请任选一个引入,或者也可以引入您自己的扩展 - - com.nepxion - discovery-console-starter-apollo - discovery-console-starter-nacos - discovery-console-starter-redis - ${discovery.version} - -``` - -:warning:特别注意:中间件的引入一定要在所有层面保持一致,绝不允许出现类似如下情况,这也是常识 -- 例如,网关用Eureka做服务注册发现,微服务用Consul做服务注册发现 -- 例如,控制平台用Nacos做远程配置中心,微服务用Redis做远程配置中心 - -:star:如果只想要“用户自定义和编程灰度路由”功能,而不想要灰度发布功能 -- “用户自定义和编程灰度路由”是不需要接入远程配置中心的,所以建议去除远程配置中心包的引入 -```xml - - com.nepxion - discovery-plugin-config-center-starter-xxx - ${discovery.version} - -``` -- “用户自定义和编程灰度路由”是不会对服务注册发现等逻辑产生影响,所以建议下面两项配置改为false -```xml -# 开启和关闭服务注册层面的控制。一旦关闭,服务注册的黑/白名单过滤功能将失效,最大注册数的限制过滤功能将失效。缺失则默认为true -spring.application.register.control.enabled=false -# 开启和关闭服务发现层面的控制。一旦关闭,服务多版本调用的控制功能将失效,动态屏蔽指定IP地址的服务实例被发现的功能将失效。缺失则默认为true -spring.application.discovery.control.enabled=false -``` - -### 兼容 -版本兼容情况 -- Spring Cloud F版或以上,请采用4.x.x版本,具体代码参考master分支 -- Spring Cloud E版,请采用3.x.x版本,具体代码参考Edgware分支 -- 4.x.x版本和3.x.x版本功能完全一致,但在Endpoint的URL使用方式上稍微有个小的区别。例如 - - 3.x.x的Endpoint URL为[http://localhost:5100/config/view](http://localhost:5100/config/view) - - 4.x.x的Endpoint URL为[http://localhost:5100/actuator/config/config/view](http://localhost:5100/actuator/config/config/view),注意,路径中config为两个,前面那个是Endpoint Id,Spring Boot 2.x.x规定Endpoint Id必须指定,且全局唯一 - -中间件兼容情况 -- Consul - - Consul服务器版本不限制,推荐用最新版本,从[https://releases.hashicorp.com/consul/](https://releases.hashicorp.com/consul/)获取 -- Zookeeper - - Spring Cloud F版或以上,必须采用Zookeeper服务器的3.5.x服务器版本(或者更高),从[http://zookeeper.apache.org/releases.html#download](http://zookeeper.apache.org/releases.html#download)获取 - - Spring Cloud E版,Zookeeper服务器版本不限制 -- Eureka - - 跟Spring Cloud版本保持一致,自行搭建服务器 -- Apollo - - Apollo服务器版本,推荐用最新版本,从[https://github.com/ctripcorp/apollo/releases](https://github.com/ctripcorp/apollo/releases)获取 -- Nacos - - Nacos服务器版本,推荐用最新版本,从[https://github.com/alibaba/nacos/releases](https://github.com/alibaba/nacos/releases)获取 -- Redis - - Redis服务器版本,推荐用最新版本,从[https://redis.io/](https://redis.io/)获取 - -## 规则定义 -规则是基于XML或者Json为配置方式,存储于本地文件或者远程配置中心,可以通过远程配置中心修改的方式达到规则动态化。其核心代码参考discovery-plugin-framework以及它的扩展、discovery-plugin-config-center以及它的扩展和discovery-plugin-admin-center等 - -### 规则示例 -XML示例(Json示例见discovery-springcloud-example-service下的rule.json) - -:warning:特别注意:服务名大小写规则 -- 在配置文件(application.properties、application.yaml等)里,定义服务名(spring.application.name)不区分大小写 -- 在规则文件(XML、Json)里,引用的服务名必须小写 -- 在Nacos、Apollo、Redis等远程配置中心的Key,包含的服务名必须小写 - -```xml - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - {"discovery-springcloud-example-a":"1.0", "discovery-springcloud-example-b":"1.0", "discovery-springcloud-example-c":"1.0;1.2"} - - - {"discovery-springcloud-example-a":"qa;dev", "discovery-springcloud-example-b":"dev", "discovery-springcloud-example-c":"qa"} - - -
{"discovery-springcloud-example-a":"192.168.43.101:1100", "discovery-springcloud-example-b":"192.168.43.101:1201", "discovery-springcloud-example-c":"192.168.43.101:1300"}
- - - {"discovery-springcloud-example-a":"1.0=90;1.1=10", "discovery-springcloud-example-b":"1.0=90;1.1=10", "discovery-springcloud-example-c":"1.0=90;1.1=10"} - - - {"discovery-springcloud-example-a":"dev=85;qa=15", "discovery-springcloud-example-b":"dev=85;qa=15", "discovery-springcloud-example-c":"dev=85;qa=15"} - -
- - - - - - - - - - {"discovery-springcloud-example-a":"1.0", "discovery-springcloud-example-b":"1.0", "discovery-springcloud-example-c":"1.0;1.2"} - {"discovery-springcloud-example-a":"qa;dev", "discovery-springcloud-example-b":"dev", "discovery-springcloud-example-c":"qa"} - {"discovery-springcloud-example-a":"192.168.43.101:1100", "discovery-springcloud-example-b":"192.168.43.101:1201", "discovery-springcloud-example-c":"192.168.43.101:1300"} - {"discovery-springcloud-example-a":"1.0=90;1.1=10", "discovery-springcloud-example-b":"1.0=90;1.1=10", "discovery-springcloud-example-c":"1.0=90;1.1=10"} - {"discovery-springcloud-example-a":"dev=85;qa=15", "discovery-springcloud-example-b":"dev=85;qa=15", "discovery-springcloud-example-c":"dev=85;qa=15"} - - - - - - - - - - -
-``` - -### 黑/白名单的IP地址注册的过滤规则 -微服务启动的时候,禁止指定的IP地址注册到服务注册发现中心。支持黑/白名单,白名单表示只允许指定IP地址前缀注册,黑名单表示不允许指定IP地址前缀注册。规则如何使用,见示例说明 -- 全局过滤,指注册到服务注册发现中心的所有微服务,只有IP地址包含在全局过滤字段的前缀中,都允许注册(对于白名单而言),或者不允许注册(对于黑名单而言) -- 局部过滤,指专门针对某个微服务而言,那么真正的过滤条件是全局过滤+局部过滤结合在一起 - -### 最大注册数的限制的过滤规则 -微服务启动的时候,一旦微服务集群下注册的实例数目已经达到上限(可配置),将禁止后续的微服务进行注册。规则如何使用,见示例说明 -- 全局配置值,只下面配置所有的微服务集群,最多能注册多少个 -- 局部配置值,指专门针对某个微服务而言,那么该值如存在,全局配置值失效 - -### 黑/白名单的IP地址发现的过滤规则 -微服务启动的时候,禁止指定的IP地址被服务发现。它使用的方式和“黑/白名单的IP地址注册的过滤规则”一致 - -### 版本访问的灰度发布规则 -```xml -1. 标准配置,举例如下 - 表示消费端1.0版本,允许访问提供端1.0和1.1版本 -2. 版本值不配置,举例如下 - 表示消费端任何版本,允许访问提供端1.0和1.1版本 - 表示消费端1.0版本,允许访问提供端任何版本 - 表示消费端任何版本,允许访问提供端任何版本 -3. 版本值空字符串,举例如下 - 表示消费端任何版本,允许访问提供端1.0和1.1版本 - 表示消费端1.0版本,允许访问提供端任何版本 - 表示消费端任何版本,允许访问提供端任何版本 -4. 版本对应关系未定义,默认消费端任何版本,允许访问提供端任何版本 - -特殊情况处理,在使用上需要极力避免该情况发生 -1. 消费端的application.properties未定义版本号,则该消费端可以访问提供端任何版本 -2. 提供端的application.properties未定义版本号,当消费端在xml里不做任何版本配置,才可以访问该提供端 -``` - -### 版本权重的灰度发布规则 -```xml -1. 标准配置,举例如下 - 表示消费端访问提供端的时候,提供端的1.0版本提供90%的权重流量,1.1版本提供10%的权重流量 - 表示所有消费端访问提供端的时候,提供端的1.0版本提供90%的权重流量,1.1版本提供10%的权重流量 -2. 局部配置,即指定consumer-service-name,专门为该消费端配置权重。全局配置,即不指定consumer-service-name,为所有消费端配置相同情形的权重。当局部配置和全局配置同时存在的时候,以局部配置优先 -3. 尽量为线上所有版本都赋予权重值 -``` - -### 全局版本权重的灰度发布规则 -```xml -1. 标准配置,举例如下 - 表示版本为1.0的服务提供85%的权重流量,版本为1.1的服务提供15%的权重流量 -2. 全局版本权重可以切换整条调用链的权重配比 -3. 尽量为线上所有版本都赋予权重值 -``` - -### 区域权重的灰度发布规则 -```xml -1. 标准配置,举例如下 - 表示消费端访问提供端的时候,区域为dev的服务提供85%的权重流量,区域为qa的服务提供15%的权重流量 - 表示所有消费端访问提供端的时候,区域为dev的服务提供85%的权重流量,区域为qa的服务提供15%的权重流量 -2. 局部配置,即指定consumer-service-name,专门为该消费端配置权重。全局配置,即不指定consumer-service-name,为所有消费端配置相同情形的权重。当局部配置和全局配置同时存在的时候,以局部配置优先 -3. 尽量为线上所有版本都赋予权重值 -``` - -### 全局区域权重的灰度发布规则 -```xml -1. 标准配置,举例如下 - 表示区域为dev的服务提供85%的权重流量,区域为qa的服务提供15%的权重流量 -2. 全局区域权重可以切换整条调用链的权重配比 -3. 尽量为线上所有区域都赋予权重值 -``` - -### 网关端全链路路由策略的灰度发布规则 -```xml -1. 标准配置,举例如下 - - - {"discovery-springcloud-example-a":"1.0", "discovery-springcloud-example-b":"1.0", "discovery-springcloud-example-c":"1.0;1.2"} - - - {"discovery-springcloud-example-a":"qa;dev", "discovery-springcloud-example-b":"dev", "discovery-springcloud-example-c":"qa"} - - -
{"discovery-springcloud-example-a":"192.168.43.101:1100", "discovery-springcloud-example-b":"192.168.43.101:1201", "discovery-springcloud-example-c":"192.168.43.101:1300"}
- - - {"discovery-springcloud-example-a":"1.0=90;1.1=10", "discovery-springcloud-example-b":"1.0=90;1.1=10", "discovery-springcloud-example-c":"1.0=90;1.1=10"} - - - {"discovery-springcloud-example-a":"dev=85;qa=15", "discovery-springcloud-example-b":"dev=85;qa=15", "discovery-springcloud-example-c":"dev=85;qa=15"} - -
-2. 用法和基于Http Header头部传路由参数一致。前置是通过前端或者网关传入,后者是配置在配置文件里。让两者全部启用的时候,以前端或者网关传入Header方式优先 -``` -:triangular_flag_on_post:注意 +### 作者简介 +- Nepxion开源社区创始人 +- 2020年阿里巴巴中国云原生峰会出品人 +- 2020年被Nacos和Spring Cloud Alibaba纳入相关开源项目 +- 2021年阿里巴巴技术峰会上海站演讲嘉宾 +- 2021年荣获陆奇博士主持的奇绩资本,进行风险投资的关注和调研 +- 2021年入选Gitee最有价值开源项目 +- 2024年入围中国开源创新榜候选项目 +- 阿里巴巴官方书籍《Nacos架构与原理》作者之一 +- Spring Cloud Alibaba Steering Committer、Nacos Group Member +- Spring Cloud Alibaba、Nacos、Sentinel、OpenTracing Committer & Contributor -路由策略的入口有三个为例: -- 从外界传入(例如:Postman),在Header上加入。例如:n-d-version={"discovery-springcloud-example-a":"1.0", "discovery-springcloud-example-b":"1.0", "discovery-springcloud-example-c":"1.0;1.2"} -- 在网关Zuul或者Spring Cloud Gateway的Filter中指定Header -- 网关端全链路路由策略的灰度发布规则,在配置中心或者本地rule.xml配置 + -其作用的优先级 -- 在服务中,Header方式>配置中心或者本地rule.xml配置 -- 在网关中,通过如下配置,决定优先级 -```xml -# 当外界传值Header的时候,网关也设置并传递同名的Header,需要决定哪个Header传递到后边的服务去。如果下面开关为true,以网关设置为优先,否则以外界传值为优先。缺失则默认为true -spring.application.strategy.gateway.header.priority=false +### 商业合作 +① Discovery系列 -# 当外界传值Header的时候,网关也设置并传递同名的Header,需要决定哪个Header传递到后边的服务去。如果下面开关为true,以网关设置为优先,否则以外界传值为优先。缺失则默认为true -spring.application.strategy.zuul.header.priority=false -``` +| 框架名称 | 框架版本 | 支持Spring Cloud版本 | 使用许可 | +| --- | --- | --- | --- | +| Discovery | 1.x.x ~ 6.x.x | Camden ~ Hoxton | 开源,永久免费 | +| DiscoveryX | 7.x.x + | 2020 + | 闭源,商业许可 | -### 用户自定义的灰度发布规则 -通过订阅业务参数的变化,实现特色化的灰度发布,例如,多数据源的数据库切换的灰度发布 -```xml -1. 标准配置,举例如下 - -2. 上述示例,是基于多数据源的数据库切换的灰度发布 - 服务a有两个库的配置,分别是测试数据库(database的value为qa)和生产数据库(database的value为prod) - 上线后,一开始数据库指向测试数据库,对应value为qa,然后灰度发布的时候,改对应value为prod,即实现数据库的灰度发布 -``` +② Polaris系列 -### 动态改变规则 -微服务启动的时候,由于规则(例如:rule.xml)已经配置在本地,使用者希望改变一下规则,而不重启微服务,达到规则的改变 -- 规则分为本地规则和动态规则 -- 本地规则是通过在本地规则(例如:rule.xml)文件定义的,也可以从远程配置中心获取,在微服务启动的时候读取 -- 动态规则是通过POST方式动态设置,或者由远程配置中心推送设置 -- 规则初始化的时候,如果接入了远程配置中心,先读取远程规则,如果不存在,再读取本地规则文件 -- 多规则灰度获取规则的时候,先获取动态规则,如果不存在,再获取本地规则 -- 规则可以持久化到远程配置中心,一旦微服务死掉后,再次启动,仍旧可以拿到灰度规则,所以动态改变规则策略属于永久灰度发布手段 -- 规则推送到远程配置中心可以分为局部推送和全局推送 - - 局部推送是基于Group+ServiceId来推送的,就是同一个Group下同一个ServiceId的服务集群独立拥有一个规则配置,如果采用这种方式,需要在每个微服务集群下做一次灰度发布。优点是独立封闭,本服务集群灰度发布失败不会影响到其它服务集群,缺点是相对繁琐 - - 全局推送是基于Group来推送的(接口参数中的ServiceId由Group来代替),就是同一个Group下所有服务集群共同拥有一个规则配置,如果采用这种方式,只需要做一次灰度发布,所有服务集群都生效。优点是非常简便,缺点具有一定风险,因为这个规则配置掌握着所有服务集群的命运。全局推送用于全链路灰度发布 - - 如果既执行了全局推送,又执行了局部推送,那么,当服务运行中,优先接受最后一次推送的规则;当服务重新启动的时候,优先读取局部推送的规则 +Polaris为Discovery高级定制版,特色功能 -### 动态改变版本 -微服务启动的时候,由于版本已经写死在application.properties里,使用者希望改变一下版本,而不重启微服务,达到访问版本的路径改变 -- 版本分为本地版本和动态版本 -- 本地版本是通过在application.properties里配置的,在微服务启动的时候读取 -- 动态版本是通过POST方式动态设置 -- 多版本灰度获取版本值的时候,先获取动态版本,如果不存在,再获取本地版本 -- 版本不会持久化到远程配置中心,一旦微服务死掉后,再次启动,拿到的还是本地版本,所以动态改变版本策略属于临时灰度发布手段 +- 基于Nepxion Discovery集成定制 +- 多云、多活、多机房流量调配 +- 跨云动态域名、跨环境适配 +- DCN、DSU、SET单元化部署 +- 组件灵活装配、配置对外屏蔽 +- 极简低代码PaaS平台 -## 策略定义 -策略是通过REST或者RPC调用传递Header或者参数,达到用户自定义和编程灰度路由的目的。使用者可以实现跟业务有关的路由策略,根据业务参数的不同,负载均衡到不同的服务器,其核心代码参考discovery-plugin-strategy以及它的扩展 - -### 服务端的编程灰度路由策略 -基于服务端的编程灰度路由,实现DiscoveryEnabledStrategy,通过RequestContextHolder(获取来自网关的Header参数)和ServiceStrategyContext(获取来自RPC方式的方法参数)获取业务上下文参数,进行路由自定义,见[示例演示](https://github.com/Nepxion/Docs/raw/master/discovery-doc/README_EXAMPLE.md)的“用户自定义和编程灰度路由的操作演示” - -### Zuul端的编程灰度路由策略 -基于Zuul端的编程灰度路由,实现DiscoveryEnabledStrategy,通过Zuul自带的RequestContext(获取来自网关的Header参数)获取业务上下文参数,进行路由自定义,见[示例演示](https://github.com/Nepxion/Docs/raw/master/discovery-doc/README_EXAMPLE.md)的“用户自定义和编程灰度路由的操作演示” - -### Gateway端的编程灰度路由策略 -基于Spring Cloud Gateway端的编程灰度路由,实现DiscoveryEnabledStrategy,通过GatewayStrategyContext(获取来自网关的Header参数)获取业务上下文参数,进行路由自定义,见[示例演示](https://github.com/Nepxion/Docs/raw/master/discovery-doc/README_EXAMPLE.md)的“用户自定义和编程灰度路由的操作演示” - -### REST调用的内置多版本灰度路由策略 -基于Feign/RestTemplate的REST调用的多版本灰度路由,在Header上传入服务名和版本对应关系的Json字符串,如下表示,如果REST请求要经过a,b,c三个服务,那么只有a服务的1.0版本,b服务的1.1版本,c服务的1.1或1.2版本,允许被调用到 -Header的Key为"n-d-version",value为: -```xml -{"discovery-springcloud-example-a":"1.0", "discovery-springcloud-example-b":"1.1", "discovery-springcloud-example-c":"1.1;1.2"} -``` -见[示例演示](https://github.com/Nepxion/Docs/raw/master/discovery-doc/README_EXAMPLE.md)的“用户自定义和编程灰度路由的操作演示” - -如果,链路调用中所有的服务都是指定某个版本(例如1.1),那么value的格式可以简化,不需要Json字符串,直接是 -```xml -1.1 -``` - -如果上述表达式还未满足需求,也可以采用通配符(具体详细用法,参考Spring AntPathMatcher) -```xml -"discovery-springcloud-example-c":"1.*;1.2.?" - 表示c服务的版本调用范围是1开头的所有版本,或者是1.2开头的所有版本(末尾必须是1个字符) -``` -```xml -* - 表示调用范围为所有服务的所有版本 -1.* - 表示调用范围为所有服务的1开头的所有版本 -``` - -多版本灰度路由架构图 -![Alt text](https://github.com/Nepxion/Docs/raw/master/discovery-doc/RouteVersion.jpg) - -### REST调用的内置多区域灰度路由策略 -基于Feign/RestTemplate的REST调用的多区域灰度路由,在Header上传入服务名和版本对应关系的Json字符串,如下表示,如果REST请求要经过a,b,c三个服务,那么只有dev区域的a服务,qa区域的b服务,dev和qa区域c服务,允许被调用到 -Header的Key为"n-d-region",value为: -```xml -{"discovery-springcloud-example-a":"dev", "discovery-springcloud-example-b":"qa", "discovery-springcloud-example-c":"dev;qa"} -``` -见[示例演示](https://github.com/Nepxion/Docs/raw/master/discovery-doc/README_EXAMPLE.md)的“用户自定义和编程灰度路由的操作演示” - -如果,链路调用中所有的服务都是指定某个区域(例如dev),那么value的格式可以简化,不需要Json字符串,直接是 -```xml -dev -``` - -如果上述表达式还未满足需求,也可以采用通配符(具体详细用法,参考Spring AntPathMatcher) -```xml -"discovery-springcloud-example-c":"d*;q?" - 表示c服务的区域调用范围是d开头的所有区域,或者是q开头的所有区域(末尾必须是1个字符) -``` -```xml -* - 表示调用范围为所有服务的所有区域 -d* - 表示调用范围为所有服务的d开头的所有区域 -``` - -多区域灰度路由架构图 -![Alt text](https://github.com/Nepxion/Docs/raw/master/discovery-doc/RouteRegion.jpg) - -:warning:特别注意:Spring Cloud内置zone的策略,功能跟region策略很相似,但zone策略不能跟用户自定义路由组合使用,故提供了更友好的region策略 - -### REST调用的内置多IP和端口灰度路由策略 -基于Feign/RestTemplate的REST调用的多版本灰度路由,在Header上传入服务名和版本对应关系的Json字符串,如下表示,如果REST请求要经过a,b,c三个服务,那么只需要指定三个服务所给定的IP(或者IP和端口组合),允许被调用到 -Header的Key为"n-d-address",value为: -```xml -{"discovery-springcloud-example-a":"192.168.43.101:1101", "discovery-springcloud-example-b":"192.168.43.101:1201", "discovery-springcloud-example-c":"192.168.43.101:1302"} -``` -见[示例演示](https://github.com/Nepxion/Docs/raw/master/discovery-doc/README_EXAMPLE.md)的“用户自定义和编程灰度路由的操作演示” - -如果上述表达式还未满足需求,也可以采用通配符(具体详细用法,参考Spring AntPathMatcher) -```xml -"discovery-springcloud-example-c":"192.168.43.*;192.168.44.10?" - 表示c服务的地址调用范围是192.168.43开头的所有IP,或者是192.168.44.10开头的所有IP(末尾必须是1个字符) -``` -```xml -* - 表示调用范围为所有服务的所有IP -192.168.43* - 表示调用范围为所有服务的192.168.43开头的所有IP -``` - -多IP和端口灰度路由架构图 -![Alt text](https://github.com/Nepxion/Docs/raw/master/discovery-doc/RouteAddress.jpg) - -### REST调用的内置版本权重灰度路由策略 -基于Feign/RestTemplate的REST调用的多版本权重灰度路由,在Header上传入服务名和版本流量百分比对应关系的Json字符串,如下表示,如果REST请求要经过a,b,c三个服务的版本权重配比,那么只需要它们版本对于流量的百分比 -Header的Key为"n-d-version-weight",value为: -```xml -{"discovery-springcloud-example-a":"1.0=90;1.1=10", "discovery-springcloud-example-b":"1.0=90;1.1=10", "discovery-springcloud-example-c":"1.0=90;1.1=10"} -``` -如果三个服务权重比一致,那么value的格式可以简化,不需要Json字符串,直接是 -```xml -1.0=90;1.1=10 -``` -见[示例演示](https://github.com/Nepxion/Docs/raw/master/discovery-doc/README_EXAMPLE.md)的“用户自定义和编程灰度路由的操作演示” - -### REST调用的内置区域权重灰度路由策略 -基于Feign/RestTemplate的REST调用的多区域灰度路由,在Header上传入区域流量百分比对应关系的字符串,如下表示,如果REST请求要经过两个区域,那么只需要它们区域对于流量的百分比 -Header的Key为"n-d-region-weight",value为: -```xml -{"discovery-springcloud-example-a":"dev=85;qa=15", "discovery-springcloud-example-b":"dev=85;qa=15", "discovery-springcloud-example-c":"dev=85;qa=15"} -``` -如果三个服务权重比一致,那么value的格式可以简化,不需要Json字符串,直接是 -```xml -dev=85;qa=15 -``` -见[示例演示](https://github.com/Nepxion/Docs/raw/master/discovery-doc/README_EXAMPLE.md)的“用户自定义和编程灰度路由的操作演示” - -### REST调用的编程灰度路由策略 -基于Feign/RestTemplate的REST调用的自定义路由,见[示例演示](https://github.com/Nepxion/Docs/raw/master/discovery-doc/README_EXAMPLE.md)的“用户自定义和编程灰度路由的操作演示” - -### RPC调用的编程灰度路由策略 -基于Feign/RestTemplate的RPC调用的自定义路由,见[示例演示](https://github.com/Nepxion/Docs/raw/master/discovery-doc/README_EXAMPLE.md)的“用户自定义和编程灰度路由的操作演示” - -## 规则和策略 -### 规则和策略的区别 -| 属性 | 规则 | 策略 | -| --- | --- | --- | -| 方式 | 通过XML或者Json配置 | 通过REST或者RPC调用传递Header或者参数 | -| 频率 | 灰度发布期间更新,频率低 | 每次调用时候传递,频率高 | -| 扩展性 | 内置,有限扩展,继承三个AbstractXXXListener | 内置,完全扩展,实现DiscoveryEnabledStrategy | -| 作用域 | 运行前,运行期 | 运行期 | -| 依赖性 | 依赖配置中心或者本地配置文件 | 依赖每次调用 | - -### 规则和策略的关系 -- 规则和策略,可以混合在一起工作,也关闭一项,让另一项单独工作 -- 规则和策略,一起工作的时候,先执行规则过滤逻辑,再执行策略过滤逻辑 -- 规则和策略关闭 - - 规则关闭,spring.application.register.control.enabled=false和spring.application.discovery.control.enabled=false - - 策略关闭,spring.application.strategy.control.enabled=false - -## 服务隔离 - -### 内置服务隔离 -元数据中的Group在一定意义上代表着系统ID或者系统逻辑分组,基于Group策略意味着只有同一个系统中的服务才能相互发生关系 - -- 注册服务隔离,基于Group黑/白名单的策略,即当前的服务所在的Group,不在Group的黑名单或者在白名单里,才允许被注册。只需要在网关或者服务端,开启如下配置即可: -```xml -# 启动和关闭注册的服务隔离(基于Group黑/白名单的策略)。缺失则默认为false -spring.application.strategy.register.isolation.enabled=true -``` -默认方式,黑/白名单通过如此方式配置 -```xml -spring.application.strategy.register.isolation.group.blacklist= -spring.application.strategy.register.isolation.group.whitelist= -``` - -- 消费端服务隔离,基于Group是否相同的策略,即消费端拿到的提供端列表,两者的Group必须相同。只需要在网关或者服务端,开启如下配置即可: -```xml -# 启动和关闭消费端的服务隔离(基于Group是否相同的策略)。缺失则默认为false -# spring.application.strategy.consumer.isolation.enabled=true -``` - -- 提供端服务隔离,基于Group是否相同的策略,即服务端被消费端调用,两者的Group必须相同,否则拒绝调用,异构系统可以通过Header方式传递n-d-service-group值进行匹配。只需要在网关或者服务端,开启如下配置即可: -```xml -# 启动和关闭提供端的服务隔离(基于Group是否相同的策略)。缺失则默认为false -# spring.application.strategy.provider.isolation.enabled=true -``` -还必须做如下配置 -```xml -# 用户自定义和编程灰度路由策略的时候,需要指定对业务RestController类的扫描路径。此项配置作用于RPC方式的调用拦截和消费端的服务隔离两项工作 -spring.application.strategy.scan.packages=com.nepxion.discovery.gray.service.feign -``` - -### 自定义服务隔离 -使用者可以继承如下类 -- AbstractRegisterListener,实现自定义”禁止注册“,用法参考discovery-springcloud-example-service下MyRegisterListener -- AbstractDiscoveryListener,实现自定义”禁止被发现“,用法参考discovery-springcloud-example-service下MyDiscoveryListener。注意,在Consul下,同时会触发service和management两个实例的事件,需要区别判断,见上图“集成了健康检查的Consul界面” -- AbstractLoadBalanceListener,实现自定义”禁止被负载均衡“,用法参考discovery-springcloud-example-service下MyLoadBalanceListener - -## 配置文件 -### 基础属性配置 -不同的服务注册发现组件对应的不同的配置值(region配置可选),请仔细阅读 -```xml -# Eureka config for discovery -eureka.instance.metadataMap.group=xxx-service-group -eureka.instance.metadataMap.version=1.0 -eureka.instance.metadataMap.region=dev - -# 奇葩的Consul配置(参考https://springcloud.cc/spring-cloud-consul.html - 元数据和Consul标签) -# Consul config for discovery -spring.cloud.consul.discovery.tags=group=xxx-service-group,version=1.0,region=dev - -# Zookeeper config for discovery -spring.cloud.zookeeper.discovery.metadata.group=xxx-service-group -spring.cloud.zookeeper.discovery.metadata.version=1.0 -spring.cloud.zookeeper.discovery.metadata.region=dev - -# Nacos config for discovery -spring.cloud.nacos.discovery.metadata.group=example-service-group -spring.cloud.nacos.discovery.metadata.version=1.0 -spring.cloud.nacos.discovery.metadata.region=dev - -# Admin config -# E版配置方式 -# 关闭访问Rest接口时候的权限验证 -management.security.enabled=false -management.port=5100 - -# F版或以上配置方式 -management.server.port=5100 -``` - -### 功能开关配置 -请注意,如下很多配置项,如果使用者不想做特色化的处理,为避免繁琐,可以零配置(除了最底下,但一般也不会被用到) -```xml -# Plugin core config -# 开启和关闭服务注册层面的控制。一旦关闭,服务注册的黑/白名单过滤功能将失效,最大注册数的限制过滤功能将失效。缺失则默认为true -# spring.application.register.control.enabled=true -# 开启和关闭服务发现层面的控制。一旦关闭,服务多版本调用的控制功能将失效,动态屏蔽指定IP地址的服务实例被发现的功能将失效。缺失则默认为true -# spring.application.discovery.control.enabled=true -# 开启和关闭通过Rest方式对规则配置的控制和推送。一旦关闭,只能通过远程配置中心来控制和推送。缺失则默认为true -# spring.application.config.rest.control.enabled=true -# 规则文件的格式,支持xml和json。缺失则默认为xml -# spring.application.config.format=xml -# spring.application.config.format=json -# 本地规则文件的路径,支持两种方式:classpath:rule.xml(rule.json) - 规则文件放在resources目录下,便于打包进jar;file:rule.xml(rule.json) - 规则文件放在工程根目录下,放置在外部便于修改。缺失则默认为不装载本地规则 -# spring.application.config.path=classpath:rule.xml -# spring.application.config.path=classpath:rule.json -# 为微服务归类的Key,一般通过group字段来归类,例如eureka.instance.metadataMap.group=xxx-group或者eureka.instance.metadataMap.application=xxx-application。缺失则默认为group -# spring.application.group.key=group -# spring.application.group.key=application -# 由于服务未注册,或者被过滤,或者被隔离,导致消费端拿不到服务实例的时候,通过日志方式通知。缺失则默认为false -# spring.application.no.server.found.notification.enabled=false - -# Plugin strategy config -# 开启和关闭策略扩展功能的控制。一旦关闭,用户自定义和编程灰度路由策略功能将失效。缺失则默认为true -# spring.application.strategy.control.enabled=true -# 开启和关闭Ribbon默认的ZoneAvoidanceRule负载均衡策略。一旦关闭,则使用RoundRobin简单轮询负载均衡策略。缺失则默认为true -# spring.application.strategy.zone.avoidance.rule.enabled=true -# 启动和关闭用户自定义和编程灰度路由策略的时候,对REST方式的调用拦截。缺失则默认为true -# spring.application.strategy.rest.intercept.enabled=true -# 用户自定义和编程灰度路由策略的时候,对REST方式调用拦截的时候(支持Feign或者RestTemplate调用),希望把来自外部自定义的Header参数传递到服务里,那么配置如下值。如果多个用“;”分隔,不允许出现空格 -spring.application.strategy.request.headers=token -# 启动和关闭用户自定义和编程灰度路由策略的时候,对RPC方式的调用拦截。缺失则默认为false -spring.application.strategy.rpc.intercept.enabled=true -# 用户自定义和编程灰度路由策略的时候,需要指定对业务RestController类的扫描路径。此项配置作用于RPC方式的调用拦截和消费端的服务隔离两项功能 -spring.application.strategy.scan.packages=com.nepxion.discovery.plugin.example.service.feign -# 启动和关闭注册的服务隔离(基于Group黑/白名单的策略)。缺失则默认为false -spring.application.strategy.register.isolation.enabled=true -# 启动和关闭消费端的服务隔离(基于Group是否相同的策略)。缺失则默认为false -spring.application.strategy.consumer.isolation.enabled=true -# 启动和关闭提供端的服务隔离(基于Group是否相同的策略)。缺失则默认为false -spring.application.strategy.provider.isolation.enabled=true -# 启动和关闭Header传递的日志打印,注意每调用一次都会打印一次,会对性能有所影响,建议压测环境和生产环境关闭。缺失则默认为false -spring.application.strategy.intercept.log.print=true -# 开启服务端实现Hystrix线程隔离模式做服务隔离时,必须把spring.application.strategy.hystrix.threadlocal.supported设置为true,同时要引入discovery-plugin-strategy-starter-hystrix包,否则线程切换时会发生ThreadLocal上下文对象丢失 -# spring.application.strategy.hystrix.threadlocal.supported=true -``` - -### 外部元数据配置 -外部系统(例如运维发布平台)在远程启动制定微服务的时候,可以通过参数传递来动态改变元数据或者增加运维特色的参数,最后注册到远程配置中心。有两种方式,如下图: -![Alt text](https://github.com/Nepxion/Docs/raw/master/discovery-doc/Metadata.jpg) -- 通过Program arguments来传递,它的用法是前面加“--”。支持Eureka、Zookeeper和Nacos(增量覆盖),Consul支持的不好(全量覆盖) -- 通过VM arguments来传递,它的用法是前面加“-D”。支持上述所有的注册组件,它的限制是变量前面必须要加“ext.” -- 两种方式尽量避免同时用 - -## 配置中心 -- 默认集成 - - 本系统跟Apollo集成,如何安装使用,请参考[https://github.com/ctripcorp/apollo](https://github.com/ctripcorp/apollo) - - 本系统跟Nacos集成,如何安装使用,请参考[https://github.com/alibaba/nacos](https://github.com/alibaba/nacos) - - 本系统跟Redis集成 -- 扩展集成 - - 使用者也可以跟更多远程配置中心集成 - - 参考三个跟Nacos或者Redis有关的工程 - -## 管理中心 -:exclamation:PORT端口号为服务端口或者管理端口都可以 -- 配置接口 -- 版本接口 -- 路由接口 -参考Swagger界面,如下图 - -![Alt text](https://github.com/Nepxion/Docs/raw/master/discovery-doc/Swagger1.jpg) - -## 控制平台 -为UI提供相关接口,包括 -- 一系列批量功能 -- 跟Nacos、Apollo和Redis集成,实现配置拉取、推送和清除 - -:exclamation:PORT端口号为服务端口或者管理端口都可以 -- 控制平台接口 -参考Swagger界面,如下图 - -![Alt text](https://github.com/Nepxion/Docs/raw/master/discovery-doc/Swagger2.jpg) - -## 监控平台 -基于Spring Boot Actuator技术的Spring Boot Admin监控平台 - -参考[https://github.com/codecentric/spring-boot-admin](https://github.com/codecentric/spring-boot-admin) - -## 熔断隔离限流降级平台 -基于Alibaba Sentinel的熔断隔离限流降级平台 - -参考[https://github.com/alibaba/Sentinel](https://github.com/alibaba/Sentinel) - -## 界面工具 -请参考[入门教程](https://github.com/Nepxion/Docs/raw/master/discovery-doc/README_QUICK_START.md)的“界面操作” - -### 基于图形化桌面程序的灰度发布 -- 见[入门教程](https://github.com/Nepxion/Docs/raw/master/discovery-doc/README_QUICK_START.md)的“运行图形化灰度发布桌面程序” - -### 基于图形化Web程序的灰度发布 -- 见[入门教程](https://github.com/Nepxion/Docs/raw/master/discovery-doc/README_QUICK_START.md)的“运行图形化灰度发布Web程序” - -### 基于Apollo界面的灰度发布 -- 见[入门教程](https://github.com/Nepxion/Docs/raw/master/discovery-doc/README_QUICK_START.md)的“运行Apollo配置界面” - -### 基于Nacos界面的灰度发布 -- 见[入门教程](https://github.com/Nepxion/Docs/raw/master/discovery-doc/README_QUICK_START.md)的“运行Nacos配置界面” - -### 基于Rest方式的灰度发布 -- 见[入门教程](https://github.com/Nepxion/Docs/raw/master/discovery-doc/README_QUICK_START.md)的“运行Swagger或者Postman方式” - -## 性能分析 -在我的电脑上,做了如下性能测试: - -应用耗时 - -| 应用 | 耗时 | 内存 | -| --- | --- | --- | -| 空的Spring Cloud启动 | 9秒 | 400M | -| 带有Discovery Plugin的Spring Cloud启动 | 13秒 | 480M | - -启动项耗时 - -| 启动项 | 耗时 | +| 框架名称 | 框架版本 | 支持Discovery版本 | 支持Spring Cloud版本 | 使用许可 | +| --- | --- | --- | --- | --- | +| Polaris | 1.x.x | 6.x.x | Finchley ~ Hoxton | 闭源,商业许可 | +| Polaris | 2.x.x | 7.x.x + | 2020 + | 闭源,商业许可 | + +有商业版需求的企业和用户,请添加微信1394997,联系作者,洽谈合作事宜 + +### 入门资料 +![](https://nepxion.github.io/Discovery/docs/discovery-doc/Logo64.png) Discovery【探索】企业级云原生微服务开源解决方案 + +① 快速入门 +- [快速入门Github版](https://github.com/Nepxion/Discovery/wiki) +- [快速入门Gitee版](https://gitee.com/Nepxion/Discovery/wikis/pages) + +② 解决方案 +- [解决方案WIKI版](http://nepxion.com/discovery) +- [解决方案PPT版](https://nepxion.github.io/Discovery/docs/link-doc/discovery-ppt.html) + +③ 最佳实践 +- [最佳实践PPT版](https://nepxion.github.io/Discovery/docs/link-doc/discovery-ppt-1.html) + +④ 平台桌面 +- [平台界面WIKI版](http://nepxion.com/discovery-platform) +- [图形桌面WIKI版](http://nepxion.com/discovery-desktop) + +⑤ 框架源码 +- [框架源码Github版](https://github.com/Nepxion/Discovery) +- [框架源码Gitee版](https://gitee.com/Nepxion/Discovery) + +⑥ 指南示例源码 +- [指南示例源码Github版](https://github.com/Nepxion/DiscoveryGuide) +- [指南示例源码Gitee版](https://gitee.com/Nepxion/DiscoveryGuide) + +⑦ 指南示例说明 +- Spring Cloud Finchley ~ Hoxton版本 + - [极简版指南示例](https://github.com/Nepxion/DiscoveryGuide/tree/6.x.x-simple),分支为6.x.x-simple + - [极简版域网关部署指南示例](https://github.com/Nepxion/DiscoveryGuide/tree/6.x.x-simple-domain-gateway),分支为6.x.x-simple-domain-gateway + - [极简版非域网关部署指南示例](https://github.com/Nepxion/DiscoveryGuide/tree/6.x.x-simple-non-domain-gateway),分支为6.x.x-simple-non-domain-gateway + - [集成版指南示例](https://github.com/Nepxion/DiscoveryGuide/tree/6.x.x),分支为6.x.x + - [高级版指南示例](https://github.com/Nepxion/DiscoveryGuide/tree/6.x.x-complex),分支为6.x.x-complex +- Spring Cloud 20xx版本 + - [极简版指南示例](https://github.com/Nepxion/DiscoveryGuide/tree/master-simple),分支为master-simple + - [极简版本地化指南示例](https://github.com/Nepxion/DiscoveryGuide/tree/master-simple-native),分支为master-simple-native + - [集成版指南示例](https://github.com/Nepxion/DiscoveryGuide/tree/master),分支为master + +![](https://nepxion.github.io/Discovery/docs/polaris-doc/Logo64.png) Polaris【北极星】企业级云原生微服务商业解决方案 + +① 解决方案 +- [解决方案WIKI版](http://nepxion.com/polaris) + +② 框架源码 +- [框架源码Github版](https://github.com/polaris-paas/polaris-sdk) +- [框架源码Gitee版](https://gitee.com/polaris-paas/polaris-sdk) + +③ 指南示例源码 +- [指南示例源码Github版](https://github.com/polaris-paas/polaris-guide) +- [指南示例源码Gitee版](https://gitee.com/polaris-paas/polaris-guide) + +④ 指南示例说明 +- Spring Cloud Finchley ~ Hoxton版本 + - [指南示例](https://github.com/polaris-paas/polaris-guide/tree/1.x.x),分支为1.x.x +- Spring Cloud 20xx版本 + - [指南示例](https://github.com/polaris-paas/polaris-guide/tree/master),分支为master + +### 功能概述 +Discovery【探索】微服务框架,基于Spring Cloud & Spring Cloud Alibaba,Discovery服务注册发现、Ribbon & Spring Cloud LoadBalancer负载均衡、Feign & RestTemplate & WebClient调用、Spring Cloud Gateway & Zuul过滤等组件全方位增强的企业级微服务开源解决方案,更贴近企业级需求,更具有企业级的插件引入、开箱即用特征 + +① 微服务框架支持的技术栈,如下 +- 支持阿里巴巴Spring Cloud Alibaba中间件生态圈 +- 支持阿里巴巴Nacos、Eureka、Consul和Zookeeper四个服务注册发现中心 +- 支持阿里巴巴Nacos、携程Apollo、Redis、Zookeeper、Consul和Etcd六个远程配置中心 +- 支持阿里巴巴Sentinel、Hystrix和Resilience4J三个熔断限流降级权限中间件 +- 支持OpenTracing和OpenTelemetry规范下的调用链中间件,Jaeger、SkyWalking和Zipkin等 +- 支持Prometheus Micrometer和Spring Boot Admin两个指标中间件 +- 支持Java Agent解决异步跨线程ThreadLocal上下文传递 +- 支持Spring Spel解决蓝绿灰度参数的驱动逻辑 +- 支持Spring Matcher解决元数据匹配的通配逻辑 +- 支持Spring Cloud Gateway、Zuul网关和微服务三大模块的蓝绿灰度发布等一系列功能 +- 支持和兼容Spring Cloud Edgware版、Finchley版、Greenwich版、Hoxton版和20xx版以及更高的Spring Cloud版本 +- 支持和兼容Java8~Java17以及更高的SDK版本 + +![](https://nepxion.github.io/Discovery/docs/discovery-doc/Diagram.jpg) + +② Discovery【探索】微服务框架支持的应用功能,如下 +- 全链路蓝绿灰度发布 + - 全链路版本、区域、 IP地址和端口匹配蓝绿发布 + - 全链路版本、区域、 IP地址和端口权重灰度发布 + - 全链路蓝 | 绿 | 兜底、蓝 | 兜底的蓝绿路由类型 + - 全链路稳定、灰度的灰度路由类型 + - 全链路网关、服务端到端混合蓝绿灰度发布 + - 全链路单网关、域网关、非域网关部署 + - 全链路条件驱动、非条件驱动 + - 全链路前端触发后端蓝绿灰度发布 + - 全局订阅式蓝绿灰度发布 + - 全链路自定义网关、服务的过滤器、负载均衡策略类触发蓝绿灰度发布 + - 全链路Header、Parameter、Cookie、域名、RPC Method等参数化规则策略驱动 + - 全链路本地和远程、局部和全局无参数化规则策略驱动 + - 全链路条件表达式、通配表达式支持 + - 全链路内置Header,支持定时Job的服务调用蓝绿灰度发布 + - 全链路手工编排、智能编排、无编排蓝绿灰度发布 +- 全链路自动化测试 + - 全链路自动化模拟流程测试 + - 全链路自动化模拟流程本地测试 + - 全链路自动化模拟流程云上测试 + - 全链路自动化流量侦测测试 + - 全链路自动化流量侦测本地测试 + - 全链路自动化流量侦测云上测试 +- 全链路流量管控对接DevOps运维平台 +- 全链路多活单元化 +- 全链路隔离路由 + - 全链路组隔离路由 + - 组负载均衡的消费端隔离 + - 组Header传值的提供端隔离 + - 全链路版本偏好路由 + - 全链路区域调试路由 + - 全链路环境隔离路由 + - 全链路可用区亲和性隔离路由 + - 全链路IP地址和端口隔离路由 +- 全链路隔离准入 + - 基于IP地址黑白名单注册准入 + - 基于最大注册数限制注册准入 + - 基于IP地址黑白名单发现准入 + - 自定义注册发现准入 +- 全链路故障转移 + - 全链路版本故障转移 + - 全链路区域故障转移 + - 全链路环境故障转移 + - 全链路可用区故障转移 + - 全链路IP地址和端口故障转移 +- 全链路服务无损下线,实时性的流量绝对无损 + - 全局唯一ID屏蔽 + - IP地址和端口屏蔽 +- 异步场景下全链路蓝绿灰度发布 + - 异步跨线程Agent插件 + - Hystrix线程池隔离插件 +- 网关动态路由 + - 路由动态添加 + - 路由动态修改 + - 路由动态删除 + - 路由动态批量更新 + - 路由查询 + - 路由动态变更后的事件通知 +- 全链路服务限流熔断降级权限 + - Sentinel基于服务名的防护 + - Sentinel基于组的防护 + - Sentinel基于版本的防护 + - Sentinel基于区域的防护 + - Sentinel基于环境的防护 + - Sentinel基于可用区的防护 + - Sentinel基于IP地址和端口的防护 + - Sentinel自定义Header、Parameter、Cookie的防护 + - Sentinel自定义业务参数的防护 + - Sentinel自定义组合式的防护 +- 全链路监控 + - 蓝绿灰度埋点和熔断埋点的调用链监控 + - 蓝绿灰度埋点和熔断埋点的日志监控 + - 熔断埋点的指标监控 +- 全链路蓝绿灰度发布编排建模和流量侦测 + - 全链路蓝绿发布编排建模 + - 全链路灰度发布编排建模 + - 全链路蓝绿发布流量侦测 + - 全链路灰度发布流量侦测 + - 全链路蓝绿灰度发布混合流量侦测 +- 全链路数据库和消息队列蓝绿发布 + - 基于多DataSource的数据库蓝绿发布 + - 基于多Queue的消息队列蓝绿发布 +- 全链路服务侧注解 +- 元数据流量染色 + - 基于Git插件的元数据流量染色 + - 基于服务名前缀的元数据流量染色 + - 基于启动参数的元数据流量染色 + - 基于配置文件的元数据流量染色 + - 基于系统参数的元数据流量染色 + - 基于POM版本号的元数据流量染色 +- 扫描目录 + - 自动扫描目录 + - 手工扫描目录 + - 注入扫描目录 +- 规则策略推送 + - 基于配置中心的规则策略订阅推送 + - 基于Swagger和Rest的规则策略推送 + - 基于平台端和桌面端的规则策略推送 +- 统一配置订阅执行器 + +![](https://nepxion.github.io/Discovery/docs/discovery-doc/Ability.jpg) + +③ Discovery【探索】微服务框架支持的功能维度,如下 + +微服务框架支持组(Group)、版本(Version)、区域(Region)、环境(Env)、可用区(Zone)、IP地址和端口(Address)、全局唯一ID七大经典维度实施流量管控的方式,通过“并集”方式叠加作用在流量控制上。上述七个维度在功能上各有各的侧重点,如下表格主要讲述各自的区别 + +| 维度 | 概念 | 场景 | 功能侧重点 | 关键头 +| --- | --- | --- | --- | --- | +| 组 | 服务实例的系统ID
系统逻辑分组 | 路由隔离 | ① 组负载均衡隔离
- 调用端和提供端的元数据group是否相同
② 组Header传值策略隔离
- Header(n-d-group)和提供端的元数据group是否相同
③ 不支持故障转移 | n-d-group | +| 版本 | 服务实例的版本
适用于生产环境 | 蓝绿灰度发布
路由转移
故障转移 | ① 版本条件匹配蓝绿发布
② 版本权重灰度发布
③ 版本偏好
- 非蓝绿灰度发布场景下,路由到相应版本的实例
- 稳定版本策略、指定版本策略
④ 版本故障转移
- 未找到相应版本的服务实例,路由到其它版本
- 负载均衡策略、稳定版本策略、指定版本策略 | n-d-version
n-d-version-weight
n-d-version-prefer
n-d-version-failover | +| 区域 | 服务实例的区域
适用于多活单元化
适用于多机房
适用于多环境 | 蓝绿灰度发布
同城双活/异地多活
路由转移
故障转移 | ① 区域条件匹配蓝绿发布
② 区域权重灰度发布
③ 区域多活单元化
④ 区域调试路由
- 多区域路由隔离下跨区服务调用的调试手段
⑤ 区域故障转移
- 未找到相应区域的服务实例,路由到其它区域
- 负载均衡策略、指定区域策略 | n-d-region
n-d-region-weight
n-d-region-transfer
n-d-region-failover | +| 环境 | 服务实例的环境
适用于测试环境 | 路由隔离
故障转移 | ① 环境隔离路由
- Header(n-d-env)和提供端的元数据env是否相同
② 环境故障转移
- 未找到相应环境的服务实例,路由到其它环境
- 指定环境(未配置,默认为common)策略 | n-d-env
n-d-env-failover | +| 可用区 | 服务实例的可用区
适用于多机房 | 路由隔离
故障转移 | ① 可用区亲和性隔离路由
- 调用端和提供端的元数据zone是否相同
② 可用区故障转移
- 未找到相应可用区的服务实例,路由到其它可用区
- 支持负载均衡策略、指定区可用区策略 | n-d-zone-failover | +| IP地址和端口 |服务实例机器地址 | 蓝绿灰度发布
路由隔离
故障转移
无损下线 | ① IP地址和端口匹配蓝绿发布
② IP地址和端口权重灰度发布
③ IP地址和端口故障转移
- 未找到相应IP地址和端口的服务实例,路由到其它地址
- 负载均衡策略、指定区IP地址和端口策略
④ IP地址和端口无损下线黑名单屏蔽 | n-d-address
n-d-address-failover
n-d-address-blacklist | +| 全局唯一ID | 服务实例机器ID | 无损下线 | ① 全局唯一ID无损下线黑名单屏蔽 | n-d-id-blacklist | + +![](https://nepxion.github.io/Discovery/docs/discovery-doc/Filter.jpg) + +### 发展历程 +- 2017年12月开始筹划 +- 2018年03月开始编码 +- 2018年06月在GitHub开源 +- 2018年06月发布v1.0.0,支持Camden版 +- 2018年06月发布v2.0.0,支持Dalston版 +- 2018年07月发布v3.0.0,支持Edgware版 +- 2018年07月发布v4.0.0,支持Finchley版 +- 2019年04月发布v5.0.0,支持Greenwich版 +- 2020年04月发布v6.0.0,支持Hoxton版 +- 2021年04月完成v7.0.0,支持2020版 +- 2022年04月完成v8.0.0,支持2021版 +- 2023年01月完成v9.0.0,支持2022版 +- 2024年03月完成v10.0.0,支持2023版 + +### 版本列表 +① 微服务框架版本兼容列表,如下 + +![](https://nepxion.github.io/Discovery/docs/icon-doc/tip.png) 提醒:版本号右边, `↑` 表示>=该版本号, `↓` 表示<=该版本号 + +| 框架版本 | 框架分支 | 框架状态 | Spring Cloud版本 | Spring Boot版本 | Spring Cloud Alibaba版本 | +| --- | --- | --- | --- | --- | --- | +| 10.0.0
商业版 | DiscoveryX/master | ![](https://nepxion.github.io/Discovery/docs/icon-doc/confirm_24.png) | 2023.x.x | 3.2.x | 2023.x.x.x | +| 9.0.0
商业版 | DiscoveryX/9.x.x | ![](https://nepxion.github.io/Discovery/docs/icon-doc/confirm_24.png) | 2022.x.x | 3.1.x
3.0.x | 2022.x.x.x | +| 8.0.0
商业版 | DiscoveryX/8.x.x | ![](https://nepxion.github.io/Discovery/docs/icon-doc/confirm_24.png) | 2021.x.x | 2.7.x
2.6.x | 2021.x.x.x | +| 7.0.0
商业版 | DiscoveryX/7.x.x | ![](https://nepxion.github.io/Discovery/docs/icon-doc/confirm_24.png) | 2020.x.x | 2.5.x
2.4.1 `↑` | 2021.x | +| 6.23.0 | Discovery/6.x.x | ![](https://nepxion.github.io/Discovery/docs/icon-doc/confirm_24.png) | Hoxton.SR5 `↑`
Hoxton
Greenwich
Finchley | 2.3.x.RELEASE
2.2.x.RELEASE
2.1.x.RELEASE
2.0.x.RELEASE | 2.2.7.RELEASE `↑` | +| 6.12.13 `↓` | Discovery/6.x.x | ![](https://nepxion.github.io/Discovery/docs/icon-doc/confirm_24.png) | Hoxton.SR5 `↑`
Hoxton
Greenwich
Finchley | 2.3.x.RELEASE
2.2.x.RELEASE
2.1.x.RELEASE
2.0.x.RELEASE | 2.2.6.RELEASE `↓`
2.1.x.RELEASE
2.0.x.RELEASE | +| ~~5.6.0~~ | ~~Discovery/5.x.x~~ | ![](https://nepxion.github.io/Discovery/docs/icon-doc/delete_24.png) | Greenwich | 2.1.x.RELEASE | 2.1.x.RELEASE | +| ~~4.15.0~~ | ~~Discovery/4.x.x~~ | ![](https://nepxion.github.io/Discovery/docs/icon-doc/delete_24.png) | Finchley | 2.0.x.RELEASE | 2.0.x.RELEASE | +| 3.41.0 | Discovery/3.x.x | ![](https://nepxion.github.io/Discovery/docs/icon-doc/arrow_up_24.png) | Edgware | 1.5.x.RELEASE | 1.5.x.RELEASE | +| ~~2.0.x~~ | ~~Discovery/2.x.x~~ | ![](https://nepxion.github.io/Discovery/docs/icon-doc/delete_24.png) | Dalston | 1.x.x.RELEASE | 1.5.x.RELEASE | +| ~~1.0.x~~ | ~~Discovery/1.x.x~~ | ![](https://nepxion.github.io/Discovery/docs/icon-doc/delete_24.png) | Camden | 1.x.x.RELEASE | 1.5.x.RELEASE | + +![](https://nepxion.github.io/Discovery/docs/icon-doc/confirm_24.png) 表示维护中 | ![](https://nepxion.github.io/Discovery/docs/icon-doc/arrow_up_24.png) 表示不维护,但可用,强烈建议升级 | ![](https://nepxion.github.io/Discovery/docs/icon-doc/delete_24.png) 表示不维护,不可用,已废弃 + +- 10.x.x版本(适用于2023.x.x)将继续维护 +- 9.x.x版本(适用于2022.x.x)将继续维护 +- 8.x.x版本(适用于2021.x.x)将继续维护 +- 7.x.x版本(适用于2020.x.x)将继续维护 +- 6.x.x版本(同时适用于Finchley、Greenwich和Hoxton)将继续维护 +- 5.x.x版本(适用于Greenwich)已废弃 +- 4.x.x版本(适用于Finchley)已废弃 +- 3.x.x版本(适用于Edgware)不维护,但可用,强烈建议升级 +- 2.x.x版本(适用于Dalston)已废弃 +- 1.x.x版本(适用于Camden)已废弃 + +② 相关中间件版本列表,如下 + +| 组件类型 | 组件版本 | | --- | --- | -| Spring Boot预热启动 | 2秒 | -| Discovery Plugin预热启动 | 2秒 | -| Spring上下文扫描加载 | 2秒 | -| RestController和Swagger扫描加载 | 1秒 | -| determine local hostname | 1.5秒 | -| 连本地配置中心,并打印本地规则和远程规则 | 1.5秒 | -| Actuator Endpoint扫描加载 | 1秒 | -| 连本地服务注册中心,并启动结束 | 2秒 | +| 基础组件 | [![Guava](https://img.shields.io/maven-central/v/com.google.guava/guava.svg?label=Guava&logo=Google)](https://search.maven.org/artifact/com.google.guava/guava)
[![Caffeine](https://img.shields.io/maven-central/v/com.github.ben-manes.caffeine/caffeine.svg?label=Caffeine&logo=Caffeine)](https://search.maven.org/artifact/com.github.ben-manes.caffeine/caffeine)
[![Redisson](https://img.shields.io/maven-central/v/org.redisson/redisson-spring-boot-starter.svg?label=Redisson&logo=Redis)](https://search.maven.org/artifact/org.redisson/redisson-spring-boot-starter)
[![Dom4J](https://img.shields.io/maven-central/v/org.dom4j/dom4j.svg?label=Dom4J&logo=XMPP)](https://search.maven.org/artifact/org.dom4j/dom4j)
[![Swagger](https://img.shields.io/maven-central/v/io.swagger/swagger-models?label=Swagger&logo=Swagger)](https://search.maven.org/artifact/io.swagger/swagger-models)
[![Swagger](https://img.shields.io/maven-central/v/io.springfox/springfox-swagger2?label=SpringFox%20Swagger&logo=Swagger)](https://search.maven.org/artifact/io.springfox/springfox-swagger2) | +| 注册配置组件 | [![Apollo](https://img.shields.io/maven-central/v/com.ctrip.framework.apollo/apollo-client.svg?label=Apollo&logo=ApolloGraphQL)](https://search.maven.org/artifact/com.ctrip.framework.apollo/apollo-client)
[![Zookeeper Curator](https://img.shields.io/maven-central/v/org.apache.curator/curator-framework.svg?label=Zookeeper%20Curator&logo=Apache)](https://search.maven.org/artifact/org.apache.curator/curator-framework)
[![Consul](https://img.shields.io/maven-central/v/com.ecwid.consul/consul-api.svg?label=Consul&logo=Consul)](https://search.maven.org/artifact/com.ecwid.consul/consul-api)
[![JEtcd](https://img.shields.io/maven-central/v/io.etcd/jetcd-core.svg?label=JEtcd&logo=Etcd)](https://search.maven.org/artifact/io.etcd/jetcd-core)
[![Nacos](https://img.shields.io/maven-central/v/com.alibaba.nacos/nacos-client.svg?label=Nacos&logo=AlibabaDotCom)](https://search.maven.org/artifact/com.alibaba.nacos/nacos-client)
[![Eureka](https://img.shields.io/maven-central/v/com.netflix.eureka/eureka-client.svg?label=Eureka&logo=Netflix)](https://search.maven.org/artifact/com.netflix.eureka/eureka-client)
[![Redis](https://img.shields.io/maven-central/v/org.springframework.data/spring-data-redis.svg?label=Redis&logo=Redis)](https://search.maven.org/artifact/org.springframework.data/spring-data-redis)
[![Redisson](https://img.shields.io/maven-central/v/org.redisson/redisson-spring-boot-starter.svg?label=Redisson&logo=Redis)](https://search.maven.org/artifact/org.redisson/redisson-spring-boot-starter) | +| 防护组件 | [![Sentinel](https://img.shields.io/maven-central/v/com.alibaba.csp/sentinel-core.svg?label=Sentinel&logo=AlibabaDotCom)](https://search.maven.org/artifact/com.alibaba.csp/sentinel-core)
[![Hystrix](https://img.shields.io/maven-central/v/com.netflix.hystrix/hystrix-core.svg?label=Hystrix&logo=Netflix)](https://search.maven.org/artifact/com.netflix.hystrix/hystrix-core) | +| 监控组件 | [![SkyWalking](https://img.shields.io/maven-central/v/org.apache.skywalking/apm-toolkit-opentracing.svg?label=SkyWalking&logo=Apache)](https://search.maven.org/artifact/org.apache.skywalking/apm-toolkit-opentracing)
[![OpenTelemetry](https://img.shields.io/maven-central/v/io.opentelemetry/opentelemetry-api.svg?label=OpenTelemetry&logo=OpenTelemetry)](https://search.maven.org/artifact/io.opentelemetry/opentelemetry-api)
[![OpenTracing](https://img.shields.io/maven-central/v/io.opentracing/opentracing-api.svg?label=OpenTracing&logo=Anaconda)](https://search.maven.org/artifact/io.opentracing/opentracing-api)
[![OpenTracing%20Spring%20Cloud](https://img.shields.io/maven-central/v/io.opentracing.contrib/opentracing-spring-cloud-starter.svg?label=OpenTracing%20Spring%20Cloud&logo=Anaconda)](https://search.maven.org/artifact/io.opentracing.contrib/opentracing-spring-cloud-starter)
[![OpenTracing%20Jaeger](https://img.shields.io/maven-central/v/io.opentracing.contrib/opentracing-spring-jaeger-starter.svg?label=OpenTracing%20Jaeger&logo=Anaconda)](https://search.maven.org/artifact/io.opentracing.contrib/opentracing-spring-jaeger-starter)
[![OpenTracing%20Concurrent](https://img.shields.io/maven-central/v/io.opentracing.contrib/opentracing-concurrent.svg?label=OpenTracing%20Concurrent&logo=Anaconda)](https://search.maven.org/artifact/io.opentracing.contrib/opentracing-concurrent)
[![Spring Boot](https://img.shields.io/maven-central/v/de.codecentric/spring-boot-admin-dependencies.svg?label=Spring%20Boot%20Admin&logo=SpringBoot)](https://search.maven.org/artifact/de.codecentric/spring-boot-admin-dependencies) | +| Spring组件 | [![Alibaba Spring](https://img.shields.io/maven-central/v/com.alibaba.spring/spring-context-support.svg?label=Alibaba%20Spring&logo=Spring)](https://search.maven.org/artifact/com.alibaba.spring/spring-context-support)
[![Spring Cloud](https://img.shields.io/maven-central/v/org.springframework.cloud/spring-cloud-dependencies.svg?label=Spring%20Cloud&logo=Spring)](https://search.maven.org/artifact/org.springframework.cloud/spring-cloud-dependencies)
[![Spring Cloud Alibaba](https://img.shields.io/maven-central/v/com.alibaba.cloud/spring-cloud-alibaba-dependencies.svg?label=Spring%20Cloud%20Alibaba&logo=Spring)](https://search.maven.org/artifact/com.alibaba.cloud/spring-cloud-alibaba-dependencies)
[![Spring Boot](https://img.shields.io/maven-central/v/org.springframework.boot/spring-boot-dependencies.svg?label=Spring%20Boot&logo=Spring)](https://search.maven.org/artifact/org.springframework.boot/spring-boot-dependencies) | + +### 企业用户 +不完全统计,目前社区开源项目(包括本框架以及关联框架或组件)已经被如下公司使用或者调研 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+ +为提供更好的专业级服务,请更多已经使用本框架的公司和企业联系我,并希望在[Github Issues](https://github.com/Nepxion/Discovery/issues/56)上登记 + +### 落地案例 +① 某大型银行信用卡新核心系统在生产环境接入Nepxion Discovery框架的服务实例数(包括异地双活,同城双活,多机房全部汇总)将近10000个 + +② 某大型互联网教育公司在生产环境接入Nepxion Discovery框架的服务实例数截至到2021年2月已达到2600多个,基本接入完毕 + + + +- [企业级落地:阿里巴巴 Nacos 企业级落地上篇](https://mp.weixin.qq.com/s?__biz=MzU4NzU0MDIzOQ==&mid=2247490123&idx=1&sn=10d7cd89bf43f07152513718c08dd80c&chksm=fdeb282bca9ca13d2ffb2128c2b5e1acfa5743c0cf835e266835cd5e0233bef5adbca896c8bd&mpshare=1&scene=1&srcid=0724z4xF3FAu0ky75IQ5kexf&sharer_sharetime=1595589366762&sharer_shareid=45ec30ab664def961bd5a4f87aafb0f2&key=ef51a5b0b69d9d3093d17fcab26ddf2c201b696670a1736109d481338e2a980b0c9a82df17369c8796381093f405f0a7cb21c9e467871948960c8890753de7c3f0346a03314d993c33e16817f805c42e&ascene=1&uin=MjczOTY4MzIw&devicetype=Windows+10+x64&version=62090529&lang=zh_CN&exportkey=AfxA6ifl0AcuT4OYhZcXm7k%3D&pass_ticket=c2pshxbFqNmjiwpp%2FUl%2FCP77XI63HuMtvWrO9d2Egrv7y16EseCu1CRLBih3O2MM) +- [企业级落地:阿里巴巴 Nacos 企业级落地中篇](https://mp.weixin.qq.com/s?__biz=MzU4NzU0MDIzOQ==&mid=2247490179&idx=2&sn=6d14417c9770729c89e0ace90f689338&chksm=fdeb28e3ca9ca1f53495cbfeba4bcc0692ff802c034f2e4290f37735428ac0138be050638d46&mpshare=1&scene=1&srcid=0730GwwgWoI8MciSSaATpowp&sharer_sharetime=1596108490727&sharer_shareid=45ec30ab664def961bd5a4f87aafb0f2&key=56c1a4d5743468c93969185004d8e48519dcd2f967bba6978f4e1be13ce7b50d42a51670394473104091352b0fd51e8baed4a72591c511a123166888fd1ff6cc5d54a9326947ef8ebec5f813817669ee&ascene=1&uin=MjczOTY4MzIw&devicetype=Windows+10+x64&version=62090529&lang=zh_CN&exportkey=Ade%2FPtqCCcfAHZQ%2F3vyVCuI%3D&pass_ticket=JDwi8tQ2jPpAhhIOjlvLIetXOdV%2FpqfV3xJ%2B0vfu4O2n10K5qhVh8aZz8bjlwA%2B8) +- [企业级落地:阿里巴巴 Nacos 企业级落地下篇](https://mp.weixin.qq.com/s?__biz=MzU4NzU0MDIzOQ==&mid=2247490231&idx=2&sn=d77c78dfaa244c8c2d95c70fdfa5638a&chksm=fdeb28d7ca9ca1c144bd38e8622af472dbbb7bbe328dcabeddac757130431d354cc75f788196&mpshare=1&scene=1&srcid=0806bN7XW61MNRzsq6IFoZbr&sharer_sharetime=1596716100660&sharer_shareid=45ec30ab664def961bd5a4f87aafb0f2&key=9255e861c291e6d5033faa3da87c4e627d0272caaf2dbd7f01f573ad886ede89da90cff052cb800b029ebfbbe146348d65533fc11db0256cdcaa17edb0752b46d61deb6de3f883413e9fa4e8394f3544&ascene=1&uin=MjczOTY4MzIw&devicetype=Windows+10+x64&version=62090529&lang=zh_CN&exportkey=AZqS6bHMqvgI%2B36YHV%2FRudU%3D&pass_ticket=0wm6xz%2FLhV%2FSxdCvwyJulMHDWW60%2BLZb6hInajgK9oW%2FE9IOemST8NPOOc4mEX7s) +- [企业级落地:全链路蓝绿灰度发布智能化实践](https://mp.weixin.qq.com/s?__biz=MzU1NTgxNDM0Nw==&mid=2247484172&idx=1&sn=41ba2fed39d468f7ee4913e9c305f1b3&chksm=fbcfdfa8ccb856be2280e9484e5e5c091645f98b78dd36e4caf9e3c580a58654d3057e0b4ab0&mpshare=1&scene=1&srcid=04239tBo6ikZqGBMEJwg0h57&sharer_sharetime=1591065506571&sharer_shareid=45ec30ab664def961bd5a4f87aafb0f2&key=1712c1d3e731e2888f16059008c5350eadd5f936fdb5e86d01f61ebf46041db0dbe926e940ae2fa24731e4e0a27412840aaed72f2159f6aaddf87489b5e7a181fe77b4962c39b5a5565dd4c93773b8ad&ascene=1&uin=MjczOTY4MzIw&devicetype=Windows+10+x64&version=62090070&lang=zh_CN&exportkey=AZwuvPfR%2BRhkKms5F7xjmXY%3D&pass_ticket=MQsjBxWL55r6TkZZPKDk9MzUlNhSMI7BVZtQPMwSXWNJ8YsqsiWz41EqXEfYqTUD) + +### 郑重致谢 +- 感谢阿里巴巴中间件Nacos、Sentinel和Spring Cloud Alibaba团队,尤其是Nacos负责人@彦林、@于怀,Sentinel负责人@宿何、@子衿,Spring Cloud Alibaba负责人@铖朴、@良名、@小马哥、@洛夜、@亦盏的技术支持 +- 感谢携程Apollo团队,尤其是@宋顺的技术支持 +- 感谢所有Committers和Contributors +- 感谢所有帮忙分析和定位问题的同学 +- 感谢所有提出宝贵建议和意见的同学 +- 感谢支持和使用本框架的公司和企业 + +### 请联系我 +微信、钉钉、公众号和文档 + +![](https://nepxion.github.io/Discovery/docs/contact-doc/wechat-1.jpg)![](https://nepxion.github.io/Discovery/docs/contact-doc/dingding-1.jpg)![](https://nepxion.github.io/Discovery/docs/contact-doc/gongzhonghao-1.jpg)![](https://nepxion.github.io/Discovery/docs/contact-doc/document-1.jpg) ## Star走势图 - [![Stargazers over time](https://starchart.cc/Nepxion/Discovery.svg)](https://starchart.cc/Nepxion/Discovery) \ No newline at end of file diff --git a/deploy.bat b/deploy.bat index b3d1147aab..483a32b4d6 100644 --- a/deploy.bat +++ b/deploy.bat @@ -15,6 +15,6 @@ @title Nepxion Discovery @color 0a -call mvn clean deploy -DskipTests -e -P release -pl discovery-plugin-starter-eureka,discovery-plugin-starter-consul,discovery-plugin-starter-zookeeper,discovery-plugin-starter-nacos,discovery-plugin-config-center-starter-apollo,discovery-plugin-config-center-starter-nacos,discovery-plugin-config-center-starter-redis,discovery-console-starter-apollo,discovery-console-starter-nacos,discovery-console-starter-redis,discovery-plugin-strategy-starter-service,discovery-plugin-strategy-starter-zuul,discovery-plugin-strategy-starter-gateway,discovery-plugin-strategy-starter-hystrix -am +call mvn clean deploy -DskipTests -e -P release -pl discovery-plugin-register-center/discovery-plugin-register-center-starter-eureka,discovery-plugin-register-center/discovery-plugin-register-center-starter-consul,discovery-plugin-register-center/discovery-plugin-register-center-starter-zookeeper,discovery-plugin-register-center/discovery-plugin-register-center-starter-nacos,discovery-plugin-config-center/discovery-plugin-config-center-starter-apollo,discovery-plugin-config-center/discovery-plugin-config-center-starter-nacos,discovery-plugin-config-center/discovery-plugin-config-center-starter-redis,discovery-plugin-config-center/discovery-plugin-config-center-starter-zookeeper,discovery-plugin-config-center/discovery-plugin-config-center-starter-consul,discovery-plugin-config-center/discovery-plugin-config-center-starter-etcd,discovery-console/discovery-console-starter-apollo,discovery-console/discovery-console-starter-nacos,discovery-console/discovery-console-starter-redis,discovery-console/discovery-console-starter-zookeeper,discovery-console/discovery-console-starter-consul,discovery-console/discovery-console-starter-etcd,discovery-plugin-admin-center/discovery-plugin-admin-center-starter,discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger,discovery-plugin-strategy/discovery-plugin-strategy-starter-service,discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul,discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway,discovery-plugin-strategy/discovery-plugin-strategy-starter-hystrix,discovery-plugin-strategy/discovery-plugin-strategy-starter-opentelemetry,discovery-plugin-strategy/discovery-plugin-strategy-starter-opentracing,discovery-plugin-strategy/discovery-plugin-strategy-starter-skywalking,discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-datasource,discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-limiter,discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-opentelemetry,discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-opentracing,discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-skywalking,discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-micrometer,discovery-plugin-test/discovery-plugin-test-starter-automation -am pause \ No newline at end of file diff --git a/discovery-common-apollo/pom.xml b/discovery-common-apollo/pom.xml deleted file mode 100644 index b98448b43e..0000000000 --- a/discovery-common-apollo/pom.xml +++ /dev/null @@ -1,33 +0,0 @@ - - - discovery-common-apollo - Nepxion Discovery Common Apollo - jar - 4.0.0 - Nepxion Discovery is an enhancement for Spring Cloud Discovery - http://www.nepxion.com - - - com.nepxion - discovery - 5.2.0-SNAPSHOT - - - - - com.ctrip.framework.apollo - apollo-client - - - - org.apache.commons - commons-lang3 - - - - org.springframework.boot - spring-boot-autoconfigure - - - \ No newline at end of file diff --git a/discovery-common-apollo/src/main/java/com/nepxion/discovery/common/apollo/configuration/ApolloAutoConfiguration.java b/discovery-common-apollo/src/main/java/com/nepxion/discovery/common/apollo/configuration/ApolloAutoConfiguration.java deleted file mode 100644 index c17a6132dd..0000000000 --- a/discovery-common-apollo/src/main/java/com/nepxion/discovery/common/apollo/configuration/ApolloAutoConfiguration.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.nepxion.discovery.common.apollo.configuration; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import org.apache.commons.lang3.StringUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.core.env.Environment; - -import com.ctrip.framework.apollo.Config; -import com.ctrip.framework.apollo.ConfigService; -import com.nepxion.discovery.common.apollo.constant.ApolloConstant; -import com.nepxion.discovery.common.apollo.operation.ApolloOperation; - -@Configuration -public class ApolloAutoConfiguration { - @Autowired - private Environment environment; - - @Bean - @ConditionalOnMissingBean - public Config apolloConfig() { - String namespace = environment.getProperty(ApolloConstant.APOLLO_PLUGIN_NAMESPACE); - if (StringUtils.isNotEmpty(namespace)) { - return ConfigService.getConfig(namespace); - } else { - return ConfigService.getAppConfig(); - } - } - - @Bean - public ApolloOperation apolloOperation() { - return new ApolloOperation(); - } -} \ No newline at end of file diff --git a/discovery-common-apollo/src/main/java/com/nepxion/discovery/common/apollo/constant/ApolloConstant.java b/discovery-common-apollo/src/main/java/com/nepxion/discovery/common/apollo/constant/ApolloConstant.java deleted file mode 100644 index 835aa9a5bf..0000000000 --- a/discovery-common-apollo/src/main/java/com/nepxion/discovery/common/apollo/constant/ApolloConstant.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.nepxion.discovery.common.apollo.constant; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import com.ctrip.framework.apollo.core.ConfigConsts; - -public class ApolloConstant implements ConfigConsts { - public static final String TYPE = "Apollo"; - public static final String APOLLO_PLUGIN_NAMESPACE = "apollo.plugin.namespace"; -} \ No newline at end of file diff --git a/discovery-common-apollo/src/main/java/com/nepxion/discovery/common/apollo/operation/ApolloOperation.java b/discovery-common-apollo/src/main/java/com/nepxion/discovery/common/apollo/operation/ApolloOperation.java deleted file mode 100644 index f1f1b38cc2..0000000000 --- a/discovery-common-apollo/src/main/java/com/nepxion/discovery/common/apollo/operation/ApolloOperation.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.nepxion.discovery.common.apollo.operation; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import org.springframework.beans.factory.annotation.Autowired; - -import com.ctrip.framework.apollo.Config; -import com.ctrip.framework.apollo.ConfigChangeListener; -import com.ctrip.framework.apollo.model.ConfigChange; -import com.ctrip.framework.apollo.model.ConfigChangeEvent; -import com.google.common.collect.Sets; - -public class ApolloOperation { - @Autowired - private Config apolloConfig; - - public String getConfig(String group, String serviceId) { - return apolloConfig.getProperty(group + "-" + serviceId, null); - } - - public ConfigChangeListener subscribeConfig(String group, String serviceId, ApolloSubscribeCallback subscribeCallback) { - ConfigChangeListener configListener = new ConfigChangeListener() { - @Override - public void onChange(ConfigChangeEvent changeEvent) { - ConfigChange change = changeEvent.getChange(group + "-" + serviceId); - String config = change.getNewValue(); - subscribeCallback.callback(config); - } - }; - - apolloConfig.addChangeListener(configListener, Sets.newHashSet(group + "-" + serviceId)); - - return configListener; - } - - public void unsubscribeConfig(String group, String serviceId, ConfigChangeListener configListener) { - apolloConfig.removeChangeListener(configListener); - } -} \ No newline at end of file diff --git a/discovery-common-nacos/pom.xml b/discovery-common-nacos/pom.xml deleted file mode 100644 index 05011c3475..0000000000 --- a/discovery-common-nacos/pom.xml +++ /dev/null @@ -1,28 +0,0 @@ - - - discovery-common-nacos - Nepxion Discovery Common Nacos - jar - 4.0.0 - Nepxion Discovery is an enhancement for Spring Cloud Discovery - http://www.nepxion.com - - - com.nepxion - discovery - 5.2.0-SNAPSHOT - - - - - com.alibaba.nacos - nacos-client - - - - org.springframework.boot - spring-boot-autoconfigure - - - \ No newline at end of file diff --git a/discovery-common-nacos/src/main/java/com/nepxion/discovery/common/nacos/configuration/NacosAutoConfiguration.java b/discovery-common-nacos/src/main/java/com/nepxion/discovery/common/nacos/configuration/NacosAutoConfiguration.java deleted file mode 100644 index d27066b279..0000000000 --- a/discovery-common-nacos/src/main/java/com/nepxion/discovery/common/nacos/configuration/NacosAutoConfiguration.java +++ /dev/null @@ -1,116 +0,0 @@ -package com.nepxion.discovery.common.nacos.configuration; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import java.util.Properties; - -import org.apache.commons.lang3.StringUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.core.env.Environment; - -import com.alibaba.nacos.api.NacosFactory; -import com.alibaba.nacos.api.config.ConfigService; -import com.alibaba.nacos.api.exception.NacosException; -import com.nepxion.discovery.common.nacos.constant.NacosConstant; -import com.nepxion.discovery.common.nacos.operation.NacosOperation; - -@Configuration -public class NacosAutoConfiguration { - @Autowired - private Environment environment; - - @Bean - @ConditionalOnMissingBean - public ConfigService nacosConfigService() throws NacosException { - Properties properties = new Properties(); - - String serverAddr = environment.getProperty(NacosConstant.NACOS_SERVER_ADDR); - if (StringUtils.isNotEmpty(serverAddr)) { - properties.put(NacosConstant.SERVER_ADDR, serverAddr); - } else { - throw new IllegalArgumentException(NacosConstant.NACOS_SERVER_ADDR + " can't be null or empty"); - } - - String accessKey = environment.getProperty(NacosConstant.NACOS_ACCESS_KEY); - if (StringUtils.isNotEmpty(accessKey)) { - properties.put(NacosConstant.ACCESS_KEY, accessKey); - } - - String secretKey = environment.getProperty(NacosConstant.NACOS_SECRET_KEY); - if (StringUtils.isNotEmpty(secretKey)) { - properties.put(NacosConstant.SECRET_KEY, secretKey); - } - - String namespace = environment.getProperty(NacosConstant.NACOS_PLUGIN_NAMESPACE); - if (StringUtils.isNotEmpty(namespace)) { - properties.put(NacosConstant.NAMESPACE, namespace); - } - - String clusterName = environment.getProperty(NacosConstant.NACOS_PLUGIN_CLUSTER_NAME); - if (StringUtils.isNotEmpty(clusterName)) { - properties.put(NacosConstant.CLUSTER_NAME, clusterName); - } - - String contextPath = environment.getProperty(NacosConstant.NACOS_PLUGIN_CONTEXT_PATH); - if (StringUtils.isNotEmpty(contextPath)) { - properties.put(NacosConstant.CONTEXT_PATH, contextPath); - } - - String endpoint = environment.getProperty(NacosConstant.NACOS_PLUGIN_ENDPOINT); - if (StringUtils.isNotEmpty(endpoint)) { - properties.put(NacosConstant.ENDPOINT, endpoint); - } - - String endpointPort = environment.getProperty(NacosConstant.NACOS_PLUGIN_ENDPOINT_PORT); - if (StringUtils.isNotEmpty(endpointPort)) { - properties.put(NacosConstant.ENDPOINT_PORT, endpointPort); - } - - String isUseEndpointParsingRule = environment.getProperty(NacosConstant.NACOS_PLUGIN_IS_USE_ENDPOINT_PARSING_RULE); - if (StringUtils.isNotEmpty(isUseEndpointParsingRule)) { - properties.put(NacosConstant.IS_USE_ENDPOINT_PARSING_RULE, isUseEndpointParsingRule); - } - - String encode = environment.getProperty(NacosConstant.NACOS_PLUGIN_ENCODE); - if (StringUtils.isNotEmpty(encode)) { - properties.put(NacosConstant.ENCODE, encode); - } - - String namingLoadCacheAtStart = environment.getProperty(NacosConstant.NACOS_PLUGIN_NAMING_LOAD_CACHE_AT_START); - if (StringUtils.isNotEmpty(namingLoadCacheAtStart)) { - properties.put(NacosConstant.NAMING_LOAD_CACHE_AT_START, namingLoadCacheAtStart); - } - - String namingClientBeatThreadCount = environment.getProperty(NacosConstant.NACOS_PLUGIN_NAMING_CLIENT_BEAT_THREAD_COUNT); - if (StringUtils.isNotEmpty(namingClientBeatThreadCount)) { - properties.put(NacosConstant.NAMING_CLIENT_BEAT_THREAD_COUNT, namingClientBeatThreadCount); - } - - String namingPollingThreadCount = environment.getProperty(NacosConstant.NACOS_PLUGIN_NAMING_POLLING_THREAD_COUNT); - if (StringUtils.isNotEmpty(namingPollingThreadCount)) { - properties.put(NacosConstant.NAMING_POLLING_THREAD_COUNT, namingPollingThreadCount); - } - - String ramRoleName = environment.getProperty(NacosConstant.NACOS_PLUGIN_RAM_ROLE_NAME); - if (StringUtils.isNotEmpty(ramRoleName)) { - properties.put(NacosConstant.RAM_ROLE_NAME, ramRoleName); - } - - return NacosFactory.createConfigService(properties); - } - - @Bean - public NacosOperation nacosOperation() { - return new NacosOperation(); - } -} \ No newline at end of file diff --git a/discovery-common-nacos/src/main/java/com/nepxion/discovery/common/nacos/constant/NacosConstant.java b/discovery-common-nacos/src/main/java/com/nepxion/discovery/common/nacos/constant/NacosConstant.java deleted file mode 100644 index aa639a2b12..0000000000 --- a/discovery-common-nacos/src/main/java/com/nepxion/discovery/common/nacos/constant/NacosConstant.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.nepxion.discovery.common.nacos.constant; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import com.alibaba.nacos.api.PropertyKeyConst; - -public class NacosConstant extends PropertyKeyConst { - public static final String TYPE = "Nacos"; - public static final String NACOS_SERVER_ADDR = "nacos.server-addr"; - public static final String NACOS_ACCESS_KEY = "nacos.access-key"; - public static final String NACOS_SECRET_KEY = "nacos.secret-key"; - public static final String NACOS_PLUGIN_NAMESPACE = "nacos.plugin.namespace"; - public static final String NACOS_PLUGIN_CLUSTER_NAME = "nacos.plugin.cluster-name"; - public static final String NACOS_PLUGIN_CONTEXT_PATH = "nacos.plugin.context-path"; - public static final String NACOS_PLUGIN_CONFIG_LONG_POLL_TIMEOUT = "nacos.plugin.config-long-poll-timeout"; - public static final String NACOS_PLUGIN_CONFIG_RETRY_TIME = "nacos.plugin.config-retry-time"; - public static final String NACOS_PLUGIN_MAX_RETRY = "nacos.plugin.max-retry"; - public static final String NACOS_PLUGIN_ENDPOINT = "nacos.plugin.endpoint"; - public static final String NACOS_PLUGIN_ENDPOINT_PORT = "nacos.plugin.endpoint-port"; - public static final String NACOS_PLUGIN_IS_USE_ENDPOINT_PARSING_RULE = "nacos.plugin.is-use-endpoint-parsing-rule"; - public static final String NACOS_PLUGIN_IS_USE_CLOUD_NAMESPACE_PARSING = "nacos.plugin.is-use-cloud-namespace-parsing"; - public static final String NACOS_PLUGIN_ENCODE = "nacos.plugin.encode"; - public static final String NACOS_PLUGIN_NAMING_LOAD_CACHE_AT_START = "nacos.plugin.naming-load-cache-at-start"; - public static final String NACOS_PLUGIN_NAMING_CLIENT_BEAT_THREAD_COUNT = "nacos.plugin.naming-client-beat-thread-count"; - public static final String NACOS_PLUGIN_NAMING_POLLING_THREAD_COUNT = "nacos.plugin.naming-polling-thread-count"; - public static final String NACOS_PLUGIN_RAM_ROLE_NAME = "nacos.plugin.ram-role-name"; - public static final String NACOS_PLUGIN_ENABLE_REMOTE_CONFIG_SYNC = "nacos.plugin.enable-remote-config-sync"; - public static final String NACOS_PLUGIN_TIMEOUT = "nacos.plugin.timout"; - - public static final long DEFAULT_TIMEOUT = 30000; -} \ No newline at end of file diff --git a/discovery-common-nacos/src/main/java/com/nepxion/discovery/common/nacos/operation/NacosOperation.java b/discovery-common-nacos/src/main/java/com/nepxion/discovery/common/nacos/operation/NacosOperation.java deleted file mode 100644 index 172f8b4a26..0000000000 --- a/discovery-common-nacos/src/main/java/com/nepxion/discovery/common/nacos/operation/NacosOperation.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.nepxion.discovery.common.nacos.operation; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import java.util.concurrent.Executor; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.core.env.Environment; - -import com.alibaba.nacos.api.config.ConfigService; -import com.alibaba.nacos.api.config.listener.Listener; -import com.alibaba.nacos.api.exception.NacosException; -import com.nepxion.discovery.common.nacos.constant.NacosConstant; - -public class NacosOperation { - @Autowired - private ConfigService nacosConfigService; - - @Autowired - private Environment environment; - - public String getConfig(String group, String serviceId) throws NacosException { - long timeout = environment.getProperty(NacosConstant.NACOS_PLUGIN_TIMEOUT, Long.class, NacosConstant.DEFAULT_TIMEOUT); - - return nacosConfigService.getConfig(serviceId, group, timeout); - } - - public boolean removeConfig(String group, String serviceId) throws NacosException { - return nacosConfigService.removeConfig(serviceId, group); - } - - public boolean publishConfig(String group, String serviceId, String config) throws NacosException { - return nacosConfigService.publishConfig(serviceId, group, config); - } - - public Listener subscribeConfig(String group, String serviceId, Executor executor, NacosSubscribeCallback subscribeCallback) throws NacosException { - Listener configListener = new Listener() { - @Override - public void receiveConfigInfo(String config) { - subscribeCallback.callback(config); - } - - @Override - public Executor getExecutor() { - return executor; - } - }; - - nacosConfigService.addListener(serviceId, group, configListener); - - return configListener; - } - - public void unsubscribeConfig(String group, String serviceId, Listener configListener) { - nacosConfigService.removeListener(serviceId, group, configListener); - } -} \ No newline at end of file diff --git a/discovery-common-redis/pom.xml b/discovery-common-redis/pom.xml deleted file mode 100644 index 29786ec5a6..0000000000 --- a/discovery-common-redis/pom.xml +++ /dev/null @@ -1,28 +0,0 @@ - - - discovery-common-redis - Nepxion Discovery Common Redis - jar - 4.0.0 - Nepxion Discovery is an enhancement for Spring Cloud Discovery - http://www.nepxion.com - - - com.nepxion - discovery - 5.2.0-SNAPSHOT - - - - - org.apache.commons - commons-lang3 - - - - org.springframework.boot - spring-boot-starter-data-redis - - - \ No newline at end of file diff --git a/discovery-common-redis/src/main/java/com/nepxion/discovery/common/redis/configuration/RedisAutoConfiguration.java b/discovery-common-redis/src/main/java/com/nepxion/discovery/common/redis/configuration/RedisAutoConfiguration.java deleted file mode 100644 index 33aa38043d..0000000000 --- a/discovery-common-redis/src/main/java/com/nepxion/discovery/common/redis/configuration/RedisAutoConfiguration.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.nepxion.discovery.common.redis.configuration; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @author JiKai Sun - * @version 1.0 - */ - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.data.redis.core.HashOperations; -import org.springframework.data.redis.core.StringRedisTemplate; - -import com.nepxion.discovery.common.redis.operation.RedisOperation; - -@Configuration -public class RedisAutoConfiguration { - @Autowired - private StringRedisTemplate stringRedisTemplate; - - @Bean - public HashOperations hashOperations() { - return stringRedisTemplate.opsForHash(); - } - - @Bean - public RedisOperation redisOperation() { - return new RedisOperation(); - } -} \ No newline at end of file diff --git a/discovery-common-redis/src/main/java/com/nepxion/discovery/common/redis/operation/RedisOperation.java b/discovery-common-redis/src/main/java/com/nepxion/discovery/common/redis/operation/RedisOperation.java deleted file mode 100644 index 4ec1487761..0000000000 --- a/discovery-common-redis/src/main/java/com/nepxion/discovery/common/redis/operation/RedisOperation.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.nepxion.discovery.common.redis.operation; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @author JiKai Sun - * @version 1.0 - */ - -import org.apache.commons.lang3.StringUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.redis.core.HashOperations; -import org.springframework.data.redis.core.StringRedisTemplate; - -public class RedisOperation { - @Autowired - private StringRedisTemplate stringRedisTemplate; - - @Autowired - private HashOperations hashOperations; - - public String getConfig(String group, String serviceId) { - return hashOperations.get(group, serviceId); - } - - public boolean removeConfig(String group, String serviceId) { - publishConfig(group, serviceId, StringUtils.EMPTY); - - return hashOperations.delete(group, serviceId) == 1; - } - - public boolean publishConfig(String group, String serviceId, String config) { - hashOperations.put(group, serviceId, config); - stringRedisTemplate.convertAndSend(group + "-" + serviceId, config); - - return true; - } - - public void subscribeConfig(String config, RedisSubscribeCallback redisSubscribeCallback) { - redisSubscribeCallback.callback(config); - } -} \ No newline at end of file diff --git a/discovery-common/pom.xml b/discovery-common/pom.xml deleted file mode 100644 index 4cf0a642d6..0000000000 --- a/discovery-common/pom.xml +++ /dev/null @@ -1,43 +0,0 @@ - - - discovery-common - Nepxion Discovery Common - jar - 4.0.0 - Nepxion Discovery is an enhancement for Spring Cloud Discovery - http://www.nepxion.com - - - com.nepxion - discovery - 5.2.0-SNAPSHOT - - - - - org.apache.commons - commons-lang3 - - - - org.apache.commons - commons-collections4 - - - - commons-io - commons-io - - - - org.springframework - spring-web - - - - com.fasterxml.jackson.core - jackson-databind - - - \ No newline at end of file diff --git a/discovery-common/src/main/java/com/nepxion/discovery/common/constant/DiscoveryConstant.java b/discovery-common/src/main/java/com/nepxion/discovery/common/constant/DiscoveryConstant.java deleted file mode 100644 index a94cece31d..0000000000 --- a/discovery-common/src/main/java/com/nepxion/discovery/common/constant/DiscoveryConstant.java +++ /dev/null @@ -1,91 +0,0 @@ -package com.nepxion.discovery.common.constant; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -public class DiscoveryConstant { - public static final String DISCOVERY_VERSION = "5.2.0-SNAPSHOT"; - - public static final String SPRING_APPLICATION_DISCOVERY_PLUGIN = "spring.application.discovery.plugin"; - public static final String SPRING_APPLICATION_DISCOVERY_VERSION = "spring.application.discovery.version"; - public static final String SPRING_APPLICATION_REGISTER_CONTROL_ENABLED = "spring.application.register.control.enabled"; - public static final String SPRING_APPLICATION_DISCOVERY_CONTROL_ENABLED = "spring.application.discovery.control.enabled"; - public static final String SPRING_APPLICATION_CONFIG_REST_CONTROL_ENABLED = "spring.application.config.rest.control.enabled"; - public static final String SPRING_APPLICATION_SERVLET_WEB_SERVER_ENABLED = "spring.application.servlet.web.server.enabled"; - public static final String SPRING_APPLICATION_REACTIVE_WEB_SERVER_ENABLED = "spring.application.reactive.web.server.enabled"; - public static final String SPRING_APPLICATION_CONFIG_FORMAT = "spring.application.config.format"; - public static final String SPRING_APPLICATION_CONFIG_PATH = "spring.application.config.path"; - public static final String SPRING_APPLICATION_GROUP_KEY = "spring.application.group.key"; - public static final String SPRING_APPLICATION_CONTEXT_PATH = "spring.application.context-path"; - public static final String SPRING_APPLICATION_NO_SERVER_FOUND_NOTIFICATION_ENABLED = "spring.application.no.server.found.notification.enabled"; - - public static final String CONTEXT_PATH = "server.servlet.context-path"; - - public static final String ANNOTATION_CONFIG_SERVLET_WEB_SERVER_APPLICATION_CONTEXT = "AnnotationConfigServletWebServerApplicationContext"; - public static final String ANNOTATION_CONFIG_REACTIVE_WEB_SERVER_APPLICATION_CONTEXT = "AnnotationConfigReactiveWebServerApplicationContext"; - - public static final String SPRING_APPLICATION_NAME = "spring.application.name"; - public static final String SPRING_APPLICATION_TYPE = "spring.application.type"; - public static final String GROUP = "group"; - public static final String SERVICE_ID = "serviceId"; - public static final String HOST = "host"; - public static final String PORT = "port"; - public static final String METADATA = "metadata"; - - public static final String SERVICE_TYPE = "service"; - public static final String GATEWAY_TYPE = "gateway"; - - public static final String DYNAMIC_VERSION = "dynamicVersion"; - public static final String RULE = "rule"; - public static final String DYNAMIC_RULE = "dynamicRule"; - public static final String REACH_MAX_LIMITED_COUNT = "reach max limited count"; - public static final String REGISTER_ISOLATION = "register isolation"; - - public static final String VERSION = "version"; - public static final String REGION = "region"; - public static final String ADDRESS = "address"; - public static final String VERSION_WEIGHT = "version-weight"; - public static final String REGION_WEIGHT = "region-weight"; - - public static final String N_D_PREFIX = "n-d-"; - public static final String N_D_SERVICE_PREFIX = "n-d-service"; - - public static final String N_D_SERVICE_TYPE = "n-d-service-type"; - public static final String N_D_SERVICE_ID = "n-d-service-id"; - public static final String N_D_SERVICE_ADDRESS = "n-d-service-address"; - public static final String N_D_SERVICE_GROUP = "n-d-service-group"; - public static final String N_D_SERVICE_VERSION = "n-d-service-version"; - public static final String N_D_SERVICE_REGION = "n-d-service-region"; - - public static final String N_D_VERSION = "n-d-version"; - public static final String N_D_REGION = "n-d-region"; - public static final String N_D_ADDRESS = "n-d-address"; - public static final String N_D_VERSION_WEIGHT = "n-d-version-weight"; - public static final String N_D_REGION_WEIGHT = "n-d-region-weight"; - - public static final String XML_FORMAT = "xml"; - public static final String JSON_FORMAT = "json"; - public static final String PREFIX_CLASSPATH = "classpath:"; - public static final String PREFIX_FILE = "file:"; - - public static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss.SSS"; - public static final String ENCODING_UTF_8 = "UTF-8"; - public static final String SEPARATE = ";"; - public static final String EQUALS = "="; - public static final String DASH = "-"; - - public static final String ASYNC = "async"; - public static final String SYNC = "sync"; - public static final String GLOBAL = "global"; - public static final String PARTIAL = "partial"; - public static final String OK = "OK"; - public static final String NO = "NO"; - public static final String UNKNOWN = "UNKNOWN"; - public static final String EXT = "ext"; -} \ No newline at end of file diff --git a/discovery-common/src/main/java/com/nepxion/discovery/common/entity/CustomizationEntity.java b/discovery-common/src/main/java/com/nepxion/discovery/common/entity/CustomizationEntity.java deleted file mode 100644 index 54fd911639..0000000000 --- a/discovery-common/src/main/java/com/nepxion/discovery/common/entity/CustomizationEntity.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.nepxion.discovery.common.entity; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import java.io.Serializable; -import java.util.LinkedHashMap; -import java.util.Map; - -import org.apache.commons.lang3.builder.EqualsBuilder; -import org.apache.commons.lang3.builder.HashCodeBuilder; -import org.apache.commons.lang3.builder.ToStringBuilder; -import org.apache.commons.lang3.builder.ToStringStyle; - -public class CustomizationEntity implements Serializable { - private static final long serialVersionUID = -5135099669922746855L; - - private Map> customizationMap = new LinkedHashMap>(); - - public Map> getCustomizationMap() { - return customizationMap; - } - - public void setCustomizationMap(Map> customizationMap) { - this.customizationMap = customizationMap; - } - - @Override - public int hashCode() { - return HashCodeBuilder.reflectionHashCode(this); - } - - @Override - public boolean equals(Object object) { - return EqualsBuilder.reflectionEquals(this, object); - } - - @Override - public String toString() { - return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); - } -} \ No newline at end of file diff --git a/discovery-common/src/main/java/com/nepxion/discovery/common/entity/FilterType.java b/discovery-common/src/main/java/com/nepxion/discovery/common/entity/FilterType.java deleted file mode 100644 index fe7db208ae..0000000000 --- a/discovery-common/src/main/java/com/nepxion/discovery/common/entity/FilterType.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.nepxion.discovery.common.entity; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -public enum FilterType { - BLACKLIST("blacklist", "blacklist"), - WHITELIST("whitelist", "whitelist"); - - private String value; - private String description; - - private FilterType(String value, String description) { - this.value = value; - this.description = description; - } - - public String getValue() { - return value; - } - - public String getDescription() { - return description; - } - - public static FilterType fromString(String value) { - for (FilterType type : FilterType.values()) { - if (type.getValue().equalsIgnoreCase(value)) { - return type; - } - } - - throw new IllegalArgumentException("No matched type with value=" + value); - } - - @Override - public String toString() { - return value; - } -} \ No newline at end of file diff --git a/discovery-common/src/main/java/com/nepxion/discovery/common/entity/InstanceEntity.java b/discovery-common/src/main/java/com/nepxion/discovery/common/entity/InstanceEntity.java deleted file mode 100644 index 61c88f1518..0000000000 --- a/discovery-common/src/main/java/com/nepxion/discovery/common/entity/InstanceEntity.java +++ /dev/null @@ -1,101 +0,0 @@ -package com.nepxion.discovery.common.entity; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import java.io.Serializable; -import java.util.Map; - -import org.apache.commons.lang3.builder.EqualsBuilder; -import org.apache.commons.lang3.builder.HashCodeBuilder; -import org.apache.commons.lang3.builder.ToStringBuilder; -import org.apache.commons.lang3.builder.ToStringStyle; - -public class InstanceEntity implements Serializable { - private static final long serialVersionUID = -3001191508072178378L; - - private String serviceType; - private String serviceId; - private String version; - private String region; - private String host; - private int port; - private Map metadata; - - public String getServiceType() { - return serviceType; - } - - public void setServiceType(String serviceType) { - this.serviceType = serviceType; - } - - public String getServiceId() { - return serviceId; - } - - public void setServiceId(String serviceId) { - this.serviceId = serviceId; - } - - public String getVersion() { - return version; - } - - public void setVersion(String version) { - this.version = version; - } - - public String getRegion() { - return region; - } - - public void setRegion(String region) { - this.region = region; - } - - public String getHost() { - return host; - } - - public void setHost(String host) { - this.host = host; - } - - public int getPort() { - return port; - } - - public void setPort(int port) { - this.port = port; - } - - public Map getMetadata() { - return metadata; - } - - public void setMetadata(Map metadata) { - this.metadata = metadata; - } - - @Override - public int hashCode() { - return HashCodeBuilder.reflectionHashCode(this); - } - - @Override - public boolean equals(Object object) { - return EqualsBuilder.reflectionEquals(this, object); - } - - @Override - public String toString() { - return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); - } -} \ No newline at end of file diff --git a/discovery-common/src/main/java/com/nepxion/discovery/common/entity/InstanceEntityWrapper.java b/discovery-common/src/main/java/com/nepxion/discovery/common/entity/InstanceEntityWrapper.java deleted file mode 100644 index c798717f7a..0000000000 --- a/discovery-common/src/main/java/com/nepxion/discovery/common/entity/InstanceEntityWrapper.java +++ /dev/null @@ -1,79 +0,0 @@ -package com.nepxion.discovery.common.entity; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import java.util.Map; - -import org.apache.commons.lang3.StringUtils; - -import com.nepxion.discovery.common.constant.DiscoveryConstant; - -public class InstanceEntityWrapper { - public static String getContextPath(InstanceEntity instanceEntity) { - Map metadata = instanceEntity.getMetadata(); - - return metadata.get(DiscoveryConstant.SPRING_APPLICATION_CONTEXT_PATH); - } - - public static String getGroup(InstanceEntity instanceEntity) { - Map metadata = instanceEntity.getMetadata(); - String groupKey = metadata.get(DiscoveryConstant.SPRING_APPLICATION_GROUP_KEY); - if (StringUtils.isEmpty(groupKey)) { - return StringUtils.EMPTY; - } - - String filter = metadata.get(groupKey); - if (filter == null) { - return StringUtils.EMPTY; - } - - return filter; - } - - public static String getPlugin(InstanceEntity instanceEntity) { - Map metadata = instanceEntity.getMetadata(); - String plugin = metadata.get(DiscoveryConstant.SPRING_APPLICATION_DISCOVERY_PLUGIN); - if (plugin == null) { - return StringUtils.EMPTY; - } - - return plugin; - } - - public static boolean isRegisterControlEnabled(InstanceEntity instanceEntity) { - Map metadata = instanceEntity.getMetadata(); - String flag = metadata.get(DiscoveryConstant.SPRING_APPLICATION_REGISTER_CONTROL_ENABLED); - if (flag == null) { - return true; - } - - return Boolean.valueOf(flag); - } - - public static boolean isDiscoveryControlEnabled(InstanceEntity instanceEntity) { - Map metadata = instanceEntity.getMetadata(); - String flag = metadata.get(DiscoveryConstant.SPRING_APPLICATION_DISCOVERY_CONTROL_ENABLED); - if (flag == null) { - return true; - } - - return Boolean.valueOf(flag); - } - - public static boolean isConfigRestControlEnabled(InstanceEntity instanceEntity) { - Map metadata = instanceEntity.getMetadata(); - String flag = metadata.get(DiscoveryConstant.SPRING_APPLICATION_CONFIG_REST_CONTROL_ENABLED); - if (flag == null) { - return true; - } - - return Boolean.valueOf(flag); - } -} \ No newline at end of file diff --git a/discovery-common/src/main/java/com/nepxion/discovery/common/entity/ResultEntity.java b/discovery-common/src/main/java/com/nepxion/discovery/common/entity/ResultEntity.java deleted file mode 100644 index d9a55cd98f..0000000000 --- a/discovery-common/src/main/java/com/nepxion/discovery/common/entity/ResultEntity.java +++ /dev/null @@ -1,55 +0,0 @@ -package com.nepxion.discovery.common.entity; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import java.io.Serializable; - -import org.apache.commons.lang3.builder.EqualsBuilder; -import org.apache.commons.lang3.builder.HashCodeBuilder; -import org.apache.commons.lang3.builder.ToStringBuilder; -import org.apache.commons.lang3.builder.ToStringStyle; - -public class ResultEntity implements Serializable { - private static final long serialVersionUID = -3322655604556025836L; - - private String url; - private String result; - - public String getUrl() { - return url; - } - - public void setUrl(String url) { - this.url = url; - } - - public String getResult() { - return result; - } - - public void setResult(String result) { - this.result = result; - } - - @Override - public int hashCode() { - return HashCodeBuilder.reflectionHashCode(this); - } - - @Override - public boolean equals(Object object) { - return EqualsBuilder.reflectionEquals(this, object); - } - - @Override - public String toString() { - return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); - } -} \ No newline at end of file diff --git a/discovery-common/src/main/java/com/nepxion/discovery/common/entity/RuleEntity.java b/discovery-common/src/main/java/com/nepxion/discovery/common/entity/RuleEntity.java deleted file mode 100644 index d6aadceea9..0000000000 --- a/discovery-common/src/main/java/com/nepxion/discovery/common/entity/RuleEntity.java +++ /dev/null @@ -1,91 +0,0 @@ -package com.nepxion.discovery.common.entity; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import java.io.Serializable; - -import org.apache.commons.lang3.builder.EqualsBuilder; -import org.apache.commons.lang3.builder.HashCodeBuilder; -import org.apache.commons.lang3.builder.ToStringBuilder; -import org.apache.commons.lang3.builder.ToStringStyle; - -public class RuleEntity implements Serializable { - private static final long serialVersionUID = 7079024435084528751L; - - private RegisterEntity registerEntity; - private DiscoveryEntity discoveryEntity; - private StrategyEntity strategyEntity; - private CustomizationEntity customizationEntity; - private StrategyCustomizationEntity strategyCustomizationEntity; - private String content; - - public RegisterEntity getRegisterEntity() { - return registerEntity; - } - - public void setRegisterEntity(RegisterEntity registerEntity) { - this.registerEntity = registerEntity; - } - - public DiscoveryEntity getDiscoveryEntity() { - return discoveryEntity; - } - - public void setDiscoveryEntity(DiscoveryEntity discoveryEntity) { - this.discoveryEntity = discoveryEntity; - } - - public CustomizationEntity getCustomizationEntity() { - return customizationEntity; - } - - public void setCustomizationEntity(CustomizationEntity customizationEntity) { - this.customizationEntity = customizationEntity; - } - - public StrategyEntity getStrategyEntity() { - return strategyEntity; - } - - public void setStrategyEntity(StrategyEntity strategyEntity) { - this.strategyEntity = strategyEntity; - } - - public StrategyCustomizationEntity getStrategyCustomizationEntity() { - return strategyCustomizationEntity; - } - - public void setStrategyCustomizationEntity(StrategyCustomizationEntity strategyCustomizationEntity) { - this.strategyCustomizationEntity = strategyCustomizationEntity; - } - - public String getContent() { - return content; - } - - public void setContent(String content) { - this.content = content; - } - - @Override - public int hashCode() { - return HashCodeBuilder.reflectionHashCode(this); - } - - @Override - public boolean equals(Object object) { - return EqualsBuilder.reflectionEquals(this, object); - } - - @Override - public String toString() { - return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); - } -} \ No newline at end of file diff --git a/discovery-common/src/main/java/com/nepxion/discovery/common/entity/ServiceType.java b/discovery-common/src/main/java/com/nepxion/discovery/common/entity/ServiceType.java deleted file mode 100644 index 61a695ac0a..0000000000 --- a/discovery-common/src/main/java/com/nepxion/discovery/common/entity/ServiceType.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.nepxion.discovery.common.entity; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import com.nepxion.discovery.common.constant.DiscoveryConstant; - -public enum ServiceType { - SERVICE(DiscoveryConstant.SERVICE_TYPE, DiscoveryConstant.SERVICE_TYPE), - GATEWAY(DiscoveryConstant.GATEWAY_TYPE, DiscoveryConstant.GATEWAY_TYPE); - - private String value; - private String description; - - private ServiceType(String value, String description) { - this.value = value; - this.description = description; - } - - public String getValue() { - return value; - } - - public String getDescription() { - return description; - } - - public static ServiceType fromString(String value) { - for (ServiceType type : ServiceType.values()) { - if (type.getValue().equalsIgnoreCase(value)) { - return type; - } - } - - throw new IllegalArgumentException("No matched type with value=" + value); - } - - @Override - public String toString() { - return value; - } -} \ No newline at end of file diff --git a/discovery-common/src/main/java/com/nepxion/discovery/common/entity/StrategyConditionEntity.java b/discovery-common/src/main/java/com/nepxion/discovery/common/entity/StrategyConditionEntity.java deleted file mode 100644 index d12686c222..0000000000 --- a/discovery-common/src/main/java/com/nepxion/discovery/common/entity/StrategyConditionEntity.java +++ /dev/null @@ -1,102 +0,0 @@ -package com.nepxion.discovery.common.entity; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import java.io.Serializable; -import java.util.LinkedHashMap; -import java.util.Map; - -import org.apache.commons.lang3.builder.EqualsBuilder; -import org.apache.commons.lang3.builder.HashCodeBuilder; -import org.apache.commons.lang3.builder.ToStringBuilder; -import org.apache.commons.lang3.builder.ToStringStyle; - -public class StrategyConditionEntity implements Serializable { - private static final long serialVersionUID = 1249482860170990672L; - - private String id; - private Map headerMap = new LinkedHashMap(); - private String versionId; - private String regionId; - private String addressId; - private String versionWeightId; - private String regionWeightId; - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public Map getHeaderMap() { - return headerMap; - } - - public void setHeaderMap(Map headerMap) { - this.headerMap = headerMap; - } - - public String getVersionId() { - return versionId; - } - - public void setVersionId(String versionId) { - this.versionId = versionId; - } - - public String getRegionId() { - return regionId; - } - - public void setRegionId(String regionId) { - this.regionId = regionId; - } - - public String getAddressId() { - return addressId; - } - - public void setAddressId(String addressId) { - this.addressId = addressId; - } - - public String getVersionWeightId() { - return versionWeightId; - } - - public void setVersionWeightId(String versionWeightId) { - this.versionWeightId = versionWeightId; - } - - public String getRegionWeightId() { - return regionWeightId; - } - - public void setRegionWeightId(String regionWeightId) { - this.regionWeightId = regionWeightId; - } - - @Override - public int hashCode() { - return HashCodeBuilder.reflectionHashCode(this); - } - - @Override - public boolean equals(Object object) { - return EqualsBuilder.reflectionEquals(this, object); - } - - @Override - public String toString() { - return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); - } -} \ No newline at end of file diff --git a/discovery-common/src/main/java/com/nepxion/discovery/common/entity/StrategyCustomizationEntity.java b/discovery-common/src/main/java/com/nepxion/discovery/common/entity/StrategyCustomizationEntity.java deleted file mode 100644 index 380e8abefe..0000000000 --- a/discovery-common/src/main/java/com/nepxion/discovery/common/entity/StrategyCustomizationEntity.java +++ /dev/null @@ -1,68 +0,0 @@ -package com.nepxion.discovery.common.entity; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import java.io.Serializable; -import java.util.Collections; -import java.util.Comparator; -import java.util.List; - -import org.apache.commons.lang3.builder.EqualsBuilder; -import org.apache.commons.lang3.builder.HashCodeBuilder; -import org.apache.commons.lang3.builder.ToStringBuilder; -import org.apache.commons.lang3.builder.ToStringStyle; - -public class StrategyCustomizationEntity implements Serializable { - private static final long serialVersionUID = 4903833660194433964L; - - private List strategyConditionEntityList; - private List strategyRouteEntityList; - - public List getStrategyConditionEntityList() { - return strategyConditionEntityList; - } - - public void setStrategyConditionEntityList(List strategyConditionEntityList) { - this.strategyConditionEntityList = strategyConditionEntityList; - } - - public List getStrategyRouteEntityList() { - return strategyRouteEntityList; - } - - public void setStrategyRouteEntityList(List strategyRouteEntityList) { - this.strategyRouteEntityList = strategyRouteEntityList; - - // Header参数越多,越排在前面 - Collections.sort(this.strategyConditionEntityList, new Comparator() { - public int compare(StrategyConditionEntity object1, StrategyConditionEntity object2) { - Integer count1 = object1.getHeaderMap().size(); - Integer count2 = object2.getHeaderMap().size(); - - return count2.compareTo(count1); - } - }); - } - - @Override - public int hashCode() { - return HashCodeBuilder.reflectionHashCode(this); - } - - @Override - public boolean equals(Object object) { - return EqualsBuilder.reflectionEquals(this, object); - } - - @Override - public String toString() { - return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); - } -} \ No newline at end of file diff --git a/discovery-common/src/main/java/com/nepxion/discovery/common/entity/StrategyType.java b/discovery-common/src/main/java/com/nepxion/discovery/common/entity/StrategyType.java deleted file mode 100644 index 2cbd309ad3..0000000000 --- a/discovery-common/src/main/java/com/nepxion/discovery/common/entity/StrategyType.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.nepxion.discovery.common.entity; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import com.nepxion.discovery.common.constant.DiscoveryConstant; - -public enum StrategyType { - VERSION(DiscoveryConstant.VERSION, DiscoveryConstant.VERSION), - REGION(DiscoveryConstant.REGION, DiscoveryConstant.REGION), - ADDRESS(DiscoveryConstant.ADDRESS, DiscoveryConstant.ADDRESS), - VERSION_WEIGHT(DiscoveryConstant.VERSION_WEIGHT, DiscoveryConstant.VERSION_WEIGHT), - REGION_WEIGHT(DiscoveryConstant.REGION_WEIGHT, DiscoveryConstant.REGION_WEIGHT); - - private String value; - private String description; - - private StrategyType(String value, String description) { - this.value = value; - this.description = description; - } - - public String getValue() { - return value; - } - - public String getDescription() { - return description; - } - - public static StrategyType fromString(String value) { - for (StrategyType type : StrategyType.values()) { - if (type.getValue().equalsIgnoreCase(value)) { - return type; - } - } - - throw new IllegalArgumentException("No matched type with value=" + value); - } - - @Override - public String toString() { - return value; - } -} \ No newline at end of file diff --git a/discovery-common/src/main/java/com/nepxion/discovery/common/entity/WeightEntityWrapper.java b/discovery-common/src/main/java/com/nepxion/discovery/common/entity/WeightEntityWrapper.java deleted file mode 100644 index 232076c635..0000000000 --- a/discovery-common/src/main/java/com/nepxion/discovery/common/entity/WeightEntityWrapper.java +++ /dev/null @@ -1,107 +0,0 @@ -package com.nepxion.discovery.common.entity; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import org.apache.commons.collections4.CollectionUtils; -import org.apache.commons.collections4.MapUtils; -import org.apache.commons.lang3.StringUtils; - -import com.nepxion.discovery.common.constant.DiscoveryConstant; -import com.nepxion.discovery.common.util.JsonUtil; -import com.nepxion.discovery.common.util.StringUtil; - -public class WeightEntityWrapper { - @SuppressWarnings("unchecked") - public static List parseWeightEntityList(String weightValue) { - List weightEntityList = new ArrayList(); - - Map jsonWeightMap = JsonUtil.fromJson(weightValue, Map.class); - for (Map.Entry entry : jsonWeightMap.entrySet()) { - String providerServiceName = entry.getKey(); - String providerWeightValue = entry.getValue(); - - WeightEntity weightEntity = new WeightEntity(); - weightEntity.setProviderServiceName(providerServiceName); - - parseWeightEntity(weightEntity, providerWeightValue); - - weightEntityList.add(weightEntity); - } - - return weightEntityList; - } - - public static void parseWeightEntity(MapWeightEntity weightEntity, String weightValue) { - Map weightMap = weightEntity.getWeightMap(); - List providerWeightValueList = StringUtil.splitToList(weightValue, DiscoveryConstant.SEPARATE); - for (String value : providerWeightValueList) { - String[] valueArray = StringUtils.split(value, DiscoveryConstant.EQUALS); - String key = valueArray[0].trim(); - int weight = 0; - try { - weight = Integer.valueOf(valueArray[1].trim()); - if (weight < 0) { - weight = 0; - } - } catch (NumberFormatException e) { - - } - - weightMap.put(key, weight); - } - } - - public static int getWeight(String consumerServiceId, String providerServiceId, String providerKey, Map> weightEntityMap) { - if (MapUtils.isEmpty(weightEntityMap)) { - return -1; - } - - List weightEntityList = weightEntityMap.get(consumerServiceId); - - return getWeight(providerServiceId, providerKey, weightEntityList); - } - - public static int getWeight(String providerServiceId, String providerKey, List weightEntityList) { - if (CollectionUtils.isEmpty(weightEntityList)) { - return -1; - } - - for (WeightEntity weightEntity : weightEntityList) { - String providerServiceName = weightEntity.getProviderServiceName(); - if (StringUtils.equalsIgnoreCase(providerServiceName, providerServiceId)) { - return getWeight(providerKey, weightEntity); - } - } - - return -1; - } - - public static int getWeight(String providerKey, MapWeightEntity weightEntity) { - if (weightEntity == null) { - return -1; - } - - Map weightMap = weightEntity.getWeightMap(); - if (MapUtils.isEmpty(weightMap)) { - return -1; - } - - Integer weight = weightMap.get(providerKey); - if (weight != null) { - return weight; - } else { - return -1; - } - } -} \ No newline at end of file diff --git a/discovery-common/src/main/java/com/nepxion/discovery/common/entity/WeightType.java b/discovery-common/src/main/java/com/nepxion/discovery/common/entity/WeightType.java deleted file mode 100644 index a8b51b9865..0000000000 --- a/discovery-common/src/main/java/com/nepxion/discovery/common/entity/WeightType.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.nepxion.discovery.common.entity; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import com.nepxion.discovery.common.constant.DiscoveryConstant; - -public enum WeightType { - VERSION(DiscoveryConstant.VERSION, DiscoveryConstant.VERSION), - REGION(DiscoveryConstant.REGION, DiscoveryConstant.REGION); - - private String value; - private String description; - - private WeightType(String value, String description) { - this.value = value; - this.description = description; - } - - public String getValue() { - return value; - } - - public String getDescription() { - return description; - } - - public static WeightType fromString(String value) { - for (WeightType type : WeightType.values()) { - if (type.getValue().equalsIgnoreCase(value)) { - return type; - } - } - - throw new IllegalArgumentException("No matched type with value=" + value); - } - - @Override - public String toString() { - return value; - } -} \ No newline at end of file diff --git a/discovery-common/src/main/java/com/nepxion/discovery/common/handler/RestErrorHandler.java b/discovery-common/src/main/java/com/nepxion/discovery/common/handler/RestErrorHandler.java deleted file mode 100644 index 8446fcdc64..0000000000 --- a/discovery-common/src/main/java/com/nepxion/discovery/common/handler/RestErrorHandler.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.nepxion.discovery.common.handler; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import java.io.IOException; -import java.io.InputStream; - -import org.apache.commons.io.IOUtils; -import org.springframework.http.client.ClientHttpResponse; -import org.springframework.web.client.DefaultResponseErrorHandler; - -import com.nepxion.discovery.common.constant.DiscoveryConstant; - -public class RestErrorHandler extends DefaultResponseErrorHandler { - private String cause; - - @Override - public void handleError(ClientHttpResponse response) throws IOException { - // 这里绝对不能关闭InputStream - InputStream inputStream = response.getBody(); - cause = IOUtils.toString(inputStream, DiscoveryConstant.ENCODING_UTF_8); - } - - public String getCause() { - return cause; - } -} \ No newline at end of file diff --git a/discovery-common/src/main/java/com/nepxion/discovery/common/thread/NamedThreadFactory.java b/discovery-common/src/main/java/com/nepxion/discovery/common/thread/NamedThreadFactory.java deleted file mode 100644 index 9acacb068c..0000000000 --- a/discovery-common/src/main/java/com/nepxion/discovery/common/thread/NamedThreadFactory.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.nepxion.discovery.common.thread; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import java.util.concurrent.ThreadFactory; -import java.util.concurrent.atomic.AtomicInteger; - -// Copy from Alibaba Sentinel project -public class NamedThreadFactory implements ThreadFactory { - private AtomicInteger count = new AtomicInteger(1); - private ThreadGroup group; - private String namePrefix; - private boolean daemon; - - public NamedThreadFactory(String namePrefix) { - this(namePrefix, false); - } - - public NamedThreadFactory(String namePrefix, boolean daemon) { - SecurityManager securityManager = System.getSecurityManager(); - this.group = securityManager != null ? securityManager.getThreadGroup() : Thread.currentThread().getThreadGroup(); - this.namePrefix = namePrefix; - this.daemon = daemon; - } - - @Override - public Thread newThread(Runnable runnable) { - Thread thread = new Thread(group, runnable, namePrefix + "-thread-" + count.getAndIncrement(), 0); - thread.setDaemon(daemon); - - return thread; - } -} \ No newline at end of file diff --git a/discovery-common/src/main/java/com/nepxion/discovery/common/util/JsonUtil.java b/discovery-common/src/main/java/com/nepxion/discovery/common/util/JsonUtil.java deleted file mode 100644 index 4df2e5eeb0..0000000000 --- a/discovery-common/src/main/java/com/nepxion/discovery/common/util/JsonUtil.java +++ /dev/null @@ -1,88 +0,0 @@ -package com.nepxion.discovery.common.util; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import java.io.IOException; - -import org.apache.commons.lang3.StringUtils; - -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.SerializerProvider; -import com.fasterxml.jackson.databind.ser.std.StdSerializer; - -public class JsonUtil { - private static ObjectMapper objectMapper; - - static { - objectMapper = new ObjectMapper(); - // objectMapper.getSerializerProvider().setNullKeySerializer(new NullKeySerializer()); - // objectMapper.setDateFormat(new SimpleDateFormat(DiscoveryConstant.DATE_FORMAT)); - } - - public static class NullKeySerializer extends StdSerializer { - private static final long serialVersionUID = -9176767187240330396L; - - public NullKeySerializer() { - this(null); - } - - public NullKeySerializer(Class object) { - super(object); - } - - @Override - public void serialize(Object value, JsonGenerator gen, SerializerProvider provider) throws IOException { - gen.writeFieldName(StringUtils.EMPTY); - } - } - - public static String toJson(T object) { - if (object == null) { - throw new IllegalArgumentException("Object is null"); - } - - try { - return objectMapper.writeValueAsString(object); - } catch (JsonProcessingException e) { - throw new IllegalArgumentException(e.getMessage(), e); - } - } - - public static T fromJson(String json, Class clazz) { - if (StringUtils.isEmpty(json)) { - throw new IllegalArgumentException("Json is null or empty"); - } - - try { - return objectMapper.readValue(json, clazz); - } catch (Exception e) { - throw new IllegalArgumentException(e.getMessage(), e); - } - } - - public static T fromJson(String json, TypeReference typeReference) { - if (StringUtils.isEmpty(json)) { - throw new IllegalArgumentException("Json is null or empty"); - } - - try { - return objectMapper.readValue(json, typeReference); - } catch (Exception e) { - throw new IllegalArgumentException(e.getMessage(), e); - } - } - - public static ObjectMapper getObjectMapper() { - return objectMapper; - } -} \ No newline at end of file diff --git a/discovery-common/src/main/java/com/nepxion/discovery/common/util/RestUtil.java b/discovery-common/src/main/java/com/nepxion/discovery/common/util/RestUtil.java deleted file mode 100644 index 94dc8ec6c7..0000000000 --- a/discovery-common/src/main/java/com/nepxion/discovery/common/util/RestUtil.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.nepxion.discovery.common.util; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import org.apache.commons.lang3.StringUtils; -import org.springframework.web.client.ResponseErrorHandler; -import org.springframework.web.client.RestTemplate; - -import com.fasterxml.jackson.core.type.TypeReference; -import com.nepxion.discovery.common.handler.RestErrorHandler; - -public class RestUtil { - public static T fromJson(RestTemplate restTemplate, String result, TypeReference typeReference) { - try { - return JsonUtil.fromJson(result, typeReference); - } catch (Exception e) { - String cause = getCause(restTemplate); - if (StringUtils.isNotEmpty(cause)) { - throw new IllegalArgumentException(cause); - } - - throw e; - } - } - - public static String getCause(RestTemplate restTemplate) { - ResponseErrorHandler responseErrorHandler = restTemplate.getErrorHandler(); - if (responseErrorHandler instanceof RestErrorHandler) { - RestErrorHandler errorHandler = (RestErrorHandler) responseErrorHandler; - - return errorHandler.getCause(); - } - - return null; - } -} \ No newline at end of file diff --git a/discovery-common/src/main/java/com/nepxion/discovery/common/util/StringUtil.java b/discovery-common/src/main/java/com/nepxion/discovery/common/util/StringUtil.java deleted file mode 100644 index c4672339ef..0000000000 --- a/discovery-common/src/main/java/com/nepxion/discovery/common/util/StringUtil.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.nepxion.discovery.common.util; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import java.util.Arrays; -import java.util.List; - -import org.apache.commons.lang3.StringUtils; - -public class StringUtil { - public static List splitToList(String value, String separate) { - if (StringUtils.isEmpty(value)) { - return null; - } - - String[] valueArray = StringUtils.split(value, separate); - - return Arrays.asList(valueArray); - } -} \ No newline at end of file diff --git a/discovery-commons/discovery-common-apollo/pom.xml b/discovery-commons/discovery-common-apollo/pom.xml new file mode 100644 index 0000000000..6fec8e711a --- /dev/null +++ b/discovery-commons/discovery-common-apollo/pom.xml @@ -0,0 +1,28 @@ + + + discovery-common-apollo + Nepxion Discovery Common Apollo + jar + 4.0.0 + Nepxion Discovery is a solution for Spring Cloud with blue green, gray, weight, limitation, circuit breaker, degrade, isolation, monitor, tracing, dye, failover, async agent + http://www.nepxion.com + + + com.nepxion + discovery-commons + 6.23.0 + + + + + ${project.groupId} + discovery-common + + + + com.ctrip.framework.apollo + apollo-client + + + \ No newline at end of file diff --git a/discovery-commons/discovery-common-apollo/src/main/java/com/nepxion/discovery/common/apollo/configuration/ApolloAutoConfiguration.java b/discovery-commons/discovery-common-apollo/src/main/java/com/nepxion/discovery/common/apollo/configuration/ApolloAutoConfiguration.java new file mode 100644 index 0000000000..95a128351f --- /dev/null +++ b/discovery-commons/discovery-common-apollo/src/main/java/com/nepxion/discovery/common/apollo/configuration/ApolloAutoConfiguration.java @@ -0,0 +1,53 @@ +package com.nepxion.discovery.common.apollo.configuration; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.env.Environment; + +import com.ctrip.framework.apollo.Config; +import com.ctrip.framework.apollo.ConfigService; +import com.nepxion.discovery.common.apollo.constant.ApolloConstant; +import com.nepxion.discovery.common.apollo.operation.ApolloOperation; + +@Configuration +public class ApolloAutoConfiguration { + @Autowired + private Environment environment; + + @Bean + @ConditionalOnMissingBean + public Config apolloConfig() { + String namespace = getNamespace(environment); + + return ConfigService.getConfig(namespace); + } + + @Bean + public ApolloOperation apolloOperation() { + return new ApolloOperation(); + } + + public static String getNamespace(Environment environment) { + String namespace = environment.getProperty(ApolloConstant.APOLLO_NAMESPACE); + if (StringUtils.isEmpty(namespace) || namespace.contains(ApolloConstant.SEPARATE)) { + namespace = environment.getProperty(ApolloConstant.APOLLO_BOOTSTRAP_NAMESPACES); + } + if (StringUtils.isEmpty(namespace) || namespace.contains(ApolloConstant.SEPARATE)) { + namespace = ApolloConstant.NAMESPACE_APPLICATION; + } + + return namespace; + } +} \ No newline at end of file diff --git a/discovery-commons/discovery-common-apollo/src/main/java/com/nepxion/discovery/common/apollo/constant/ApolloConstant.java b/discovery-commons/discovery-common-apollo/src/main/java/com/nepxion/discovery/common/apollo/constant/ApolloConstant.java new file mode 100644 index 0000000000..944f0bb0d0 --- /dev/null +++ b/discovery-commons/discovery-common-apollo/src/main/java/com/nepxion/discovery/common/apollo/constant/ApolloConstant.java @@ -0,0 +1,18 @@ +package com.nepxion.discovery.common.apollo.constant; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import com.ctrip.framework.apollo.core.ConfigConsts; + +public class ApolloConstant implements ConfigConsts { + public static final String APOLLO_BOOTSTRAP_NAMESPACES = "apollo.bootstrap.namespaces"; + public static final String APOLLO_NAMESPACE = "apollo.namespace"; + public static final String SEPARATE = ","; +} \ No newline at end of file diff --git a/discovery-commons/discovery-common-apollo/src/main/java/com/nepxion/discovery/common/apollo/operation/ApolloOperation.java b/discovery-commons/discovery-common-apollo/src/main/java/com/nepxion/discovery/common/apollo/operation/ApolloOperation.java new file mode 100644 index 0000000000..b1aaa4e924 --- /dev/null +++ b/discovery-commons/discovery-common-apollo/src/main/java/com/nepxion/discovery/common/apollo/operation/ApolloOperation.java @@ -0,0 +1,46 @@ +package com.nepxion.discovery.common.apollo.operation; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.springframework.beans.factory.annotation.Autowired; + +import com.ctrip.framework.apollo.Config; +import com.ctrip.framework.apollo.ConfigChangeListener; +import com.ctrip.framework.apollo.model.ConfigChange; +import com.ctrip.framework.apollo.model.ConfigChangeEvent; +import com.google.common.collect.Sets; + +public class ApolloOperation { + @Autowired + private Config apolloConfig; + + public String getConfig(String group, String serviceId) { + return apolloConfig.getProperty(group + "-" + serviceId, null); + } + + public ConfigChangeListener subscribeConfig(String group, String serviceId, ApolloSubscribeCallback apolloSubscribeCallback) { + ConfigChangeListener configChangeListener = new ConfigChangeListener() { + @Override + public void onChange(ConfigChangeEvent changeEvent) { + ConfigChange change = changeEvent.getChange(group + "-" + serviceId); + String config = change.getNewValue(); + apolloSubscribeCallback.callback(config); + } + }; + + apolloConfig.addChangeListener(configChangeListener, Sets.newHashSet(group + "-" + serviceId)); + + return configChangeListener; + } + + public void unsubscribeConfig(String group, String serviceId, ConfigChangeListener configChangeListener) { + apolloConfig.removeChangeListener(configChangeListener); + } +} \ No newline at end of file diff --git a/discovery-common-apollo/src/main/java/com/nepxion/discovery/common/apollo/operation/ApolloSubscribeCallback.java b/discovery-commons/discovery-common-apollo/src/main/java/com/nepxion/discovery/common/apollo/operation/ApolloSubscribeCallback.java similarity index 100% rename from discovery-common-apollo/src/main/java/com/nepxion/discovery/common/apollo/operation/ApolloSubscribeCallback.java rename to discovery-commons/discovery-common-apollo/src/main/java/com/nepxion/discovery/common/apollo/operation/ApolloSubscribeCallback.java diff --git a/discovery-commons/discovery-common-apollo/src/main/java/com/nepxion/discovery/common/apollo/proccessor/ApolloProcessor.java b/discovery-commons/discovery-common-apollo/src/main/java/com/nepxion/discovery/common/apollo/proccessor/ApolloProcessor.java new file mode 100644 index 0000000000..7140656275 --- /dev/null +++ b/discovery-commons/discovery-common-apollo/src/main/java/com/nepxion/discovery/common/apollo/proccessor/ApolloProcessor.java @@ -0,0 +1,90 @@ +package com.nepxion.discovery.common.apollo.proccessor; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import javax.annotation.PostConstruct; + +import org.springframework.beans.factory.annotation.Autowired; + +import com.ctrip.framework.apollo.ConfigChangeListener; +import com.nepxion.discovery.common.apollo.operation.ApolloOperation; +import com.nepxion.discovery.common.apollo.operation.ApolloSubscribeCallback; +import com.nepxion.discovery.common.entity.ConfigType; +import com.nepxion.discovery.common.processor.DiscoveryConfigProcessor; + +public abstract class ApolloProcessor extends DiscoveryConfigProcessor { + @Autowired + private ApolloOperation apolloOperation; + + private ConfigChangeListener configChangeListener; + + @PostConstruct + public void initialize() { + beforeInitialization(); + + String group = getGroup(); + String dataId = getDataId(); + + logSubscribeStarted(); + + try { + configChangeListener = apolloOperation.subscribeConfig(group, dataId, new ApolloSubscribeCallback() { + @Override + public void callback(String config) { + try { + callbackConfig(config); + } catch (Exception e) { + logCallbackFailed(e); + } + } + }); + } catch (Exception e) { + logSubscribeFailed(e); + } + + logGetStarted(); + + try { + String config = apolloOperation.getConfig(group, dataId); + if (config != null) { + callbackConfig(config); + } else { + logNotFound(); + } + } catch (Exception e) { + logGetFailed(e); + } + + afterInitialization(); + } + + @Override + public void destroy() { + if (configChangeListener == null) { + return; + } + + String group = getGroup(); + String dataId = getDataId(); + + logUnsubscribeStarted(); + + try { + apolloOperation.unsubscribeConfig(group, dataId, configChangeListener); + } catch (Exception e) { + logUnsubscribeFailed(e); + } + } + + @Override + public ConfigType getConfigType() { + return ConfigType.APOLLO; + } +} \ No newline at end of file diff --git a/discovery-commons/discovery-common-apollo/src/main/resources/META-INF/additional-spring-configuration-metadata.json b/discovery-commons/discovery-common-apollo/src/main/resources/META-INF/additional-spring-configuration-metadata.json new file mode 100644 index 0000000000..2ef842fcef --- /dev/null +++ b/discovery-commons/discovery-common-apollo/src/main/resources/META-INF/additional-spring-configuration-metadata.json @@ -0,0 +1,10 @@ +{ + "properties": [ + { + "name": "apollo.namespace", + "type": "java.lang.String", + "defaultValue": "application", + "description": "Apollo namespace." + } + ] +} \ No newline at end of file diff --git a/discovery-commons/discovery-common-apollo/src/main/resources/META-INF/spring.factories b/discovery-commons/discovery-common-apollo/src/main/resources/META-INF/spring.factories new file mode 100644 index 0000000000..825892edf0 --- /dev/null +++ b/discovery-commons/discovery-common-apollo/src/main/resources/META-INF/spring.factories @@ -0,0 +1,2 @@ +org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ +com.nepxion.discovery.common.apollo.configuration.ApolloAutoConfiguration \ No newline at end of file diff --git a/discovery-commons/discovery-common-consul/pom.xml b/discovery-commons/discovery-common-consul/pom.xml new file mode 100644 index 0000000000..a7cdc4836a --- /dev/null +++ b/discovery-commons/discovery-common-consul/pom.xml @@ -0,0 +1,28 @@ + + + discovery-common-consul + Nepxion Discovery Common Consul + jar + 4.0.0 + Nepxion Discovery is a solution for Spring Cloud with blue green, gray, weight, limitation, circuit breaker, degrade, isolation, monitor, tracing, dye, failover, async agent + http://www.nepxion.com + + + com.nepxion + discovery-commons + 6.23.0 + + + + + ${project.groupId} + discovery-common + + + + com.ecwid.consul + consul-api + + + \ No newline at end of file diff --git a/discovery-commons/discovery-common-consul/src/main/java/com/nepxion/discovery/common/consul/configuration/ConsulAutoConfiguration.java b/discovery-commons/discovery-common-consul/src/main/java/com/nepxion/discovery/common/consul/configuration/ConsulAutoConfiguration.java new file mode 100644 index 0000000000..347904dd20 --- /dev/null +++ b/discovery-commons/discovery-common-consul/src/main/java/com/nepxion/discovery/common/consul/configuration/ConsulAutoConfiguration.java @@ -0,0 +1,46 @@ +package com.nepxion.discovery.common.consul.configuration; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Congwei Xu + * @version 1.0 + */ + +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.env.Environment; + +import com.ecwid.consul.v1.ConsulClient; +import com.nepxion.discovery.common.consul.constant.ConsulConstant; +import com.nepxion.discovery.common.consul.operation.ConsulOperation; +import com.nepxion.discovery.common.exception.DiscoveryException; + +@Configuration +public class ConsulAutoConfiguration { + @Autowired + private Environment environment; + + @Bean + public ConsulOperation consulOperation() { + return new ConsulOperation(); + } + + @Bean + @ConditionalOnMissingBean + public ConsulClient consulClient() { + String consulHost = environment.getProperty(ConsulConstant.CONSUL_HOST); + if (StringUtils.isBlank(consulHost)) { + throw new DiscoveryException(ConsulConstant.CONSUL_HOST + " can't be null or empty"); + } + + int consulPort = environment.getProperty(ConsulConstant.CONSUL_PORT, Integer.class); + + return new ConsulClient(consulHost, consulPort); + } +} \ No newline at end of file diff --git a/discovery-commons/discovery-common-consul/src/main/java/com/nepxion/discovery/common/consul/constant/ConsulConstant.java b/discovery-commons/discovery-common-consul/src/main/java/com/nepxion/discovery/common/consul/constant/ConsulConstant.java new file mode 100644 index 0000000000..298c9317f0 --- /dev/null +++ b/discovery-commons/discovery-common-consul/src/main/java/com/nepxion/discovery/common/consul/constant/ConsulConstant.java @@ -0,0 +1,18 @@ +package com.nepxion.discovery.common.consul.constant; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Congwei Xu + * @version 1.0 + */ + +public class ConsulConstant { + public static final String CONSUL_HOST = "consul.host"; + public static final String CONSUL_PORT = "consul.port"; + public static final String CONSUL_TIMEOUT = "consul.timeout"; + public static final String CONSUL_TOKEN = "consul.token"; + public static final int CONSUL_DEFAULT_TIMEOUT = 1; +} \ No newline at end of file diff --git a/discovery-commons/discovery-common-consul/src/main/java/com/nepxion/discovery/common/consul/operation/ConsulListener.java b/discovery-commons/discovery-common-consul/src/main/java/com/nepxion/discovery/common/consul/operation/ConsulListener.java new file mode 100644 index 0000000000..4608dc838c --- /dev/null +++ b/discovery-commons/discovery-common-consul/src/main/java/com/nepxion/discovery/common/consul/operation/ConsulListener.java @@ -0,0 +1,82 @@ +package com.nepxion.discovery.common.consul.operation; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Congwei Xu + * @version 1.0 + */ + +import java.nio.charset.StandardCharsets; +import java.util.concurrent.TimeUnit; + +import com.ecwid.consul.v1.ConsulClient; +import com.ecwid.consul.v1.QueryParams; +import com.ecwid.consul.v1.Response; +import com.ecwid.consul.v1.kv.model.GetValue; + +public class ConsulListener implements Runnable { + private String group; + private String serviceId; + + private int timeout; + private String token; + + private ConsulClient consulClient; + private ConsulSubscribeCallback consulSubscribeCallback; + + private volatile long lastIndex; + private volatile boolean running = true; + + public ConsulListener(String group, String serviceId, int timeout, String token, ConsulClient consulClient, ConsulSubscribeCallback consulSubscribeCallback) { + this.group = group; + this.serviceId = serviceId; + this.timeout = timeout; + this.token = token; + this.consulClient = consulClient; + this.consulSubscribeCallback = consulSubscribeCallback; + + initialize(); + } + + private void initialize() { + Response response = consulClient.getKVValue(group + "-" + serviceId, token); + if (response != null) { + lastIndex = response.getConsulIndex(); + } + } + + @Override + public void run() { + while (running) { + Response response = consulClient.getKVValue(group + "-" + serviceId, token, new QueryParams(timeout, lastIndex)); + if (response == null) { + try { + TimeUnit.MILLISECONDS.sleep(timeout * 1000); + } catch (InterruptedException e) { + } + + continue; + } + + Long currentIndex = response.getConsulIndex(); + if (currentIndex == null || currentIndex <= lastIndex) { + continue; + } + lastIndex = currentIndex; + + GetValue getValue = response.getValue(); + if (getValue != null) { + String value = getValue.getDecodedValue(StandardCharsets.UTF_8); + + consulSubscribeCallback.callback(value); + } + } + } + + public void stop() { + running = false; + } +} \ No newline at end of file diff --git a/discovery-commons/discovery-common-consul/src/main/java/com/nepxion/discovery/common/consul/operation/ConsulOperation.java b/discovery-commons/discovery-common-consul/src/main/java/com/nepxion/discovery/common/consul/operation/ConsulOperation.java new file mode 100644 index 0000000000..4db10097cb --- /dev/null +++ b/discovery-commons/discovery-common-consul/src/main/java/com/nepxion/discovery/common/consul/operation/ConsulOperation.java @@ -0,0 +1,86 @@ +package com.nepxion.discovery.common.consul.operation; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Congwei Xu + * @version 1.0 + */ + +import java.nio.charset.StandardCharsets; +import java.util.concurrent.ExecutorService; + +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.env.Environment; + +import com.ecwid.consul.v1.ConsulClient; +import com.ecwid.consul.v1.Response; +import com.ecwid.consul.v1.kv.model.GetValue; +import com.nepxion.discovery.common.consul.constant.ConsulConstant; + +public class ConsulOperation { + @Autowired + private ConsulClient consulClient; + + @Autowired + private Environment environment; + + public String getConfig(String group, String serviceId) { + String token = getToken(); + + Response response = consulClient.getKVValue(group + "-" + serviceId, token); + if (response == null) { + return null; + } + + GetValue getValue = response.getValue(); + if (getValue == null) { + return null; + } + + return getValue.getDecodedValue(StandardCharsets.UTF_8); + } + + public boolean removeConfig(String group, String serviceId) { + String token = getToken(); + + consulClient.deleteKVValue(group + "-" + serviceId, token); + + return true; + } + + public boolean publishConfig(String group, String serviceId, String config) { + String token = getToken(); + + consulClient.setKVValue(group + "-" + serviceId, config, token, null); + + return true; + } + + public ConsulListener subscribeConfig(String group, String serviceId, ExecutorService executorService, ConsulSubscribeCallback consulSubscribeCallback) throws Exception { + int timeout = getTimeout(); + String token = getToken(); + + ConsulListener consulListener = new ConsulListener(group, serviceId, timeout, token, consulClient, consulSubscribeCallback); + executorService.submit(consulListener); + + return consulListener; + } + + public void unsubscribeConfig(String group, String serviceId, ConsulListener consulListener) throws Exception { + consulListener.stop(); + } + + private int getTimeout() { + return environment.getProperty(ConsulConstant.CONSUL_TIMEOUT, Integer.class, ConsulConstant.CONSUL_DEFAULT_TIMEOUT); + } + + private String getToken() { + String token = environment.getProperty(ConsulConstant.CONSUL_TOKEN, String.class); + + return StringUtils.isNotBlank(token) ? token : null; + } +} \ No newline at end of file diff --git a/discovery-commons/discovery-common-consul/src/main/java/com/nepxion/discovery/common/consul/operation/ConsulSubscribeCallback.java b/discovery-commons/discovery-common-consul/src/main/java/com/nepxion/discovery/common/consul/operation/ConsulSubscribeCallback.java new file mode 100644 index 0000000000..9331d918d4 --- /dev/null +++ b/discovery-commons/discovery-common-consul/src/main/java/com/nepxion/discovery/common/consul/operation/ConsulSubscribeCallback.java @@ -0,0 +1,14 @@ +package com.nepxion.discovery.common.consul.operation; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Congwei Xu + * @version 1.0 + */ + +public interface ConsulSubscribeCallback { + void callback(String config); +} \ No newline at end of file diff --git a/discovery-commons/discovery-common-consul/src/main/java/com/nepxion/discovery/common/consul/proccessor/ConsulProcessor.java b/discovery-commons/discovery-common-consul/src/main/java/com/nepxion/discovery/common/consul/proccessor/ConsulProcessor.java new file mode 100644 index 0000000000..52b40ce628 --- /dev/null +++ b/discovery-commons/discovery-common-consul/src/main/java/com/nepxion/discovery/common/consul/proccessor/ConsulProcessor.java @@ -0,0 +1,97 @@ +package com.nepxion.discovery.common.consul.proccessor; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.concurrent.ExecutorService; + +import javax.annotation.PostConstruct; + +import org.springframework.beans.factory.annotation.Autowired; + +import com.nepxion.discovery.common.consul.operation.ConsulListener; +import com.nepxion.discovery.common.consul.operation.ConsulOperation; +import com.nepxion.discovery.common.consul.operation.ConsulSubscribeCallback; +import com.nepxion.discovery.common.entity.ConfigType; +import com.nepxion.discovery.common.processor.DiscoveryConfigProcessor; +import com.nepxion.discovery.common.thread.DiscoveryThreadPoolFactory; + +public abstract class ConsulProcessor extends DiscoveryConfigProcessor { + private ExecutorService executorService = DiscoveryThreadPoolFactory.getExecutorService("consul-config"); + + @Autowired + private ConsulOperation consulOperation; + + private ConsulListener consulListener; + + @PostConstruct + public void initialize() { + beforeInitialization(); + + String group = getGroup(); + String dataId = getDataId(); + + logSubscribeStarted(); + + try { + consulListener = consulOperation.subscribeConfig(group, dataId, executorService, new ConsulSubscribeCallback() { + @Override + public void callback(String config) { + try { + callbackConfig(config); + } catch (Exception e) { + logCallbackFailed(e); + } + } + }); + } catch (Exception e) { + logSubscribeFailed(e); + } + + logGetStarted(); + + try { + String config = consulOperation.getConfig(group, dataId); + if (config != null) { + callbackConfig(config); + } else { + logNotFound(); + } + } catch (Exception e) { + logGetFailed(e); + } + + afterInitialization(); + } + + @Override + public void destroy() { + if (consulListener == null) { + return; + } + + String group = getGroup(); + String dataId = getDataId(); + + logUnsubscribeStarted(); + + try { + consulOperation.unsubscribeConfig(group, dataId, consulListener); + } catch (Exception e) { + logUnsubscribeFailed(e); + } + + executorService.shutdownNow(); + } + + @Override + public ConfigType getConfigType() { + return ConfigType.CONSUL; + } +} \ No newline at end of file diff --git a/discovery-commons/discovery-common-consul/src/main/resources/META-INF/additional-spring-configuration-metadata.json b/discovery-commons/discovery-common-consul/src/main/resources/META-INF/additional-spring-configuration-metadata.json new file mode 100644 index 0000000000..95554f3e2c --- /dev/null +++ b/discovery-commons/discovery-common-consul/src/main/resources/META-INF/additional-spring-configuration-metadata.json @@ -0,0 +1,25 @@ +{ + "properties": [ + { + "name": "consul.host", + "type": "java.lang.String", + "description": "Consul host." + }, + { + "name": "consul.port", + "type": "java.lang.Integer", + "description": "Consul port." + }, + { + "name": "consul.timeout", + "type": "java.lang.Integer", + "defaultValue": 1, + "description": "Consul timeout, default value is 1 second." + }, + { + "name": "consul.token", + "type": "java.lang.String", + "description": "Consul token." + } + ] +} \ No newline at end of file diff --git a/discovery-commons/discovery-common-consul/src/main/resources/META-INF/spring.factories b/discovery-commons/discovery-common-consul/src/main/resources/META-INF/spring.factories new file mode 100644 index 0000000000..119a08ed9a --- /dev/null +++ b/discovery-commons/discovery-common-consul/src/main/resources/META-INF/spring.factories @@ -0,0 +1,2 @@ +org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ +com.nepxion.discovery.common.consul.configuration.ConsulAutoConfiguration \ No newline at end of file diff --git a/discovery-commons/discovery-common-etcd/pom.xml b/discovery-commons/discovery-common-etcd/pom.xml new file mode 100644 index 0000000000..adceaa382c --- /dev/null +++ b/discovery-commons/discovery-common-etcd/pom.xml @@ -0,0 +1,28 @@ + + + discovery-common-etcd + Nepxion Discovery Common Etcd + jar + 4.0.0 + Nepxion Discovery is a solution for Spring Cloud with blue green, gray, weight, limitation, circuit breaker, degrade, isolation, monitor, tracing, dye, failover, async agent + http://www.nepxion.com + + + com.nepxion + discovery-commons + 6.23.0 + + + + + ${project.groupId} + discovery-common + + + + io.etcd + jetcd-core + + + \ No newline at end of file diff --git a/discovery-commons/discovery-common-etcd/src/main/java/com/nepxion/discovery/common/etcd/configuration/EtcdAutoConfiguration.java b/discovery-commons/discovery-common-etcd/src/main/java/com/nepxion/discovery/common/etcd/configuration/EtcdAutoConfiguration.java new file mode 100644 index 0000000000..a28d47ff36 --- /dev/null +++ b/discovery-commons/discovery-common-etcd/src/main/java/com/nepxion/discovery/common/etcd/configuration/EtcdAutoConfiguration.java @@ -0,0 +1,62 @@ +package com.nepxion.discovery.common.etcd.configuration; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Congwei Xu + * @version 1.0 + */ + +import io.etcd.jetcd.ByteSequence; +import io.etcd.jetcd.Client; +import io.etcd.jetcd.ClientBuilder; + +import java.nio.charset.StandardCharsets; + +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.env.Environment; + +import com.nepxion.discovery.common.etcd.constant.EtcdConstant; +import com.nepxion.discovery.common.etcd.operation.EtcdOperation; +import com.nepxion.discovery.common.exception.DiscoveryException; + +@Configuration +public class EtcdAutoConfiguration { + @Autowired + private Environment environment; + + @Bean + public EtcdOperation etcdOperation() { + return new EtcdOperation(); + } + + @Bean + @ConditionalOnMissingBean + public Client client() { + String serverAddr = environment.getProperty(EtcdConstant.ETCD_SERVER_ADDR); + if (StringUtils.isBlank(serverAddr)) { + throw new DiscoveryException(EtcdConstant.ETCD_SERVER_ADDR + " can't be null or empty"); + } + + ClientBuilder clientBuilder = Client.builder().endpoints(serverAddr); + + String username = environment.getProperty(EtcdConstant.ETCD_USERNAME); + if (StringUtils.isNotBlank(username)) { + clientBuilder.user(ByteSequence.from(username, StandardCharsets.UTF_8)); + } + + String password = environment.getProperty(EtcdConstant.ETCD_PASSWORD); + if (StringUtils.isNotBlank(password)) { + clientBuilder.password(ByteSequence.from(password, StandardCharsets.UTF_8)); + } + clientBuilder.loadBalancerPolicy(EtcdConstant.ETCD_CLIENT_ROUND_ROBIN); + + return clientBuilder.build(); + } +} \ No newline at end of file diff --git a/discovery-commons/discovery-common-etcd/src/main/java/com/nepxion/discovery/common/etcd/constant/EtcdConstant.java b/discovery-commons/discovery-common-etcd/src/main/java/com/nepxion/discovery/common/etcd/constant/EtcdConstant.java new file mode 100644 index 0000000000..7114bc5510 --- /dev/null +++ b/discovery-commons/discovery-common-etcd/src/main/java/com/nepxion/discovery/common/etcd/constant/EtcdConstant.java @@ -0,0 +1,17 @@ +package com.nepxion.discovery.common.etcd.constant; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Congwei Xu + * @version 1.0 + */ + +public class EtcdConstant { + public static final String ETCD_SERVER_ADDR = "etcd.server.addr"; + public static final String ETCD_USERNAME = "etcd.username"; + public static final String ETCD_PASSWORD = "etcd.password"; + public static final String ETCD_CLIENT_ROUND_ROBIN = "round_robin"; +} \ No newline at end of file diff --git a/discovery-commons/discovery-common-etcd/src/main/java/com/nepxion/discovery/common/etcd/operation/EtcdOperation.java b/discovery-commons/discovery-common-etcd/src/main/java/com/nepxion/discovery/common/etcd/operation/EtcdOperation.java new file mode 100644 index 0000000000..e528fe58f4 --- /dev/null +++ b/discovery-commons/discovery-common-etcd/src/main/java/com/nepxion/discovery/common/etcd/operation/EtcdOperation.java @@ -0,0 +1,117 @@ +package com.nepxion.discovery.common.etcd.operation; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Congwei Xu + * @version 1.0 + */ + +import io.etcd.jetcd.ByteSequence; +import io.etcd.jetcd.Client; +import io.etcd.jetcd.KV; +import io.etcd.jetcd.KeyValue; +import io.etcd.jetcd.Watch; +import io.etcd.jetcd.Watch.Listener; +import io.etcd.jetcd.kv.GetResponse; +import io.etcd.jetcd.watch.WatchEvent; +import io.etcd.jetcd.watch.WatchEvent.EventType; +import io.etcd.jetcd.watch.WatchResponse; + +import java.nio.charset.StandardCharsets; +import java.util.concurrent.ExecutionException; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.DisposableBean; +import org.springframework.beans.factory.annotation.Autowired; + +public class EtcdOperation implements DisposableBean { + private static final Logger LOG = LoggerFactory.getLogger(EtcdOperation.class); + + @Autowired + private Client client; + + public String getConfig(String group, String serviceId) throws ExecutionException, InterruptedException { + ByteSequence byteSequence = ByteSequence.from(group + "-" + serviceId, StandardCharsets.UTF_8); + + KV kvClient = client.getKVClient(); + GetResponse getResponse = kvClient.get(byteSequence).get(); + if (getResponse.getKvs().size() > 0) { + KeyValue keyValue = getResponse.getKvs().get(0); + + return keyValue.getValue().toString(StandardCharsets.UTF_8); + } + + return null; + } + + public boolean removeConfig(String group, String serviceId) throws ExecutionException, InterruptedException { + ByteSequence byteSequence = ByteSequence.from(group + "-" + serviceId, StandardCharsets.UTF_8); + + KV kvClient = client.getKVClient(); + kvClient.delete(byteSequence); + + return true; + } + + public boolean publishConfig(String group, String serviceId, String config) throws ExecutionException, InterruptedException { + ByteSequence keyByteSequence = ByteSequence.from(group + "-" + serviceId, StandardCharsets.UTF_8); + ByteSequence valueByteSequence = ByteSequence.from(config, StandardCharsets.UTF_8); + + KV kvClient = client.getKVClient(); + kvClient.put(keyByteSequence, valueByteSequence); + + return true; + } + + public Watch subscribeConfig(String group, String serviceId, EtcdSubscribeCallback etcdSubscribeCallback) throws Exception { + ByteSequence byteSequence = ByteSequence.from(group + "-" + serviceId, StandardCharsets.UTF_8); + + Watch watchClient = client.getWatchClient(); + Listener listener = new Listener() { + @Override + public void onNext(WatchResponse response) { + for (WatchEvent event : response.getEvents()) { + EventType eventType = event.getEventType(); + if (eventType == EventType.PUT) { + KeyValue keyValue = event.getKeyValue(); + if (keyValue != null) { + String config = keyValue.getValue().toString(StandardCharsets.UTF_8); + + etcdSubscribeCallback.callback(config); + } + } else if (eventType == EventType.DELETE) { + etcdSubscribeCallback.callback(null); + } + } + } + + @Override + public void onError(Throwable throwable) { + + } + + @Override + public void onCompleted() { + + } + }; + watchClient.watch(byteSequence, listener); + + return watchClient; + } + + public void unsubscribeConfig(String group, String serviceId, Watch watchClient) { + watchClient.close(); + } + + @Override + public void destroy() throws Exception { + client.close(); + + LOG.info("Shutting down JEtcd client..."); + } +} \ No newline at end of file diff --git a/discovery-commons/discovery-common-etcd/src/main/java/com/nepxion/discovery/common/etcd/operation/EtcdSubscribeCallback.java b/discovery-commons/discovery-common-etcd/src/main/java/com/nepxion/discovery/common/etcd/operation/EtcdSubscribeCallback.java new file mode 100644 index 0000000000..0992f7b8d9 --- /dev/null +++ b/discovery-commons/discovery-common-etcd/src/main/java/com/nepxion/discovery/common/etcd/operation/EtcdSubscribeCallback.java @@ -0,0 +1,14 @@ +package com.nepxion.discovery.common.etcd.operation; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Congwei Xu + * @version 1.0 + */ + +public interface EtcdSubscribeCallback { + void callback(String config); +} \ No newline at end of file diff --git a/discovery-commons/discovery-common-etcd/src/main/java/com/nepxion/discovery/common/etcd/proccessor/EtcdProcessor.java b/discovery-commons/discovery-common-etcd/src/main/java/com/nepxion/discovery/common/etcd/proccessor/EtcdProcessor.java new file mode 100644 index 0000000000..d5d926b758 --- /dev/null +++ b/discovery-commons/discovery-common-etcd/src/main/java/com/nepxion/discovery/common/etcd/proccessor/EtcdProcessor.java @@ -0,0 +1,91 @@ +package com.nepxion.discovery.common.etcd.proccessor; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import io.etcd.jetcd.Watch; + +import javax.annotation.PostConstruct; + +import org.springframework.beans.factory.annotation.Autowired; + +import com.nepxion.discovery.common.entity.ConfigType; +import com.nepxion.discovery.common.etcd.operation.EtcdOperation; +import com.nepxion.discovery.common.etcd.operation.EtcdSubscribeCallback; +import com.nepxion.discovery.common.processor.DiscoveryConfigProcessor; + +public abstract class EtcdProcessor extends DiscoveryConfigProcessor { + @Autowired + private EtcdOperation etcdOperation; + + private Watch watchClient; + + @PostConstruct + public void initialize() { + beforeInitialization(); + + String group = getGroup(); + String dataId = getDataId(); + + logSubscribeStarted(); + + try { + watchClient = etcdOperation.subscribeConfig(group, dataId, new EtcdSubscribeCallback() { + @Override + public void callback(String config) { + try { + callbackConfig(config); + } catch (Exception e) { + logCallbackFailed(e); + } + } + }); + } catch (Exception e) { + logSubscribeFailed(e); + } + + logGetStarted(); + + try { + String config = etcdOperation.getConfig(group, dataId); + if (config != null) { + callbackConfig(config); + } else { + logNotFound(); + } + } catch (Exception e) { + logGetFailed(e); + } + + afterInitialization(); + } + + @Override + public void destroy() { + if (watchClient == null) { + return; + } + + String group = getGroup(); + String dataId = getDataId(); + + logUnsubscribeStarted(); + + try { + etcdOperation.unsubscribeConfig(group, dataId, watchClient); + } catch (Exception e) { + logUnsubscribeFailed(e); + } + } + + @Override + public ConfigType getConfigType() { + return ConfigType.ETCD; + } +} \ No newline at end of file diff --git a/discovery-commons/discovery-common-etcd/src/main/resources/META-INF/additional-spring-configuration-metadata.json b/discovery-commons/discovery-common-etcd/src/main/resources/META-INF/additional-spring-configuration-metadata.json new file mode 100644 index 0000000000..34a5117897 --- /dev/null +++ b/discovery-commons/discovery-common-etcd/src/main/resources/META-INF/additional-spring-configuration-metadata.json @@ -0,0 +1,19 @@ +{ + "properties": [ + { + "name": "etcd.server.addr", + "type": "java.lang.String", + "description": "Etcd server address." + }, + { + "name": "etcd.username", + "type": "java.lang.String", + "description": "Etcd username." + }, + { + "name": "etcd.password", + "type": "java.lang.String", + "description": "Etcd password." + } + ] +} \ No newline at end of file diff --git a/discovery-commons/discovery-common-etcd/src/main/resources/META-INF/spring.factories b/discovery-commons/discovery-common-etcd/src/main/resources/META-INF/spring.factories new file mode 100644 index 0000000000..c21ff998c1 --- /dev/null +++ b/discovery-commons/discovery-common-etcd/src/main/resources/META-INF/spring.factories @@ -0,0 +1,2 @@ +org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ +com.nepxion.discovery.common.etcd.configuration.EtcdAutoConfiguration \ No newline at end of file diff --git a/discovery-commons/discovery-common-nacos/pom.xml b/discovery-commons/discovery-common-nacos/pom.xml new file mode 100644 index 0000000000..6a1b4be49c --- /dev/null +++ b/discovery-commons/discovery-common-nacos/pom.xml @@ -0,0 +1,33 @@ + + + discovery-common-nacos + Nepxion Discovery Common Nacos + jar + 4.0.0 + Nepxion Discovery is a solution for Spring Cloud with blue green, gray, weight, limitation, circuit breaker, degrade, isolation, monitor, tracing, dye, failover, async agent + http://www.nepxion.com + + + com.nepxion + discovery-commons + 6.23.0 + + + + + ${project.groupId} + discovery-common + + + + com.alibaba.nacos + nacos-client + + + + com.alibaba.spring + spring-context-support + + + \ No newline at end of file diff --git a/discovery-commons/discovery-common-nacos/src/main/java/com/nepxion/discovery/common/nacos/configuration/NacosAutoConfiguration.java b/discovery-commons/discovery-common-nacos/src/main/java/com/nepxion/discovery/common/nacos/configuration/NacosAutoConfiguration.java new file mode 100644 index 0000000000..70ea074393 --- /dev/null +++ b/discovery-commons/discovery-common-nacos/src/main/java/com/nepxion/discovery/common/nacos/configuration/NacosAutoConfiguration.java @@ -0,0 +1,58 @@ +package com.nepxion.discovery.common.nacos.configuration; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.Properties; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.env.Environment; + +import com.alibaba.nacos.api.NacosFactory; +import com.alibaba.nacos.api.config.ConfigService; +import com.alibaba.nacos.api.exception.NacosException; +import com.nepxion.discovery.common.nacos.constant.NacosConstant; +import com.nepxion.discovery.common.nacos.operation.NacosOperation; +import com.nepxion.discovery.common.util.PropertiesUtil; + +@Configuration +public class NacosAutoConfiguration { + @Autowired + private Environment environment; + + @Bean + @ConditionalOnMissingBean + public ConfigService nacosConfigService() throws NacosException { + Properties properties = createNacosProperties(environment, true); + + return NacosFactory.createConfigService(properties); + } + + @Bean + public NacosOperation nacosOperation() { + return new NacosOperation(); + } + + public static Properties createNacosProperties(Environment environment, boolean enableRemoteSyncConfig) { + Properties properties = new Properties(); + + // 支持从spring.cloud.nacos.config前缀方式获取 + PropertiesUtil.enrichProperties(properties, environment, NacosConstant.SPRING_CLOUD_NACOS_CONFIG_PREFIX, true, true); + + // 支持从nacos前缀方式获取 + PropertiesUtil.enrichProperties(properties, environment, NacosConstant.NACOS_PREFIX, true, true); + + properties.put(NacosConstant.ENABLE_REMOTE_SYNC_CONFIG, Boolean.toString(enableRemoteSyncConfig)); + + return properties; + } +} \ No newline at end of file diff --git a/discovery-commons/discovery-common-nacos/src/main/java/com/nepxion/discovery/common/nacos/constant/NacosConstant.java b/discovery-commons/discovery-common-nacos/src/main/java/com/nepxion/discovery/common/nacos/constant/NacosConstant.java new file mode 100644 index 0000000000..70fcc75176 --- /dev/null +++ b/discovery-commons/discovery-common-nacos/src/main/java/com/nepxion/discovery/common/nacos/constant/NacosConstant.java @@ -0,0 +1,22 @@ +package com.nepxion.discovery.common.nacos.constant; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import com.alibaba.nacos.api.PropertyKeyConst; + +public class NacosConstant extends PropertyKeyConst { + public static final String NACOS_PREFIX = "nacos"; + public static final String NACOS_TIMEOUT = "nacos.timout"; + + public static final String SPRING_CLOUD_NACOS_CONFIG_PREFIX = "spring.cloud.nacos.config"; + public static final String SPRING_CLOUD_NACOS_CONFIG_TIMEOUT = "spring.cloud.nacos.config.timout"; + + public static final long NACOS_DEFAULT_TIMEOUT = 30000; +} \ No newline at end of file diff --git a/discovery-commons/discovery-common-nacos/src/main/java/com/nepxion/discovery/common/nacos/operation/NacosOperation.java b/discovery-commons/discovery-common-nacos/src/main/java/com/nepxion/discovery/common/nacos/operation/NacosOperation.java new file mode 100644 index 0000000000..dce569a69e --- /dev/null +++ b/discovery-commons/discovery-common-nacos/src/main/java/com/nepxion/discovery/common/nacos/operation/NacosOperation.java @@ -0,0 +1,85 @@ +package com.nepxion.discovery.common.nacos.operation; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.concurrent.Executor; + +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.DisposableBean; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.env.Environment; + +import com.alibaba.nacos.api.config.ConfigService; +import com.alibaba.nacos.api.config.listener.Listener; +import com.alibaba.nacos.api.exception.NacosException; +import com.nepxion.discovery.common.entity.FormatType; +import com.nepxion.discovery.common.nacos.constant.NacosConstant; + +public class NacosOperation implements DisposableBean { + private static final Logger LOG = LoggerFactory.getLogger(NacosOperation.class); + + @Autowired + private ConfigService nacosConfigService; + + @Autowired + private Environment environment; + + public String getConfig(String group, String serviceId) throws NacosException { + String timeout = environment.getProperty(NacosConstant.NACOS_TIMEOUT); + if (StringUtils.isEmpty(timeout)) { + timeout = environment.getProperty(NacosConstant.SPRING_CLOUD_NACOS_CONFIG_TIMEOUT); + } + + return nacosConfigService.getConfig(serviceId, group, StringUtils.isNotEmpty(timeout) ? Long.valueOf(timeout) : NacosConstant.NACOS_DEFAULT_TIMEOUT); + } + + public boolean removeConfig(String group, String serviceId) throws NacosException { + return nacosConfigService.removeConfig(serviceId, group); + } + + public boolean publishConfig(String group, String serviceId, String config) throws NacosException { + return nacosConfigService.publishConfig(serviceId, group, config); + } + + public boolean publishConfig(String group, String serviceId, String config, FormatType formatType) throws NacosException { + return nacosConfigService.publishConfig(serviceId, group, config, formatType.toString()); + } + + public Listener subscribeConfig(String group, String serviceId, Executor executor, NacosSubscribeCallback nacosSubscribeCallback) throws NacosException { + Listener listener = new Listener() { + @Override + public void receiveConfigInfo(String config) { + nacosSubscribeCallback.callback(config); + } + + @Override + public Executor getExecutor() { + return executor; + } + }; + + nacosConfigService.addListener(serviceId, group, listener); + + return listener; + } + + public void unsubscribeConfig(String group, String serviceId, Listener listener) { + nacosConfigService.removeListener(serviceId, group, listener); + } + + @Override + public void destroy() throws Exception { + nacosConfigService.shutDown(); + + LOG.info("Shutting down Nacos config service..."); + } +} \ No newline at end of file diff --git a/discovery-common-nacos/src/main/java/com/nepxion/discovery/common/nacos/operation/NacosSubscribeCallback.java b/discovery-commons/discovery-common-nacos/src/main/java/com/nepxion/discovery/common/nacos/operation/NacosSubscribeCallback.java similarity index 100% rename from discovery-common-nacos/src/main/java/com/nepxion/discovery/common/nacos/operation/NacosSubscribeCallback.java rename to discovery-commons/discovery-common-nacos/src/main/java/com/nepxion/discovery/common/nacos/operation/NacosSubscribeCallback.java diff --git a/discovery-commons/discovery-common-nacos/src/main/java/com/nepxion/discovery/common/nacos/proccessor/NacosProcessor.java b/discovery-commons/discovery-common-nacos/src/main/java/com/nepxion/discovery/common/nacos/proccessor/NacosProcessor.java new file mode 100644 index 0000000000..af14cc6603 --- /dev/null +++ b/discovery-commons/discovery-common-nacos/src/main/java/com/nepxion/discovery/common/nacos/proccessor/NacosProcessor.java @@ -0,0 +1,97 @@ +package com.nepxion.discovery.common.nacos.proccessor; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.concurrent.ExecutorService; + +import javax.annotation.PostConstruct; + +import org.springframework.beans.factory.annotation.Autowired; + +import com.alibaba.nacos.api.config.listener.Listener; +import com.nepxion.discovery.common.entity.ConfigType; +import com.nepxion.discovery.common.nacos.operation.NacosOperation; +import com.nepxion.discovery.common.nacos.operation.NacosSubscribeCallback; +import com.nepxion.discovery.common.processor.DiscoveryConfigProcessor; +import com.nepxion.discovery.common.thread.DiscoveryThreadPoolFactory; + +public abstract class NacosProcessor extends DiscoveryConfigProcessor { + private ExecutorService executorService = DiscoveryThreadPoolFactory.getExecutorService("nacos-config"); + + @Autowired + private NacosOperation nacosOperation; + + private Listener listener; + + @PostConstruct + public void initialize() { + beforeInitialization(); + + String group = getGroup(); + String dataId = getDataId(); + + logSubscribeStarted(); + + try { + listener = nacosOperation.subscribeConfig(group, dataId, executorService, new NacosSubscribeCallback() { + @Override + public void callback(String config) { + try { + callbackConfig(config); + } catch (Exception e) { + logCallbackFailed(e); + } + } + }); + } catch (Exception e) { + logSubscribeFailed(e); + } + + logGetStarted(); + + try { + String config = nacosOperation.getConfig(group, dataId); + if (config != null) { + callbackConfig(config); + } else { + logNotFound(); + } + } catch (Exception e) { + logGetFailed(e); + } + + afterInitialization(); + } + + @Override + public void destroy() { + if (listener == null) { + return; + } + + String group = getGroup(); + String dataId = getDataId(); + + logUnsubscribeStarted(); + + try { + nacosOperation.unsubscribeConfig(group, dataId, listener); + } catch (Exception e) { + logUnsubscribeFailed(e); + } + + executorService.shutdownNow(); + } + + @Override + public ConfigType getConfigType() { + return ConfigType.NACOS; + } +} \ No newline at end of file diff --git a/discovery-commons/discovery-common-nacos/src/main/resources/META-INF/additional-spring-configuration-metadata.json b/discovery-commons/discovery-common-nacos/src/main/resources/META-INF/additional-spring-configuration-metadata.json new file mode 100644 index 0000000000..63dbb1455d --- /dev/null +++ b/discovery-commons/discovery-common-nacos/src/main/resources/META-INF/additional-spring-configuration-metadata.json @@ -0,0 +1,16 @@ +{ + "properties": [ + { + "name": "nacos.timout", + "type": "java.lang.Integer", + "defaultValue": 30000, + "description": "Nacos timout." + }, + { + "name": "spring.cloud.nacos.config.timout", + "type": "java.lang.Integer", + "defaultValue": 30000, + "description": "Spring Cloud Nacos config timout." + } + ] +} \ No newline at end of file diff --git a/discovery-commons/discovery-common-nacos/src/main/resources/META-INF/spring.factories b/discovery-commons/discovery-common-nacos/src/main/resources/META-INF/spring.factories new file mode 100644 index 0000000000..5dace7e0d9 --- /dev/null +++ b/discovery-commons/discovery-common-nacos/src/main/resources/META-INF/spring.factories @@ -0,0 +1,2 @@ +org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ +com.nepxion.discovery.common.nacos.configuration.NacosAutoConfiguration \ No newline at end of file diff --git a/discovery-commons/discovery-common-redis/pom.xml b/discovery-commons/discovery-common-redis/pom.xml new file mode 100644 index 0000000000..1ad9538174 --- /dev/null +++ b/discovery-commons/discovery-common-redis/pom.xml @@ -0,0 +1,28 @@ + + + discovery-common-redis + Nepxion Discovery Common Redis + jar + 4.0.0 + Nepxion Discovery is a solution for Spring Cloud with blue green, gray, weight, limitation, circuit breaker, degrade, isolation, monitor, tracing, dye, failover, async agent + http://www.nepxion.com + + + com.nepxion + discovery-commons + 6.23.0 + + + + + ${project.groupId} + discovery-common + + + + org.springframework.boot + spring-boot-starter-data-redis + + + \ No newline at end of file diff --git a/discovery-commons/discovery-common-redis/src/main/java/com/nepxion/discovery/common/redis/configuration/RedisAutoConfiguration.java b/discovery-commons/discovery-common-redis/src/main/java/com/nepxion/discovery/common/redis/configuration/RedisAutoConfiguration.java new file mode 100644 index 0000000000..53a44f9890 --- /dev/null +++ b/discovery-commons/discovery-common-redis/src/main/java/com/nepxion/discovery/common/redis/configuration/RedisAutoConfiguration.java @@ -0,0 +1,48 @@ +package com.nepxion.discovery.common.redis.configuration; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @author JiKai Sun + * @version 1.0 + */ + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.redis.connection.RedisConnectionFactory; +import org.springframework.data.redis.core.HashOperations; +import org.springframework.data.redis.core.StringRedisTemplate; +import org.springframework.data.redis.listener.RedisMessageListenerContainer; + +import com.nepxion.discovery.common.redis.operation.RedisOperation; + +@Configuration +public class RedisAutoConfiguration { + @Autowired + private StringRedisTemplate stringRedisTemplate; + + @Autowired + private RedisConnectionFactory redisConnectionFactory; + + @Bean + public RedisMessageListenerContainer configMessageListenerContainer() { + RedisMessageListenerContainer configMessageListenerContainer = new RedisMessageListenerContainer(); + configMessageListenerContainer.setConnectionFactory(redisConnectionFactory); + + return configMessageListenerContainer; + } + + @Bean + public HashOperations hashOperations() { + return stringRedisTemplate.opsForHash(); + } + + @Bean + public RedisOperation redisOperation() { + return new RedisOperation(); + } +} \ No newline at end of file diff --git a/discovery-common-redis/src/main/java/com/nepxion/discovery/common/redis/constant/RedisConstant.java b/discovery-commons/discovery-common-redis/src/main/java/com/nepxion/discovery/common/redis/constant/RedisConstant.java similarity index 86% rename from discovery-common-redis/src/main/java/com/nepxion/discovery/common/redis/constant/RedisConstant.java rename to discovery-commons/discovery-common-redis/src/main/java/com/nepxion/discovery/common/redis/constant/RedisConstant.java index 84ff9722ef..06ca30bf46 100644 --- a/discovery-common-redis/src/main/java/com/nepxion/discovery/common/redis/constant/RedisConstant.java +++ b/discovery-commons/discovery-common-redis/src/main/java/com/nepxion/discovery/common/redis/constant/RedisConstant.java @@ -11,5 +11,5 @@ */ public class RedisConstant { - public static final String TYPE = "Redis"; + } \ No newline at end of file diff --git a/discovery-commons/discovery-common-redis/src/main/java/com/nepxion/discovery/common/redis/operation/RedisOperation.java b/discovery-commons/discovery-common-redis/src/main/java/com/nepxion/discovery/common/redis/operation/RedisOperation.java new file mode 100644 index 0000000000..68c8bf3d74 --- /dev/null +++ b/discovery-commons/discovery-common-redis/src/main/java/com/nepxion/discovery/common/redis/operation/RedisOperation.java @@ -0,0 +1,76 @@ +package com.nepxion.discovery.common.redis.operation; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @author JiKai Sun + * @version 1.0 + */ + +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.DisposableBean; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.redis.core.HashOperations; +import org.springframework.data.redis.core.StringRedisTemplate; +import org.springframework.data.redis.listener.PatternTopic; +import org.springframework.data.redis.listener.RedisMessageListenerContainer; +import org.springframework.data.redis.listener.adapter.MessageListenerAdapter; + +public class RedisOperation implements DisposableBean { + private static final Logger LOG = LoggerFactory.getLogger(RedisOperation.class); + + @Autowired + private StringRedisTemplate stringRedisTemplate; + + @Autowired + private HashOperations hashOperations; + + @Autowired + private RedisMessageListenerContainer configMessageListenerContainer; + + public String getConfig(String group, String serviceId) { + return hashOperations.get(group, serviceId); + } + + public boolean removeConfig(String group, String serviceId) { + publishConfig(group, serviceId, StringUtils.EMPTY); + + return hashOperations.delete(group, serviceId) == 1; + } + + public boolean publishConfig(String group, String serviceId, String config) { + hashOperations.put(group, serviceId, config); + stringRedisTemplate.convertAndSend(group + "-" + serviceId, config); + + return true; + } + + public MessageListenerAdapter subscribeConfig(String group, String serviceId, Object delegate, String listenerMethod) { + MessageListenerAdapter messageListenerAdapter = new MessageListenerAdapter(delegate, listenerMethod); + messageListenerAdapter.afterPropertiesSet(); + + configMessageListenerContainer.addMessageListener(messageListenerAdapter, new PatternTopic(group + "-" + serviceId)); + + return messageListenerAdapter; + } + + public void unsubscribeConfig(String group, String serviceId, MessageListenerAdapter messageListenerAdapter) { + configMessageListenerContainer.removeMessageListener(messageListenerAdapter, new PatternTopic(group + "-" + serviceId)); + } + + public void subscribeConfig(String config, RedisSubscribeCallback redisSubscribeCallback) { + redisSubscribeCallback.callback(config); + } + + @Override + public void destroy() throws Exception { + configMessageListenerContainer.destroy(); + + LOG.info("Shutting down Redis message listener..."); + } +} \ No newline at end of file diff --git a/discovery-common-redis/src/main/java/com/nepxion/discovery/common/redis/operation/RedisSubscribeCallback.java b/discovery-commons/discovery-common-redis/src/main/java/com/nepxion/discovery/common/redis/operation/RedisSubscribeCallback.java similarity index 100% rename from discovery-common-redis/src/main/java/com/nepxion/discovery/common/redis/operation/RedisSubscribeCallback.java rename to discovery-commons/discovery-common-redis/src/main/java/com/nepxion/discovery/common/redis/operation/RedisSubscribeCallback.java diff --git a/discovery-commons/discovery-common-redis/src/main/java/com/nepxion/discovery/common/redis/proccessor/RedisProcessor.java b/discovery-commons/discovery-common-redis/src/main/java/com/nepxion/discovery/common/redis/proccessor/RedisProcessor.java new file mode 100644 index 0000000000..435a32c653 --- /dev/null +++ b/discovery-commons/discovery-common-redis/src/main/java/com/nepxion/discovery/common/redis/proccessor/RedisProcessor.java @@ -0,0 +1,94 @@ +package com.nepxion.discovery.common.redis.proccessor; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import javax.annotation.PostConstruct; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.redis.listener.adapter.MessageListenerAdapter; + +import com.nepxion.discovery.common.entity.ConfigType; +import com.nepxion.discovery.common.processor.DiscoveryConfigProcessor; +import com.nepxion.discovery.common.redis.operation.RedisOperation; +import com.nepxion.discovery.common.redis.operation.RedisSubscribeCallback; + +public abstract class RedisProcessor extends DiscoveryConfigProcessor { + @Autowired + private RedisOperation redisOperation; + + private MessageListenerAdapter messageListenerAdapter; + + @PostConstruct + public void initialize() { + beforeInitialization(); + + String group = getGroup(); + String dataId = getDataId(); + + logSubscribeStarted(); + + try { + messageListenerAdapter = redisOperation.subscribeConfig(group, dataId, this, "subscribeConfig"); + } catch (Exception e) { + logSubscribeFailed(e); + } + + logGetStarted(); + + try { + String config = redisOperation.getConfig(group, dataId); + if (config != null) { + callbackConfig(config); + } else { + logNotFound(); + } + } catch (Exception e) { + logGetFailed(e); + } + + afterInitialization(); + } + + public void subscribeConfig(String config) { + redisOperation.subscribeConfig(config, new RedisSubscribeCallback() { + @Override + public void callback(String config) { + try { + callbackConfig(config); + } catch (Exception e) { + logCallbackFailed(e); + } + } + }); + } + + @Override + public void destroy() { + if (messageListenerAdapter == null) { + return; + } + + String group = getGroup(); + String dataId = getDataId(); + + logUnsubscribeStarted(); + + try { + redisOperation.unsubscribeConfig(group, dataId, messageListenerAdapter); + } catch (Exception e) { + logUnsubscribeFailed(e); + } + } + + @Override + public ConfigType getConfigType() { + return ConfigType.REDIS; + } +} \ No newline at end of file diff --git a/discovery-commons/discovery-common-redis/src/main/resources/META-INF/spring.factories b/discovery-commons/discovery-common-redis/src/main/resources/META-INF/spring.factories new file mode 100644 index 0000000000..fcedb94f7b --- /dev/null +++ b/discovery-commons/discovery-common-redis/src/main/resources/META-INF/spring.factories @@ -0,0 +1,2 @@ +org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ +com.nepxion.discovery.common.redis.configuration.RedisAutoConfiguration \ No newline at end of file diff --git a/discovery-commons/discovery-common-zookeeper/pom.xml b/discovery-commons/discovery-common-zookeeper/pom.xml new file mode 100644 index 0000000000..28313bea2c --- /dev/null +++ b/discovery-commons/discovery-common-zookeeper/pom.xml @@ -0,0 +1,33 @@ + + + discovery-common-zookeeper + Nepxion Discovery Common Zookeeper + jar + 4.0.0 + Nepxion Discovery is a solution for Spring Cloud with blue green, gray, weight, limitation, circuit breaker, degrade, isolation, monitor, tracing, dye, failover, async agent + http://www.nepxion.com + + + com.nepxion + discovery-commons + 6.23.0 + + + + + ${project.groupId} + discovery-common + + + + org.apache.curator + curator-framework + + + + org.apache.curator + curator-recipes + + + \ No newline at end of file diff --git a/discovery-commons/discovery-common-zookeeper/src/main/java/com/nepxion/discovery/common/zookeeper/configuration/ZookeeperAutoConfiguration.java b/discovery-commons/discovery-common-zookeeper/src/main/java/com/nepxion/discovery/common/zookeeper/configuration/ZookeeperAutoConfiguration.java new file mode 100644 index 0000000000..acb79e90c6 --- /dev/null +++ b/discovery-commons/discovery-common-zookeeper/src/main/java/com/nepxion/discovery/common/zookeeper/configuration/ZookeeperAutoConfiguration.java @@ -0,0 +1,52 @@ +package com.nepxion.discovery.common.zookeeper.configuration; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author rotten + * @version 1.0 + */ + +import org.apache.commons.lang3.StringUtils; +import org.apache.curator.framework.CuratorFramework; +import org.apache.curator.framework.CuratorFrameworkFactory; +import org.apache.curator.retry.ExponentialBackoffRetry; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.env.Environment; + +import com.nepxion.discovery.common.exception.DiscoveryException; +import com.nepxion.discovery.common.zookeeper.constant.ZookeeperConstant; +import com.nepxion.discovery.common.zookeeper.operation.ZookeeperOperation; + +@Configuration +public class ZookeeperAutoConfiguration { + @Autowired + private Environment environment; + + @Bean + public ZookeeperOperation zookeeperOperation() { + return new ZookeeperOperation(); + } + + @Bean + @ConditionalOnMissingBean + public CuratorFramework curatorFramework() { + String connectString = environment.getProperty(ZookeeperConstant.ZOOKEEPER_CONNECT_STRING); + if (StringUtils.isEmpty(connectString)) { + throw new DiscoveryException(ZookeeperConstant.ZOOKEEPER_CONNECT_STRING + " can't be null or empty"); + } + + int retryCount = environment.getProperty(ZookeeperConstant.ZOOKEEPER_RETRY_COUNT, Integer.class, ZookeeperConstant.ZOOKEEPER_DEFAULT_RETRY_COUNT_VALUE); + int sleepTime = environment.getProperty(ZookeeperConstant.ZOOKEEPER_SLEEP_TIME, Integer.class, ZookeeperConstant.ZOOKEEPER_DEFAULT_SLEEP_TIME_VALUE); + + CuratorFramework curatorFramework = CuratorFrameworkFactory.builder().connectString(connectString).retryPolicy(new ExponentialBackoffRetry(sleepTime, retryCount)).build(); + curatorFramework.start(); + + return curatorFramework; + } +} \ No newline at end of file diff --git a/discovery-commons/discovery-common-zookeeper/src/main/java/com/nepxion/discovery/common/zookeeper/constant/ZookeeperConstant.java b/discovery-commons/discovery-common-zookeeper/src/main/java/com/nepxion/discovery/common/zookeeper/constant/ZookeeperConstant.java new file mode 100644 index 0000000000..620e5967f2 --- /dev/null +++ b/discovery-commons/discovery-common-zookeeper/src/main/java/com/nepxion/discovery/common/zookeeper/constant/ZookeeperConstant.java @@ -0,0 +1,18 @@ +package com.nepxion.discovery.common.zookeeper.constant; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author rotten + * @version 1.0 + */ + +public class ZookeeperConstant { + public static final String ZOOKEEPER_CONNECT_STRING = "zookeeper.connect-string"; + public static final String ZOOKEEPER_RETRY_COUNT = "zookeeper.retry-count"; + public static final String ZOOKEEPER_SLEEP_TIME = "zookeeper.sleep-time"; + public static final int ZOOKEEPER_DEFAULT_RETRY_COUNT_VALUE = 3; + public static final int ZOOKEEPER_DEFAULT_SLEEP_TIME_VALUE = 3000; +} \ No newline at end of file diff --git a/discovery-commons/discovery-common-zookeeper/src/main/java/com/nepxion/discovery/common/zookeeper/operation/ZookeeperListener.java b/discovery-commons/discovery-common-zookeeper/src/main/java/com/nepxion/discovery/common/zookeeper/operation/ZookeeperListener.java new file mode 100644 index 0000000000..a7f5b6f922 --- /dev/null +++ b/discovery-commons/discovery-common-zookeeper/src/main/java/com/nepxion/discovery/common/zookeeper/operation/ZookeeperListener.java @@ -0,0 +1,42 @@ +package com.nepxion.discovery.common.zookeeper.operation; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.io.IOException; + +import org.apache.curator.framework.recipes.cache.NodeCache; +import org.apache.curator.framework.recipes.cache.NodeCacheListener; + +public class ZookeeperListener { + private NodeCache nodeCache; + private NodeCacheListener nodeCacheListener; + + public ZookeeperListener(NodeCache nodeCache, NodeCacheListener nodeCacheListener) { + this.nodeCache = nodeCache; + this.nodeCacheListener = nodeCacheListener; + } + + public NodeCache getNodeCache() { + return nodeCache; + } + + public NodeCacheListener getNodeCacheListener() { + return nodeCacheListener; + } + + public void addListener() { + nodeCache.getListenable().addListener(nodeCacheListener); + } + + public void removeListener() throws IOException { + nodeCache.getListenable().removeListener(nodeCacheListener); + nodeCache.close(); + } +} \ No newline at end of file diff --git a/discovery-commons/discovery-common-zookeeper/src/main/java/com/nepxion/discovery/common/zookeeper/operation/ZookeeperOperation.java b/discovery-commons/discovery-common-zookeeper/src/main/java/com/nepxion/discovery/common/zookeeper/operation/ZookeeperOperation.java new file mode 100644 index 0000000000..9b1feeabde --- /dev/null +++ b/discovery-commons/discovery-common-zookeeper/src/main/java/com/nepxion/discovery/common/zookeeper/operation/ZookeeperOperation.java @@ -0,0 +1,143 @@ +package com.nepxion.discovery.common.zookeeper.operation; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author rotten + * @author Haojun Ren + * @version 1.0 + */ + +import org.apache.curator.framework.CuratorFramework; +import org.apache.curator.framework.recipes.cache.ChildData; +import org.apache.curator.framework.recipes.cache.NodeCache; +import org.apache.curator.framework.recipes.cache.NodeCacheListener; +import org.apache.zookeeper.CreateMode; +import org.apache.zookeeper.data.Stat; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.DisposableBean; +import org.springframework.beans.factory.annotation.Autowired; + +public class ZookeeperOperation implements DisposableBean { + private static final Logger LOG = LoggerFactory.getLogger(ZookeeperOperation.class); + + @Autowired + private CuratorFramework curatorFramework; + + public String getConfig(String group, String serviceId) throws Exception { + String path = getPath(group, serviceId); + + boolean hasPath = hasPath(path); + if (!hasPath) { + return null; + } + + return convertConfig(path); + } + + public boolean removeConfig(String group, String serviceId) throws Exception { + String path = getPath(group, serviceId); + + boolean hasPath = hasPath(path); + if (!hasPath) { + return false; + } + + curatorFramework.delete().forPath(path); + + return true; + } + + public boolean publishConfig(String group, String serviceId, String config) throws Exception { + byte[] bytes = config.getBytes(); + if (bytes == null) { + return false; + } + + String path = getPath(group, serviceId); + Stat stat = curatorFramework.checkExists().forPath(path); + if (stat == null) { + curatorFramework.create().creatingParentContainersIfNeeded().withMode(CreateMode.PERSISTENT).forPath(path, bytes); + } else { + curatorFramework.setData().forPath(path, bytes); + } + + return true; + } + + public ZookeeperListener subscribeConfig(String group, String serviceId, ZookeeperSubscribeCallback zookeeperSubscribeCallback) throws Exception { + String path = getPath(group, serviceId); + + NodeCache nodeCache = new NodeCache(curatorFramework, path); + nodeCache.start(true); + + NodeCacheListener nodeCacheListener = new NodeCacheListener() { + @Override + public void nodeChanged() throws Exception { + String config = convertConfig(nodeCache); + + zookeeperSubscribeCallback.callback(config); + } + }; + + ZookeeperListener zookeeperListener = new ZookeeperListener(nodeCache, nodeCacheListener); + zookeeperListener.addListener(); + + return zookeeperListener; + } + + public void unsubscribeConfig(String group, String serviceId, ZookeeperListener zookeeperListener) throws Exception { + zookeeperListener.removeListener(); + } + + public String getPath(String group, String serviceId) { + return String.format("/%s/%s", group, serviceId); + } + + public boolean hasPath(String path) throws Exception { + return curatorFramework.checkExists().forPath(path) != null; + } + + public boolean hasPath(String group, String serviceId) throws Exception { + String path = getPath(group, serviceId); + + return hasPath(path); + } + + public String convertConfig(String path) throws Exception { + return convertConfig(curatorFramework, path); + } + + public String convertConfig(CuratorFramework curatorFramework, String path) throws Exception { + byte[] bytes = curatorFramework.getData().forPath(path); + if (bytes == null) { + return null; + } + + return new String(bytes); + } + + public String convertConfig(NodeCache nodeCache) throws Exception { + ChildData childData = nodeCache.getCurrentData(); + if (childData == null) { + return null; + } + + byte[] bytes = childData.getData(); + if (bytes == null) { + return null; + } + + return new String(bytes); + } + + @Override + public void destroy() throws Exception { + curatorFramework.close(); + + LOG.info("Shutting down Zookeeper CuratorFramework..."); + } +} \ No newline at end of file diff --git a/discovery-commons/discovery-common-zookeeper/src/main/java/com/nepxion/discovery/common/zookeeper/operation/ZookeeperSubscribeCallback.java b/discovery-commons/discovery-common-zookeeper/src/main/java/com/nepxion/discovery/common/zookeeper/operation/ZookeeperSubscribeCallback.java new file mode 100644 index 0000000000..34eb40d6e5 --- /dev/null +++ b/discovery-commons/discovery-common-zookeeper/src/main/java/com/nepxion/discovery/common/zookeeper/operation/ZookeeperSubscribeCallback.java @@ -0,0 +1,14 @@ +package com.nepxion.discovery.common.zookeeper.operation; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author rotten + * @version 1.0 + */ + +public interface ZookeeperSubscribeCallback { + void callback(String config); +} \ No newline at end of file diff --git a/discovery-commons/discovery-common-zookeeper/src/main/java/com/nepxion/discovery/common/zookeeper/proccessor/ZookeeperProcessor.java b/discovery-commons/discovery-common-zookeeper/src/main/java/com/nepxion/discovery/common/zookeeper/proccessor/ZookeeperProcessor.java new file mode 100644 index 0000000000..c078418526 --- /dev/null +++ b/discovery-commons/discovery-common-zookeeper/src/main/java/com/nepxion/discovery/common/zookeeper/proccessor/ZookeeperProcessor.java @@ -0,0 +1,90 @@ +package com.nepxion.discovery.common.zookeeper.proccessor; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import javax.annotation.PostConstruct; + +import org.springframework.beans.factory.annotation.Autowired; + +import com.nepxion.discovery.common.entity.ConfigType; +import com.nepxion.discovery.common.processor.DiscoveryConfigProcessor; +import com.nepxion.discovery.common.zookeeper.operation.ZookeeperListener; +import com.nepxion.discovery.common.zookeeper.operation.ZookeeperOperation; +import com.nepxion.discovery.common.zookeeper.operation.ZookeeperSubscribeCallback; + +public abstract class ZookeeperProcessor extends DiscoveryConfigProcessor { + @Autowired + private ZookeeperOperation zookeeperOperation; + + private ZookeeperListener zookeeperListener; + + @PostConstruct + public void initialize() { + beforeInitialization(); + + String group = getGroup(); + String dataId = getDataId(); + + logSubscribeStarted(); + + try { + zookeeperListener = zookeeperOperation.subscribeConfig(group, dataId, new ZookeeperSubscribeCallback() { + @Override + public void callback(String config) { + try { + callbackConfig(config); + } catch (Exception e) { + logCallbackFailed(e); + } + } + }); + } catch (Exception e) { + logSubscribeFailed(e); + } + + logGetStarted(); + + try { + String config = zookeeperOperation.getConfig(group, dataId); + if (config != null) { + callbackConfig(config); + } else { + logNotFound(); + } + } catch (Exception e) { + logGetFailed(e); + } + + afterInitialization(); + } + + @Override + public void destroy() { + if (zookeeperListener == null) { + return; + } + + String group = getGroup(); + String dataId = getDataId(); + + logUnsubscribeStarted(); + + try { + zookeeperOperation.unsubscribeConfig(group, dataId, zookeeperListener); + } catch (Exception e) { + logUnsubscribeFailed(e); + } + } + + @Override + public ConfigType getConfigType() { + return ConfigType.ZOOKEEPER; + } +} \ No newline at end of file diff --git a/discovery-commons/discovery-common-zookeeper/src/main/resources/META-INF/additional-spring-configuration-metadata.json b/discovery-commons/discovery-common-zookeeper/src/main/resources/META-INF/additional-spring-configuration-metadata.json new file mode 100644 index 0000000000..15ed6c4fb0 --- /dev/null +++ b/discovery-commons/discovery-common-zookeeper/src/main/resources/META-INF/additional-spring-configuration-metadata.json @@ -0,0 +1,21 @@ +{ + "properties": [ + { + "name": "zookeeper.connect-string", + "type": "java.lang.String", + "description": "Zookeeper connect string." + }, + { + "name": "zookeeper.retry-count", + "type": "java.lang.Integer", + "defaultValue": 3, + "description": "Zookeeper retry count." + }, + { + "name": "zookeeper.sleep-time", + "type": "java.lang.Integer", + "defaultValue": 3000, + "description": "Zookeeper sleep time." + } + ] +} \ No newline at end of file diff --git a/discovery-commons/discovery-common-zookeeper/src/main/resources/META-INF/spring.factories b/discovery-commons/discovery-common-zookeeper/src/main/resources/META-INF/spring.factories new file mode 100644 index 0000000000..4afe740a1d --- /dev/null +++ b/discovery-commons/discovery-common-zookeeper/src/main/resources/META-INF/spring.factories @@ -0,0 +1,2 @@ +org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ +com.nepxion.discovery.common.zookeeper.configuration.ZookeeperAutoConfiguration \ No newline at end of file diff --git a/discovery-commons/discovery-common/pom.xml b/discovery-commons/discovery-common/pom.xml new file mode 100644 index 0000000000..62bc2aae25 --- /dev/null +++ b/discovery-commons/discovery-common/pom.xml @@ -0,0 +1,90 @@ + + + discovery-common + Nepxion Discovery Common + jar + 4.0.0 + Nepxion Discovery is a solution for Spring Cloud with blue green, gray, weight, limitation, circuit breaker, degrade, isolation, monitor, tracing, dye, failover, async agent + http://www.nepxion.com + + + com.nepxion + discovery-commons + 6.23.0 + + + + + javax.annotation + javax.annotation-api + + + + org.apache.commons + commons-lang3 + + + + org.apache.commons + commons-collections4 + + + + commons-io + commons-io + + + + org.dom4j + dom4j + + + + com.fasterxml.jackson.core + jackson-databind + + + + org.yaml + snakeyaml + + + + org.slf4j + slf4j-api + + + + org.springframework + spring-web + + + + org.springframework + spring-expression + + + + org.springframework.boot + spring-boot-autoconfigure + + + + org.springframework.boot + spring-boot-configuration-processor + + + + com.alibaba.spring + spring-context-support + provided + + + + ch.qos.logback + logback-classic + provided + + + \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/constant/DiscoveryConstant.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/constant/DiscoveryConstant.java new file mode 100644 index 0000000000..4c6a9e9e11 --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/constant/DiscoveryConstant.java @@ -0,0 +1,262 @@ +package com.nepxion.discovery.common.constant; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +public class DiscoveryConstant { + public static final String DISCOVERY_VERSION = "6.23.0"; + + public static final String NEPXION = "nepxion"; + public static final String NEPXION_UPPERCASE = "NEPXION"; + public static final String NEPXION_FIRST_UPPERCASE = "Nepxion"; + public static final String NEPXION_DISCOVERY = "Nepxion Discovery"; + + public static final String SPRING_APPLICATION_DISCOVERY_PLUGIN = "spring.application.discovery.plugin"; + public static final String SPRING_APPLICATION_DISCOVERY_VERSION = "spring.application.discovery.version"; + public static final String SPRING_APPLICATION_DISCOVERY_AGENT_VERSION = "spring.application.discovery.agent.version"; + public static final String SPRING_APPLICATION_WEIGHT_RANDOM_TYPE = "spring.application.weight.random.type"; + public static final String SPRING_APPLICATION_CONFIG_FORMAT = "spring.application.config.format"; + public static final String SPRING_APPLICATION_CONFIG_PATH = "spring.application.config.path"; + public static final String SPRING_APPLICATION_GROUP_KEY = "spring.application.group.key"; + public static final String SPRING_APPLICATION_CONTEXT_PATH = "spring.application.context-path"; + public static final String SPRING_APPLICATION_DEFAULT_PROPERTIES_PATH = "spring.application.default.properties.path"; + public static final String SPRING_APPLICATION_DEFAULT_PROPERTIES_PATH_VALUE = "spring-application-default"; + public static final String SPRING_APPLICATION_NO_SERVERS_NOTIFY_ENABLED = "spring.application.no.servers.notify.enabled"; + public static final String SPRING_APPLICATION_PARAMETER_EVENT_ONSTART_ENABLED = "spring.application.parameter.event.onstart.enabled"; + + public static final String MAP_WEIGHT_RANDOM = "MapWeightRandom"; + public static final String ARRAY_WEIGHT_RANDOM = "ArrayWeightRandom"; + + public static final String CONTEXT_PATH = "server.servlet.context-path"; + + public static final String SPRING_APPLICATION_GROUP_GENERATOR_ENABLED = "spring.application.group.generator.enabled"; + public static final String SPRING_APPLICATION_GROUP_GENERATOR_LENGTH = "spring.application.group.generator.length"; + public static final String SPRING_APPLICATION_GROUP_GENERATOR_CHARACTER = "spring.application.group.generator.character"; + + public static final String SPRING_APPLICATION_GIT_GENERATOR_ENABLED = "spring.application.git.generator.enabled"; + public static final String SPRING_APPLICATION_GIT_GENERATOR_PATH = "spring.application.git.generator.path"; + public static final String SPRING_APPLICATION_GIT_VERSION_KEY = "spring.application.git.version.key"; + public static final String GIT = "git"; + public static final String GIT_COMMIT_ID = "git.commit.id"; + public static final String GIT_COMMIT_ID_ABBREV = "git.commit.id.abbrev"; + public static final String GIT_COMMIT_TIME = "git.commit.time"; + public static final String GIT_BUILD_VERSION = "git.build.version"; + public static final String GIT_TOTAL_COMMIT_COUNT = "git.total.commit.count"; + + public static final String APP_ID = "app.id"; + public static final String SPRING_BOOT_VERSION = "spring.boot.version"; + public static final String SPRING_APPLICATION_UUID = "spring.application.uuid"; + public static final String SPRING_APPLICATION_NAME = "spring.application.name"; + public static final String SPRING_APPLICATION_TYPE = "spring.application.type"; + public static final String SPRING_APPLICATION_GATEWAY_TYPE = "spring.application.gateway.type"; + public static final String SPRING_APPLICATION_PROTOCOL = "spring.application.protocol"; + public static final String GROUP = "group"; + public static final String SERVICE_ID = "serviceId"; + public static final String HOST = "host"; + public static final String PORT = "port"; + public static final String METADATA = "metadata"; + public static final String SPRING_CLOUD_DISCOVERY_PREFIX = "spring.cloud.discovery"; + + public static final String SERVICE = "service"; + public static final String GATEWAY = "gateway"; + public static final String CONSOLE = "console"; + public static final String TEST = "test"; + + public static final String DYNAMIC_VERSION = "dynamic-version"; + public static final String RULE = "rule"; + public static final String DYNAMIC_RULE = "dynamic-rule"; + public static final String DYNAMIC_GLOBAL_RULE = "dynamic-global-rule"; + public static final String DYNAMIC_PARTIAL_RULE = "dynamic-partial-rule"; + public static final String REACH_MAX_LIMITED_COUNT = "reach max limited count"; + public static final String REGISTER_ISOLATION = "register isolation"; + + public static final String VERSION = "version"; + public static final String REGION = "region"; + public static final String ENVIRONMENT = "env"; + public static final String ZONE = "zone"; + public static final String ADDRESS = "address"; + public static final String VERSION_WEIGHT = "version-weight"; + public static final String REGION_WEIGHT = "region-weight"; + public static final String VERSION_PREFER = "version-prefer"; + public static final String VERSION_FAILOVER = "version-failover"; + public static final String REGION_TRANSFER = "region-transfer"; + public static final String REGION_FAILOVER = "region-failover"; + public static final String ENVIRONMENT_FAILOVER = "env-failover"; + public static final String ZONE_FAILOVER = "zone-failover"; + public static final String ADDRESS_FAILOVER = "address-failover"; + public static final String ID_BLACKLIST = "id-blacklist"; + public static final String ADDRESS_BLACKLIST = "address-blacklist"; + public static final String ACTIVE = "active"; + + public static final String N_D_PREFIX = "n-d-"; + public static final String N_D_SERVICE_PREFIX = "n-d-service"; + + public static final String N_D_SERVICE_GROUP = "n-d-service-group"; + public static final String N_D_SERVICE_TYPE = "n-d-service-type"; + public static final String N_D_SERVICE_APP_ID = "n-d-service-app-id"; + public static final String N_D_SERVICE_ID = "n-d-service-id"; + public static final String N_D_SERVICE_ADDRESS = "n-d-service-address"; + public static final String N_D_SERVICE_VERSION = "n-d-service-version"; + public static final String N_D_SERVICE_REGION = "n-d-service-region"; + public static final String N_D_SERVICE_ENVIRONMENT = "n-d-service-env"; + public static final String N_D_SERVICE_ZONE = "n-d-service-zone"; + + public static final String N_D_GROUP = "n-d-group"; + public static final String N_D_VERSION = "n-d-version"; + public static final String N_D_REGION = "n-d-region"; + public static final String N_D_ENVIRONMENT = "n-d-env"; + public static final String N_D_ADDRESS = "n-d-address"; + public static final String N_D_VERSION_WEIGHT = "n-d-version-weight"; + public static final String N_D_REGION_WEIGHT = "n-d-region-weight"; + public static final String N_D_VERSION_PREFER = "n-d-version-prefer"; + public static final String N_D_VERSION_FAILOVER = "n-d-version-failover"; + public static final String N_D_REGION_TRANSFER = "n-d-region-transfer"; + public static final String N_D_REGION_FAILOVER = "n-d-region-failover"; + public static final String N_D_ENVIRONMENT_FAILOVER = "n-d-env-failover"; + public static final String N_D_ZONE_FAILOVER = "n-d-zone-failover"; + public static final String N_D_ADDRESS_FAILOVER = "n-d-address-failover"; + public static final String N_D_ID_BLACKLIST = "n-d-id-blacklist"; + public static final String N_D_ADDRESS_BLACKLIST = "n-d-address-blacklist"; + + public static final String N_D_ACCESS_TOKEN = "n-d-access-token"; + public static final String BEARER = "Bearer"; + + public static final String BLUE_GREEN = "blue-green"; + public static final String BLUE_GREEN_BASIC = "blue-green-basic"; + public static final String BLUE_BASIC = "blue-basic"; + + public static final String PORTAL = "portal"; + public static final String BLUE = "blue"; + public static final String GREEN = "green"; + public static final String BASIC = "basic"; + public static final String GRAY = "gray"; + public static final String STABLE = "stable"; + public static final String UNDEFINED = "undefined"; + + public static final String DOMAIN_GATEWAY = "domain-gateway"; + public static final String NON_DOMAIN_GATEWAY = "non-domain-gateway"; + + public static final String SORT_BY_VERSION = "version"; + public static final String SORT_BY_TIME = "time"; + + public static final String BLACKLIST = "blacklist"; + public static final String WHITELIST = "whitelist"; + + public static final String TRACE_ID = "trace-id"; + public static final String SPAN_ID = "span-id"; + public static final String SPAN_TAG_PLUGIN_NAME = "plugin"; + + public static final String CLASS = "class"; + public static final String METHOD = "method"; + public static final String PARAMETER = "parameter"; + public static final String RETURN = "return"; + public static final String PARAMETER_MAP = "parameterMap"; + public static final String EVENT = "event"; + public static final String ERROR = "error"; + public static final String ERROR_OBJECT = "error.object"; + + public static final String HEADER_TYPE = "Header"; + public static final String PARAMETER_TYPE = "Parameter"; + public static final String COOKIE_TYPE = "Cookie"; + + public static final String XML_FORMAT = "xml"; + public static final String JSON_FORMAT = "json"; + public static final String YAML_FORMAT = "yaml"; + public static final String PROPERTIES_FORMAT = "properties"; + public static final String HTML_FORMAT = "html"; + public static final String TEXT_FORMAT = "text"; + public static final String PREFIX_CLASSPATH = "classpath:"; + public static final String PREFIX_FILE = "file:"; + + public static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss.SSS"; + public static final String ENCODING_UTF_8 = "UTF-8"; + public static final String ENCODING_GBK = "GBK"; + public static final String ENCODING_ISO_8859_1 = "ISO-8859-1"; + public static final String SEPARATE = ";"; + public static final String EQUALS = "="; + public static final String DASH = "-"; + + public static final String ASYNC = "async"; + public static final String SYNC = "sync"; + public static final String GLOBAL = "global"; + public static final String PARTIAL = "partial"; + public static final String NA = "N/A"; + public static final String DEFAULT = "default"; + public static final String UNKNOWN = "unknown"; + public static final String IGNORED = "ignored"; + + public static final String ENDPOINT_SCAN_PACKAGES = "com.nepxion.discovery.plugin.admincenter.endpoint"; + public static final String INSPECTOR_ENDPOINT_CLASS_NAME = "com.nepxion.discovery.plugin.admincenter.endpoint.InspectorEndpoint"; + public static final String INSPECTOR_ENDPOINT_METHOD_NAME = "inspect"; + public static final String INSPECTOR_ENDPOINT_URL = "inspector/inspect"; + public static final String INSPECTOR_ENDPOINT_HEADER = "endpoint-inspector-inspect"; + + public static final String EXPRESSION_PREFIX = "H"; + public static final String EXPRESSION_REGEX = "\\#" + EXPRESSION_PREFIX + "\\['\\S+'\\]"; + public static final String EXPRESSION_SUB_PREFIX = "#" + EXPRESSION_PREFIX + "['"; + public static final String EXPRESSION_SUB_SUFFIX = "']"; + + public static final String EXPRESSION_SINGLE_QUOTES_REGEX = "[^\\S\"']+|\"[^\"]*\"|'[^']*'"; + public static final String EXPRESSION_SINGLE_QUOTES = "'"; + + public static final String EMPTY_XML_RULE = "\n\n"; + public static final String EMPTY_JSON_RULE_SINGLE = "{}"; + public static final String EMPTY_JSON_RULE_MULTIPLE = "[]"; + + public static final String NACOS = "Nacos"; + public static final String APOLLO = "Apollo"; + public static final String REDIS = "Redis"; + public static final String ZOOKEEPER = "Zookeeper"; + public static final String CONSUL = "Consul"; + public static final String ETCD = "Etcd"; + public static final String EUREKA = "Eureka"; + public static final String RIBBON = "Ribbon"; + public static final String SPRING_CLOUD_LOADBALANCER = "Spring Cloud LoadBalancer"; + public static final String FEIGN = "Feign"; + public static final String REST_TEMPLATE = "RestTemplate"; + public static final String WEB_CLIENT = "WebClient"; + public static final String HYSTRIX = "Hystrix"; + public static final String SENTINEL = "Sentinel"; + public static final String OPENTELEMETRY = "OpenTelemetry"; + public static final String OPENTRACING = "OpenTracing"; + public static final String SKYWALKING = "SkyWalking"; + + public static final String SPRING_CLOUD_GATEWAY = "Spring Cloud Gateway"; + public static final String SPRING_CLOUD_GATEWAY_TYPE = "spring-cloud-gateway"; + public static final String SPRING_CLOUD_GATEWAY_DYNAMIC_ROUTE_DESCRIPTION = "Gateway dynamic route"; + + public static final String ZUUL = "Zuul"; + public static final String ZUUL_TYPE = "zuul"; + public static final String ZUUL_DYNAMIC_ROUTE_DESCRIPTION = "Zuul dynamic route"; + + public static final String DYNAMIC_ROUTE_KEY = "dynamic-route"; + + public static final String SENTINEL_FLOW = "flow"; + public static final String SENTINEL_DEGRADE = "degrade"; + public static final String SENTINEL_AUTHORITY = "authority"; + public static final String SENTINEL_SYSTEM = "system"; + public static final String SENTINEL_PARAM_FLOW = "param-flow"; + + public static final String SENTINEL_FLOW_KEY = "sentinel-flow"; + public static final String SENTINEL_DEGRADE_KEY = "sentinel-degrade"; + public static final String SENTINEL_AUTHORITY_KEY = "sentinel-authority"; + public static final String SENTINEL_SYSTEM_KEY = "sentinel-system"; + public static final String SENTINEL_PARAM_FLOW_KEY = "sentinel-param-flow"; + + public static final String SENTINEL_FLOW_DESCRIPTION = "Sentinel flow rules"; + public static final String SENTINEL_DEGRADE_DESCRIPTION = "Sentinel degrade rules"; + public static final String SENTINEL_AUTHORITY_DESCRIPTION = "Sentinel authority rules"; + public static final String SENTINEL_SYSTEM_DESCRIPTION = "Sentinel system rules"; + public static final String SENTINEL_PARAM_FLOW_DESCRIPTION = "Sentinel param flow rules"; + + public static final String SENTINEL_PASS_QPS_KEY = "sentinel-pass-qps"; + public static final String SENTINEL_BLOCK_QPS_KEY = "sentinel-block-qps"; + public static final String SENTINEL_SUCCESS_QPS_KEY = "sentinel-success-qps"; + public static final String SENTINEL_EXCEPTION_QPS_KEY = "sentinel-exception-qps"; +} \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/constant/DiscoveryMetaDataConstant.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/constant/DiscoveryMetaDataConstant.java new file mode 100644 index 0000000000..9c91fea664 --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/constant/DiscoveryMetaDataConstant.java @@ -0,0 +1,29 @@ +package com.nepxion.discovery.common.constant; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +public class DiscoveryMetaDataConstant { + public static final String SPRING_APPLICATION_DISCOVERY_PLUGIN = "spring_application_discovery_plugin"; + public static final String SPRING_APPLICATION_DISCOVERY_VERSION = "spring_application_discovery_version"; + public static final String SPRING_APPLICATION_DISCOVERY_AGENT_VERSION = "spring_application_discovery_agent_version"; + + public static final String SPRING_APPLICATION_GROUP_KEY = "spring_application_group_key"; + public static final String SPRING_APPLICATION_CONTEXT_PATH = "spring_application_context-path"; + + public static final String SPRING_BOOT_VERSION = "spring_boot_version"; + public static final String SPRING_APPLICATION_UUID = "spring_application_uuid"; + public static final String SPRING_APPLICATION_APP_ID = "spring_application_app_id"; + public static final String SPRING_APPLICATION_NAME = "spring_application_name"; + public static final String SPRING_APPLICATION_TYPE = "spring_application_type"; + public static final String SPRING_APPLICATION_GATEWAY_TYPE = "spring_application_gateway_type"; + public static final String SPRING_APPLICATION_PROTOCOL = "spring_application_protocol"; + + public static final String SEPARATE = "_"; +} \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/constant/DiscoverySwaggerConstant.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/constant/DiscoverySwaggerConstant.java new file mode 100644 index 0000000000..96d98e4758 --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/constant/DiscoverySwaggerConstant.java @@ -0,0 +1,34 @@ +package com.nepxion.discovery.common.constant; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +public class DiscoverySwaggerConstant { + public static final String SWAGGER_ENABLED = "swagger.enabled"; + + public static final String SWAGGER_SERVICE_GROUP = "swagger.service.group"; + public static final String SWAGGER_SERVICE_PACKAGES = "swagger.service.packages"; + public static final String SWAGGER_SERVICE_DESCRIPTION = "swagger.service.description"; + public static final String SWAGGER_SERVICE_VERSION = "swagger.service.version"; + public static final String SWAGGER_SERVICE_LICENSE_NAME = "swagger.service.license.name"; + public static final String SWAGGER_SERVICE_LICENSE_URL = "swagger.service.license.url"; + public static final String SWAGGER_SERVICE_CONTACT_NAME = "swagger.service.contact.name"; + public static final String SWAGGER_SERVICE_CONTACT_URL = "swagger.service.contact.url"; + public static final String SWAGGER_SERVICE_CONTACT_EMAIL = "swagger.service.contact.email"; + public static final String SWAGGER_SERVICE_TERMSOFSERVICE_URL = "swagger.service.termsOfService.url"; + + public static final String SWAGGER_DEFAULT_GROUP_VALUE = DiscoveryConstant.NEPXION_DISCOVERY; + public static final String SWAGGER_DEFAULT_VERSION_VALUE = DiscoveryConstant.DISCOVERY_VERSION; + public static final String SWAGGER_DEFAULT_LICENSE_NAME_VALUE = "Apache License 2.0"; + public static final String SWAGGER_DEFAULT_LICENSE_URL_VALUE = "http://www.apache.org/licenses/LICENSE-2.0"; + public static final String SWAGGER_DEFAULT_CONTACT_NAME_VALUE = DiscoveryConstant.NEPXION_FIRST_UPPERCASE; + public static final String SWAGGER_DEFAULT_CONTACT_URL_VALUE = "https://github.com/Nepxion/Discovery"; + public static final String SWAGGER_DEFAULT_CONTACT_EMAIL_VALUE = "1394997@qq.com"; + public static final String SWAGGER_DEFAULT_TERMSOFSERVICE_URL_VALUE = "http://nepxion.com/discovery"; +} \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/context/DiscoveryMetaDataPreInstallation.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/context/DiscoveryMetaDataPreInstallation.java new file mode 100644 index 0000000000..a4b20096b1 --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/context/DiscoveryMetaDataPreInstallation.java @@ -0,0 +1,21 @@ +package com.nepxion.discovery.common.context; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.LinkedHashMap; +import java.util.Map; + +public class DiscoveryMetaDataPreInstallation { + private static Map metadata = new LinkedHashMap(); + + public static Map getMetadata() { + return metadata; + } +} \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/delegate/DiscoveryClientDelegate.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/delegate/DiscoveryClientDelegate.java new file mode 100644 index 0000000000..4abe572174 --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/delegate/DiscoveryClientDelegate.java @@ -0,0 +1,14 @@ +package com.nepxion.discovery.common.delegate; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +public interface DiscoveryClientDelegate { + T getDelegate(); +} \ No newline at end of file diff --git a/discovery-plugin-config-center/src/main/java/com/nepxion/discovery/plugin/configcenter/parser/xml/dom4j/Dom4JConstant.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/dom4j/Dom4JConstant.java similarity index 83% rename from discovery-plugin-config-center/src/main/java/com/nepxion/discovery/plugin/configcenter/parser/xml/dom4j/Dom4JConstant.java rename to discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/dom4j/Dom4JConstant.java index f84490ebfc..db75bfa0c5 100644 --- a/discovery-plugin-config-center/src/main/java/com/nepxion/discovery/plugin/configcenter/parser/xml/dom4j/Dom4JConstant.java +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/dom4j/Dom4JConstant.java @@ -1,4 +1,4 @@ -package com.nepxion.discovery.plugin.configcenter.parser.xml.dom4j; +package com.nepxion.discovery.common.dom4j; /** *

Title: Nepxion Discovery

diff --git a/discovery-plugin-config-center/src/main/java/com/nepxion/discovery/plugin/configcenter/parser/xml/dom4j/Dom4JParser.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/dom4j/Dom4JParser.java similarity index 97% rename from discovery-plugin-config-center/src/main/java/com/nepxion/discovery/plugin/configcenter/parser/xml/dom4j/Dom4JParser.java rename to discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/dom4j/Dom4JParser.java index 66637b91e0..6659100759 100644 --- a/discovery-plugin-config-center/src/main/java/com/nepxion/discovery/plugin/configcenter/parser/xml/dom4j/Dom4JParser.java +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/dom4j/Dom4JParser.java @@ -1,4 +1,4 @@ -package com.nepxion.discovery.plugin.configcenter.parser.xml.dom4j; +package com.nepxion.discovery.common.dom4j; /** *

Title: Nepxion Discovery

diff --git a/discovery-plugin-config-center/src/main/java/com/nepxion/discovery/plugin/configcenter/parser/xml/dom4j/Dom4JReader.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/dom4j/Dom4JReader.java similarity index 98% rename from discovery-plugin-config-center/src/main/java/com/nepxion/discovery/plugin/configcenter/parser/xml/dom4j/Dom4JReader.java rename to discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/dom4j/Dom4JReader.java index 58b0c055da..efe7b39cf3 100644 --- a/discovery-plugin-config-center/src/main/java/com/nepxion/discovery/plugin/configcenter/parser/xml/dom4j/Dom4JReader.java +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/dom4j/Dom4JReader.java @@ -1,4 +1,4 @@ -package com.nepxion.discovery.plugin.configcenter.parser.xml.dom4j; +package com.nepxion.discovery.common.dom4j; /** *

Title: Nepxion Discovery

diff --git a/discovery-plugin-config-center/src/main/java/com/nepxion/discovery/plugin/configcenter/parser/xml/dom4j/Dom4JWriter.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/dom4j/Dom4JWriter.java similarity index 95% rename from discovery-plugin-config-center/src/main/java/com/nepxion/discovery/plugin/configcenter/parser/xml/dom4j/Dom4JWriter.java rename to discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/dom4j/Dom4JWriter.java index adc03d6755..40b5a7b486 100644 --- a/discovery-plugin-config-center/src/main/java/com/nepxion/discovery/plugin/configcenter/parser/xml/dom4j/Dom4JWriter.java +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/dom4j/Dom4JWriter.java @@ -1,4 +1,4 @@ -package com.nepxion.discovery.plugin.configcenter.parser.xml.dom4j; +package com.nepxion.discovery.common.dom4j; /** *

Title: Nepxion Discovery

diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/AddressEntity.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/AddressEntity.java new file mode 100644 index 0000000000..f7cee0b217 --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/AddressEntity.java @@ -0,0 +1,55 @@ +package com.nepxion.discovery.common.entity; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.io.Serializable; + +import org.apache.commons.lang3.builder.EqualsBuilder; +import org.apache.commons.lang3.builder.HashCodeBuilder; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; + +public class AddressEntity implements Serializable { + private static final long serialVersionUID = -7878358363389123165L; + + private String host; + private int port; + + public String getHost() { + return host; + } + + public void setHost(String host) { + this.host = host; + } + + public int getPort() { + return port; + } + + public void setPort(int port) { + this.port = port; + } + + @Override + public int hashCode() { + return HashCodeBuilder.reflectionHashCode(this); + } + + @Override + public boolean equals(Object object) { + return EqualsBuilder.reflectionEquals(this, object); + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); + } +} \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/AddressWeightEntity.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/AddressWeightEntity.java new file mode 100644 index 0000000000..2984a84364 --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/AddressWeightEntity.java @@ -0,0 +1,14 @@ +package com.nepxion.discovery.common.entity; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +public class AddressWeightEntity extends MapWeightEntity { + private static final long serialVersionUID = 8727285274914899508L; +} \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/ArithmeticType.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/ArithmeticType.java new file mode 100644 index 0000000000..95cdaf0e0e --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/ArithmeticType.java @@ -0,0 +1,45 @@ +package com.nepxion.discovery.common.entity; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +public enum ArithmeticType { + EQUAL("=="), + NOT_EQUAL("!="), + GREATER_THAN(">"), + GREATER_THAN_OR_EQUAL(">="), + LESS_THAN("<"), + LESS_THAN_OR_EQUAL("<="), + MATCHES("matches"); + + private String value; + + private ArithmeticType(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + + public static ArithmeticType fromString(String value) { + for (ArithmeticType type : ArithmeticType.values()) { + if (type.getValue().equalsIgnoreCase(value)) { + return type; + } + } + + throw new IllegalArgumentException("No matched type with value=" + value); + } + + @Override + public String toString() { + return value; + } +} \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/AuthenticationEntity.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/AuthenticationEntity.java new file mode 100644 index 0000000000..7331df3012 --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/AuthenticationEntity.java @@ -0,0 +1,64 @@ +package com.nepxion.discovery.common.entity; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.io.Serializable; + +import org.apache.commons.lang3.builder.EqualsBuilder; +import org.apache.commons.lang3.builder.HashCodeBuilder; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; + +public class AuthenticationEntity implements Serializable { + private static final long serialVersionUID = -4809725024485088246L; + + private boolean passed = false; + private String error; + private String token; + + public boolean isPassed() { + return passed; + } + + public void setPassed(boolean passed) { + this.passed = passed; + } + + public String getError() { + return error; + } + + public void setError(String error) { + this.error = error; + } + + public String getToken() { + return token; + } + + public void setToken(String token) { + this.token = token; + } + + @Override + public int hashCode() { + return HashCodeBuilder.reflectionHashCode(this); + } + + @Override + public boolean equals(Object object) { + return EqualsBuilder.reflectionEquals(this, object); + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); + } +} \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/BlueGreenRouteType.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/BlueGreenRouteType.java new file mode 100644 index 0000000000..4415c18bd8 --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/BlueGreenRouteType.java @@ -0,0 +1,42 @@ +package com.nepxion.discovery.common.entity; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import com.nepxion.discovery.common.constant.DiscoveryConstant; + +public enum BlueGreenRouteType { + BLUE_GREEN_BASIC(DiscoveryConstant.BLUE_GREEN_BASIC), + BLUE_BASIC(DiscoveryConstant.BLUE_BASIC); + + private String value; + + private BlueGreenRouteType(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + + public static BlueGreenRouteType fromString(String value) { + for (BlueGreenRouteType type : BlueGreenRouteType.values()) { + if (type.getValue().equalsIgnoreCase(value)) { + return type; + } + } + + throw new IllegalArgumentException("No matched type with value=" + value); + } + + @Override + public String toString() { + return value; + } +} \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/ConditionBlueGreenEntity.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/ConditionBlueGreenEntity.java new file mode 100644 index 0000000000..0247e7b4f6 --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/ConditionBlueGreenEntity.java @@ -0,0 +1,44 @@ +package com.nepxion.discovery.common.entity; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.apache.commons.lang3.builder.EqualsBuilder; +import org.apache.commons.lang3.builder.HashCodeBuilder; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; + +public class ConditionBlueGreenEntity extends ConditionEntity { + private static final long serialVersionUID = -7956080532519640606L; + + private String route; + + public String getRoute() { + return route; + } + + public void setRoute(String route) { + this.route = route; + } + + @Override + public int hashCode() { + return HashCodeBuilder.reflectionHashCode(this); + } + + @Override + public boolean equals(Object object) { + return EqualsBuilder.reflectionEquals(this, object); + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); + } +} \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/ConditionBlueGreenRoute.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/ConditionBlueGreenRoute.java new file mode 100644 index 0000000000..352a15ba4a --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/ConditionBlueGreenRoute.java @@ -0,0 +1,42 @@ +package com.nepxion.discovery.common.entity; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import com.nepxion.discovery.common.constant.DiscoveryConstant; + +public enum ConditionBlueGreenRoute { + GREEN(DiscoveryConstant.GREEN), + BLUE(DiscoveryConstant.BLUE); + + private String value; + + private ConditionBlueGreenRoute(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + + public static ConditionBlueGreenRoute fromString(String value) { + for (ConditionBlueGreenRoute type : ConditionBlueGreenRoute.values()) { + if (type.getValue().equalsIgnoreCase(value)) { + return type; + } + } + + throw new IllegalArgumentException("No matched type with value=" + value); + } + + @Override + public String toString() { + return value; + } +} \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/ConditionEntity.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/ConditionEntity.java new file mode 100644 index 0000000000..c10dd15b9d --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/ConditionEntity.java @@ -0,0 +1,46 @@ +package com.nepxion.discovery.common.entity; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.io.Serializable; + +import org.apache.commons.lang3.builder.EqualsBuilder; +import org.apache.commons.lang3.builder.HashCodeBuilder; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; + +public class ConditionEntity implements Serializable { + private static final long serialVersionUID = -248974985112862553L; + + private String expression; + + public String getExpression() { + return expression; + } + + public void setExpression(String expression) { + this.expression = expression; + } + + @Override + public int hashCode() { + return HashCodeBuilder.reflectionHashCode(this); + } + + @Override + public boolean equals(Object object) { + return EqualsBuilder.reflectionEquals(this, object); + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); + } +} \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/ConditionGrayEntity.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/ConditionGrayEntity.java new file mode 100644 index 0000000000..bcc5d1e66d --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/ConditionGrayEntity.java @@ -0,0 +1,46 @@ +package com.nepxion.discovery.common.entity; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.List; + +import org.apache.commons.lang3.builder.EqualsBuilder; +import org.apache.commons.lang3.builder.HashCodeBuilder; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; + +public class ConditionGrayEntity extends ConditionEntity { + private static final long serialVersionUID = 676393557437861018L; + + private List weight; + + public List getWeight() { + return weight; + } + + public void setWeight(List weight) { + this.weight = weight; + } + + @Override + public int hashCode() { + return HashCodeBuilder.reflectionHashCode(this); + } + + @Override + public boolean equals(Object object) { + return EqualsBuilder.reflectionEquals(this, object); + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); + } +} \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/ConditionRouteStrategy.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/ConditionRouteStrategy.java new file mode 100644 index 0000000000..32be06833e --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/ConditionRouteStrategy.java @@ -0,0 +1,67 @@ +package com.nepxion.discovery.common.entity; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.io.Serializable; +import java.util.List; + +import org.apache.commons.lang3.builder.EqualsBuilder; +import org.apache.commons.lang3.builder.HashCodeBuilder; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; + +import com.nepxion.discovery.common.constant.DiscoveryConstant; + +public class ConditionRouteStrategy implements Serializable { + private static final long serialVersionUID = -6036447421562945200L; + + private List service; + private boolean condition = false; + private String sort = DiscoveryConstant.SORT_BY_VERSION; + + public List getService() { + return service; + } + + public void setService(List service) { + this.service = service; + } + + public boolean isCondition() { + return condition; + } + + public void setCondition(boolean condition) { + this.condition = condition; + } + + public String getSort() { + return sort; + } + + public void setSort(String sort) { + this.sort = sort; + } + + @Override + public int hashCode() { + return HashCodeBuilder.reflectionHashCode(this); + } + + @Override + public boolean equals(Object object) { + return EqualsBuilder.reflectionEquals(this, object); + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); + } +} \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/ConditionStrategy.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/ConditionStrategy.java new file mode 100644 index 0000000000..11d0a4509b --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/ConditionStrategy.java @@ -0,0 +1,86 @@ +package com.nepxion.discovery.common.entity; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.io.Serializable; +import java.util.List; +import java.util.Map; + +import org.apache.commons.lang3.builder.EqualsBuilder; +import org.apache.commons.lang3.builder.HashCodeBuilder; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; + +import com.nepxion.discovery.common.constant.DiscoveryConstant; + +public class ConditionStrategy implements Serializable { + private static final long serialVersionUID = 2137809071409890088L; + + private List service; + private List blueGreen; + private List gray; + private Map header; + private String sort = DiscoveryConstant.SORT_BY_VERSION; + + public List getService() { + return service; + } + + public void setService(List service) { + this.service = service; + } + + public List getBlueGreen() { + return blueGreen; + } + + public void setBlueGreen(List blueGreen) { + this.blueGreen = blueGreen; + } + + public List getGray() { + return gray; + } + + public void setGray(List gray) { + this.gray = gray; + } + + public Map getHeader() { + return header; + } + + public void setHeader(Map header) { + this.header = header; + } + + public String getSort() { + return sort; + } + + public void setSort(String sort) { + this.sort = sort; + } + + @Override + public int hashCode() { + return HashCodeBuilder.reflectionHashCode(this); + } + + @Override + public boolean equals(Object object) { + return EqualsBuilder.reflectionEquals(this, object); + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); + } +} \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/ConditionType.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/ConditionType.java new file mode 100644 index 0000000000..878d7b1677 --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/ConditionType.java @@ -0,0 +1,42 @@ +package com.nepxion.discovery.common.entity; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import com.nepxion.discovery.common.constant.DiscoveryConstant; + +public enum ConditionType { + BLUE_GREEN(DiscoveryConstant.BLUE_GREEN), + GRAY(DiscoveryConstant.GRAY); + + private String value; + + private ConditionType(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + + public static ConditionType fromString(String value) { + for (ConditionType type : ConditionType.values()) { + if (type.getValue().equalsIgnoreCase(value)) { + return type; + } + } + + throw new IllegalArgumentException("No matched type with value=" + value); + } + + @Override + public String toString() { + return value; + } +} \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/ConfigFormatType.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/ConfigFormatType.java new file mode 100644 index 0000000000..4719b1391b --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/ConfigFormatType.java @@ -0,0 +1,42 @@ +package com.nepxion.discovery.common.entity; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import com.nepxion.discovery.common.constant.DiscoveryConstant; + +public enum ConfigFormatType { + XML_FORMAT(DiscoveryConstant.XML_FORMAT), + JSON_FORMAT(DiscoveryConstant.JSON_FORMAT); + + private String value; + + private ConfigFormatType(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + + public static ConfigFormatType fromString(String value) { + for (ConfigFormatType type : ConfigFormatType.values()) { + if (type.getValue().equalsIgnoreCase(value)) { + return type; + } + } + + throw new IllegalArgumentException("No matched type with value=" + value); + } + + @Override + public String toString() { + return value; + } +} \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/ConfigType.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/ConfigType.java new file mode 100644 index 0000000000..78981b4179 --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/ConfigType.java @@ -0,0 +1,68 @@ +package com.nepxion.discovery.common.entity; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import com.nepxion.discovery.common.constant.DiscoveryConstant; + +public enum ConfigType { + NACOS(DiscoveryConstant.NACOS), + APOLLO(DiscoveryConstant.APOLLO), + REDIS(DiscoveryConstant.REDIS), + ZOOKEEPER(DiscoveryConstant.ZOOKEEPER), + CONSUL(DiscoveryConstant.CONSUL), + ETCD(DiscoveryConstant.ETCD); + + public static final ConfigType[] SINGLE_KEY_CONFIG_TYPES = new ConfigType[] { APOLLO, CONSUL, ETCD }; + public static final ConfigType[] MULTI_KEY_CONFIG_TYPES = new ConfigType[] { NACOS, REDIS, ZOOKEEPER }; + + private String value; + + private ConfigType(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + + public static ConfigType[] getSingleKeyConfigTypes() { + return SINGLE_KEY_CONFIG_TYPES; + } + + public static ConfigType[] getMultiKeyConfigTypes() { + return MULTI_KEY_CONFIG_TYPES; + } + + public static boolean isSingleKey(ConfigType configType) { + for (int i = 0; i < SINGLE_KEY_CONFIG_TYPES.length; i++) { + ConfigType type = SINGLE_KEY_CONFIG_TYPES[i]; + if (type == configType) { + return true; + } + } + + return false; + } + + public static ConfigType fromString(String value) { + for (ConfigType type : ConfigType.values()) { + if (type.getValue().equalsIgnoreCase(value)) { + return type; + } + } + + throw new IllegalArgumentException("No matched type with value=" + value); + } + + @Override + public String toString() { + return value; + } +} \ No newline at end of file diff --git a/discovery-common/src/main/java/com/nepxion/discovery/common/entity/CountFilterEntity.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/CountFilterEntity.java similarity index 100% rename from discovery-common/src/main/java/com/nepxion/discovery/common/entity/CountFilterEntity.java rename to discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/CountFilterEntity.java diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/DeployType.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/DeployType.java new file mode 100644 index 0000000000..0491ceb15f --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/DeployType.java @@ -0,0 +1,42 @@ +package com.nepxion.discovery.common.entity; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import com.nepxion.discovery.common.constant.DiscoveryConstant; + +public enum DeployType { + DOMAIN_GATEWAY(DiscoveryConstant.DOMAIN_GATEWAY), + NON_DOMAIN_GATEWAY(DiscoveryConstant.NON_DOMAIN_GATEWAY); + + private String value; + + private DeployType(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + + public static DeployType fromString(String value) { + for (DeployType type : DeployType.values()) { + if (type.getValue().equalsIgnoreCase(value)) { + return type; + } + } + + throw new IllegalArgumentException("No matched type with value=" + value); + } + + @Override + public String toString() { + return value; + } +} \ No newline at end of file diff --git a/discovery-common/src/main/java/com/nepxion/discovery/common/entity/DiscoveryEntity.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/DiscoveryEntity.java similarity index 76% rename from discovery-common/src/main/java/com/nepxion/discovery/common/entity/DiscoveryEntity.java rename to discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/DiscoveryEntity.java index 61ea417951..e23ae4f998 100644 --- a/discovery-common/src/main/java/com/nepxion/discovery/common/entity/DiscoveryEntity.java +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/DiscoveryEntity.java @@ -13,6 +13,7 @@ public class DiscoveryEntity extends FilterHolderEntity { private static final long serialVersionUID = -7417362859952278987L; private VersionFilterEntity versionFilterEntity; + private RegionFilterEntity regionFilterEntity; private WeightFilterEntity weightFilterEntity; public VersionFilterEntity getVersionFilterEntity() { @@ -23,6 +24,14 @@ public void setVersionFilterEntity(VersionFilterEntity versionFilterEntity) { this.versionFilterEntity = versionFilterEntity; } + public RegionFilterEntity getRegionFilterEntity() { + return regionFilterEntity; + } + + public void setRegionFilterEntity(RegionFilterEntity regionFilterEntity) { + this.regionFilterEntity = regionFilterEntity; + } + public WeightFilterEntity getWeightFilterEntity() { return weightFilterEntity; } diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/DiscoveryType.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/DiscoveryType.java new file mode 100644 index 0000000000..92a8480365 --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/DiscoveryType.java @@ -0,0 +1,44 @@ +package com.nepxion.discovery.common.entity; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import com.nepxion.discovery.common.constant.DiscoveryConstant; + +public enum DiscoveryType { + NACOS(DiscoveryConstant.NACOS), + CONSUL(DiscoveryConstant.CONSUL), + EUREKA(DiscoveryConstant.EUREKA), + ZOOKEEPER(DiscoveryConstant.ZOOKEEPER); + + private String value; + + private DiscoveryType(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + + public static DiscoveryType fromString(String value) { + for (DiscoveryType type : DiscoveryType.values()) { + if (type.getValue().equalsIgnoreCase(value)) { + return type; + } + } + + throw new IllegalArgumentException("No matched type with value=" + value); + } + + @Override + public String toString() { + return value; + } +} \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/ElementType.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/ElementType.java new file mode 100644 index 0000000000..58b247a1cf --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/ElementType.java @@ -0,0 +1,47 @@ +package com.nepxion.discovery.common.entity; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import com.nepxion.discovery.common.constant.DiscoveryConstant; + +public enum ElementType { + PORTAL(DiscoveryConstant.PORTAL), + BLUE(DiscoveryConstant.BLUE), + GREEN(DiscoveryConstant.GREEN), + BASIC(DiscoveryConstant.BASIC), + GRAY(DiscoveryConstant.GRAY), + STABLE(DiscoveryConstant.STABLE), + UNDEFINED(DiscoveryConstant.UNDEFINED); + + private String value; + + private ElementType(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + + public static ElementType fromString(String value) { + for (ElementType type : ElementType.values()) { + if (type.getValue().equalsIgnoreCase(value)) { + return type; + } + } + + throw new IllegalArgumentException("No matched type with value=" + value); + } + + @Override + public String toString() { + return value; + } +} \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/EscapeType.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/EscapeType.java new file mode 100644 index 0000000000..167597076d --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/EscapeType.java @@ -0,0 +1,53 @@ +package com.nepxion.discovery.common.entity; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +public enum EscapeType { + AND("&", "&"), + LESS_THAN("<", "<"), + DOUBLE_QUOTATION("\"", """); + // GREATER_THAN(">", ">"); + // SINGLE_QUOTATION("'", "'"); + + private String source; + private String target; + + private EscapeType(String source, String target) { + this.source = source; + this.target = target; + } + + public String getSource() { + return source; + } + + public String getTarget() { + return target; + } + + @Override + public String toString() { + return source; + } + + public static String escape(String value, boolean escaped) { + if (value == null) { + return null; + } + + EscapeType[] escapeTypes = EscapeType.values(); + for (int i = 0; i < escapeTypes.length; i++) { + EscapeType escapeType = escapeTypes[i]; + value = value.replace(escaped ? escapeType.getSource() : escapeType.getTarget(), escaped ? escapeType.getTarget() : escapeType.getSource()); + } + + return value; + } +} \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/FailoverType.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/FailoverType.java new file mode 100644 index 0000000000..30c5fc53cb --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/FailoverType.java @@ -0,0 +1,47 @@ +package com.nepxion.discovery.common.entity; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import com.nepxion.discovery.common.constant.DiscoveryConstant; + +public enum FailoverType { + VERSION_PREFER(DiscoveryConstant.VERSION_PREFER), + VERSION_FAILOVER(DiscoveryConstant.VERSION_FAILOVER), + REGION_TRANSFER(DiscoveryConstant.REGION_TRANSFER), + REGION_FAILOVER(DiscoveryConstant.REGION_FAILOVER), + ENVIRONMENT_FAILOVER(DiscoveryConstant.ENVIRONMENT_FAILOVER), + ZONE_FAILOVER(DiscoveryConstant.ZONE_FAILOVER), + ADDRESS_FAILOVER(DiscoveryConstant.ADDRESS_FAILOVER); + + private String value; + + private FailoverType(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + + public static FailoverType fromString(String value) { + for (FailoverType type : FailoverType.values()) { + if (type.getValue().equalsIgnoreCase(value)) { + return type; + } + } + + throw new IllegalArgumentException("No matched type with value=" + value); + } + + @Override + public String toString() { + return value; + } +} \ No newline at end of file diff --git a/discovery-common/src/main/java/com/nepxion/discovery/common/entity/FilterHolderEntity.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/FilterHolderEntity.java similarity index 100% rename from discovery-common/src/main/java/com/nepxion/discovery/common/entity/FilterHolderEntity.java rename to discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/FilterHolderEntity.java diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/FilterType.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/FilterType.java new file mode 100644 index 0000000000..6b01b4469f --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/FilterType.java @@ -0,0 +1,42 @@ +package com.nepxion.discovery.common.entity; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import com.nepxion.discovery.common.constant.DiscoveryConstant; + +public enum FilterType { + BLACKLIST(DiscoveryConstant.BLACKLIST), + WHITELIST(DiscoveryConstant.WHITELIST); + + private String value; + + private FilterType(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + + public static FilterType fromString(String value) { + for (FilterType type : FilterType.values()) { + if (type.getValue().equalsIgnoreCase(value)) { + return type; + } + } + + throw new IllegalArgumentException("No matched type with value=" + value); + } + + @Override + public String toString() { + return value; + } +} \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/FormatType.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/FormatType.java new file mode 100644 index 0000000000..3dc1875d77 --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/FormatType.java @@ -0,0 +1,46 @@ +package com.nepxion.discovery.common.entity; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import com.nepxion.discovery.common.constant.DiscoveryConstant; + +public enum FormatType { + XML_FORMAT(DiscoveryConstant.XML_FORMAT), + JSON_FORMAT(DiscoveryConstant.JSON_FORMAT), + YAML_FORMAT(DiscoveryConstant.YAML_FORMAT), + PROPERTIES_FORMAT(DiscoveryConstant.PROPERTIES_FORMAT), + HTML_FORMAT(DiscoveryConstant.HTML_FORMAT), + TEXT_FORMAT(DiscoveryConstant.TEXT_FORMAT); + + private String value; + + private FormatType(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + + public static FormatType fromString(String value) { + for (FormatType type : FormatType.values()) { + if (type.getValue().equalsIgnoreCase(value)) { + return type; + } + } + + throw new IllegalArgumentException("No matched type with value=" + value); + } + + @Override + public String toString() { + return value; + } +} \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/GatewayStrategyRouteEntity.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/GatewayStrategyRouteEntity.java new file mode 100644 index 0000000000..10c310596a --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/GatewayStrategyRouteEntity.java @@ -0,0 +1,212 @@ +package com.nepxion.discovery.common.entity; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import org.apache.commons.lang3.builder.EqualsBuilder; +import org.apache.commons.lang3.builder.HashCodeBuilder; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; + +import com.nepxion.discovery.common.util.JsonUtil; + +public class GatewayStrategyRouteEntity implements Serializable { + private static final long serialVersionUID = 8552414941889295450L; + + private String id; + private String uri; + private List predicates = new ArrayList(); + private List userPredicates = new ArrayList(); + private List filters = new ArrayList(); + private List userFilters = new ArrayList(); + private int order = 0; + private Map metadata = new HashMap(); + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getUri() { + return uri; + } + + public void setUri(String uri) { + this.uri = uri; + } + + public List getPredicates() { + return predicates; + } + + public void setPredicates(List predicates) { + this.predicates = predicates; + } + + public List getUserPredicates() { + return userPredicates; + } + + public void setUserPredicates(List userPredicates) { + this.userPredicates = userPredicates; + } + + public List getFilters() { + return filters; + } + + public void setFilters(List filters) { + this.filters = filters; + } + + public List getUserFilters() { + return userFilters; + } + + public void setUserFilters(List userFilters) { + this.userFilters = userFilters; + } + + public int getOrder() { + return order; + } + + public void setOrder(int order) { + this.order = order; + } + + public Map getMetadata() { + return metadata; + } + + public void setMetadata(Map metadata) { + if (metadata != null) { + this.metadata = metadata; + } + } + + public static class Predicate extends Clause { + private static final long serialVersionUID = -5113611207453059195L; + + @Override + public int hashCode() { + return HashCodeBuilder.reflectionHashCode(this); + } + + @Override + public boolean equals(Object object) { + return EqualsBuilder.reflectionEquals(this, object); + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); + } + } + + public static class Filter extends Clause { + private static final long serialVersionUID = 4975847305584873755L; + + @Override + public int hashCode() { + return HashCodeBuilder.reflectionHashCode(this); + } + + @Override + public boolean equals(Object object) { + return EqualsBuilder.reflectionEquals(this, object); + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); + } + } + + public static class Clause implements Serializable { + private static final long serialVersionUID = -6284675851623689077L; + + private String name; + private Map args = new LinkedHashMap<>(); + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Map getArgs() { + return args; + } + + public void setArgs(Map args) { + this.args = args; + } + + public void addArg(String key, String value) { + this.args.put(key, value); + } + + @Override + public int hashCode() { + return HashCodeBuilder.reflectionHashCode(this); + } + + @Override + public boolean equals(Object object) { + return EqualsBuilder.reflectionEquals(this, object); + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); + } + } + + public static String toClausesJson(List clauses) { + StringBuilder stringBuilder = new StringBuilder(); + + for (Clause clause : clauses) { + stringBuilder.append(String.format("%s=%s, ", clause.getName(), JsonUtil.toJson(clause.getArgs()))); + } + + if (stringBuilder.length() > 0) { + stringBuilder.delete(stringBuilder.length() - 2, stringBuilder.length()); + } + + return stringBuilder.toString(); + } + + @Override + public int hashCode() { + return HashCodeBuilder.reflectionHashCode(this); + } + + @Override + public boolean equals(Object object) { + return EqualsBuilder.reflectionEquals(this, object); + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); + } +} \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/GatewayType.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/GatewayType.java new file mode 100644 index 0000000000..bafae264ad --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/GatewayType.java @@ -0,0 +1,60 @@ +package com.nepxion.discovery.common.entity; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import com.nepxion.discovery.common.constant.DiscoveryConstant; + +public enum GatewayType { + SPRING_CLOUD_GATEWAY(DiscoveryConstant.SPRING_CLOUD_GATEWAY_TYPE, DiscoveryConstant.SPRING_CLOUD_GATEWAY), + ZUUL(DiscoveryConstant.ZUUL_TYPE, DiscoveryConstant.ZUUL); + + private String value; + private String name; + + private GatewayType(String value, String name) { + this.value = value; + this.name = name; + } + + public String getValue() { + return value; + } + + public String getName() { + return name; + } + + public static GatewayType fromString(String value) { + return fromString(value, true); + } + + public static GatewayType fromString(String value, boolean fromValue) { + if (fromValue) { + for (GatewayType type : GatewayType.values()) { + if (type.getValue().equalsIgnoreCase(value)) { + return type; + } + } + } else { + for (GatewayType type : GatewayType.values()) { + if (type.getName().equalsIgnoreCase(value)) { + return type; + } + } + } + + throw new IllegalArgumentException("No matched type with value=" + value); + } + + @Override + public String toString() { + return value; + } +} \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/HeadersInjectorEntity.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/HeadersInjectorEntity.java new file mode 100644 index 0000000000..7a13a43be7 --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/HeadersInjectorEntity.java @@ -0,0 +1,65 @@ +package com.nepxion.discovery.common.entity; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.io.Serializable; +import java.util.List; + +import org.apache.commons.lang3.builder.EqualsBuilder; +import org.apache.commons.lang3.builder.HashCodeBuilder; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; + +public class HeadersInjectorEntity implements Serializable { + private static final long serialVersionUID = 4754115929939146799L; + + private HeadersInjectorType headersInjectorType; + private List headers; + + public HeadersInjectorEntity() { + + } + + public HeadersInjectorEntity(HeadersInjectorType headersInjectorType, List headers) { + this.headersInjectorType = headersInjectorType; + this.headers = headers; + } + + public HeadersInjectorType getHeadersInjectorType() { + return headersInjectorType; + } + + public void setHeadersInjectorType(HeadersInjectorType headersInjectorType) { + this.headersInjectorType = headersInjectorType; + } + + public List getHeaders() { + return headers; + } + + public void setHeaders(List headers) { + this.headers = headers; + } + + @Override + public int hashCode() { + return HashCodeBuilder.reflectionHashCode(this); + } + + @Override + public boolean equals(Object object) { + return EqualsBuilder.reflectionEquals(this, object); + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); + } +} \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/HeadersInjectorType.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/HeadersInjectorType.java new file mode 100644 index 0000000000..fc5fbe876e --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/HeadersInjectorType.java @@ -0,0 +1,16 @@ +package com.nepxion.discovery.common.entity; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +public enum HeadersInjectorType { + TRANSMISSION, + TRACER, + ALL; +} \ No newline at end of file diff --git a/discovery-common/src/main/java/com/nepxion/discovery/common/entity/HostFilterEntity.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/HostFilterEntity.java similarity index 100% rename from discovery-common/src/main/java/com/nepxion/discovery/common/entity/HostFilterEntity.java rename to discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/HostFilterEntity.java diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/InspectorDebugEntity.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/InspectorDebugEntity.java new file mode 100644 index 0000000000..804fee05f1 --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/InspectorDebugEntity.java @@ -0,0 +1,93 @@ +package com.nepxion.discovery.common.entity; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.io.Serializable; +import java.util.List; +import java.util.Map; + +import org.apache.commons.lang3.builder.EqualsBuilder; +import org.apache.commons.lang3.builder.HashCodeBuilder; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; + +public class InspectorDebugEntity implements Serializable { + private static final long serialVersionUID = 1251618912673295400L; + + private String protocol = "http"; + private String portal; + private String path; + private List service; + private Map header; + private List filter; + + public String getProtocol() { + return protocol; + } + + public void setProtocol(String protocol) { + this.protocol = protocol; + } + + public String getPortal() { + return portal; + } + + public void setPortal(String portal) { + this.portal = portal; + } + + public String getPath() { + return path; + } + + public void setPath(String path) { + this.path = path; + } + + public List getService() { + return service; + } + + public void setService(List service) { + this.service = service; + } + + public Map getHeader() { + return header; + } + + public void setHeader(Map header) { + this.header = header; + } + + public List getFilter() { + return filter; + } + + public void setFilter(List filter) { + this.filter = filter; + } + + @Override + public int hashCode() { + return HashCodeBuilder.reflectionHashCode(this); + } + + @Override + public boolean equals(Object object) { + return EqualsBuilder.reflectionEquals(this, object); + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); + } +} \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/InspectorEntity.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/InspectorEntity.java new file mode 100644 index 0000000000..7dea545af5 --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/InspectorEntity.java @@ -0,0 +1,56 @@ +package com.nepxion.discovery.common.entity; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.io.Serializable; +import java.util.List; + +import org.apache.commons.lang3.builder.EqualsBuilder; +import org.apache.commons.lang3.builder.HashCodeBuilder; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; + +public class InspectorEntity implements Serializable { + private static final long serialVersionUID = 2651428583729465720L; + + private List serviceIdList; + private String result; + + public List getServiceIdList() { + return serviceIdList; + } + + public void setServiceIdList(List serviceIdList) { + this.serviceIdList = serviceIdList; + } + + public String getResult() { + return result; + } + + public void setResult(String result) { + this.result = result; + } + + @Override + public int hashCode() { + return HashCodeBuilder.reflectionHashCode(this); + } + + @Override + public boolean equals(Object object) { + return EqualsBuilder.reflectionEquals(this, object); + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); + } +} \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/InstanceEntity.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/InstanceEntity.java new file mode 100644 index 0000000000..1af346bf6c --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/InstanceEntity.java @@ -0,0 +1,191 @@ +package com.nepxion.discovery.common.entity; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.io.Serializable; +import java.util.Map; + +import org.apache.commons.lang3.builder.EqualsBuilder; +import org.apache.commons.lang3.builder.HashCodeBuilder; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; + +public class InstanceEntity implements Serializable { + private static final long serialVersionUID = -3001191508072178378L; + + private String plugin; + private String group; + private String serviceType; + private String serviceId; + private String serviceAppId; + private String serviceUUId; + private String version; + private String region; + private String environment; + private String zone; + private boolean active; + private String protocol; + private String contextPath; + private String formatContextPath; + private String host; + private int port; + private Map metadata; + + public String getPlugin() { + return plugin; + } + + public void setPlugin(String plugin) { + this.plugin = plugin; + } + + public String getGroup() { + return group; + } + + public void setGroup(String group) { + this.group = group; + } + + public String getServiceType() { + return serviceType; + } + + public void setServiceType(String serviceType) { + this.serviceType = serviceType; + } + + public String getServiceId() { + return serviceId; + } + + public void setServiceId(String serviceId) { + this.serviceId = serviceId; + } + + public String getServiceAppId() { + return serviceAppId; + } + + public void setServiceAppId(String serviceAppId) { + this.serviceAppId = serviceAppId; + } + + public String getServiceUUId() { + return serviceUUId; + } + + public void setServiceUUId(String serviceUUId) { + this.serviceUUId = serviceUUId; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public String getRegion() { + return region; + } + + public void setRegion(String region) { + this.region = region; + } + + public String getEnvironment() { + return environment; + } + + public void setEnvironment(String environment) { + this.environment = environment; + } + + public String getZone() { + return zone; + } + + public void setZone(String zone) { + this.zone = zone; + } + + public boolean isActive() { + return active; + } + + public void setActive(boolean active) { + this.active = active; + } + + public String getProtocol() { + return protocol; + } + + public void setProtocol(String protocol) { + this.protocol = protocol; + } + + public String getContextPath() { + return contextPath; + } + + public void setContextPath(String contextPath) { + this.contextPath = contextPath; + } + + public String getFormatContextPath() { + return formatContextPath; + } + + public void setFormatContextPath(String formatContextPath) { + this.formatContextPath = formatContextPath; + } + + public String getHost() { + return host; + } + + public void setHost(String host) { + this.host = host; + } + + public int getPort() { + return port; + } + + public void setPort(int port) { + this.port = port; + } + + public Map getMetadata() { + return metadata; + } + + public void setMetadata(Map metadata) { + this.metadata = metadata; + } + + @Override + public int hashCode() { + return HashCodeBuilder.reflectionHashCode(this); + } + + @Override + public boolean equals(Object object) { + return EqualsBuilder.reflectionEquals(this, object); + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); + } +} \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/InstanceEntityWrapper.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/InstanceEntityWrapper.java new file mode 100644 index 0000000000..9581c54d4d --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/InstanceEntityWrapper.java @@ -0,0 +1,212 @@ +package com.nepxion.discovery.common.entity; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.Map; + +import org.apache.commons.lang3.StringUtils; + +import com.nepxion.discovery.common.constant.DiscoveryConstant; +import com.nepxion.discovery.common.constant.DiscoveryMetaDataConstant; +import com.nepxion.discovery.common.util.UrlUtil; + +public class InstanceEntityWrapper { + public static String getPlugin(InstanceEntity instanceEntity) { + Map metadata = instanceEntity.getMetadata(); + + return getPlugin(metadata); + } + + public static String getGroup(InstanceEntity instanceEntity) { + Map metadata = instanceEntity.getMetadata(); + + return getGroup(metadata); + } + + public static String getServiceType(InstanceEntity instanceEntity) { + Map metadata = instanceEntity.getMetadata(); + + return getServiceType(metadata); + } + + public static String getGatewayType(InstanceEntity instanceEntity) { + Map metadata = instanceEntity.getMetadata(); + + return getGatewayType(metadata); + } + + public static String getServiceAppId(InstanceEntity instanceEntity) { + Map metadata = instanceEntity.getMetadata(); + + return getServiceAppId(metadata); + } + + public static String getServiceUUId(InstanceEntity instanceEntity) { + Map metadata = instanceEntity.getMetadata(); + + return getServiceUUId(metadata); + } + + public static String getVersion(InstanceEntity instanceEntity) { + Map metadata = instanceEntity.getMetadata(); + + return getVersion(metadata); + } + + public static String getRegion(InstanceEntity instanceEntity) { + Map metadata = instanceEntity.getMetadata(); + + return getRegion(metadata); + } + + public static String getEnvironment(InstanceEntity instanceEntity) { + Map metadata = instanceEntity.getMetadata(); + + return getEnvironment(metadata); + } + + public static String getZone(InstanceEntity instanceEntity) { + Map metadata = instanceEntity.getMetadata(); + + return getZone(metadata); + } + + public static boolean isActive(InstanceEntity instanceEntity) { + Map metadata = instanceEntity.getMetadata(); + + return isActive(metadata); + } + + public static String getProtocol(InstanceEntity instanceEntity) { + Map metadata = instanceEntity.getMetadata(); + + return getProtocol(metadata); + } + + public static String getContextPath(InstanceEntity instanceEntity) { + Map metadata = instanceEntity.getMetadata(); + + return getContextPath(metadata); + } + + public static String getFormatContextPath(InstanceEntity instanceEntity) { + Map metadata = instanceEntity.getMetadata(); + + return getFormatContextPath(metadata); + } + + public static String getPlugin(Map metadata) { + String plugin = metadata.get(DiscoveryMetaDataConstant.SPRING_APPLICATION_DISCOVERY_PLUGIN); + if (StringUtils.isEmpty(plugin)) { + return StringUtils.EMPTY; + } + + return plugin; + } + + public static String getGroup(Map metadata) { + String groupKey = metadata.get(DiscoveryMetaDataConstant.SPRING_APPLICATION_GROUP_KEY); + if (StringUtils.isEmpty(groupKey)) { + groupKey = DiscoveryConstant.GROUP; + } + + String group = metadata.get(groupKey); + if (StringUtils.isEmpty(group)) { + return StringUtils.EMPTY; + } + + return group; + } + + public static String getServiceType(Map metadata) { + return metadata.get(DiscoveryMetaDataConstant.SPRING_APPLICATION_TYPE); + } + + public static String getGatewayType(Map metadata) { + return metadata.get(DiscoveryMetaDataConstant.SPRING_APPLICATION_GATEWAY_TYPE); + } + + public static String getServiceAppId(Map metadata) { + return metadata.get(DiscoveryMetaDataConstant.SPRING_APPLICATION_APP_ID); + } + + public static String getServiceUUId(Map metadata) { + return metadata.get(DiscoveryMetaDataConstant.SPRING_APPLICATION_UUID); + } + + public static String getVersion(Map metadata) { + String version = metadata.get(DiscoveryConstant.VERSION); + if (StringUtils.isEmpty(version)) { + version = DiscoveryConstant.DEFAULT; + } + + return version; + } + + public static String getRegion(Map metadata) { + String region = metadata.get(DiscoveryConstant.REGION); + if (StringUtils.isEmpty(region)) { + region = DiscoveryConstant.DEFAULT; + } + + return region; + } + + public static String getEnvironment(Map metadata) { + String environment = metadata.get(DiscoveryConstant.ENVIRONMENT); + if (StringUtils.isEmpty(environment)) { + environment = DiscoveryConstant.DEFAULT; + } + + return environment; + } + + public static String getZone(Map metadata) { + String zone = metadata.get(DiscoveryConstant.ZONE); + if (StringUtils.isEmpty(zone)) { + zone = DiscoveryConstant.DEFAULT; + } + + return zone; + } + + public static boolean isActive(Map metadata) { + String active = metadata.get(DiscoveryConstant.ACTIVE); + if (StringUtils.isEmpty(active)) { + return false; + } + + return Boolean.valueOf(active); + } + + public static String getProtocol(Map metadata) { + String protocol = metadata.get(DiscoveryMetaDataConstant.SPRING_APPLICATION_PROTOCOL); + if (StringUtils.isEmpty(protocol)) { + return "http"; + } + + return protocol; + } + + public static String getContextPath(Map metadata) { + String contextPath = metadata.get(DiscoveryMetaDataConstant.SPRING_APPLICATION_CONTEXT_PATH); + if (StringUtils.isEmpty(contextPath)) { + return "/"; + } + + return contextPath; + } + + public static String getFormatContextPath(Map metadata) { + String contextPath = getContextPath(metadata); + + return UrlUtil.formatContextPath(contextPath); + } +} \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/InterceptorType.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/InterceptorType.java new file mode 100644 index 0000000000..cbedacf53b --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/InterceptorType.java @@ -0,0 +1,43 @@ +package com.nepxion.discovery.common.entity; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import com.nepxion.discovery.common.constant.DiscoveryConstant; + +public enum InterceptorType { + FEIGN(DiscoveryConstant.FEIGN), + REST_TEMPLATE(DiscoveryConstant.REST_TEMPLATE), + WEB_CLIENT(DiscoveryConstant.WEB_CLIENT); + + private String value; + + private InterceptorType(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + + public static InterceptorType fromString(String value) { + for (InterceptorType type : InterceptorType.values()) { + if (type.getValue().equalsIgnoreCase(value)) { + return type; + } + } + + throw new IllegalArgumentException("No matched type with value=" + value); + } + + @Override + public String toString() { + return value; + } +} \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/LoadBalancerType.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/LoadBalancerType.java new file mode 100644 index 0000000000..c283f91867 --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/LoadBalancerType.java @@ -0,0 +1,42 @@ +package com.nepxion.discovery.common.entity; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import com.nepxion.discovery.common.constant.DiscoveryConstant; + +public enum LoadBalancerType { + RIBBON(DiscoveryConstant.RIBBON), + SPRING_CLOUD_LOADBALANCER(DiscoveryConstant.SPRING_CLOUD_LOADBALANCER); + + private String value; + + private LoadBalancerType(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + + public static LoadBalancerType fromString(String value) { + for (LoadBalancerType type : LoadBalancerType.values()) { + if (type.getValue().equalsIgnoreCase(value)) { + return type; + } + } + + throw new IllegalArgumentException("No matched type with value=" + value); + } + + @Override + public String toString() { + return value; + } +} \ No newline at end of file diff --git a/discovery-common/src/main/java/com/nepxion/discovery/common/entity/MapWeightEntity.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/MapWeightEntity.java similarity index 100% rename from discovery-common/src/main/java/com/nepxion/discovery/common/entity/MapWeightEntity.java rename to discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/MapWeightEntity.java diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/MetadataParameter.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/MetadataParameter.java new file mode 100644 index 0000000000..d158e47f05 --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/MetadataParameter.java @@ -0,0 +1,67 @@ +package com.nepxion.discovery.common.entity; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.io.Serializable; +import java.util.List; + +import org.apache.commons.lang3.builder.EqualsBuilder; +import org.apache.commons.lang3.builder.HashCodeBuilder; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; + +public class MetadataParameter implements Serializable { + private static final long serialVersionUID = -8708814947706738426L; + + public static final String SEPARATE = " | "; + + private List metadataKeys; + private List serviceIds; + private String separate = SEPARATE; + + public List getMetadataKeys() { + return metadataKeys; + } + + public void setMetadataKeys(List metadataKeys) { + this.metadataKeys = metadataKeys; + } + + public List getServiceIds() { + return serviceIds; + } + + public void setServiceIds(List serviceIds) { + this.serviceIds = serviceIds; + } + + public String getSeparate() { + return separate; + } + + public void setSeparate(String separate) { + this.separate = separate; + } + + @Override + public int hashCode() { + return HashCodeBuilder.reflectionHashCode(this); + } + + @Override + public boolean equals(Object object) { + return EqualsBuilder.reflectionEquals(this, object); + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); + } +} \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/PackagesInjectorEntity.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/PackagesInjectorEntity.java new file mode 100644 index 0000000000..c27d91ca43 --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/PackagesInjectorEntity.java @@ -0,0 +1,65 @@ +package com.nepxion.discovery.common.entity; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.io.Serializable; +import java.util.List; + +import org.apache.commons.lang3.builder.EqualsBuilder; +import org.apache.commons.lang3.builder.HashCodeBuilder; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; + +public class PackagesInjectorEntity implements Serializable { + private static final long serialVersionUID = 5730588860616523887L; + + private PackagesInjectorType packagesInjectorType; + private List packages; + + public PackagesInjectorEntity() { + + } + + public PackagesInjectorEntity(PackagesInjectorType packagesInjectorType, List packages) { + this.packagesInjectorType = packagesInjectorType; + this.packages = packages; + } + + public PackagesInjectorType getPackagesInjectorType() { + return packagesInjectorType; + } + + public void setPackagesInjectorType(PackagesInjectorType packagesInjectorType) { + this.packagesInjectorType = packagesInjectorType; + } + + public List getPackages() { + return packages; + } + + public void setPackages(List packages) { + this.packages = packages; + } + + @Override + public int hashCode() { + return HashCodeBuilder.reflectionHashCode(this); + } + + @Override + public boolean equals(Object object) { + return EqualsBuilder.reflectionEquals(this, object); + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); + } +} \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/PackagesInjectorType.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/PackagesInjectorType.java new file mode 100644 index 0000000000..9e7b864616 --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/PackagesInjectorType.java @@ -0,0 +1,17 @@ +package com.nepxion.discovery.common.entity; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +public enum PackagesInjectorType { + RPC, + PROVIDER_ISOLATION, + TRACER, + ALL; +} \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/ParameterEntity.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/ParameterEntity.java new file mode 100644 index 0000000000..4d4fb6b277 --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/ParameterEntity.java @@ -0,0 +1,49 @@ +package com.nepxion.discovery.common.entity; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.io.Serializable; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import org.apache.commons.lang3.builder.EqualsBuilder; +import org.apache.commons.lang3.builder.HashCodeBuilder; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; + +public class ParameterEntity implements Serializable { + private static final long serialVersionUID = -5135099669922746855L; + + private Map> parameterServiceMap = new LinkedHashMap>(); + + public Map> getParameterServiceMap() { + return parameterServiceMap; + } + + public void setParameterServiceMap(Map> parameterServiceMap) { + this.parameterServiceMap = parameterServiceMap; + } + + @Override + public int hashCode() { + return HashCodeBuilder.reflectionHashCode(this); + } + + @Override + public boolean equals(Object object) { + return EqualsBuilder.reflectionEquals(this, object); + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); + } +} \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/ParameterServiceEntity.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/ParameterServiceEntity.java new file mode 100644 index 0000000000..e1730f40c7 --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/ParameterServiceEntity.java @@ -0,0 +1,48 @@ +package com.nepxion.discovery.common.entity; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.io.Serializable; +import java.util.LinkedHashMap; +import java.util.Map; + +import org.apache.commons.lang3.builder.EqualsBuilder; +import org.apache.commons.lang3.builder.HashCodeBuilder; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; + +public class ParameterServiceEntity implements Serializable { + private static final long serialVersionUID = 3102584092049806966L; + + private Map parameterMap = new LinkedHashMap(); + + public Map getParameterMap() { + return parameterMap; + } + + public void setParameterMap(Map parameterMap) { + this.parameterMap = parameterMap; + } + + @Override + public int hashCode() { + return HashCodeBuilder.reflectionHashCode(this); + } + + @Override + public boolean equals(Object object) { + return EqualsBuilder.reflectionEquals(this, object); + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); + } +} \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/ParameterType.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/ParameterType.java new file mode 100644 index 0000000000..97857ba51b --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/ParameterType.java @@ -0,0 +1,43 @@ +package com.nepxion.discovery.common.entity; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import com.nepxion.discovery.common.constant.DiscoveryConstant; + +public enum ParameterType { + HEADER(DiscoveryConstant.HEADER_TYPE), + PARAMETER(DiscoveryConstant.PARAMETER_TYPE), + COOKIE(DiscoveryConstant.COOKIE_TYPE); + + private String value; + + private ParameterType(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + + public static ParameterType fromString(String value) { + for (ParameterType type : ParameterType.values()) { + if (type.getValue().equalsIgnoreCase(value)) { + return type; + } + } + + throw new IllegalArgumentException("No matched type with value=" + value); + } + + @Override + public String toString() { + return value; + } +} \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/PortalType.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/PortalType.java new file mode 100644 index 0000000000..b405b541f4 --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/PortalType.java @@ -0,0 +1,42 @@ +package com.nepxion.discovery.common.entity; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import com.nepxion.discovery.common.constant.DiscoveryConstant; + +public enum PortalType { + GATEWAY(DiscoveryConstant.GATEWAY), + SERVICE(DiscoveryConstant.SERVICE); + + private String value; + + private PortalType(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + + public static PortalType fromString(String value) { + for (PortalType type : PortalType.values()) { + if (type.getValue().equalsIgnoreCase(value)) { + return type; + } + } + + throw new IllegalArgumentException("No matched type with value=" + value); + } + + @Override + public String toString() { + return value; + } +} \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/ProtectorType.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/ProtectorType.java new file mode 100644 index 0000000000..82bc310f10 --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/ProtectorType.java @@ -0,0 +1,42 @@ +package com.nepxion.discovery.common.entity; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import com.nepxion.discovery.common.constant.DiscoveryConstant; + +public enum ProtectorType { + HYSTRIX(DiscoveryConstant.HYSTRIX), + SENTINEL(DiscoveryConstant.SENTINEL); + + private String value; + + private ProtectorType(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + + public static ProtectorType fromString(String value) { + for (ProtectorType type : ProtectorType.values()) { + if (type.getValue().equalsIgnoreCase(value)) { + return type; + } + } + + throw new IllegalArgumentException("No matched type with value=" + value); + } + + @Override + public String toString() { + return value; + } +} \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/RegionEntity.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/RegionEntity.java new file mode 100644 index 0000000000..26dde9fdf8 --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/RegionEntity.java @@ -0,0 +1,74 @@ +package com.nepxion.discovery.common.entity; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.io.Serializable; +import java.util.List; + +import org.apache.commons.lang3.builder.EqualsBuilder; +import org.apache.commons.lang3.builder.HashCodeBuilder; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; + +public class RegionEntity implements Serializable { + private static final long serialVersionUID = 4242096651626967253L; + + private String consumerServiceName; + private String providerServiceName; + private List consumerRegionValueList; + private List providerRegionValueList; + + public String getConsumerServiceName() { + return consumerServiceName; + } + + public void setConsumerServiceName(String consumerServiceName) { + this.consumerServiceName = consumerServiceName; + } + + public String getProviderServiceName() { + return providerServiceName; + } + + public void setProviderServiceName(String providerServiceName) { + this.providerServiceName = providerServiceName; + } + + public List getConsumerRegionValueList() { + return consumerRegionValueList; + } + + public void setConsumerRegionValueList(List consumerRegionValueList) { + this.consumerRegionValueList = consumerRegionValueList; + } + + public List getProviderRegionValueList() { + return providerRegionValueList; + } + + public void setProviderRegionValueList(List providerRegionValueList) { + this.providerRegionValueList = providerRegionValueList; + } + + @Override + public int hashCode() { + return HashCodeBuilder.reflectionHashCode(this); + } + + @Override + public boolean equals(Object object) { + return EqualsBuilder.reflectionEquals(this, object); + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); + } +} \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/RegionFilterEntity.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/RegionFilterEntity.java new file mode 100644 index 0000000000..d62f4eee59 --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/RegionFilterEntity.java @@ -0,0 +1,49 @@ +package com.nepxion.discovery.common.entity; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.io.Serializable; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import org.apache.commons.lang3.builder.EqualsBuilder; +import org.apache.commons.lang3.builder.HashCodeBuilder; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; + +public class RegionFilterEntity implements Serializable { + private static final long serialVersionUID = 5574079766640689952L; + + private Map> regionEntityMap = new LinkedHashMap>(); + + public Map> getRegionEntityMap() { + return regionEntityMap; + } + + public void setRegionEntityMap(Map> regionEntityMap) { + this.regionEntityMap = regionEntityMap; + } + + @Override + public int hashCode() { + return HashCodeBuilder.reflectionHashCode(this); + } + + @Override + public boolean equals(Object object) { + return EqualsBuilder.reflectionEquals(this, object); + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); + } +} \ No newline at end of file diff --git a/discovery-common/src/main/java/com/nepxion/discovery/common/entity/RegionWeightEntity.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/RegionWeightEntity.java similarity index 100% rename from discovery-common/src/main/java/com/nepxion/discovery/common/entity/RegionWeightEntity.java rename to discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/RegionWeightEntity.java diff --git a/discovery-common/src/main/java/com/nepxion/discovery/common/entity/RegisterEntity.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/RegisterEntity.java similarity index 100% rename from discovery-common/src/main/java/com/nepxion/discovery/common/entity/RegisterEntity.java rename to discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/RegisterEntity.java diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/RelationalType.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/RelationalType.java new file mode 100644 index 0000000000..83502abccb --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/RelationalType.java @@ -0,0 +1,40 @@ +package com.nepxion.discovery.common.entity; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +public enum RelationalType { + AND("and"), + OR("or"); + + private String value; + + private RelationalType(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + + public static RelationalType fromString(String value) { + for (RelationalType type : RelationalType.values()) { + if (type.getValue().equalsIgnoreCase(value)) { + return type; + } + } + + throw new IllegalArgumentException("No matched type with value=" + value); + } + + @Override + public String toString() { + return value; + } +} \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/ResultEntity.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/ResultEntity.java new file mode 100644 index 0000000000..98df2039b3 --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/ResultEntity.java @@ -0,0 +1,82 @@ +package com.nepxion.discovery.common.entity; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.io.Serializable; + +import org.apache.commons.lang3.builder.EqualsBuilder; +import org.apache.commons.lang3.builder.HashCodeBuilder; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; + +public class ResultEntity implements Serializable { + private static final long serialVersionUID = -3322655604556025836L; + + private String serviceId; + private String host; + private int port; + private String url; + private String result; + + public String getServiceId() { + return serviceId; + } + + public void setServiceId(String serviceId) { + this.serviceId = serviceId; + } + + public String getHost() { + return host; + } + + public void setHost(String host) { + this.host = host; + } + + public int getPort() { + return port; + } + + public void setPort(int port) { + this.port = port; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public String getResult() { + return result; + } + + public void setResult(String result) { + this.result = result; + } + + @Override + public int hashCode() { + return HashCodeBuilder.reflectionHashCode(this); + } + + @Override + public boolean equals(Object object) { + return EqualsBuilder.reflectionEquals(this, object); + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); + } +} \ No newline at end of file diff --git a/discovery-common/src/main/java/com/nepxion/discovery/common/entity/RouterEntity.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/RouterEntity.java similarity index 83% rename from discovery-common/src/main/java/com/nepxion/discovery/common/entity/RouterEntity.java rename to discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/RouterEntity.java index 7d7eda1a03..f6780d0d75 100644 --- a/discovery-common/src/main/java/com/nepxion/discovery/common/entity/RouterEntity.java +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/RouterEntity.java @@ -25,9 +25,12 @@ public class RouterEntity implements Serializable { private String serviceId; private String version; private String region; + private String environment; + private String zone; private String host; private int port; private int weight = -1; + private String protocol; private String contextPath; private List nexts = new ArrayList(); @@ -64,6 +67,22 @@ public void setRegion(String region) { this.region = region; } + public String getEnvironment() { + return environment; + } + + public void setEnvironment(String environment) { + this.environment = environment; + } + + public String getZone() { + return zone; + } + + public void setZone(String zone) { + this.zone = zone; + } + public String getHost() { return host; } @@ -88,6 +107,14 @@ public void setWeight(int weight) { this.weight = weight; } + public String getProtocol() { + return protocol; + } + + public void setProtocol(String protocol) { + this.protocol = protocol; + } + public String getContextPath() { return contextPath; } diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/RuleEntity.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/RuleEntity.java new file mode 100644 index 0000000000..16a54398c3 --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/RuleEntity.java @@ -0,0 +1,109 @@ +package com.nepxion.discovery.common.entity; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.io.Serializable; + +import org.apache.commons.lang3.builder.EqualsBuilder; +import org.apache.commons.lang3.builder.HashCodeBuilder; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; + +public class RuleEntity implements Serializable { + private static final long serialVersionUID = 7079024435084528751L; + + private RegisterEntity registerEntity; + private DiscoveryEntity discoveryEntity; + private StrategyEntity strategyEntity; + private StrategyReleaseEntity strategyReleaseEntity; + private StrategyFailoverEntity strategyFailoverEntity; + private StrategyBlacklistEntity strategyBlacklistEntity; + private ParameterEntity parameterEntity; + private String content; + + public RegisterEntity getRegisterEntity() { + return registerEntity; + } + + public void setRegisterEntity(RegisterEntity registerEntity) { + this.registerEntity = registerEntity; + } + + public DiscoveryEntity getDiscoveryEntity() { + return discoveryEntity; + } + + public void setDiscoveryEntity(DiscoveryEntity discoveryEntity) { + this.discoveryEntity = discoveryEntity; + } + + public StrategyEntity getStrategyEntity() { + return strategyEntity; + } + + public void setStrategyEntity(StrategyEntity strategyEntity) { + this.strategyEntity = strategyEntity; + } + + public StrategyReleaseEntity getStrategyReleaseEntity() { + return strategyReleaseEntity; + } + + public void setStrategyReleaseEntity(StrategyReleaseEntity strategyReleaseEntity) { + this.strategyReleaseEntity = strategyReleaseEntity; + } + + public StrategyFailoverEntity getStrategyFailoverEntity() { + return strategyFailoverEntity; + } + + public void setStrategyFailoverEntity(StrategyFailoverEntity strategyFailoverEntity) { + this.strategyFailoverEntity = strategyFailoverEntity; + } + + public StrategyBlacklistEntity getStrategyBlacklistEntity() { + return strategyBlacklistEntity; + } + + public void setStrategyBlacklistEntity(StrategyBlacklistEntity strategyBlacklistEntity) { + this.strategyBlacklistEntity = strategyBlacklistEntity; + } + + public ParameterEntity getParameterEntity() { + return parameterEntity; + } + + public void setParameterEntity(ParameterEntity parameterEntity) { + this.parameterEntity = parameterEntity; + } + + public String getContent() { + return content; + } + + public void setContent(String content) { + this.content = content; + } + + @Override + public int hashCode() { + return HashCodeBuilder.reflectionHashCode(this); + } + + @Override + public boolean equals(Object object) { + return EqualsBuilder.reflectionEquals(this, object); + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); + } +} \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/RuleEntityWrapper.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/RuleEntityWrapper.java new file mode 100644 index 0000000000..5973e346d4 --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/RuleEntityWrapper.java @@ -0,0 +1,83 @@ +package com.nepxion.discovery.common.entity; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +public class RuleEntityWrapper { + // 以局部规则为准,如果局部规则规则里某些属性没有,而全局规则有,则从全局规则把那些属性复制到局部规则,并合并创建最终的复合规则 + public static RuleEntity assemble(RuleEntity partialRuleEntity, RuleEntity globalRuleEntity) { + RuleEntity ruleEntity = new RuleEntity(); + + RegisterEntity registerEntity = null; + if (partialRuleEntity != null && partialRuleEntity.getRegisterEntity() != null) { + registerEntity = partialRuleEntity.getRegisterEntity(); + } else if (globalRuleEntity != null && globalRuleEntity.getRegisterEntity() != null) { + registerEntity = globalRuleEntity.getRegisterEntity(); + } + ruleEntity.setRegisterEntity(registerEntity); + + DiscoveryEntity discoveryEntity = null; + if (partialRuleEntity != null && partialRuleEntity.getDiscoveryEntity() != null) { + discoveryEntity = partialRuleEntity.getDiscoveryEntity(); + } else if (globalRuleEntity != null && globalRuleEntity.getDiscoveryEntity() != null) { + discoveryEntity = globalRuleEntity.getDiscoveryEntity(); + } + ruleEntity.setDiscoveryEntity(discoveryEntity); + + StrategyEntity strategyEntity = null; + if (partialRuleEntity != null && partialRuleEntity.getStrategyEntity() != null) { + strategyEntity = partialRuleEntity.getStrategyEntity(); + } else if (globalRuleEntity != null && globalRuleEntity.getStrategyEntity() != null) { + strategyEntity = globalRuleEntity.getStrategyEntity(); + } + ruleEntity.setStrategyEntity(strategyEntity); + + StrategyReleaseEntity strategyReleaseEntity = null; + if (partialRuleEntity != null && partialRuleEntity.getStrategyReleaseEntity() != null) { + strategyReleaseEntity = partialRuleEntity.getStrategyReleaseEntity(); + } else if (globalRuleEntity != null && globalRuleEntity.getStrategyReleaseEntity() != null) { + strategyReleaseEntity = globalRuleEntity.getStrategyReleaseEntity(); + } + ruleEntity.setStrategyReleaseEntity(strategyReleaseEntity); + + StrategyFailoverEntity strategyFailoverEntity = null; + if (partialRuleEntity != null && partialRuleEntity.getStrategyFailoverEntity() != null) { + strategyFailoverEntity = partialRuleEntity.getStrategyFailoverEntity(); + } else if (globalRuleEntity != null && globalRuleEntity.getStrategyFailoverEntity() != null) { + strategyFailoverEntity = globalRuleEntity.getStrategyFailoverEntity(); + } + ruleEntity.setStrategyFailoverEntity(strategyFailoverEntity); + + StrategyBlacklistEntity strategyBlacklistEntity = null; + if (partialRuleEntity != null && partialRuleEntity.getStrategyBlacklistEntity() != null) { + strategyBlacklistEntity = partialRuleEntity.getStrategyBlacklistEntity(); + } else if (globalRuleEntity != null && globalRuleEntity.getStrategyBlacklistEntity() != null) { + strategyBlacklistEntity = globalRuleEntity.getStrategyBlacklistEntity(); + } + ruleEntity.setStrategyBlacklistEntity(strategyBlacklistEntity); + + ParameterEntity parameterEntity = null; + if (partialRuleEntity != null && partialRuleEntity.getParameterEntity() != null) { + parameterEntity = partialRuleEntity.getParameterEntity(); + } else if (globalRuleEntity != null && globalRuleEntity.getParameterEntity() != null) { + parameterEntity = globalRuleEntity.getParameterEntity(); + } + ruleEntity.setParameterEntity(parameterEntity); + + String content = null; + if (partialRuleEntity != null && partialRuleEntity.getContent() != null) { + content = partialRuleEntity.getContent(); + } else if (globalRuleEntity != null && globalRuleEntity.getContent() != null) { + content = globalRuleEntity.getContent(); + } + ruleEntity.setContent(content); + + return ruleEntity; + } +} \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/SentinelMetricType.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/SentinelMetricType.java new file mode 100644 index 0000000000..e63f971a6f --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/SentinelMetricType.java @@ -0,0 +1,44 @@ +package com.nepxion.discovery.common.entity; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Tank + * @version 1.0 + */ + +import com.nepxion.discovery.common.constant.DiscoveryConstant; + +public enum SentinelMetricType { + PASS_QPS(DiscoveryConstant.SENTINEL_PASS_QPS_KEY), + BLOCK_QPS(DiscoveryConstant.SENTINEL_BLOCK_QPS_KEY), + SUCCESS_QPS(DiscoveryConstant.SENTINEL_SUCCESS_QPS_KEY), + EXCEPTION_QPS(DiscoveryConstant.SENTINEL_EXCEPTION_QPS_KEY); + + private String value; + + private SentinelMetricType(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + + public static SentinelMetricType fromString(String value) { + for (SentinelMetricType type : SentinelMetricType.values()) { + if (type.getValue().equalsIgnoreCase(value)) { + return type; + } + } + + throw new IllegalArgumentException("No matched type with value=" + value); + } + + @Override + public String toString() { + return value; + } +} \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/SentinelRuleType.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/SentinelRuleType.java new file mode 100644 index 0000000000..194898cd3b --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/SentinelRuleType.java @@ -0,0 +1,69 @@ +package com.nepxion.discovery.common.entity; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import com.nepxion.discovery.common.constant.DiscoveryConstant; + +public enum SentinelRuleType { + FLOW(DiscoveryConstant.SENTINEL_FLOW, DiscoveryConstant.SENTINEL_FLOW_KEY, DiscoveryConstant.SENTINEL_FLOW_DESCRIPTION), + DEGRADE(DiscoveryConstant.SENTINEL_DEGRADE, DiscoveryConstant.SENTINEL_DEGRADE_KEY, DiscoveryConstant.SENTINEL_DEGRADE_DESCRIPTION), + AUTHORITY(DiscoveryConstant.SENTINEL_AUTHORITY, DiscoveryConstant.SENTINEL_AUTHORITY_KEY, DiscoveryConstant.SENTINEL_AUTHORITY_DESCRIPTION), + SYSTEM(DiscoveryConstant.SENTINEL_SYSTEM, DiscoveryConstant.SENTINEL_SYSTEM_KEY, DiscoveryConstant.SENTINEL_SYSTEM_DESCRIPTION), + PARAM_FLOW(DiscoveryConstant.SENTINEL_PARAM_FLOW, DiscoveryConstant.SENTINEL_PARAM_FLOW_KEY, DiscoveryConstant.SENTINEL_PARAM_FLOW_DESCRIPTION); + + private String value; + private String key; + private String description; + + private SentinelRuleType(String value, String key, String description) { + this.value = value; + this.key = key; + this.description = description; + } + + public String getValue() { + return value; + } + + public String getKey() { + return key; + } + + public String getDescription() { + return description; + } + + public static SentinelRuleType fromString(String value) { + return fromString(value, true); + } + + public static SentinelRuleType fromString(String value, boolean fromValue) { + if (fromValue) { + for (SentinelRuleType type : SentinelRuleType.values()) { + if (type.getValue().equalsIgnoreCase(value)) { + return type; + } + } + } else { + for (SentinelRuleType type : SentinelRuleType.values()) { + if (type.getKey().equalsIgnoreCase(value)) { + return type; + } + } + } + + throw new IllegalArgumentException("No matched type with value=" + value); + } + + @Override + public String toString() { + return value; + } +} \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/ServiceType.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/ServiceType.java new file mode 100644 index 0000000000..86130eeec4 --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/ServiceType.java @@ -0,0 +1,44 @@ +package com.nepxion.discovery.common.entity; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import com.nepxion.discovery.common.constant.DiscoveryConstant; + +public enum ServiceType { + SERVICE(DiscoveryConstant.SERVICE), + GATEWAY(DiscoveryConstant.GATEWAY), + CONSOLE(DiscoveryConstant.CONSOLE), + TEST(DiscoveryConstant.TEST); + + private String value; + + private ServiceType(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + + public static ServiceType fromString(String value) { + for (ServiceType type : ServiceType.values()) { + if (type.getValue().equalsIgnoreCase(value)) { + return type; + } + } + + throw new IllegalArgumentException("No matched type with value=" + value); + } + + @Override + public String toString() { + return value; + } +} \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/StrategyBlacklistEntity.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/StrategyBlacklistEntity.java new file mode 100644 index 0000000000..de37ed1874 --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/StrategyBlacklistEntity.java @@ -0,0 +1,55 @@ +package com.nepxion.discovery.common.entity; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.io.Serializable; + +import org.apache.commons.lang3.builder.EqualsBuilder; +import org.apache.commons.lang3.builder.HashCodeBuilder; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; + +public class StrategyBlacklistEntity implements Serializable { + private static final long serialVersionUID = -5342596042988530380L; + + private String idValue; + private String addressValue; + + public String getIdValue() { + return idValue; + } + + public void setIdValue(String idValue) { + this.idValue = idValue; + } + + public String getAddressValue() { + return addressValue; + } + + public void setAddressValue(String addressValue) { + this.addressValue = addressValue; + } + + @Override + public int hashCode() { + return HashCodeBuilder.reflectionHashCode(this); + } + + @Override + public boolean equals(Object object) { + return EqualsBuilder.reflectionEquals(this, object); + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); + } +} \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/StrategyConditionBlueGreenEntity.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/StrategyConditionBlueGreenEntity.java new file mode 100644 index 0000000000..4aff4c62ad --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/StrategyConditionBlueGreenEntity.java @@ -0,0 +1,60 @@ +package com.nepxion.discovery.common.entity; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +public class StrategyConditionBlueGreenEntity extends StrategyConditionEntity { + private static final long serialVersionUID = 7119457349396638259L; + + private String versionId; + private String regionId; + private String addressId; + private String versionWeightId; + private String regionWeightId; + + public String getVersionId() { + return versionId; + } + + public void setVersionId(String versionId) { + this.versionId = versionId; + } + + public String getRegionId() { + return regionId; + } + + public void setRegionId(String regionId) { + this.regionId = regionId; + } + + public String getAddressId() { + return addressId; + } + + public void setAddressId(String addressId) { + this.addressId = addressId; + } + + public String getVersionWeightId() { + return versionWeightId; + } + + public void setVersionWeightId(String versionWeightId) { + this.versionWeightId = versionWeightId; + } + + public String getRegionWeightId() { + return regionWeightId; + } + + public void setRegionWeightId(String regionWeightId) { + this.regionWeightId = regionWeightId; + } +} \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/StrategyConditionEntity.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/StrategyConditionEntity.java new file mode 100644 index 0000000000..23c5f33a59 --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/StrategyConditionEntity.java @@ -0,0 +1,55 @@ +package com.nepxion.discovery.common.entity; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.io.Serializable; + +import org.apache.commons.lang3.builder.EqualsBuilder; +import org.apache.commons.lang3.builder.HashCodeBuilder; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; + +public class StrategyConditionEntity implements Serializable { + private static final long serialVersionUID = 1249482860170990672L; + + private String id; + private String expression; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getExpression() { + return expression; + } + + public void setExpression(String expression) { + this.expression = expression; + } + + @Override + public int hashCode() { + return HashCodeBuilder.reflectionHashCode(this); + } + + @Override + public boolean equals(Object object) { + return EqualsBuilder.reflectionEquals(this, object); + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); + } +} \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/StrategyConditionGrayEntity.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/StrategyConditionGrayEntity.java new file mode 100644 index 0000000000..2b63df15f3 --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/StrategyConditionGrayEntity.java @@ -0,0 +1,42 @@ +package com.nepxion.discovery.common.entity; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +public class StrategyConditionGrayEntity extends StrategyConditionEntity { + private static final long serialVersionUID = 4992751531082022953L; + + private VersionWeightEntity versionWeightEntity; + private RegionWeightEntity regionWeightEntity; + private AddressWeightEntity addressWeightEntity; + + public VersionWeightEntity getVersionWeightEntity() { + return versionWeightEntity; + } + + public void setVersionWeightEntity(VersionWeightEntity versionWeightEntity) { + this.versionWeightEntity = versionWeightEntity; + } + + public RegionWeightEntity getRegionWeightEntity() { + return regionWeightEntity; + } + + public void setRegionWeightEntity(RegionWeightEntity regionWeightEntity) { + this.regionWeightEntity = regionWeightEntity; + } + + public AddressWeightEntity getAddressWeightEntity() { + return addressWeightEntity; + } + + public void setAddressWeightEntity(AddressWeightEntity addressWeightEntity) { + this.addressWeightEntity = addressWeightEntity; + } +} \ No newline at end of file diff --git a/discovery-common/src/main/java/com/nepxion/discovery/common/entity/StrategyEntity.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/StrategyEntity.java similarity index 100% rename from discovery-common/src/main/java/com/nepxion/discovery/common/entity/StrategyEntity.java rename to discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/StrategyEntity.java diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/StrategyFailoverEntity.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/StrategyFailoverEntity.java new file mode 100644 index 0000000000..6975774125 --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/StrategyFailoverEntity.java @@ -0,0 +1,100 @@ +package com.nepxion.discovery.common.entity; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.io.Serializable; + +import org.apache.commons.lang3.builder.EqualsBuilder; +import org.apache.commons.lang3.builder.HashCodeBuilder; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; + +public class StrategyFailoverEntity implements Serializable { + private static final long serialVersionUID = 5321045298130813301L; + + private String versionPreferValue; + private String versionFailoverValue; + private String regionTransferValue; + private String regionFailoverValue; + private String environmentFailoverValue; + private String zoneFailoverValue; + private String addressFailoverValue; + + public String getVersionPreferValue() { + return versionPreferValue; + } + + public void setVersionPreferValue(String versionPreferValue) { + this.versionPreferValue = versionPreferValue; + } + + public String getVersionFailoverValue() { + return versionFailoverValue; + } + + public void setVersionFailoverValue(String versionFailoverValue) { + this.versionFailoverValue = versionFailoverValue; + } + + public String getRegionTransferValue() { + return regionTransferValue; + } + + public void setRegionTransferValue(String regionTransferValue) { + this.regionTransferValue = regionTransferValue; + } + + public String getRegionFailoverValue() { + return regionFailoverValue; + } + + public void setRegionFailoverValue(String regionFailoverValue) { + this.regionFailoverValue = regionFailoverValue; + } + + public String getEnvironmentFailoverValue() { + return environmentFailoverValue; + } + + public void setEnvironmentFailoverValue(String environmentFailoverValue) { + this.environmentFailoverValue = environmentFailoverValue; + } + + public String getZoneFailoverValue() { + return zoneFailoverValue; + } + + public void setZoneFailoverValue(String zoneFailoverValue) { + this.zoneFailoverValue = zoneFailoverValue; + } + + public String getAddressFailoverValue() { + return addressFailoverValue; + } + + public void setAddressFailoverValue(String addressFailoverValue) { + this.addressFailoverValue = addressFailoverValue; + } + + @Override + public int hashCode() { + return HashCodeBuilder.reflectionHashCode(this); + } + + @Override + public boolean equals(Object object) { + return EqualsBuilder.reflectionEquals(this, object); + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); + } +} \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/StrategyHeaderEntity.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/StrategyHeaderEntity.java new file mode 100644 index 0000000000..e462a1da71 --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/StrategyHeaderEntity.java @@ -0,0 +1,53 @@ +package com.nepxion.discovery.common.entity; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.io.Serializable; +import java.util.Map; + +import org.apache.commons.collections4.MapUtils; +import org.apache.commons.lang3.builder.EqualsBuilder; +import org.apache.commons.lang3.builder.HashCodeBuilder; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; +import org.springframework.util.LinkedCaseInsensitiveMap; + +public class StrategyHeaderEntity implements Serializable { + private static final long serialVersionUID = 7784567539151885177L; + + private Map headerMap = new LinkedCaseInsensitiveMap(); + + public Map getHeaderMap() { + return headerMap; + } + + public void setHeaderMap(Map headerMap) { + this.headerMap.clear(); + + if (MapUtils.isNotEmpty(headerMap)) { + this.headerMap.putAll(headerMap); + } + } + + @Override + public int hashCode() { + return HashCodeBuilder.reflectionHashCode(this); + } + + @Override + public boolean equals(Object object) { + return EqualsBuilder.reflectionEquals(this, object); + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); + } +} \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/StrategyReleaseEntity.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/StrategyReleaseEntity.java new file mode 100644 index 0000000000..fc602d4e64 --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/StrategyReleaseEntity.java @@ -0,0 +1,104 @@ +package com.nepxion.discovery.common.entity; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.io.Serializable; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; + +import org.apache.commons.collections4.CollectionUtils; +import org.apache.commons.lang3.builder.EqualsBuilder; +import org.apache.commons.lang3.builder.HashCodeBuilder; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; + +import com.nepxion.discovery.common.constant.DiscoveryConstant; +import com.nepxion.discovery.common.util.StringUtil; + +public class StrategyReleaseEntity implements Serializable { + private static final long serialVersionUID = 4903833660194433964L; + + private List strategyConditionBlueGreenEntityList; + private List strategyConditionGrayEntityList; + private List strategyRouteEntityList; + private StrategyHeaderEntity strategyHeaderEntity; + + public List getStrategyConditionBlueGreenEntityList() { + return strategyConditionBlueGreenEntityList; + } + + public void setStrategyConditionBlueGreenEntityList(List strategyConditionBlueGreenEntityList) { + this.strategyConditionBlueGreenEntityList = strategyConditionBlueGreenEntityList; + } + + public List getStrategyConditionGrayEntityList() { + return strategyConditionGrayEntityList; + } + + public void setStrategyConditionGrayEntityList(List strategyConditionGrayEntityList) { + this.strategyConditionGrayEntityList = strategyConditionGrayEntityList; + } + + public List getStrategyRouteEntityList() { + return strategyRouteEntityList; + } + + public void setStrategyRouteEntityList(List strategyRouteEntityList) { + this.strategyRouteEntityList = strategyRouteEntityList; + + // Header参数越多,越排在前面 + if (CollectionUtils.isNotEmpty(strategyConditionBlueGreenEntityList)) { + Collections.sort(strategyConditionBlueGreenEntityList, new Comparator() { + public int compare(StrategyConditionBlueGreenEntity strategyConditionBlueGreenEntity1, StrategyConditionBlueGreenEntity strategyConditionBlueGreenEntity2) { + Integer count1 = StringUtil.count(strategyConditionBlueGreenEntity1.getExpression(), DiscoveryConstant.EXPRESSION_SUB_PREFIX); + Integer count2 = StringUtil.count(strategyConditionBlueGreenEntity2.getExpression(), DiscoveryConstant.EXPRESSION_SUB_PREFIX); + + return count2.compareTo(count1); + } + }); + } + + // Header参数越多,越排在前面 + if (CollectionUtils.isNotEmpty(strategyConditionGrayEntityList)) { + Collections.sort(strategyConditionGrayEntityList, new Comparator() { + public int compare(StrategyConditionGrayEntity strategyConditionGrayEntity1, StrategyConditionGrayEntity strategyConditionGrayEntity2) { + Integer count1 = StringUtil.count(strategyConditionGrayEntity1.getExpression(), DiscoveryConstant.EXPRESSION_SUB_PREFIX); + Integer count2 = StringUtil.count(strategyConditionGrayEntity2.getExpression(), DiscoveryConstant.EXPRESSION_SUB_PREFIX); + + return count2.compareTo(count1); + } + }); + } + } + + public StrategyHeaderEntity getStrategyHeaderEntity() { + return strategyHeaderEntity; + } + + public void setStrategyHeaderEntity(StrategyHeaderEntity strategyHeaderEntity) { + this.strategyHeaderEntity = strategyHeaderEntity; + } + + @Override + public int hashCode() { + return HashCodeBuilder.reflectionHashCode(this); + } + + @Override + public boolean equals(Object object) { + return EqualsBuilder.reflectionEquals(this, object); + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); + } +} \ No newline at end of file diff --git a/discovery-common/src/main/java/com/nepxion/discovery/common/entity/StrategyRouteEntity.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/StrategyRouteEntity.java similarity index 91% rename from discovery-common/src/main/java/com/nepxion/discovery/common/entity/StrategyRouteEntity.java rename to discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/StrategyRouteEntity.java index 24212dc791..e5c0e51a2f 100644 --- a/discovery-common/src/main/java/com/nepxion/discovery/common/entity/StrategyRouteEntity.java +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/StrategyRouteEntity.java @@ -20,7 +20,7 @@ public class StrategyRouteEntity implements Serializable { private static final long serialVersionUID = -949309319161395011L; private String id; - private StrategyType type; + private StrategyRouteType type; private String value; public String getId() { @@ -31,11 +31,11 @@ public void setId(String id) { this.id = id; } - public StrategyType getType() { + public StrategyRouteType getType() { return type; } - public void setType(StrategyType type) { + public void setType(StrategyRouteType type) { this.type = type; } diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/StrategyRouteType.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/StrategyRouteType.java new file mode 100644 index 0000000000..4836a842bc --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/StrategyRouteType.java @@ -0,0 +1,47 @@ +package com.nepxion.discovery.common.entity; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import com.nepxion.discovery.common.constant.DiscoveryConstant; + +public enum StrategyRouteType { + VERSION(DiscoveryConstant.VERSION), + REGION(DiscoveryConstant.REGION), + ADDRESS(DiscoveryConstant.ADDRESS), + VERSION_WEIGHT(DiscoveryConstant.VERSION_WEIGHT), + REGION_WEIGHT(DiscoveryConstant.REGION_WEIGHT), + ID_BLACKLIST(DiscoveryConstant.ID_BLACKLIST), + ADDRESS_BLACKLIST(DiscoveryConstant.ADDRESS_BLACKLIST); + + private String value; + + private StrategyRouteType(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + + public static StrategyRouteType fromString(String value) { + for (StrategyRouteType type : StrategyRouteType.values()) { + if (type.getValue().equalsIgnoreCase(value)) { + return type; + } + } + + throw new IllegalArgumentException("No matched type with value=" + value); + } + + @Override + public String toString() { + return value; + } +} \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/SubscriptionType.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/SubscriptionType.java new file mode 100644 index 0000000000..36fc62a61e --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/SubscriptionType.java @@ -0,0 +1,42 @@ +package com.nepxion.discovery.common.entity; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import com.nepxion.discovery.common.constant.DiscoveryConstant; + +public enum SubscriptionType { + PARTIAL(DiscoveryConstant.PARTIAL), + GLOBAL(DiscoveryConstant.GLOBAL); + + private String value; + + private SubscriptionType(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + + public static SubscriptionType fromString(String value) { + for (SubscriptionType type : SubscriptionType.values()) { + if (type.getValue().equalsIgnoreCase(value)) { + return type; + } + } + + throw new IllegalArgumentException("No matched type with value=" + value); + } + + @Override + public String toString() { + return value; + } +} \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/TracingType.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/TracingType.java new file mode 100644 index 0000000000..831d29e3e3 --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/TracingType.java @@ -0,0 +1,43 @@ +package com.nepxion.discovery.common.entity; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import com.nepxion.discovery.common.constant.DiscoveryConstant; + +public enum TracingType { + OPENTELEMETRY(DiscoveryConstant.OPENTELEMETRY), + OPENTRACING(DiscoveryConstant.OPENTRACING), + SKYWALKING(DiscoveryConstant.SKYWALKING); + + private String value; + + private TracingType(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + + public static TracingType fromString(String value) { + for (TracingType type : TracingType.values()) { + if (type.getValue().equalsIgnoreCase(value)) { + return type; + } + } + + throw new IllegalArgumentException("No matched type with value=" + value); + } + + @Override + public String toString() { + return value; + } +} \ No newline at end of file diff --git a/discovery-common/src/main/java/com/nepxion/discovery/common/entity/UserEntity.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/UserEntity.java similarity index 88% rename from discovery-common/src/main/java/com/nepxion/discovery/common/entity/UserEntity.java rename to discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/UserEntity.java index 34fe4b1eeb..303ace4752 100644 --- a/discovery-common/src/main/java/com/nepxion/discovery/common/entity/UserEntity.java +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/UserEntity.java @@ -9,12 +9,16 @@ * @version 1.0 */ +import java.io.Serializable; + import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; -public class UserEntity { +public class UserEntity implements Serializable { + private static final long serialVersionUID = 7873578695343188087L; + private String userId; private String password; diff --git a/discovery-common/src/main/java/com/nepxion/discovery/common/entity/VersionEntity.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/VersionEntity.java similarity index 100% rename from discovery-common/src/main/java/com/nepxion/discovery/common/entity/VersionEntity.java rename to discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/VersionEntity.java diff --git a/discovery-common/src/main/java/com/nepxion/discovery/common/entity/VersionFilterEntity.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/VersionFilterEntity.java similarity index 100% rename from discovery-common/src/main/java/com/nepxion/discovery/common/entity/VersionFilterEntity.java rename to discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/VersionFilterEntity.java diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/VersionSortEntity.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/VersionSortEntity.java new file mode 100644 index 0000000000..bf9ab4e0af --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/VersionSortEntity.java @@ -0,0 +1,55 @@ +package com.nepxion.discovery.common.entity; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.io.Serializable; + +import org.apache.commons.lang3.builder.EqualsBuilder; +import org.apache.commons.lang3.builder.HashCodeBuilder; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; + +public class VersionSortEntity implements Serializable { + private static final long serialVersionUID = -6333633245983610222L; + + private String version; + private String serviceUUId; + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public String getServiceUUId() { + return serviceUUId; + } + + public void setServiceUUId(String serviceUUId) { + this.serviceUUId = serviceUUId; + } + + @Override + public int hashCode() { + return HashCodeBuilder.reflectionHashCode(this); + } + + @Override + public boolean equals(Object object) { + return EqualsBuilder.reflectionEquals(this, object); + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); + } +} \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/VersionSortType.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/VersionSortType.java new file mode 100644 index 0000000000..7c2761a0dd --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/VersionSortType.java @@ -0,0 +1,42 @@ +package com.nepxion.discovery.common.entity; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import com.nepxion.discovery.common.constant.DiscoveryConstant; + +public enum VersionSortType { + TIME(DiscoveryConstant.SORT_BY_TIME), + VERSION(DiscoveryConstant.SORT_BY_VERSION); + + private String value; + + private VersionSortType(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + + public static VersionSortType fromString(String value) { + for (VersionSortType type : VersionSortType.values()) { + if (type.getValue().equalsIgnoreCase(value)) { + return type; + } + } + + throw new IllegalArgumentException("No matched type with value=" + value); + } + + @Override + public String toString() { + return value; + } +} \ No newline at end of file diff --git a/discovery-common/src/main/java/com/nepxion/discovery/common/entity/VersionWeightEntity.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/VersionWeightEntity.java similarity index 100% rename from discovery-common/src/main/java/com/nepxion/discovery/common/entity/VersionWeightEntity.java rename to discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/VersionWeightEntity.java diff --git a/discovery-common/src/main/java/com/nepxion/discovery/common/entity/WeightEntity.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/WeightEntity.java similarity index 100% rename from discovery-common/src/main/java/com/nepxion/discovery/common/entity/WeightEntity.java rename to discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/WeightEntity.java diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/WeightEntityWrapper.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/WeightEntityWrapper.java new file mode 100644 index 0000000000..4bed4351b8 --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/WeightEntityWrapper.java @@ -0,0 +1,140 @@ +package com.nepxion.discovery.common.entity; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import org.apache.commons.collections4.CollectionUtils; +import org.apache.commons.collections4.MapUtils; +import org.apache.commons.lang3.StringUtils; + +import com.nepxion.discovery.common.constant.DiscoveryConstant; +import com.nepxion.discovery.common.util.JsonUtil; +import com.nepxion.discovery.common.util.StringUtil; + +public class WeightEntityWrapper { + @SuppressWarnings("unchecked") + public static List parseWeightEntityList(String weightValue) { + List weightEntityList = new ArrayList(); + + Map jsonWeightMap = JsonUtil.fromJson(weightValue, Map.class); + for (Map.Entry entry : jsonWeightMap.entrySet()) { + String providerServiceName = entry.getKey(); + String providerWeightValue = entry.getValue(); + + WeightEntity weightEntity = new WeightEntity(); + weightEntity.setProviderServiceName(providerServiceName); + + parseWeightEntity(weightEntity, providerWeightValue); + + weightEntityList.add(weightEntity); + } + + return weightEntityList; + } + + public static void parseWeightEntity(MapWeightEntity weightEntity, String weightValue) { + Map weightMap = weightEntity.getWeightMap(); + List providerWeightValueList = StringUtil.splitToList(weightValue); + if (CollectionUtils.isNotEmpty(providerWeightValueList)) { + for (String value : providerWeightValueList) { + String[] valueArray = StringUtils.split(value, DiscoveryConstant.EQUALS); + String key = valueArray[0].trim(); + int weight = 0; + try { + weight = Integer.valueOf(valueArray[1].trim()); + if (weight < 0) { + weight = 0; + } + } catch (Exception e) { + + } + + weightMap.put(key, weight); + } + } + } + + public static int getWeight(String consumerServiceId, String providerServiceId, String providerKey, Map> weightEntityMap) { + if (MapUtils.isEmpty(weightEntityMap)) { + return -1; + } + + List weightEntityList = weightEntityMap.get(consumerServiceId); + + return getWeight(providerServiceId, providerKey, weightEntityList); + } + + public static int getWeight(String providerServiceId, String providerKey, List weightEntityList) { + if (CollectionUtils.isEmpty(weightEntityList)) { + return -1; + } + + for (WeightEntity weightEntity : weightEntityList) { + String providerServiceName = weightEntity.getProviderServiceName(); + if (StringUtils.equalsIgnoreCase(providerServiceName, providerServiceId)) { + return getWeight(providerKey, weightEntity); + } + } + + return -1; + } + + public static int getWeight(String providerKey, MapWeightEntity weightEntity) { + if (weightEntity == null) { + return -1; + } + + Map weightMap = weightEntity.getWeightMap(); + if (MapUtils.isEmpty(weightMap)) { + return -1; + } + + Integer weight = weightMap.get(providerKey); + if (weight != null) { + return weight; + } else { + return -1; + } + } + + public static int getWeight(WeightFilterEntity weightFilterEntity, String providerServiceId, String providerVersion, String providerRegion, String serviceId) { + int weight = -1; + if (StringUtils.isNotEmpty(serviceId) && weight < 0) { + Map> versionWeightEntityMap = weightFilterEntity.getVersionWeightEntityMap(); + weight = getWeight(serviceId, providerServiceId, providerVersion, versionWeightEntityMap); + } + if (weight < 0) { + List versionWeightEntityList = weightFilterEntity.getVersionWeightEntityList(); + weight = getWeight(providerServiceId, providerVersion, versionWeightEntityList); + } + if (weight < 0) { + VersionWeightEntity versionWeightEntity = weightFilterEntity.getVersionWeightEntity(); + weight = getWeight(providerVersion, versionWeightEntity); + } + + if (StringUtils.isNotEmpty(serviceId) && weight < 0) { + Map> regionWeightEntityMap = weightFilterEntity.getRegionWeightEntityMap(); + weight = getWeight(serviceId, providerServiceId, providerRegion, regionWeightEntityMap); + } + if (weight < 0) { + List regionWeightEntityList = weightFilterEntity.getRegionWeightEntityList(); + weight = getWeight(providerServiceId, providerRegion, regionWeightEntityList); + } + if (weight < 0) { + RegionWeightEntity regionWeightEntity = weightFilterEntity.getRegionWeightEntity(); + weight = getWeight(providerRegion, regionWeightEntity); + } + + return weight; + } +} \ No newline at end of file diff --git a/discovery-common/src/main/java/com/nepxion/discovery/common/entity/WeightFilterEntity.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/WeightFilterEntity.java similarity index 100% rename from discovery-common/src/main/java/com/nepxion/discovery/common/entity/WeightFilterEntity.java rename to discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/WeightFilterEntity.java diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/WeightRandomType.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/WeightRandomType.java new file mode 100644 index 0000000000..666a19f3a2 --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/WeightRandomType.java @@ -0,0 +1,42 @@ +package com.nepxion.discovery.common.entity; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import com.nepxion.discovery.common.constant.DiscoveryConstant; + +public enum WeightRandomType { + MAP_WEIGHT_RANDOM(DiscoveryConstant.MAP_WEIGHT_RANDOM), + ARRAY_WEIGHT_RANDOM(DiscoveryConstant.ARRAY_WEIGHT_RANDOM); + + private String value; + + private WeightRandomType(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + + public static WeightRandomType fromString(String value) { + for (WeightRandomType type : WeightRandomType.values()) { + if (type.getValue().equalsIgnoreCase(value)) { + return type; + } + } + + throw new IllegalArgumentException("No matched type with value=" + value); + } + + @Override + public String toString() { + return value; + } +} \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/WeightType.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/WeightType.java new file mode 100644 index 0000000000..195599c6c3 --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/WeightType.java @@ -0,0 +1,43 @@ +package com.nepxion.discovery.common.entity; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import com.nepxion.discovery.common.constant.DiscoveryConstant; + +public enum WeightType { + VERSION(DiscoveryConstant.VERSION), + REGION(DiscoveryConstant.REGION), + ADDRESS(DiscoveryConstant.ADDRESS); + + private String value; + + private WeightType(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + + public static WeightType fromString(String value) { + for (WeightType type : WeightType.values()) { + if (type.getValue().equalsIgnoreCase(value)) { + return type; + } + } + + throw new IllegalArgumentException("No matched type with value=" + value); + } + + @Override + public String toString() { + return value; + } +} \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/ZuulStrategyRouteEntity.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/ZuulStrategyRouteEntity.java new file mode 100644 index 0000000000..45dc3d7404 --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/ZuulStrategyRouteEntity.java @@ -0,0 +1,111 @@ +package com.nepxion.discovery.common.entity; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.io.Serializable; +import java.util.LinkedHashSet; +import java.util.Set; + +import org.apache.commons.lang3.builder.EqualsBuilder; +import org.apache.commons.lang3.builder.HashCodeBuilder; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; + +public class ZuulStrategyRouteEntity implements Serializable { + private static final long serialVersionUID = 7174491897992085456L; + + private String id; + private String serviceId; + private String path; + private String url; + private boolean stripPrefix = true; + private Boolean retryable; + private Set sensitiveHeaders = new LinkedHashSet<>(); + private boolean customSensitiveHeaders = false; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getServiceId() { + return serviceId; + } + + public void setServiceId(String serviceId) { + this.serviceId = serviceId; + } + + public String getPath() { + return path; + } + + public void setPath(String path) { + this.path = path; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public boolean isStripPrefix() { + return stripPrefix; + } + + public void setStripPrefix(boolean stripPrefix) { + this.stripPrefix = stripPrefix; + } + + public Boolean getRetryable() { + return retryable; + } + + public void setRetryable(Boolean retryable) { + this.retryable = retryable; + } + + public Set getSensitiveHeaders() { + return sensitiveHeaders; + } + + public void setSensitiveHeaders(Set sensitiveHeaders) { + this.sensitiveHeaders = sensitiveHeaders; + } + + public boolean isCustomSensitiveHeaders() { + return customSensitiveHeaders; + } + + public void setCustomSensitiveHeaders(boolean customSensitiveHeaders) { + this.customSensitiveHeaders = customSensitiveHeaders; + } + + @Override + public int hashCode() { + return HashCodeBuilder.reflectionHashCode(this); + } + + @Override + public boolean equals(Object object) { + return EqualsBuilder.reflectionEquals(this, object); + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); + } +} \ No newline at end of file diff --git a/discovery-common/src/main/java/com/nepxion/discovery/common/exception/DiscoveryException.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/exception/DiscoveryException.java similarity index 100% rename from discovery-common/src/main/java/com/nepxion/discovery/common/exception/DiscoveryException.java rename to discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/exception/DiscoveryException.java diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/expression/DiscoveryExpressionResolver.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/expression/DiscoveryExpressionResolver.java new file mode 100644 index 0000000000..f8660399da --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/expression/DiscoveryExpressionResolver.java @@ -0,0 +1,95 @@ +package com.nepxion.discovery.common.expression; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.apache.commons.lang3.StringUtils; +import org.springframework.expression.ExpressionParser; +import org.springframework.expression.TypeComparator; +import org.springframework.expression.spel.standard.SpelExpressionParser; +import org.springframework.expression.spel.support.StandardEvaluationContext; + +import com.nepxion.discovery.common.constant.DiscoveryConstant; + +public class DiscoveryExpressionResolver { + public static final ExpressionParser EXPRESSION_PARSER = new SpelExpressionParser(); + + public static boolean eval(String expression, String key, Map map, TypeComparator typeComparator) { + StandardEvaluationContext context = new StandardEvaluationContext(); + context.setTypeComparator(typeComparator); + if (map != null) { + context.setVariable(key, map); + } else { + context.setVariable(key, new HashMap()); + } + + return eval(expression, context); + } + + public static boolean eval(String expression, StandardEvaluationContext context) { + try { + Boolean result = EXPRESSION_PARSER.parseExpression(expression).getValue(context, Boolean.class); + + return result != null ? result.booleanValue() : false; + } catch (Exception e) { + return false; + } + } + + public static final Pattern EXPRESSION_PATTERN = Pattern.compile(DiscoveryConstant.EXPRESSION_REGEX); + + public static List extractList(String expression) { + List list = new ArrayList(); + + Matcher matcher = EXPRESSION_PATTERN.matcher(expression); + while (matcher.find()) { + String group = matcher.group(); + String name = StringUtils.substringBetween(group, DiscoveryConstant.EXPRESSION_SUB_PREFIX, DiscoveryConstant.EXPRESSION_SUB_SUFFIX).trim(); + + list.add(name); + } + + return list; + } + + public static final Pattern EXPRESSION_SINGLE_QUOTES_PATTERN = Pattern.compile(DiscoveryConstant.EXPRESSION_SINGLE_QUOTES_REGEX); + + public static Map extractMap(String expression) { + Map map = new LinkedHashMap(); + + Matcher matcher = EXPRESSION_SINGLE_QUOTES_PATTERN.matcher(expression); + int index = 0; + String key = null; + while (matcher.find()) { + String group = matcher.group(); + if (group.startsWith(DiscoveryConstant.EXPRESSION_SINGLE_QUOTES) && group.endsWith(DiscoveryConstant.EXPRESSION_SINGLE_QUOTES)) { + String name = StringUtils.substringBetween(group, DiscoveryConstant.EXPRESSION_SINGLE_QUOTES, DiscoveryConstant.EXPRESSION_SINGLE_QUOTES).trim(); + if (index % 2 == 0) { + // 偶数个元素为Key + key = name; + } else if (index % 2 == 1) { + // 奇数个元素为Value + map.put(key, name); + } + + index++; + } + } + + return map; + } +} \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/expression/DiscoveryTypeComparator.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/expression/DiscoveryTypeComparator.java new file mode 100644 index 0000000000..5813422c1b --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/expression/DiscoveryTypeComparator.java @@ -0,0 +1,38 @@ +package com.nepxion.discovery.common.expression; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.math.BigDecimal; + +import org.springframework.expression.spel.SpelEvaluationException; +import org.springframework.expression.spel.support.StandardTypeComparator; +import org.springframework.lang.Nullable; + +public class DiscoveryTypeComparator extends StandardTypeComparator { + @Override + public int compare(@Nullable Object left, @Nullable Object right) throws SpelEvaluationException { + if (left == null) { + return right == null ? 0 : -1; + } else if (right == null) { + return 1; + } + + try { + BigDecimal leftValue = new BigDecimal(left.toString()); + BigDecimal rightValue = new BigDecimal(right.toString()); + + return super.compare(leftValue, rightValue); + } catch (Exception e) { + + } + + return super.compare(left, right); + } +} \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/future/DiscoveryFutureCallback.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/future/DiscoveryFutureCallback.java new file mode 100644 index 0000000000..56dc322ca7 --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/future/DiscoveryFutureCallback.java @@ -0,0 +1,14 @@ +package com.nepxion.discovery.common.future; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +public interface DiscoveryFutureCallback { + T callback() throws Exception; +} \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/future/DiscoveryFutureResolver.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/future/DiscoveryFutureResolver.java new file mode 100644 index 0000000000..0d360c1ac5 --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/future/DiscoveryFutureResolver.java @@ -0,0 +1,28 @@ +package com.nepxion.discovery.common.future; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Future; + +public class DiscoveryFutureResolver { + public static T call(ExecutorService executorService, DiscoveryFutureCallback discoveryFutureCallback) throws InterruptedException, ExecutionException { + Future future = executorService.submit(new Callable() { + @Override + public T call() throws Exception { + return discoveryFutureCallback.callback(); + } + }); + + return future.get(); + } +} \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/handler/DiscoveryResponseErrorContext.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/handler/DiscoveryResponseErrorContext.java new file mode 100644 index 0000000000..e47157f987 --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/handler/DiscoveryResponseErrorContext.java @@ -0,0 +1,57 @@ +package com.nepxion.discovery.common.handler; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.apache.commons.lang3.builder.EqualsBuilder; +import org.apache.commons.lang3.builder.HashCodeBuilder; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; + +public class DiscoveryResponseErrorContext { + private static final ThreadLocal THREAD_LOCAL = new ThreadLocal() { + @Override + protected DiscoveryResponseErrorContext initialValue() { + return new DiscoveryResponseErrorContext(); + } + }; + + private String error; + + public static DiscoveryResponseErrorContext getCurrentContext() { + return THREAD_LOCAL.get(); + } + + public static void clearCurrentContext() { + THREAD_LOCAL.remove(); + } + + public String getError() { + return error; + } + + public void setError(String error) { + this.error = error; + } + + @Override + public int hashCode() { + return HashCodeBuilder.reflectionHashCode(this); + } + + @Override + public boolean equals(Object object) { + return EqualsBuilder.reflectionEquals(this, object); + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); + } +} \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/handler/DiscoveryResponseErrorHandler.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/handler/DiscoveryResponseErrorHandler.java new file mode 100644 index 0000000000..2cc9144676 --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/handler/DiscoveryResponseErrorHandler.java @@ -0,0 +1,37 @@ +package com.nepxion.discovery.common.handler; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.io.IOException; +import java.io.InputStream; + +import org.apache.commons.io.IOUtils; +import org.springframework.http.client.ClientHttpResponse; +import org.springframework.web.client.DefaultResponseErrorHandler; + +import com.nepxion.discovery.common.constant.DiscoveryConstant; + +public class DiscoveryResponseErrorHandler extends DefaultResponseErrorHandler { + @Override + public void handleError(ClientHttpResponse response) throws IOException { + InputStream inputStream = response.getBody(); + String error = IOUtils.toString(inputStream, DiscoveryConstant.ENCODING_UTF_8); + + DiscoveryResponseErrorContext.getCurrentContext().setError(error); + } + + public String getError() { + String error = DiscoveryResponseErrorContext.getCurrentContext().getError(); + + DiscoveryResponseErrorContext.clearCurrentContext(); + + return error; + } +} \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/json/DiscoveryPrettyPrinter.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/json/DiscoveryPrettyPrinter.java new file mode 100644 index 0000000000..d9d578a1df --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/json/DiscoveryPrettyPrinter.java @@ -0,0 +1,68 @@ +package com.nepxion.discovery.common.json; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.io.IOException; + +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.core.util.DefaultIndenter; +import com.fasterxml.jackson.core.util.DefaultPrettyPrinter; +import com.fasterxml.jackson.core.util.Separators; + +public class DiscoveryPrettyPrinter extends DefaultPrettyPrinter { + private static final long serialVersionUID = 7557042630980590487L; + + public DiscoveryPrettyPrinter() { + _arrayIndenter = DefaultIndenter.SYSTEM_LINEFEED_INSTANCE; + _objectIndenter = DefaultIndenter.SYSTEM_LINEFEED_INSTANCE; + } + + public DiscoveryPrettyPrinter(DefaultPrettyPrinter base) { + super(base); + } + + @Override + public DiscoveryPrettyPrinter createInstance() { + if (getClass() != DiscoveryPrettyPrinter.class) { + throw new IllegalStateException("Failed `createInstance()`: " + getClass().getName() + + " does not override method; it has to"); + } + return new DiscoveryPrettyPrinter(this); + } + + @Override + public DiscoveryPrettyPrinter withSeparators(Separators separators) { + this._separators = separators; + this._objectFieldValueSeparatorWithSpaces = separators.getObjectFieldValueSeparator() + " "; + return this; + } + + @Override + public void writeEndArray(JsonGenerator g, int nrOfValues) throws IOException { + if (!_arrayIndenter.isInline()) { + --_nesting; + } + if (nrOfValues > 0) { + _arrayIndenter.writeIndentation(g, _nesting); + } + g.writeRaw(']'); + } + + @Override + public void writeEndObject(JsonGenerator g, int nrOfEntries) throws IOException { + if (!_objectIndenter.isInline()) { + --_nesting; + } + if (nrOfEntries > 0) { + _objectIndenter.writeIndentation(g, _nesting); + } + g.writeRaw('}'); + } +} \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/lock/DiscoveryLock.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/lock/DiscoveryLock.java new file mode 100644 index 0000000000..90125f41b6 --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/lock/DiscoveryLock.java @@ -0,0 +1,29 @@ +package com.nepxion.discovery.common.lock; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.List; + +public interface DiscoveryLock { + // 尝试获取锁 + boolean tryLock(String key); + + // 持有锁 + void lock(String key); + + // 释放锁 + void unlock(String key); + + // 获取被持有的所有锁名称列表 + List getHeldLocks(); + + // 进程结束时销毁锁 + void destroy() throws Exception; +} \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/logback/LevelColorConverter.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/logback/LevelColorConverter.java new file mode 100644 index 0000000000..ce1bc30513 --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/logback/LevelColorConverter.java @@ -0,0 +1,40 @@ +package com.nepxion.discovery.common.logback; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.pattern.color.ForegroundCompositeConverterBase; + +// Refer to color definition with https://logback.qos.ch/manual/layouts.html#coloring +// Windows终端默认不能显示ANSI颜色,需要在注册表HKEY_CURRENT_USER\Console中新建一个DWORD类型的值VirtualTerminalLevel,数值为1 +public class LevelColorConverter extends ForegroundCompositeConverterBase { + @Override + protected String getForegroundColorCode(ILoggingEvent event) { + Level level = event.getLevel(); + switch (level.toInt()) { + // ERROR等级为红色 + case Level.ERROR_INT: + return LogbackConstant.RED_FG; + // WARN等级为黄色 + case Level.WARN_INT: + return LogbackConstant.YELLOW_FG; + // INFO等级为蓝色 + case Level.INFO_INT: + return LogbackConstant.GREEN_FG; + // DEBUG等级为绿色 + case Level.DEBUG_INT: + return LogbackConstant.BLUE_FG; + // 其他为默认颜色 + default: + return LogbackConstant.DEFAULT_FG; + } + } +} \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/logback/LogbackConstant.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/logback/LogbackConstant.java new file mode 100644 index 0000000000..4134aafbe3 --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/logback/LogbackConstant.java @@ -0,0 +1,16 @@ +package com.nepxion.discovery.common.logback; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import ch.qos.logback.core.pattern.color.ANSIConstants; + +public class LogbackConstant extends ANSIConstants { + public static final String ANSI_COLOR = "ansi-color"; +} \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/logback/MdcColorConverter.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/logback/MdcColorConverter.java new file mode 100644 index 0000000000..2bed434fc2 --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/logback/MdcColorConverter.java @@ -0,0 +1,26 @@ +package com.nepxion.discovery.common.logback; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.pattern.color.ForegroundCompositeConverterBase; + +import org.apache.commons.lang3.StringUtils; + +// Refer to color definition with https://logback.qos.ch/manual/layouts.html#coloring +// Windows终端默认不能显示ANSI颜色,需要在注册表HKEY_CURRENT_USER\Console中新建一个DWORD类型的值VirtualTerminalLevel,数值为1 +public class MdcColorConverter extends ForegroundCompositeConverterBase { + @Override + protected String getForegroundColorCode(ILoggingEvent event) { + String ansiColor = event.getMDCPropertyMap().get(LogbackConstant.ANSI_COLOR); + + return StringUtils.isNotEmpty(ansiColor) ? ansiColor : LogbackConstant.DEFAULT_FG; + } +} \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/processor/DiscoveryConfigProcessor.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/processor/DiscoveryConfigProcessor.java new file mode 100644 index 0000000000..b72bd69d2e --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/processor/DiscoveryConfigProcessor.java @@ -0,0 +1,113 @@ +package com.nepxion.discovery.common.processor; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.springframework.beans.factory.DisposableBean; + +import com.nepxion.discovery.common.entity.ConfigType; + +public abstract class DiscoveryConfigProcessor implements DisposableBean { + public void logGetStarted() { + String group = getGroup(); + String dataId = getDataId(); + String description = getDescription(); + ConfigType configType = getConfigType(); + boolean isConfigSingleKey = isConfigSingleKey(); + + DiscoveryConfigProcessorLogger.logGetStarted(group, dataId, description, configType, isConfigSingleKey); + } + + public void logGetFailed(Exception e) { + String group = getGroup(); + String dataId = getDataId(); + String description = getDescription(); + ConfigType configType = getConfigType(); + boolean isConfigSingleKey = isConfigSingleKey(); + + DiscoveryConfigProcessorLogger.logGetFailed(group, dataId, description, configType, isConfigSingleKey, e); + } + + public void logNotFound() { + String description = getDescription(); + ConfigType configType = getConfigType(); + + DiscoveryConfigProcessorLogger.logNotFound(description, configType); + } + + public void logSubscribeStarted() { + String group = getGroup(); + String dataId = getDataId(); + String description = getDescription(); + ConfigType configType = getConfigType(); + boolean isConfigSingleKey = isConfigSingleKey(); + + DiscoveryConfigProcessorLogger.logSubscribeStarted(group, dataId, description, configType, isConfigSingleKey); + } + + public void logSubscribeFailed(Exception e) { + String group = getGroup(); + String dataId = getDataId(); + String description = getDescription(); + ConfigType configType = getConfigType(); + boolean isConfigSingleKey = isConfigSingleKey(); + + DiscoveryConfigProcessorLogger.logSubscribeFailed(group, dataId, description, configType, isConfigSingleKey, e); + } + + public void logUnsubscribeStarted() { + String group = getGroup(); + String dataId = getDataId(); + String description = getDescription(); + ConfigType configType = getConfigType(); + boolean isConfigSingleKey = isConfigSingleKey(); + + DiscoveryConfigProcessorLogger.logUnsubscribeStarted(group, dataId, description, configType, isConfigSingleKey); + } + + public void logUnsubscribeFailed(Exception e) { + String group = getGroup(); + String dataId = getDataId(); + String description = getDescription(); + ConfigType configType = getConfigType(); + boolean isConfigSingleKey = isConfigSingleKey(); + + DiscoveryConfigProcessorLogger.logUnsubscribeFailed(group, dataId, description, configType, isConfigSingleKey, e); + } + + public void logCallbackFailed(Exception e) { + String description = getDescription(); + + DiscoveryConfigProcessorLogger.logCallbackFailed(description, e); + } + + public boolean isConfigSingleKey() { + ConfigType configType = getConfigType(); + + return ConfigType.isSingleKey(configType); + } + + public void beforeInitialization() { + + } + + public void afterInitialization() { + + } + + public abstract ConfigType getConfigType(); + + public abstract String getGroup(); + + public abstract String getDataId(); + + public abstract String getDescription(); + + public abstract void callbackConfig(String config); +} \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/processor/DiscoveryConfigProcessorLogger.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/processor/DiscoveryConfigProcessorLogger.java new file mode 100644 index 0000000000..4469d3cd94 --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/processor/DiscoveryConfigProcessorLogger.java @@ -0,0 +1,55 @@ +package com.nepxion.discovery.common.processor; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.nepxion.discovery.common.entity.ConfigType; + +public class DiscoveryConfigProcessorLogger { + private static final Logger LOG = LoggerFactory.getLogger(DiscoveryConfigProcessorLogger.class); + + public static void logGetStarted(String group, String dataId, String description, ConfigType configType, boolean isConfigSingleKey) { + LOG.info("Get {} config from {} server, " + getLogKey(isConfigSingleKey), description, configType, group, dataId); + } + + public static void logGetFailed(String group, String dataId, String description, ConfigType configType, boolean isConfigSingleKey, Exception e) { + LOG.error("Get {} config from {} server failed, " + getLogKey(isConfigSingleKey), description, configType, group, dataId, e); + } + + public static void logNotFound(String description, ConfigType configType) { + LOG.info("Not found {} config from {} server", description, configType); + } + + public static void logSubscribeStarted(String group, String dataId, String description, ConfigType configType, boolean isConfigSingleKey) { + LOG.info("Subscribe {} config from {} server, " + getLogKey(isConfigSingleKey), description, configType, group, dataId); + } + + public static void logSubscribeFailed(String group, String dataId, String description, ConfigType configType, boolean isConfigSingleKey, Exception e) { + LOG.error("Subscribe {} config from {} server failed, " + getLogKey(isConfigSingleKey), description, configType, group, dataId, e); + } + + public static void logUnsubscribeStarted(String group, String dataId, String description, ConfigType configType, boolean isConfigSingleKey) { + LOG.info("Unsubscribe {} config from {} server, " + getLogKey(isConfigSingleKey), description, configType, group, dataId); + } + + public static void logUnsubscribeFailed(String group, String dataId, String description, ConfigType configType, boolean isConfigSingleKey, Exception e) { + LOG.error("Unsubscribe {} config from {} server failed, " + getLogKey(isConfigSingleKey), description, configType, group, dataId, e); + } + + public static void logCallbackFailed(String description, Exception e) { + LOG.error("Callback {} config failed", description, e); + } + + private static String getLogKey(boolean isConfigSingleKey) { + return isConfigSingleKey ? "key={}-{}" : "group={}, dataId={}"; + } +} \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/property/DiscoveryContent.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/property/DiscoveryContent.java new file mode 100644 index 0000000000..ca46058bb8 --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/property/DiscoveryContent.java @@ -0,0 +1,47 @@ +package com.nepxion.discovery.common.property; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; + +import org.apache.commons.io.FileUtils; +import org.apache.commons.io.IOUtils; + +import com.nepxion.discovery.common.util.IOUtil; + +public class DiscoveryContent { + private String content; + + public DiscoveryContent(String path, String encoding) throws IOException { + InputStream inputStream = null; + try { + inputStream = IOUtil.getInputStream(path); + this.content = IOUtils.toString(inputStream, encoding); + } finally { + if (inputStream != null) { + IOUtils.closeQuietly(inputStream); + } + } + } + + public DiscoveryContent(File file, String encoding) throws IOException { + this.content = FileUtils.readFileToString(file, encoding); + } + + public DiscoveryContent(StringBuilder stringBuilder) throws IOException { + this.content = stringBuilder.toString(); + } + + public String getContent() { + return content; + } +} \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/property/DiscoveryProperties.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/property/DiscoveryProperties.java new file mode 100644 index 0000000000..c7192e4af1 --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/property/DiscoveryProperties.java @@ -0,0 +1,353 @@ +package com.nepxion.discovery.common.property; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.Reader; +import java.io.Serializable; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Properties; + +import org.apache.commons.io.IOUtils; + +import com.nepxion.discovery.common.util.MathsUtil; + +public class DiscoveryProperties implements Serializable { + private static final long serialVersionUID = 7157091468155324287L; + + private final Map map = new LinkedHashMap(); + + private String content; + + // 配置文件含中文,stringEncoding必须为GBK,readerEncoding必须为UTF-8,文本文件编码必须为ANSI + public DiscoveryProperties(String path, String stringEncoding, String readerEncoding) throws IOException { + this(new DiscoveryContent(path, stringEncoding).getContent(), readerEncoding); + } + + // 配置文件含中文,stringEncoding必须为UTF-8,readerEncoding必须为UTF-8 + public DiscoveryProperties(byte[] bytes, String stringEncoding, String readerEncoding) throws IOException { + this(new String(bytes, stringEncoding), readerEncoding); + } + + // 配置文件含中文,encoding必须为UTF-8 + public DiscoveryProperties(String content, String encoding) throws IOException { + this.content = content; + + InputStream inputStream = null; + Reader reader = null; + try { + inputStream = IOUtils.toInputStream(content, encoding); + reader = new InputStreamReader(inputStream, encoding); + + Properties properties = new Properties(); + properties.load(reader); + for (Iterator iterator = properties.keySet().iterator(); iterator.hasNext();) { + String key = iterator.next().toString(); + String value = properties.getProperty(key); + put(key, value); + } + } finally { + if (reader != null) { + IOUtils.closeQuietly(reader); + } + + if (inputStream != null) { + IOUtils.closeQuietly(inputStream); + } + } + } + + public String getContent() { + return content; + } + + public void put(String key, String value) { + if (value == null) { + throw new IllegalArgumentException("Value is null for key [" + key + "]"); + } + + Long result = MathsUtil.calculate(value); + if (result != null) { + map.put(key, String.valueOf(result)); + } else { + map.put(key, value); + } + } + + public Map getMap() { + return map; + } + + public String getString(String key) { + if (!map.containsKey(key)) { + throw new IllegalArgumentException("Key [" + key + "] isn't found in properties"); + } + + return map.get(key); + } + + public String getString(String key, String defaultValue) { + String value = getString(key); + if (value != null) { + return value; + } else { + return defaultValue; + } + } + + public boolean getBoolean(String key) { + String value = getString(key); + if (value != null) { + try { + return Boolean.parseBoolean(value); + } catch (Exception e) { + throw new IllegalArgumentException("Value [" + value + "] for key [" + key + "] can't be parsed to boolean", e); + } + } else { + throw new IllegalArgumentException("Value [" + value + "] for key [" + key + "] is null"); + } + } + + public boolean getBoolean(String key, boolean defaultValue) { + String value = getString(key); + if (value != null) { + try { + return Boolean.parseBoolean(value); + } catch (Exception e) { + throw new IllegalArgumentException("Value [" + value + "] for key [" + key + "] can't be parsed to boolean", e); + } + } else { + return defaultValue; + } + } + + public int getInteger(String key) { + String value = getString(key); + if (value != null) { + try { + return Integer.parseInt(value); + } catch (Exception e) { + throw new IllegalArgumentException("Value [" + value + "] for key [" + key + "] can't be parsed to int", e); + } + } else { + throw new IllegalArgumentException("Value [" + value + "] for key [" + key + "] is null"); + } + } + + public int getInteger(String key, int defaultValue) { + String value = getString(key); + if (value != null) { + try { + return Integer.parseInt(value); + } catch (Exception e) { + throw new IllegalArgumentException("Value [" + value + "] for key [" + key + "] can't be parsed to int", e); + } + } else { + return defaultValue; + } + } + + public long getLong(String key) { + String value = getString(key); + if (value != null) { + try { + return Long.parseLong(value); + } catch (Exception e) { + throw new IllegalArgumentException("Value [" + value + "] for key [" + key + "] can't be parsed to long", e); + } + } else { + throw new IllegalArgumentException("Value [" + value + "] for key [" + key + "] is null"); + } + } + + public long getLong(String key, long defaultValue) { + String value = getString(key); + if (value != null) { + try { + return Long.parseLong(value); + } catch (Exception e) { + throw new IllegalArgumentException("Value [" + value + "] for key [" + key + "] can't be parsed to long", e); + } + } else { + return defaultValue; + } + } + + public short getShort(String key, short defaultValue) { + String value = getString(key); + if (value != null) { + try { + return Short.parseShort(value); + } catch (Exception e) { + throw new IllegalArgumentException("Value [" + value + "] for key [" + key + "] can't be parsed to short", e); + } + } else { + throw new IllegalArgumentException("Value [" + value + "] for key [" + key + "] is null"); + } + } + + public Short getShort(String key, Short defaultValue) { + String value = getString(key); + if (value != null) { + try { + return Short.parseShort(value); + } catch (Exception e) { + throw new IllegalArgumentException("Value [" + value + "] for key [" + key + "] can't be parsed to short", e); + } + } else { + return defaultValue; + } + } + + public byte getByte(String key) { + String value = getString(key); + if (value != null) { + try { + return Byte.parseByte(value); + } catch (Exception e) { + throw new IllegalArgumentException("Value [" + value + "] for key [" + key + "] can't be parsed to byte", e); + } + } else { + throw new IllegalArgumentException("Value [" + value + "] for key [" + key + "] is null"); + } + } + + public byte getByte(String key, byte defaultValue) { + String value = getString(key); + if (value != null) { + try { + return Byte.parseByte(value); + } catch (Exception e) { + throw new IllegalArgumentException("Value [" + value + "] for key [" + key + "] can't be parsed to byte", e); + } + } else { + return defaultValue; + } + } + + public double getDouble(String key) { + String value = getString(key); + if (value != null) { + try { + return Double.parseDouble(value); + } catch (Exception e) { + throw new IllegalArgumentException("Value [" + value + "] for key [" + key + "] can't be parsed to double", e); + } + } else { + throw new IllegalArgumentException("Value [" + value + "] for key [" + key + "] is null"); + } + } + + public double getDouble(String key, double defaultValue) { + String value = getString(key); + if (value != null) { + try { + return Double.parseDouble(value); + } catch (Exception e) { + throw new IllegalArgumentException("Value [" + value + "] for key [" + key + "] can't be parsed to double", e); + } + } else { + return defaultValue; + } + } + + public float getFloat(String key) { + String value = getString(key); + if (value != null) { + try { + return Float.parseFloat(value); + } catch (Exception e) { + throw new IllegalArgumentException("Value [" + value + "] for key [" + key + "] can't be parsed to float", e); + } + } else { + throw new IllegalArgumentException("Value [" + value + "] for key [" + key + "] is null"); + } + } + + public float getFloat(String key, float defaultValue) { + String value = getString(key); + if (value != null) { + try { + return Float.parseFloat(value); + } catch (Exception e) { + throw new IllegalArgumentException("Value [" + value + "] for key [" + key + "] can't be parsed to float", e); + } + } else { + return defaultValue; + } + } + + public BigInteger getBigInteger(String key) { + String value = getString(key); + if (value != null) { + try { + return BigInteger.valueOf(Long.parseLong(value)); + } catch (Exception e) { + throw new IllegalArgumentException("Value [" + value + "] for key [" + key + "] can't be parsed to BigInteger", e); + } + } else { + throw new IllegalArgumentException("Value [" + value + "] for key [" + key + "] is null"); + } + } + + public BigInteger getBigInteger(String key, BigInteger defaultValue) { + String value = getString(key); + if (value != null) { + try { + return BigInteger.valueOf(Long.parseLong(value)); + } catch (Exception e) { + throw new IllegalArgumentException("Value [" + value + "] for key [" + key + "] can't be parsed to BigInteger", e); + } + } else { + return defaultValue; + } + } + + public BigDecimal getBigDecimal(String key) { + String value = getString(key); + if (value != null) { + try { + return BigDecimal.valueOf(Double.parseDouble(value)); + } catch (Exception e) { + throw new IllegalArgumentException("Value [" + value + "] for key [" + key + "] can't be parsed to BigDecimal", e); + } + } else { + throw new IllegalArgumentException("Value [" + value + "] for key [" + key + "] is null"); + } + } + + public BigDecimal getBigDecimal(String key, BigDecimal defaultValue) { + String value = getString(key); + if (value != null) { + try { + return BigDecimal.valueOf(Double.parseDouble(value)); + } catch (Exception e) { + throw new IllegalArgumentException("Value [" + value + "] for key [" + key + "] can't be parsed to BigDecimal", e); + } + } else { + return defaultValue; + } + } + + public void mergeProperties(DiscoveryProperties properties) { + map.putAll(properties.getMap()); + } + + @Override + public String toString() { + return map.toString(); + } +} \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/thread/DiscoveryNamedThreadFactory.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/thread/DiscoveryNamedThreadFactory.java new file mode 100644 index 0000000000..3f9db49b74 --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/thread/DiscoveryNamedThreadFactory.java @@ -0,0 +1,39 @@ +package com.nepxion.discovery.common.thread; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.concurrent.ThreadFactory; +import java.util.concurrent.atomic.AtomicInteger; + +public class DiscoveryNamedThreadFactory implements ThreadFactory { + private AtomicInteger count = new AtomicInteger(1); + private ThreadGroup group; + private String namePrefix; + private boolean daemon; + + public DiscoveryNamedThreadFactory(String namePrefix) { + this(namePrefix, false); + } + + public DiscoveryNamedThreadFactory(String namePrefix, boolean daemon) { + SecurityManager securityManager = System.getSecurityManager(); + this.group = securityManager != null ? securityManager.getThreadGroup() : Thread.currentThread().getThreadGroup(); + this.namePrefix = namePrefix; + this.daemon = daemon; + } + + @Override + public Thread newThread(Runnable runnable) { + Thread thread = new Thread(group, runnable, namePrefix + "-thread-" + count.getAndIncrement(), 0); + thread.setDaemon(daemon); + + return thread; + } +} \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/thread/DiscoveryThreadPoolFactory.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/thread/DiscoveryThreadPoolFactory.java new file mode 100644 index 0000000000..a15b3b0887 --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/thread/DiscoveryThreadPoolFactory.java @@ -0,0 +1,21 @@ +package com.nepxion.discovery.common.thread; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.concurrent.ArrayBlockingQueue; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; + +public class DiscoveryThreadPoolFactory { + public static ExecutorService getExecutorService(String name) { + return new ThreadPoolExecutor(2, 4, 0, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(1), new DiscoveryNamedThreadFactory(name), new ThreadPoolExecutor.DiscardOldestPolicy()); + } +} \ No newline at end of file diff --git a/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/util/BeanRegisterUtil.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/util/BeanRegisterUtil.java similarity index 96% rename from discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/util/BeanRegisterUtil.java rename to discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/util/BeanRegisterUtil.java index 411cdfd5c8..478e5c893a 100644 --- a/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/util/BeanRegisterUtil.java +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/util/BeanRegisterUtil.java @@ -1,4 +1,4 @@ -package com.nepxion.discovery.plugin.framework.util; +package com.nepxion.discovery.common.util; /** *

Title: Nepxion Discovery

diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/util/ClassUtil.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/util/ClassUtil.java new file mode 100644 index 0000000000..9061ee1207 --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/util/ClassUtil.java @@ -0,0 +1,36 @@ +package com.nepxion.discovery.common.util; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.LinkedHashMap; +import java.util.Map; + +import org.apache.commons.lang3.ArrayUtils; + +public class ClassUtil { + public static Map getParameterMap(String[] methodParameterNames, Object[] arguments) { + Map parameterMap = new LinkedHashMap(); + if (ArrayUtils.isNotEmpty(arguments)) { + for (int i = 0; i < arguments.length; i++) { + String parameterName = null; + if (ArrayUtils.isNotEmpty(methodParameterNames)) { + parameterName = methodParameterNames[i]; + } else { + parameterName = String.valueOf(i); + } + Object argument = arguments[i]; + + parameterMap.put(parameterName, argument); + } + } + + return parameterMap; + } +} \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/util/EnvironmentUtil.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/util/EnvironmentUtil.java new file mode 100644 index 0000000000..09e1888584 --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/util/EnvironmentUtil.java @@ -0,0 +1,20 @@ +package com.nepxion.discovery.common.util; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.apache.commons.lang3.StringUtils; +import org.springframework.core.env.ConfigurableEnvironment; +import org.springframework.core.env.StandardEnvironment; + +public class EnvironmentUtil { + public static boolean isStandardEnvironment(ConfigurableEnvironment environment) { + return StringUtils.equals(environment.getClass().getName(), StandardEnvironment.class.getName()); + } +} \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/util/FileUtil.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/util/FileUtil.java new file mode 100644 index 0000000000..a53a9734ab --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/util/FileUtil.java @@ -0,0 +1,179 @@ +package com.nepxion.discovery.common.util; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.io.BufferedOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; + +import org.apache.commons.io.FileUtils; +import org.apache.commons.io.IOUtils; +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.context.ApplicationContext; + +import com.nepxion.discovery.common.constant.DiscoveryConstant; + +public class FileUtil { + private static final Logger LOG = LoggerFactory.getLogger(FileUtil.class); + + public static File getFile(ApplicationContext applicationContext, String path) { + if (StringUtils.isEmpty(path)) { + throw new IllegalArgumentException("File path doesn't set"); + } + + try { + String filePath = applicationContext.getEnvironment().resolvePlaceholders(path); + + File file = applicationContext.getResource(filePath).getFile(); + + LOG.info("File [{}] is found", path); + + return file; + } catch (Exception e) { + LOG.warn("File [{}] isn't found or valid, ignore to load...", path); + } + + return null; + } + + public static InputStream getInputStream(ApplicationContext applicationContext, String path) { + if (StringUtils.isEmpty(path)) { + throw new IllegalArgumentException("File path doesn't set"); + } + + try { + String filePath = applicationContext.getEnvironment().resolvePlaceholders(path); + + InputStream inputStream = applicationContext.getResource(filePath).getInputStream(); + + LOG.info("File [{}] is found", path); + + return inputStream; + } catch (Exception e) { + LOG.warn("File [{}] isn't found or valid, ignore to load...", path); + } + + return null; + } + + public static String getText(ApplicationContext applicationContext, String path) { + InputStream inputStream = null; + try { + inputStream = getInputStream(applicationContext, path); + if (inputStream != null) { + try { + return IOUtils.toString(inputStream, DiscoveryConstant.ENCODING_UTF_8); + } catch (IOException e) { + LOG.warn("InputStream to String failed, ignore to load..."); + } + } + } finally { + if (inputStream != null) { + IOUtils.closeQuietly(inputStream); + } + } + + return null; + } + + public static void toFile(String text, String directoryPath, String fileName, String encoding) throws IOException { + File directory = new File(directoryPath); + if (!directory.exists() || !directory.isDirectory()) { + directory.mkdirs(); + } + + File file = new File(directoryPath + File.separator + fileName); + FileUtils.writeStringToFile(file, text, encoding); + } + + public static void toFile(byte[] bytes, String directoryPath, String fileName) throws IOException { + File directory = new File(directoryPath); + if (!directory.exists() || !directory.isDirectory()) { + directory.mkdirs(); + } + + BufferedOutputStream bos = null; + FileOutputStream fos = null; + try { + File file = new File(directoryPath + File.separator + fileName); + fos = new FileOutputStream(file); + bos = new BufferedOutputStream(fos); + bos.write(bytes); + } finally { + if (bos != null) { + IOUtils.closeQuietly(bos); + } + if (fos != null) { + IOUtils.closeQuietly(fos); + } + } + } + + public static byte[] fromFile(String directoryPath, String fileName) throws IOException { + File file = new File(directoryPath + File.separator + fileName); + + return FileUtils.readFileToByteArray(file); + } + + public static void forceDeleteDirectory(File directory, int forceTimes) { + if (directory.isDirectory() && directory.exists()) { + try { + FileUtils.deleteDirectory(directory); + forceTimes--; + if (forceTimes > 0) { + forceDeleteDirectory(directory, forceTimes); + } else { + throw new IOException("Force delete directory=" + directory + " failed"); + } + } catch (IOException e) { + + } + } + } + + public static void forceDeleteFile(File file, int forceTimes) { + if (file.isFile() && file.exists()) { + try { + FileUtils.deleteQuietly(file); + forceTimes--; + if (forceTimes > 0) { + forceDeleteFile(file, forceTimes); + } else { + throw new IOException("Force delete file=" + file + " failed"); + } + } catch (IOException e) { + + } + } + } + + public static byte[] getBytes(File file) throws FileNotFoundException, IOException { + InputStream inputStream = null; + try { + inputStream = new FileInputStream(file); + + return IOUtils.toByteArray(inputStream); + } catch (FileNotFoundException e) { + throw e; + } catch (IOException e) { + throw e; + } finally { + if (inputStream != null) { + IOUtils.closeQuietly(inputStream); + } + } + } +} \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/util/FormatUtil.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/util/FormatUtil.java new file mode 100644 index 0000000000..869a4c1648 --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/util/FormatUtil.java @@ -0,0 +1,28 @@ +package com.nepxion.discovery.common.util; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import com.nepxion.discovery.common.entity.FormatType; + +public class FormatUtil { + public static FormatType getFormatType(String content) { + if (XmlUtil.isXmlFormat(content)) { + return FormatType.XML_FORMAT; + } else if (JsonUtil.isJsonFormat(content)) { + return FormatType.JSON_FORMAT; + /*} else if (YamlUtil.isYamlFormat(content)) { + return FormatType.YAML_FORMAT; + } else if (PropertiesUtil.isPropertiesFormat(content)) { + return FormatType.PROPERTIES_FORMAT;*/ + } else { + return FormatType.TEXT_FORMAT; + } + } +} \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/util/IOUtil.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/util/IOUtil.java new file mode 100644 index 0000000000..30d68d869c --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/util/IOUtil.java @@ -0,0 +1,27 @@ +package com.nepxion.discovery.common.util; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; + +public class IOUtil { + public static InputStream getInputStream(String path) throws IOException { + // 从Resource路径获取 + InputStream inputStream = IOUtil.class.getClassLoader().getResourceAsStream(path); + if (inputStream == null) { + // 从文件路径获取 + inputStream = new FileInputStream(path); + } + + return inputStream; + } +} \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/util/JsonUtil.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/util/JsonUtil.java new file mode 100644 index 0000000000..0cf33c415f --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/util/JsonUtil.java @@ -0,0 +1,136 @@ +package com.nepxion.discovery.common.util; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.io.IOException; +import java.util.Map; + +import org.apache.commons.lang3.StringUtils; + +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializerProvider; +import com.fasterxml.jackson.databind.ser.std.StdSerializer; +import com.nepxion.discovery.common.json.DiscoveryPrettyPrinter; + +public class JsonUtil { + private static ObjectMapper objectMapper; + private static DiscoveryPrettyPrinter discoveryPrettyPrinter; + + static { + objectMapper = new ObjectMapper(); + // objectMapper.getSerializerProvider().setNullKeySerializer(new NullKeySerializer()); + // objectMapper.setDateFormat(new SimpleDateFormat(DiscoveryConstant.DATE_FORMAT)); + + discoveryPrettyPrinter = new DiscoveryPrettyPrinter(); + } + + public static class NullKeySerializer extends StdSerializer { + private static final long serialVersionUID = -9176767187240330396L; + + public NullKeySerializer() { + this(null); + } + + public NullKeySerializer(Class object) { + super(object); + } + + @Override + public void serialize(Object value, JsonGenerator gen, SerializerProvider provider) throws IOException { + gen.writeFieldName(StringUtils.EMPTY); + } + } + + public static String toJson(T object) { + if (object == null) { + throw new IllegalArgumentException("Object is null"); + } + + try { + return objectMapper.writeValueAsString(object); + } catch (JsonProcessingException e) { + throw new IllegalArgumentException(e.getMessage(), e); + } + } + + public static String toPrettyJson(T object) { + if (object == null) { + throw new IllegalArgumentException("Object is null"); + } + + try { + return objectMapper.writer(discoveryPrettyPrinter).writeValueAsString(object); + } catch (JsonProcessingException e) { + throw new IllegalArgumentException(e.getMessage(), e); + } + } + + public static T fromJson(String json, Class clazz) { + if (StringUtils.isEmpty(json)) { + throw new IllegalArgumentException("Json is null or empty"); + } + + try { + return objectMapper.readValue(json, clazz); + } catch (Exception e) { + throw new IllegalArgumentException(e.getMessage(), e); + } + } + + public static T fromJson(String json, TypeReference typeReference) { + if (StringUtils.isEmpty(json)) { + throw new IllegalArgumentException("Json is null or empty"); + } + + try { + return objectMapper.readValue(json, typeReference); + } catch (Exception e) { + throw new IllegalArgumentException(e.getMessage(), e); + } + } + + public static boolean isJsonFormat(String json) { + if (StringUtils.isBlank(json)) { + return false; + } + + try { + objectMapper.readTree(json); + + return true; + } catch (Exception e) { + return false; + } + } + + @SuppressWarnings("unchecked") + public static String fromJsonMap(String json, String key) { + if (StringUtils.isEmpty(json)) { + return null; + } + + String value = null; + try { + Map map = fromJson(json, Map.class); + value = map.get(key); + } catch (Exception e) { + value = json; + } + + return value; + } + + public static ObjectMapper getObjectMapper() { + return objectMapper; + } +} \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/util/MathsUtil.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/util/MathsUtil.java new file mode 100644 index 0000000000..c1ccb7e7be --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/util/MathsUtil.java @@ -0,0 +1,34 @@ +package com.nepxion.discovery.common.util; + +/** + *

Title: Nepxion Aquarius

+ *

Description: Nepxion Aquarius

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.apache.commons.lang3.StringUtils; + +public class MathsUtil { + private static final char ASTERISK = '*'; + + public static Long calculate(String value) { + if (StringUtils.isEmpty(value)) { + return null; + } + + long result = 1; + try { + String[] array = StringUtils.split(value, ASTERISK); + for (String data : array) { + result *= Long.parseLong(data.trim()); + } + } catch (Exception e) { + return null; + } + + return result; + } +} \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/util/PluginInfoUtil.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/util/PluginInfoUtil.java new file mode 100644 index 0000000000..d5d9abe1f7 --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/util/PluginInfoUtil.java @@ -0,0 +1,104 @@ +package com.nepxion.discovery.common.util; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.apache.commons.collections4.CollectionUtils; +import org.apache.commons.lang3.StringUtils; + +public class PluginInfoUtil { + private static Pattern pattern = Pattern.compile("\\[\\S+\\]"); + + public static List> assembleAll(String text, String filters) { + List filterList = StringUtil.splitToList(filters, ","); + + return assembleAll(text, filterList); + } + + public static List> assembleAll(String text, List filterList) { + List> list = new ArrayList>(); + + List singleList = StringUtil.splitToList(text, " -> "); + for (String value : singleList) { + Map map = assembleSingle(value, filterList); + + list.add(map); + } + + return list; + } + + public static Map assembleSingle(String text, String filters) { + List filterList = StringUtil.splitToList(filters, ","); + + return assembleSingle(text, filterList); + } + + public static Map assembleSingle(String text, List filterList) { + text = StringUtils.replace(text, "][", "] ["); + Matcher matcher = pattern.matcher(text); + + Map map = new LinkedHashMap(); + while (matcher.find()) { + String group = matcher.group(); + String value = StringUtils.substringBetween(group, "[", "]"); + String[] array = StringUtils.split(value, "="); + if (CollectionUtils.isEmpty(filterList) || filterList.contains(array[0])) { + map.put(array[0], array[1]); + } + } + + return map; + } + + public static String extractAll(String text, String filters) { + List filterList = StringUtil.splitToList(filters, ","); + + return extractAll(text, filterList); + } + + public static String extractAll(String text, List filterList) { + if (CollectionUtils.isEmpty(filterList)) { + return text; + } + + StringBuilder stringBuilder = new StringBuilder(); + + List> list = assembleAll(text, filterList); + for (Map map : list) { + for (Map.Entry entry : map.entrySet()) { + String key = entry.getKey(); + String value = entry.getValue(); + stringBuilder.append("[").append(key).append("=").append(value).append("]"); + } + stringBuilder.append(" -> "); + } + + stringBuilder.delete(stringBuilder.length() - 4, stringBuilder.length()); + + return stringBuilder.toString(); + } + + public static String substringSingle(String text, String keyword) { + if (text.contains("[" + keyword + "=")) { + String value = text.substring(text.indexOf("[" + keyword + "=") + keyword.length() + 2); + + return value.substring(0, value.indexOf("]")); + } + + return null; + } +} \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/util/PropertiesUtil.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/util/PropertiesUtil.java new file mode 100644 index 0000000000..97f2eb0d6d --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/util/PropertiesUtil.java @@ -0,0 +1,107 @@ +package com.nepxion.discovery.common.util; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.Reader; +import java.util.Map; +import java.util.Properties; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.apache.commons.io.IOUtils; +import org.apache.commons.lang3.StringUtils; +import org.springframework.core.env.ConfigurableEnvironment; +import org.springframework.core.env.Environment; + +import com.alibaba.spring.util.PropertySourcesUtils; +import com.nepxion.discovery.common.constant.DiscoveryConstant; + +// Copy from Spring Cloud Alibaba project +public class PropertiesUtil { + public static final Pattern PATTERN = Pattern.compile("-(\\w)"); + + public static void enrichProperties(Properties properties, Environment environment, String prefix, boolean replaceExistedKey, boolean ignoreEmptyValue) { + enrichProperties(properties, environment, PATTERN, prefix, replaceExistedKey, ignoreEmptyValue); + } + + public static void enrichProperties(Properties properties, Environment environment, Pattern pattern, String prefix, boolean replaceExistedKey, boolean ignoreEmptyValue) { + Map map = PropertySourcesUtils.getSubProperties((ConfigurableEnvironment) environment, prefix); + for (Map.Entry entry : map.entrySet()) { + String key = resolveKey(pattern, entry.getKey()); + String value = String.valueOf(entry.getValue()); + + addProperty(properties, key, value, replaceExistedKey, ignoreEmptyValue); + } + } + + public static void addProperty(Properties properties, String key, String value, boolean replaceExistedKey, boolean ignoreEmptyValue) { + if (properties.containsKey(key)) { + if (replaceExistedKey) { + addProperty(properties, key, value, ignoreEmptyValue); + } + } else { + addProperty(properties, key, value, ignoreEmptyValue); + } + } + + public static void addProperty(Properties properties, String key, String value, boolean ignoreEmptyValue) { + if (StringUtils.isBlank(value)) { + if (!ignoreEmptyValue) { + properties.put(key, value); + } + } else { + properties.put(key, value); + } + } + + public static String resolveKey(String key) { + return resolveKey(PATTERN, key); + } + + public static String resolveKey(Pattern pattern, String key) { + Matcher matcher = pattern.matcher(key); + StringBuffer stringBuffer = new StringBuffer(); + while (matcher.find()) { + matcher.appendReplacement(stringBuffer, matcher.group(1).toUpperCase()); + } + matcher.appendTail(stringBuffer); + + return stringBuffer.toString(); + } + + public static boolean isPropertiesFormat(String properties) { + if (StringUtils.isBlank(properties)) { + return false; + } + + InputStream inputStream = null; + Reader reader = null; + try { + inputStream = IOUtils.toInputStream(properties, DiscoveryConstant.ENCODING_UTF_8); + reader = new InputStreamReader(inputStream, DiscoveryConstant.ENCODING_UTF_8); + + new Properties().load(reader); + + return true; + } catch (Exception e) { + return false; + } finally { + if (reader != null) { + IOUtils.closeQuietly(reader); + } + + if (inputStream != null) { + IOUtils.closeQuietly(inputStream); + } + } + } +} \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/util/ReflectionUtil.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/util/ReflectionUtil.java new file mode 100644 index 0000000000..a7898660f4 --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/util/ReflectionUtil.java @@ -0,0 +1,48 @@ +package com.nepxion.discovery.common.util; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +public class ReflectionUtil { + private static Map methodCache = new ConcurrentHashMap(); + private static Map fieldCache = new ConcurrentHashMap(); + + public static Object invoke(Class clazz, Object instance, String name, Class[] parameterTypes, Object[] args) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { + String key = clazz.getName() + name; + + Method method = methodCache.get(key); + if (method == null) { + method = clazz.getMethod(name, parameterTypes); + + methodCache.put(key, method); + } + + return method.invoke(instance, args); + } + + public static Object getValue(Class clazz, Object instance, String name) throws NoSuchFieldException, IllegalAccessException { + String key = clazz.getName() + name; + + Field field = fieldCache.get(key); + if (field == null) { + field = clazz.getDeclaredField(name); + field.setAccessible(true); + + fieldCache.put(key, field); + } + + return field.get(instance); + } +} \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/util/ResponseUtil.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/util/ResponseUtil.java new file mode 100644 index 0000000000..0927868b59 --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/util/ResponseUtil.java @@ -0,0 +1,47 @@ +package com.nepxion.discovery.common.util; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.apache.commons.lang3.exception.ExceptionUtils; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; + +public class ResponseUtil { + public static ResponseEntity getSuccessResponse(T result) { + return ResponseEntity.ok().body(result); + } + + public static ResponseEntity getFailureResponse(T result) { + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result); + } + + public static ResponseEntity getFailureResponse(Exception e) { + String message = getFailureMessage(e); + + return getFailureResponse(message); + } + + public static String getFailureMessage(Exception e) { + return getFailureMessage(e, false); + } + + public static String getFailureMessage(Exception e, boolean detailed) { + String message = null; + if (detailed) { + message = ExceptionUtils.getStackTrace(e); + } else { + message = e.getMessage(); + } + + // message = "An internal error occurred while processing your request\n" + message; + + return message; + } +} diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/util/RestUtil.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/util/RestUtil.java new file mode 100644 index 0000000000..017709a754 --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/util/RestUtil.java @@ -0,0 +1,104 @@ +package com.nepxion.discovery.common.util; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import org.apache.commons.collections4.MapUtils; +import org.apache.commons.lang3.StringUtils; +import org.springframework.http.HttpHeaders; +import org.springframework.web.client.ResponseErrorHandler; +import org.springframework.web.client.RestTemplate; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.nepxion.discovery.common.constant.DiscoveryConstant; +import com.nepxion.discovery.common.handler.DiscoveryResponseErrorHandler; + +public class RestUtil { + public static HttpHeaders processHeader(HttpHeaders httpHeaders, Map headerMap) { + if (MapUtils.isNotEmpty(headerMap)) { + for (Map.Entry entry : headerMap.entrySet()) { + String key = entry.getKey(); + String value = entry.getValue(); + httpHeaders.add(key, value); + } + } + + return httpHeaders; + } + + public static String processParameter(String url, Map parameterMap) { + if (MapUtils.isNotEmpty(parameterMap)) { + StringBuilder parameterStringBuilder = new StringBuilder(); + + int index = 0; + for (Map.Entry entry : parameterMap.entrySet()) { + String key = entry.getKey(); + String value = entry.getValue(); + + parameterStringBuilder.append(key + DiscoveryConstant.EQUALS + value); + if (index < parameterMap.size() - 1) { + parameterStringBuilder.append("&"); + } + + index++; + } + + String parameter = parameterStringBuilder.toString(); + parameter = StringUtils.isNotEmpty(parameter) ? "?" + parameter : ""; + + url += parameter; + } + + return url; + } + + public static HttpHeaders processCookie(HttpHeaders httpHeaders, Map cookieMap) { + if (MapUtils.isNotEmpty(cookieMap)) { + List cookieList = new ArrayList(); + for (Map.Entry entry : cookieMap.entrySet()) { + String key = entry.getKey(); + String value = entry.getValue(); + + cookieList.add(key + DiscoveryConstant.EQUALS + value); + } + + httpHeaders.put(DiscoveryConstant.COOKIE_TYPE, cookieList); + } + + return httpHeaders; + } + + public static T fromJson(RestTemplate restTemplate, String result, TypeReference typeReference) { + try { + return JsonUtil.fromJson(result, typeReference); + } catch (Exception e) { + String error = getError(restTemplate); + if (StringUtils.isNotEmpty(error)) { + throw new IllegalArgumentException(error); + } + + throw e; + } + } + + public static String getError(RestTemplate restTemplate) { + ResponseErrorHandler responseErrorHandler = restTemplate.getErrorHandler(); + if (responseErrorHandler instanceof DiscoveryResponseErrorHandler) { + DiscoveryResponseErrorHandler discoveryResponseErrorHandler = (DiscoveryResponseErrorHandler) responseErrorHandler; + + return discoveryResponseErrorHandler.getError(); + } + + return null; + } +} \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/util/StringUtil.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/util/StringUtil.java new file mode 100644 index 0000000000..c07cfaab4c --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/util/StringUtil.java @@ -0,0 +1,214 @@ +package com.nepxion.discovery.common.util; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.Arrays; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import org.apache.commons.collections4.CollectionUtils; +import org.apache.commons.collections4.MapUtils; +import org.apache.commons.io.FileUtils; +import org.apache.commons.lang3.StringUtils; + +import com.nepxion.discovery.common.constant.DiscoveryConstant; + +public class StringUtil { + public static List splitToList(String value) { + return splitToList(value, DiscoveryConstant.SEPARATE); + } + + public static List splitToList(String value, String separate) { + if (StringUtils.isEmpty(value)) { + return null; + } + + String[] valueArray = StringUtils.splitByWholeSeparator(value, separate); + + return Arrays.asList(valueArray); + } + + public static String convertToString(List list) { + return convertToString(list, DiscoveryConstant.SEPARATE); + } + + public static String convertToString(List list, String separate) { + if (CollectionUtils.isEmpty(list)) { + return null; + } + + StringBuilder stringBuilder = new StringBuilder(); + for (int i = 0; i < list.size(); i++) { + String value = list.get(i); + stringBuilder.append(value); + if (i < list.size() - 1) { + stringBuilder.append(separate); + } + } + + return stringBuilder.toString(); + } + + public static Map splitToMap(String value) { + return splitToMap(value, DiscoveryConstant.EQUALS, DiscoveryConstant.SEPARATE); + } + + public static Map splitToMap(String value, String equals, String separate) { + if (StringUtils.isEmpty(value)) { + return null; + } + + Map map = new LinkedHashMap(); + String[] separateArray = StringUtils.splitByWholeSeparator(value, separate); + for (String separateValue : separateArray) { + String[] equalsArray = StringUtils.splitByWholeSeparator(separateValue, equals); + map.put(equalsArray[0].trim(), equalsArray[1].trim()); + } + + return map; + } + + public static Map> splitToComplexMap(String value) { + return splitToComplexMap(value, DiscoveryConstant.SEPARATE); + } + + // Json {"a":"1;2", "b":"3;4"} -> Map {a=[1, 2], b=[3, 4]} + // String "1;2;3;4"-> Map {undefined=[1, 2, 3, 4]} + @SuppressWarnings("unchecked") + public static Map> splitToComplexMap(String value, String separate) { + if (StringUtils.isEmpty(value)) { + return null; + } + + Map> map = new LinkedHashMap>(); + try { + Map jsonMap = JsonUtil.fromJson(value, Map.class); + for (Map.Entry entry : jsonMap.entrySet()) { + String key = entry.getKey(); + String list = entry.getValue(); + + map.put(key, StringUtil.splitToList(list, separate)); + } + } catch (Exception e) { + List valueList = StringUtil.splitToList(value, separate); + + map.put(DiscoveryConstant.UNDEFINED, valueList); + } + + return map; + } + + public static String convertToString(Map map) { + return convertToString(map, DiscoveryConstant.EQUALS, DiscoveryConstant.SEPARATE); + } + + public static String convertToString(Map map, String equals, String separate) { + if (MapUtils.isEmpty(map)) { + return null; + } + + StringBuilder stringBuilder = new StringBuilder(); + int index = 0; + for (Map.Entry entry : map.entrySet()) { + String key = entry.getKey(); + Object value = entry.getValue(); + stringBuilder.append(key + equals + value); + + if (index < map.size() - 1) { + stringBuilder.append(separate); + } + + index++; + } + + return stringBuilder.toString(); + } + + public static String convertToComplexString(Map> map) { + return convertToComplexString(map, DiscoveryConstant.SEPARATE); + } + + // Map {a=[1, 2], b=[3, 4]} -> Json {"a":"1;2", "b":"3;4"} + // Map {undefined=[1, 2, 3, 4]} -> String "1;2;3;4" + public static String convertToComplexString(Map> map, String separate) { + if (MapUtils.isEmpty(map)) { + return null; + } + + if (map.size() == 1 && map.containsKey(DiscoveryConstant.UNDEFINED)) { + List value = map.get(DiscoveryConstant.UNDEFINED); + + return convertToString(value); + } else { + Map jsonMap = new LinkedHashMap(); + for (Map.Entry> entry : map.entrySet()) { + String key = entry.getKey(); + List value = entry.getValue(); + + jsonMap.put(key, convertToString(value)); + } + + return JsonUtil.toJson(jsonMap); + } + } + + public static Map convertToMap(List list) { + return convertToMap(list, DiscoveryConstant.EQUALS); + } + + public static Map convertToMap(List list, String separate) { + if (list == null) { + return null; + } + + Map map = new LinkedHashMap(); + for (String value : list) { + String[] valueArray = StringUtils.splitByWholeSeparator(value, separate); + map.put(valueArray[0], valueArray[1]); + } + + return map; + } + + public static String firstToUpperCase(String value) { + return StringUtils.capitalize(value); + } + + public static String firstToLowerCase(String value) { + return StringUtils.uncapitalize(value); + } + + public static String simulateText(String value, int size, String padValue) { + return StringUtils.rightPad(value, size, padValue); + } + + public static String simulateText(int size) { + return simulateText("10", size, "10"); + } + + public static String toDisplaySize(String value) { + return FileUtils.byteCountToDisplaySize(value.length()); + } + + public static int count(String text, String keyText) { + if (StringUtils.isEmpty(text) || StringUtils.isEmpty(keyText)) { + return -1; + } + + int count = 0; + while (text.indexOf(keyText) != -1) { + text = text.substring(text.indexOf(keyText) + 1, text.length()); + count++; + } + + return count; + } +} \ No newline at end of file diff --git a/discovery-common/src/main/java/com/nepxion/discovery/common/util/UrlUtil.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/util/UrlUtil.java similarity index 90% rename from discovery-common/src/main/java/com/nepxion/discovery/common/util/UrlUtil.java rename to discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/util/UrlUtil.java index a1f76b081e..047161287d 100644 --- a/discovery-common/src/main/java/com/nepxion/discovery/common/util/UrlUtil.java +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/util/UrlUtil.java @@ -13,10 +13,6 @@ public class UrlUtil { public static String formatUrl(String url) { - if (!url.startsWith("http://")) { - url = "http://" + url; - } - if (!url.endsWith("/")) { url = url + "/"; } diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/util/UuidUtil.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/util/UuidUtil.java new file mode 100644 index 0000000000..cf84fa49d7 --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/util/UuidUtil.java @@ -0,0 +1,96 @@ +package com.nepxion.discovery.common.util; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.UUID; + +import org.apache.commons.lang3.RandomUtils; +import org.apache.commons.lang3.StringUtils; + +public class UuidUtil { + public static final String DATE_FORMAT = "yyyyMMdd-HHmmss-SSS"; + public static final String SEPARATOR = "-"; + public static final String RANDOMS_EPARATOR = "-"; + public static final int[] RANDOM_ARRAY = { 9999, 999, 999 }; + + public static String getTimeUUID() { + return getTimeUUID(null); + } + + public static String getTimeUUID(String prefix) { + return getTimeUUID(prefix, RANDOM_ARRAY); + } + + public static String getTimeUUID(String prefix, int[] randomArray) { + return getTimeUUID(prefix, DATE_FORMAT, randomArray, SEPARATOR, RANDOMS_EPARATOR); + } + + public static String getTimeUUID(String prefix, String dataFormat) { + return getTimeUUID(prefix, dataFormat, RANDOM_ARRAY, SEPARATOR, RANDOMS_EPARATOR); + } + + /** + * 获取日期时间戳和随机数混合的全局唯一ID + * @param prefix 前缀 + * @param dataFormat 日期时间戳格式 + * @param randomArray 随机数数组,数组元素个数即随机数个数。例如,{ 9, 99, 999 },第一个随机数是0 ~ 9,第二个随机数是0 ~ 99,第三个随机数是0 ~ 999 + * @param separator 日期时间戳和随机数分隔符 + * @param randomSeparator 随机数之间的分隔符号 + * @return 字符串格式的全局唯一ID + */ + public static String getTimeUUID(String prefix, String dataFormat, int[] randomArray, String separator, String randomSeparator) { + if (dataFormat == null) { + throw new IllegalArgumentException("dataFormat can't be null"); + } + + if (randomArray == null) { + throw new IllegalArgumentException("randomArray can't be null"); + } + + StringBuilder stringBuilder = new StringBuilder(); + if (StringUtils.isNotEmpty(prefix)) { + stringBuilder.append(prefix).append(separator); + } + + stringBuilder.append(new SimpleDateFormat(dataFormat).format(new Date())).append(separator); + + for (int random : randomArray) { + String result = random(random); + + stringBuilder.append(result).append(randomSeparator); + } + + if (stringBuilder.length() > 0) { + stringBuilder.delete(stringBuilder.length() - 1, stringBuilder.length()); + } + + return stringBuilder.toString(); + } + + public static String random(int random) { + return random(random, String.valueOf(random).length()); + } + + /** + * 获取随机数。例如,输入999, 5, 在0 ~ 999产生随机数,由于要求是随机数位数为5,那么产生的值前面由0补齐 + * @param random 随机数最大值 + * @param padSize 随机数位数 + * @return 随机数 + */ + public static String random(int random, int padSize) { + return StringUtils.leftPad(String.valueOf(RandomUtils.nextInt(0, random)), padSize, "0"); + } + + public static String getUUID() { + return UUID.randomUUID().toString(); + } +} \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/util/VersionSortUtil.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/util/VersionSortUtil.java new file mode 100644 index 0000000000..2149a58c7e --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/util/VersionSortUtil.java @@ -0,0 +1,82 @@ +package com.nepxion.discovery.common.util; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; + +import org.apache.commons.collections4.CollectionUtils; + +import com.nepxion.discovery.common.constant.DiscoveryConstant; +import com.nepxion.discovery.common.entity.InstanceEntity; +import com.nepxion.discovery.common.entity.VersionSortEntity; +import com.nepxion.discovery.common.entity.VersionSortType; + +public class VersionSortUtil { + public static List assembleVersionList(List instanceEntityList, VersionSortType versionSortType) { + if (CollectionUtils.isEmpty(instanceEntityList)) { + return null; + } + + List versionSortEntityList = new ArrayList(); + for (InstanceEntity instanceEntity : instanceEntityList) { + String version = instanceEntity.getVersion(); + String serviceUUId = instanceEntity.getServiceUUId(); + + VersionSortEntity versionSortEntity = new VersionSortEntity(); + versionSortEntity.setVersion(version); + versionSortEntity.setServiceUUId(serviceUUId); + + versionSortEntityList.add(versionSortEntity); + } + + List versionList = VersionSortUtil.getVersionList(versionSortEntityList, versionSortType); + + // 当服务未接入本框架或者版本号未设置(表现出来的值为DiscoveryConstant.DEFAULT),被认为是老版本 + String defaultVersion = DiscoveryConstant.DEFAULT; + if (versionList.contains(defaultVersion)) { + versionList.remove(defaultVersion); + versionList.add(0, defaultVersion); + } + + return versionList; + } + + public static List getVersionList(List versionSortEntityList, VersionSortType versionSortType) { + List versionList = new ArrayList(); + + Collections.sort(versionSortEntityList, new Comparator() { + public int compare(VersionSortEntity versionSortEntity1, VersionSortEntity versionSortEntity2) { + if (versionSortType == VersionSortType.VERSION) { + String version1 = versionSortEntity1.getVersion(); + String version2 = versionSortEntity2.getVersion(); + + return version1.compareTo(version2); + } else { + String serviceUUId1 = versionSortEntity1.getServiceUUId(); + String serviceUUId2 = versionSortEntity2.getServiceUUId(); + + return serviceUUId1.compareTo(serviceUUId2); + } + } + }); + + for (VersionSortEntity versionSortEntity : versionSortEntityList) { + String version = versionSortEntity.getVersion(); + if (!versionList.contains(version)) { + versionList.add(version); + } + } + + return versionList; + } +} \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/util/XmlUtil.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/util/XmlUtil.java new file mode 100644 index 0000000000..acbc99ad4e --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/util/XmlUtil.java @@ -0,0 +1,24 @@ +package com.nepxion.discovery.common.util; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import com.nepxion.discovery.common.dom4j.Dom4JReader; + +public class XmlUtil { + public static boolean isXmlFormat(String xml) { + try { + Dom4JReader.getDocument(xml); + + return true; + } catch (Exception e) { + return false; + } + } +} \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/util/YamlUtil.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/util/YamlUtil.java new file mode 100644 index 0000000000..3cd6dfa3c6 --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/util/YamlUtil.java @@ -0,0 +1,84 @@ +package com.nepxion.discovery.common.util; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.apache.commons.lang3.StringUtils; +import org.yaml.snakeyaml.DumperOptions; +import org.yaml.snakeyaml.DumperOptions.FlowStyle; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.constructor.SafeConstructor; +import org.yaml.snakeyaml.representer.Representer; + +public class YamlUtil { + private static DumperOptions dumperOptions = new DumperOptions(); + static { + dumperOptions.setDefaultFlowStyle(FlowStyle.BLOCK); + } + + public static boolean isYamlFormat(String yaml) { + if (StringUtils.isBlank(yaml)) { + return false; + } + + // 非线程安全 + Yaml snakeYaml = new Yaml(); + try { + snakeYaml.load(yaml); + + return true; + } catch (Exception e) { + return false; + } + } + + public static String toYaml(T object) { + // 非线程安全 + Yaml snakeYaml = new Yaml(dumperOptions); + + return snakeYaml.dump(object); + } + + public static T fromYaml(String yaml, Class clazz) { + // 非线程安全 + Yaml snakeYaml = new Yaml(); + + return snakeYaml.loadAs(yaml, clazz); + } + + public static boolean isYamlFormat(SafeConstructor safeConstructor, String yaml) { + if (StringUtils.isBlank(yaml)) { + return false; + } + + // 非线程安全 + Yaml snakeYaml = new Yaml(safeConstructor); + try { + snakeYaml.load(yaml); + + return true; + } catch (Exception e) { + return false; + } + } + + public static String toYaml(SafeConstructor safeConstructor, T object) { + // 非线程安全 + Yaml snakeYaml = new Yaml(safeConstructor, new Representer(), dumperOptions); + + return snakeYaml.dump(object); + } + + public static T fromYaml(SafeConstructor safeConstructor, String yaml, Class clazz) { + // 非线程安全 + Yaml snakeYaml = new Yaml(safeConstructor); + + return snakeYaml.loadAs(yaml, clazz); + } +} \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/yaml/YamlSafeConstructor.java b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/yaml/YamlSafeConstructor.java new file mode 100644 index 0000000000..b08203ece0 --- /dev/null +++ b/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/yaml/YamlSafeConstructor.java @@ -0,0 +1,32 @@ +package com.nepxion.discovery.common.yaml; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.Collections; +import java.util.Set; +import java.util.stream.Collectors; + +import org.springframework.util.Assert; +import org.yaml.snakeyaml.constructor.Constructor; + +public class YamlSafeConstructor extends Constructor { + private Set supportedTypes; + + public YamlSafeConstructor(Set> supportedClasses) { + supportedTypes = supportedClasses.stream().map(Class::getName).collect(Collectors.collectingAndThen(Collectors.toSet(), Collections::unmodifiableSet)); + } + + @Override + protected Class getClassForName(String name) throws ClassNotFoundException { + Assert.state(supportedTypes.contains(name), "Unsupported '" + name + "' type encountered in YAML document"); + + return super.getClassForName(name); + } +} \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/resources/META-INF/additional-spring-configuration-metadata.json b/discovery-commons/discovery-common/src/main/resources/META-INF/additional-spring-configuration-metadata.json new file mode 100644 index 0000000000..66b8081967 --- /dev/null +++ b/discovery-commons/discovery-common/src/main/resources/META-INF/additional-spring-configuration-metadata.json @@ -0,0 +1,146 @@ +{ + "properties": [ + { + "name": "spring.application.weight.random.type", + "type": "java.lang.String", + "defaultValue": "MapWeightRandom", + "description": "Weight random type, it can be MapWeightRandom or ArrayWeightRandom." + }, + { + "name": "spring.application.config.format", + "type": "java.lang.String", + "defaultValue": "xml", + "description": "Config format, it can be xml or json." + }, + { + "name": "spring.application.config.path", + "type": "java.lang.String", + "defaultValue": "classpath:rule.xml", + "description": "Config path, it can be classpath:xxx or file:xxx." + }, + { + "name": "spring.application.group.key", + "type": "java.lang.String", + "defaultValue": "group", + "description": "Group key." + }, + { + "name": "spring.application.default.properties.path", + "type": "java.lang.String", + "defaultValue": "spring-application-default.properties", + "description": "Default properties path, it can be classpath:xxx or file:xxx." + }, + { + "name": "spring.application.group.generator.enabled", + "type": "java.lang.Boolean", + "defaultValue": false, + "description": "Whether group generator is enabled." + }, + { + "name": "spring.application.group.generator.length", + "type": "java.lang.Integer", + "defaultValue": -1, + "description": "Group generator length." + }, + { + "name": "spring.application.group.generator.character", + "type": "java.lang.String", + "defaultValue": "", + "description": "Group generator character." + }, + { + "name": "spring.application.git.generator.enabled", + "type": "java.lang.Boolean", + "defaultValue": false, + "description": "Whether git generator is enabled." + }, + { + "name": "spring.application.git.generator.path", + "type": "java.lang.String", + "defaultValue": "classpath:git.json", + "description": "Git generator path, it can be classpath:xxx or file:xxx." + }, + { + "name": "spring.application.git.version.key", + "type": "java.lang.String", + "defaultValue": "git.commit.id", + "description": "Git version key, it can be git.commit.id or git.build.version or another." + }, + { + "name": "spring.application.no.servers.notify.enabled", + "type": "java.lang.Boolean", + "defaultValue": false, + "description": "Whether no server notify is enabled." + }, + { + "name": "spring.application.parameter.event.onstart.enabled", + "type": "java.lang.Boolean", + "defaultValue": true, + "description": "Whether parameter event onstart is enabled." + }, + { + "name": "swagger.enabled", + "type": "java.lang.Boolean", + "defaultValue": true, + "description": "Whether swagger is enabled." + }, + { + "name": "swagger.service.group", + "type": "java.lang.String", + "defaultValue": "", + "description": "Swagger service group defined outside." + }, + { + "name": "swagger.service.packages", + "type": "java.lang.String", + "defaultValue": "", + "description": "Swagger service packages defined outside." + }, + { + "name": "swagger.service.description", + "type": "java.lang.String", + "description": "Swagger service description." + }, + { + "name": "swagger.service.version", + "type": "java.lang.String", + "description": "Swagger service version." + }, + { + "name": "swagger.service.license.name", + "type": "java.lang.String", + "defaultValue": "Apache License 2.0", + "description": "Swagger service license name." + }, + { + "name": "swagger.service.license.url", + "type": "java.lang.String", + "defaultValue": "http://www.apache.org/licenses/LICENSE-2.0", + "description": "Swagger service license url." + }, + { + "name": "swagger.service.contact.name", + "type": "java.lang.String", + "defaultValue": "Nepxion", + "description": "Swagger service contact." + }, + { + "name": "swagger.service.contact.url", + "type": "java.lang.String", + "defaultValue": "https://github.com/Nepxion/Discovery", + "description": "Swagger service contact url." + }, + { + "name": "swagger.service.contact.email", + "type": "java.lang.String", + "defaultValue": "1394997@qq.com", + "description": "Swagger service contact email." + }, + { + "name": "swagger.service.termsOfService.url", + "type": "java.lang.String", + "defaultValue": "http://nepxion.com/discovery", + "description": "Swagger service termsOfService url." + } + ] +} \ No newline at end of file diff --git a/discovery-common/src/main/resources/com/nepxion/apollo/resource/logo.txt b/discovery-commons/discovery-common/src/main/resources/com/nepxion/apollo/resource/logo.txt similarity index 100% rename from discovery-common/src/main/resources/com/nepxion/apollo/resource/logo.txt rename to discovery-commons/discovery-common/src/main/resources/com/nepxion/apollo/resource/logo.txt diff --git a/discovery-commons/discovery-common/src/main/resources/com/nepxion/caffeine/resource/logo.txt b/discovery-commons/discovery-common/src/main/resources/com/nepxion/caffeine/resource/logo.txt new file mode 100644 index 0000000000..2b107bd7ba --- /dev/null +++ b/discovery-commons/discovery-common/src/main/resources/com/nepxion/caffeine/resource/logo.txt @@ -0,0 +1,40 @@ + ,-----. +' .--./ +| | +' '--'\ + `-----' + ,---. + / O \ +| .-. | +| | | | +`--' `--' +,------. +| .---' +| `--, +| |` +`--' +,------. +| .---' +| `--, +| |` +`--' +,------. +| .---' +| `--, +| `---. +`------' +,--. +| | +| | +| | +`--' +,--. ,--. +| ,'.| | +| |' ' | +| | ` | +`--' `--' +,------. +| .---' +| `--, +| `---. +`------' \ No newline at end of file diff --git a/discovery-common/src/main/resources/com/nepxion/consul/resource/logo.txt b/discovery-commons/discovery-common/src/main/resources/com/nepxion/consul/resource/logo.txt similarity index 100% rename from discovery-common/src/main/resources/com/nepxion/consul/resource/logo.txt rename to discovery-commons/discovery-common/src/main/resources/com/nepxion/consul/resource/logo.txt diff --git a/discovery-common/src/main/resources/com/nepxion/discovery/resource/logo.txt b/discovery-commons/discovery-common/src/main/resources/com/nepxion/discovery/resource/logo.txt similarity index 100% rename from discovery-common/src/main/resources/com/nepxion/discovery/resource/logo.txt rename to discovery-commons/discovery-common/src/main/resources/com/nepxion/discovery/resource/logo.txt diff --git a/discovery-commons/discovery-common/src/main/resources/com/nepxion/docker/resource/logo.txt b/discovery-commons/discovery-common/src/main/resources/com/nepxion/docker/resource/logo.txt new file mode 100644 index 0000000000..30c6535ab4 --- /dev/null +++ b/discovery-commons/discovery-common/src/main/resources/com/nepxion/docker/resource/logo.txt @@ -0,0 +1,30 @@ +,------. +| .-. \ +| | \ : +| '--' / +`-------' + ,-----. +' .-. ' +| | | | +' '-' ' + `-----' + ,-----. +' .--./ +| | +' '--'\ + `-----' +,--. ,--. +| .' / +| . ' +| |\ \ +`--' '--' +,------. +| .---' +| `--, +| `---. +`------' +,------. +| .--. ' +| '--'.' +| |\ \ +`--' '--' \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/resources/com/nepxion/etcd/resource/logo.txt b/discovery-commons/discovery-common/src/main/resources/com/nepxion/etcd/resource/logo.txt new file mode 100644 index 0000000000..b127fcd5ea --- /dev/null +++ b/discovery-commons/discovery-common/src/main/resources/com/nepxion/etcd/resource/logo.txt @@ -0,0 +1,20 @@ +,------. +| .---' +| `--, +| `---. +`------' +,--------. +'--. .--' + | | + | | + `--' + ,-----. +' .--./ +| | +' '--'\ + `-----' +,------. +| .-. \ +| | \ : +| '--' / +`-------' \ No newline at end of file diff --git a/discovery-common/src/main/resources/com/nepxion/eureka/resource/logo.txt b/discovery-commons/discovery-common/src/main/resources/com/nepxion/eureka/resource/logo.txt similarity index 100% rename from discovery-common/src/main/resources/com/nepxion/eureka/resource/logo.txt rename to discovery-commons/discovery-common/src/main/resources/com/nepxion/eureka/resource/logo.txt diff --git a/discovery-commons/discovery-common/src/main/resources/com/nepxion/h2/resource/logo.txt b/discovery-commons/discovery-common/src/main/resources/com/nepxion/h2/resource/logo.txt new file mode 100644 index 0000000000..cb4fdab2dc --- /dev/null +++ b/discovery-commons/discovery-common/src/main/resources/com/nepxion/h2/resource/logo.txt @@ -0,0 +1,10 @@ +,--. ,--. +| '--' | +| .--. | +| | | | +`--' `--' + ,---. +'.-. \ + .-' .' +/ '-. +'-----' \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/resources/com/nepxion/hystrix/resource/logo.txt b/discovery-commons/discovery-common/src/main/resources/com/nepxion/hystrix/resource/logo.txt new file mode 100644 index 0000000000..0d875b1855 --- /dev/null +++ b/discovery-commons/discovery-common/src/main/resources/com/nepxion/hystrix/resource/logo.txt @@ -0,0 +1,35 @@ +,--. ,--. +| '--' | +| .--. | +| | | | +`--' `--' +,--. ,--. + \ `.' / + '. / + | | + `--' + ,---. +' .-' +`. `-. +.-' | +`-----' +,--------. +'--. .--' + | | + | | + `--' +,------. +| .--. ' +| '--'.' +| |\ \ +`--' '--' +,--. +| | +| | +| | +`--' +,--. ,--. + \ `.' / + .' \ + / .'. \ +'--' '--' \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/resources/com/nepxion/istio/resource/logo.txt b/discovery-commons/discovery-common/src/main/resources/com/nepxion/istio/resource/logo.txt new file mode 100644 index 0000000000..0d2612f636 --- /dev/null +++ b/discovery-commons/discovery-common/src/main/resources/com/nepxion/istio/resource/logo.txt @@ -0,0 +1,25 @@ +,--. +| | +| | +| | +`--' + ,---. +' .-' +`. `-. +.-' | +`-----' +,--------. +'--. .--' + | | + | | + `--' +,--. +| | +| | +| | +`--' + ,-----. +' .-. ' +| | | | +' '-' ' + `-----' \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/resources/com/nepxion/kafka/resource/logo.txt b/discovery-commons/discovery-common/src/main/resources/com/nepxion/kafka/resource/logo.txt new file mode 100644 index 0000000000..e95b9b15e4 --- /dev/null +++ b/discovery-commons/discovery-common/src/main/resources/com/nepxion/kafka/resource/logo.txt @@ -0,0 +1,25 @@ +,--. ,--. +| .' / +| . ' +| |\ \ +`--' '--' + ,---. + / O \ +| .-. | +| | | | +`--' `--' +,------. +| .---' +| `--, +| |` +`--' +,--. ,--. +| .' / +| . ' +| |\ \ +`--' '--' + ,---. + / O \ +| .-. | +| | | | +`--' `--' \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/resources/com/nepxion/kubernetes/resource/logo.txt b/discovery-commons/discovery-common/src/main/resources/com/nepxion/kubernetes/resource/logo.txt new file mode 100644 index 0000000000..9a229d5291 --- /dev/null +++ b/discovery-commons/discovery-common/src/main/resources/com/nepxion/kubernetes/resource/logo.txt @@ -0,0 +1,15 @@ +,--. ,--. +| .' / +| . ' +| |\ \ +`--' '--' + ,---. +| o | +.' '. +| o | + `---' + ,---. +' .-' +`. `-. +.-' | +`-----' \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/resources/com/nepxion/ldap/resource/logo.txt b/discovery-commons/discovery-common/src/main/resources/com/nepxion/ldap/resource/logo.txt new file mode 100644 index 0000000000..3ea369bd6c --- /dev/null +++ b/discovery-commons/discovery-common/src/main/resources/com/nepxion/ldap/resource/logo.txt @@ -0,0 +1,20 @@ +,--. +| | +| | +| '--. +`-----' +,------. +| .-. \ +| | \ : +| '--' / +`-------' + ,---. + / O \ +| .-. | +| | | | +`--' `--' +,------. +| .--. ' +| '--' | +| | --' +`--' \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/resources/com/nepxion/mysql/resource/logo.txt b/discovery-commons/discovery-common/src/main/resources/com/nepxion/mysql/resource/logo.txt new file mode 100644 index 0000000000..88615454df --- /dev/null +++ b/discovery-commons/discovery-common/src/main/resources/com/nepxion/mysql/resource/logo.txt @@ -0,0 +1,25 @@ +,--. ,--. +| `.' | +| |'.'| | +| | | | +`--' `--' +,--. ,--. + \ `.' / + '. / + | | + `--' + ,---. +' .-' +`. `-. +.-' | +`-----' + ,-----. +' .-. ' +| | | | +' '-' '-. + `-----'--' +,--. +| | +| | +| '--. +`-----' \ No newline at end of file diff --git a/discovery-common/src/main/resources/com/nepxion/nacos/resource/logo.txt b/discovery-commons/discovery-common/src/main/resources/com/nepxion/nacos/resource/logo.txt similarity index 100% rename from discovery-common/src/main/resources/com/nepxion/nacos/resource/logo.txt rename to discovery-commons/discovery-common/src/main/resources/com/nepxion/nacos/resource/logo.txt diff --git a/discovery-commons/discovery-common/src/main/resources/com/nepxion/opentelemetry/resource/logo.txt b/discovery-commons/discovery-common/src/main/resources/com/nepxion/opentelemetry/resource/logo.txt new file mode 100644 index 0000000000..43972487b1 --- /dev/null +++ b/discovery-commons/discovery-common/src/main/resources/com/nepxion/opentelemetry/resource/logo.txt @@ -0,0 +1,40 @@ + ,-----. +' .-. ' +| | | | +' '-' ' + `-----' +,------. +| .--. ' +| '--' | +| | --' +`--' +,------. +| .---' +| `--, +| `---. +`------' +,--. ,--. +| ,'.| | +| |' ' | +| | ` | +`--' `--' +,--------. +'--. .--' + | | + | | + `--' +,------. +| .---' +| `--, +| `---. +`------' +,--. +| | +| | +| '--. +`-----' +,------. +| .---' +| `--, +| `---. +`------' \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/resources/com/nepxion/opentracing/resource/logo.txt b/discovery-commons/discovery-common/src/main/resources/com/nepxion/opentracing/resource/logo.txt new file mode 100644 index 0000000000..e8ea0a61e2 --- /dev/null +++ b/discovery-commons/discovery-common/src/main/resources/com/nepxion/opentracing/resource/logo.txt @@ -0,0 +1,40 @@ + ,-----. +' .-. ' +| | | | +' '-' ' + `-----' +,------. +| .--. ' +| '--' | +| | --' +`--' +,------. +| .---' +| `--, +| `---. +`------' +,--. ,--. +| ,'.| | +| |' ' | +| | ` | +`--' `--' +,--------. +'--. .--' + | | + | | + `--' +,------. +| .--. ' +| '--'.' +| |\ \ +`--' '--' + ,---. + / O \ +| .-. | +| | | | +`--' `--' + ,-----. +' .--./ +| | +' '--'\ + `-----' \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/resources/com/nepxion/platform/resource/logo.txt b/discovery-commons/discovery-common/src/main/resources/com/nepxion/platform/resource/logo.txt new file mode 100644 index 0000000000..5a9fdc3d91 --- /dev/null +++ b/discovery-commons/discovery-common/src/main/resources/com/nepxion/platform/resource/logo.txt @@ -0,0 +1,40 @@ +,------. +| .--. ' +| '--' | +| | --' +`--' +,--. +| | +| | +| '--. +`-----' + ,---. + / O \ +| .-. | +| | | | +`--' `--' +,--------. +'--. .--' + | | + | | + `--' +,------. +| .---' +| `--, +| |` +`--' + ,-----. +' .-. ' +| | | | +' '-' ' + `-----' +,------. +| .--. ' +| '--'.' +| |\ \ +`--' '--' +,--. ,--. +| `.' | +| |'.'| | +| | | | +`--' `--' \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/resources/com/nepxion/rabbitmq/resource/logo.txt b/discovery-commons/discovery-common/src/main/resources/com/nepxion/rabbitmq/resource/logo.txt new file mode 100644 index 0000000000..5eb57957bc --- /dev/null +++ b/discovery-commons/discovery-common/src/main/resources/com/nepxion/rabbitmq/resource/logo.txt @@ -0,0 +1,40 @@ +,------. +| .--. ' +| '--'.' +| |\ \ +`--' '--' + ,---. + / O \ +| .-. | +| | | | +`--' `--' +,-----. +| |) /_ +| .-. \ +| '--' / +`------' +,-----. +| |) /_ +| .-. \ +| '--' / +`------' +,--. +| | +| | +| | +`--' +,--------. +'--. .--' + | | + | | + `--' +,--. ,--. +| `.' | +| |'.'| | +| | | | +`--' `--' + ,-----. +' .-. ' +| | | | +' '-' '-. + `-----'--' \ No newline at end of file diff --git a/discovery-common/src/main/resources/com/nepxion/redis/resource/logo.txt b/discovery-commons/discovery-common/src/main/resources/com/nepxion/redis/resource/logo.txt similarity index 100% rename from discovery-common/src/main/resources/com/nepxion/redis/resource/logo.txt rename to discovery-commons/discovery-common/src/main/resources/com/nepxion/redis/resource/logo.txt diff --git a/discovery-commons/discovery-common/src/main/resources/com/nepxion/redisson/resource/logo.txt b/discovery-commons/discovery-common/src/main/resources/com/nepxion/redisson/resource/logo.txt new file mode 100644 index 0000000000..7603bc3400 --- /dev/null +++ b/discovery-commons/discovery-common/src/main/resources/com/nepxion/redisson/resource/logo.txt @@ -0,0 +1,40 @@ +,------. +| .--. ' +| '--'.' +| |\ \ +`--' '--' +,------. +| .---' +| `--, +| `---. +`------' +,------. +| .-. \ +| | \ : +| '--' / +`-------' +,--. +| | +| | +| | +`--' + ,---. +' .-' +`. `-. +.-' | +`-----' + ,---. +' .-' +`. `-. +.-' | +`-----' + ,-----. +' .-. ' +| | | | +' '-' ' + `-----' +,--. ,--. +| ,'.| | +| |' ' | +| | ` | +`--' `--' \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/resources/com/nepxion/ribbon/resource/logo.txt b/discovery-commons/discovery-common/src/main/resources/com/nepxion/ribbon/resource/logo.txt new file mode 100644 index 0000000000..39128bbff3 --- /dev/null +++ b/discovery-commons/discovery-common/src/main/resources/com/nepxion/ribbon/resource/logo.txt @@ -0,0 +1,30 @@ +,------. +| .--. ' +| '--'.' +| |\ \ +`--' '--' +,--. +| | +| | +| | +`--' +,-----. +| |) /_ +| .-. \ +| '--' / +`------' +,-----. +| |) /_ +| .-. \ +| '--' / +`------' + ,-----. +' .-. ' +| | | | +' '-' ' + `-----' +,--. ,--. +| ,'.| | +| |' ' | +| | ` | +`--' `--' \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/resources/com/nepxion/rocketmq/resource/logo.txt b/discovery-commons/discovery-common/src/main/resources/com/nepxion/rocketmq/resource/logo.txt new file mode 100644 index 0000000000..547ab549f8 --- /dev/null +++ b/discovery-commons/discovery-common/src/main/resources/com/nepxion/rocketmq/resource/logo.txt @@ -0,0 +1,40 @@ +,------. +| .--. ' +| '--'.' +| |\ \ +`--' '--' + ,-----. +' .-. ' +| | | | +' '-' ' + `-----' + ,-----. +' .--./ +| | +' '--'\ + `-----' +,--. ,--. +| .' / +| . ' +| |\ \ +`--' '--' +,------. +| .---' +| `--, +| `---. +`------' +,--------. +'--. .--' + | | + | | + `--' +,--. ,--. +| `.' | +| |'.'| | +| | | | +`--' `--' + ,-----. +' .-. ' +| | | | +' '-' '-. + `-----'--' \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/resources/com/nepxion/sclb/resource/logo.txt b/discovery-commons/discovery-common/src/main/resources/com/nepxion/sclb/resource/logo.txt new file mode 100644 index 0000000000..4221311388 --- /dev/null +++ b/discovery-commons/discovery-common/src/main/resources/com/nepxion/sclb/resource/logo.txt @@ -0,0 +1,20 @@ + ,---. +' .-' +`. `-. +.-' | +`-----' + ,-----. +' .--./ +| | +' '--'\ + `-----' +,--. +| | +| | +| '--. +`-----' +,-----. +| |) /_ +| .-. \ +| '--' / +`------' \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/resources/com/nepxion/sentinel/resource/logo.txt b/discovery-commons/discovery-common/src/main/resources/com/nepxion/sentinel/resource/logo.txt new file mode 100644 index 0000000000..f9f979f6a1 --- /dev/null +++ b/discovery-commons/discovery-common/src/main/resources/com/nepxion/sentinel/resource/logo.txt @@ -0,0 +1,40 @@ + ,---. +' .-' +`. `-. +.-' | +`-----' +,------. +| .---' +| `--, +| `---. +`------' +,--. ,--. +| ,'.| | +| |' ' | +| | ` | +`--' `--' +,--------. +'--. .--' + | | + | | + `--' +,--. +| | +| | +| | +`--' +,--. ,--. +| ,'.| | +| |' ' | +| | ` | +`--' `--' +,------. +| .---' +| `--, +| `---. +`------' +,--. +| | +| | +| '--. +`-----' \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/main/resources/com/nepxion/skywalking/resource/logo.txt b/discovery-commons/discovery-common/src/main/resources/com/nepxion/skywalking/resource/logo.txt new file mode 100644 index 0000000000..1e7ed2fbc6 --- /dev/null +++ b/discovery-commons/discovery-common/src/main/resources/com/nepxion/skywalking/resource/logo.txt @@ -0,0 +1,35 @@ + ,---. +' .-' +`. `-. +.-' | +`-----' +,--. ,--. +| .' / +| . ' +| |\ \ +`--' '--' +,--. ,--. + \ `.' / + '. / + | | + `--' +,--. ,--. +| | | | +| |.'.| | +| ,'. | +'--' '--' + ,---. + / O \ +| .-. | +| | | | +`--' `--' +,--. +| | +| | +| '--. +`-----' +,--. ,--. +| .' / +| . ' +| |\ \ +`--' '--' \ No newline at end of file diff --git a/discovery-common/src/main/resources/com/nepxion/zookeeper/resource/logo.txt b/discovery-commons/discovery-common/src/main/resources/com/nepxion/zookeeper/resource/logo.txt similarity index 100% rename from discovery-common/src/main/resources/com/nepxion/zookeeper/resource/logo.txt rename to discovery-commons/discovery-common/src/main/resources/com/nepxion/zookeeper/resource/logo.txt diff --git a/discovery-commons/discovery-common/src/test/java/com/nepxion/discovery/common/ConditionStrategyYamlTest.java b/discovery-commons/discovery-common/src/test/java/com/nepxion/discovery/common/ConditionStrategyYamlTest.java new file mode 100644 index 0000000000..cff45e54e2 --- /dev/null +++ b/discovery-commons/discovery-common/src/test/java/com/nepxion/discovery/common/ConditionStrategyYamlTest.java @@ -0,0 +1,66 @@ +package com.nepxion.discovery.common; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.util.LinkedHashSet; +import java.util.Set; + +import org.apache.commons.io.IOUtils; + +import com.nepxion.discovery.common.constant.DiscoveryConstant; +import com.nepxion.discovery.common.entity.ConditionStrategy; +import com.nepxion.discovery.common.util.YamlUtil; +import com.nepxion.discovery.common.yaml.YamlSafeConstructor; + +public class ConditionStrategyYamlTest { + public static void main(String[] args) { + Set> supportedClasses = new LinkedHashSet<>(); + supportedClasses.add(ConditionStrategy.class); + + YamlSafeConstructor yamlSafeConstructor = new YamlSafeConstructor(supportedClasses); + + String yml = testFile("sample.yaml"); + + System.out.println("Yaml:\n" + yml); + + ConditionStrategy conditionStrategy = YamlUtil.fromYaml(yamlSafeConstructor, yml, ConditionStrategy.class); + + System.out.println("To object:\n" + conditionStrategy); + + String yaml = YamlUtil.toYaml(yamlSafeConstructor, conditionStrategy); + + System.out.println("To yaml:\n" + yaml); + } + + public static String testFile(String fileName) { + File file = new File("src/test/resources/" + fileName); + InputStream inputStream = null; + String rule = null; + try { + inputStream = new FileInputStream(file); + rule = IOUtils.toString(inputStream, DiscoveryConstant.ENCODING_UTF_8); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } finally { + if (inputStream != null) { + IOUtils.closeQuietly(inputStream); + } + } + + return rule; + } +} \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/test/java/com/nepxion/discovery/common/DiscoveryExpressionTest.java b/discovery-commons/discovery-common/src/test/java/com/nepxion/discovery/common/DiscoveryExpressionTest.java new file mode 100644 index 0000000000..ee412c5cd5 --- /dev/null +++ b/discovery-commons/discovery-common/src/test/java/com/nepxion/discovery/common/DiscoveryExpressionTest.java @@ -0,0 +1,92 @@ +package com.nepxion.discovery.common; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.apache.commons.lang3.StringUtils; + +import com.nepxion.discovery.common.expression.DiscoveryExpressionResolver; +import com.nepxion.discovery.common.expression.DiscoveryTypeComparator; +import com.nepxion.discovery.common.util.StringUtil; + +public class DiscoveryExpressionTest { + public static void main(String[] args) { + System.out.println(test1()); + System.out.println(test2()); + System.out.println(test3()); + System.out.println(test4()); + } + + private static boolean test1() { + // String expression = "#H['a'] != 'x' || #H['b'] != 'y'"; + // String expression = "#H['a'] == '123' && #H['b'] == '456'"; + // String expression = "#H['a'] == '123' || #H['b'] == '456'"; + // String expression = "#H['a'] >= '123' && #H['b'] <= '456'"; + // String expression = "#H['a'] >= '123' || #H['b'] <= '456'"; + // String expression = "#H['a'] != '123' || #H['b'] != '456'"; + // String expression = "#H['a'] < '2' && #H['b'] == '3'"; + String expression = "#H['a'] matches '[a-z]{3}2'"; + Map map = new HashMap(); + // map.put("a", "123"); + // map.put("b", "456"); + map.put("a", "1.2333"); + map.put("b", "y"); + + return DiscoveryExpressionResolver.eval(expression, "H", map, new DiscoveryTypeComparator()); + } + + private static List test2() { + String regex = "\\#H\\['\\S+'\\]"; + Pattern pattern = Pattern.compile(regex); + + String expression = "#H['a-A'] != '123' || #H['b//SS'] != '456' && #H['C**44!!66'] == '123'"; + Matcher matcher = pattern.matcher(expression); + + List list = new ArrayList(); + while (matcher.find()) { + String group = matcher.group(); + String value = StringUtils.substringBetween(group, "#H['", "']"); + list.add(value); + } + + return list; + } + + private static List test3() { + String regex = "\\[\\S+\\]"; + Pattern pattern = Pattern.compile(regex); + + String expression = "[ID=solar-service-a][H=172.27.208.1:3001][V=1.0][R=dev][E=env1][G=solar-group][TID=123][SID=N/A]"; + expression = StringUtils.replace(expression, "][", "] ["); + Matcher matcher = pattern.matcher(expression); + + List list = new ArrayList(); + while (matcher.find()) { + String group = matcher.group(); + String value = StringUtils.substringBetween(group, "[", "]"); + list.add(value); + } + + return list; + } + + private static int test4() { + String expression = "#H['a-A'] != '123' || #H['b//SS'] != '456' && #H['C**44!!66'] == '123'"; + String key = "#H['"; + + return StringUtil.count(expression, key); + } +} \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/test/java/com/nepxion/discovery/common/EscapeTest.java b/discovery-commons/discovery-common/src/test/java/com/nepxion/discovery/common/EscapeTest.java new file mode 100644 index 0000000000..40b114bfed --- /dev/null +++ b/discovery-commons/discovery-common/src/test/java/com/nepxion/discovery/common/EscapeTest.java @@ -0,0 +1,24 @@ +package com.nepxion.discovery.common; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import com.nepxion.discovery.common.entity.EscapeType; + +public class EscapeTest { + public static void main(String[] args) { + String value = "#H['a'] == '1' && #H['b'] <= '2' && #H['c'] != '3'"; + + value = EscapeType.escape(value, true); + System.out.println(value); + + value = EscapeType.escape(value, false); + System.out.println(value); + } +} diff --git a/discovery-commons/discovery-common/src/test/java/com/nepxion/discovery/common/FormatUtilTest.java b/discovery-commons/discovery-common/src/test/java/com/nepxion/discovery/common/FormatUtilTest.java new file mode 100644 index 0000000000..67952cb40a --- /dev/null +++ b/discovery-commons/discovery-common/src/test/java/com/nepxion/discovery/common/FormatUtilTest.java @@ -0,0 +1,62 @@ +package com.nepxion.discovery.common; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; + +import org.apache.commons.io.IOUtils; + +import com.nepxion.discovery.common.constant.DiscoveryConstant; +import com.nepxion.discovery.common.util.FormatUtil; + +public class FormatUtilTest { + public static void main(String[] args) { + long time = System.currentTimeMillis(); + + System.out.println(FormatUtil.getFormatType(testFile("sample.xml"))); + System.out.println(System.currentTimeMillis() - time); + + time = System.currentTimeMillis(); + System.out.println(FormatUtil.getFormatType(testFile("sample.json"))); + System.out.println(System.currentTimeMillis() - time); + + time = System.currentTimeMillis(); + System.out.println(FormatUtil.getFormatType(testFile("sample.properties"))); + System.out.println(System.currentTimeMillis() - time); + + time = System.currentTimeMillis(); + System.out.println(FormatUtil.getFormatType(testFile("sample.yaml"))); + System.out.println(System.currentTimeMillis() - time); + } + + public static String testFile(String fileName) { + File file = new File("src/test/resources/" + fileName); + InputStream inputStream = null; + String rule = null; + try { + inputStream = new FileInputStream(file); + rule = IOUtils.toString(inputStream, DiscoveryConstant.ENCODING_UTF_8); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } finally { + if (inputStream != null) { + IOUtils.closeQuietly(inputStream); + } + } + + return rule; + } +} \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/test/java/com/nepxion/discovery/common/PluginInfoTest.java b/discovery-commons/discovery-common/src/test/java/com/nepxion/discovery/common/PluginInfoTest.java new file mode 100644 index 0000000000..4fbec216b2 --- /dev/null +++ b/discovery-commons/discovery-common/src/test/java/com/nepxion/discovery/common/PluginInfoTest.java @@ -0,0 +1,40 @@ +package com.nepxion.discovery.common; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.Arrays; +import java.util.List; + +import com.nepxion.discovery.common.util.PluginInfoUtil; + +public class PluginInfoTest { + public static void main(String[] args) { + String result = "[ID=discovery-guide-gateway][UID=20221026-220729-881-6282-394-753][T=gateway][P=Nacos][H=192.168.31.237:5001][V=1.0][R=default][E=default][Z=default][G=discovery-guide-group][A=false][TID=775868f091ec26d][SID=696bb7770c01037e]"; + System.out.println(PluginInfoUtil.assembleSingle(result, (List) null)); + System.out.println(PluginInfoUtil.assembleSingle(result, (String) null)); + System.out.println(PluginInfoUtil.assembleSingle(result, Arrays.asList("ID", "V", "ABC"))); + System.out.println(PluginInfoUtil.assembleSingle(result, "ID,V,ABC")); + + System.out.println(PluginInfoUtil.substringSingle(result, "ID")); + System.out.println(PluginInfoUtil.substringSingle(result, "V")); + System.out.println(PluginInfoUtil.substringSingle(result, "ABC")); + + String resultAll = "[ID=discovery-guide-gateway][UID=20221026-220729-881-6282-394-753][T=gateway][P=Nacos][H=192.168.31.237:5001][V=1.0][R=default][E=default][Z=default][G=discovery-guide-group][A=false][TID=775868f091ec26d][SID=696bb7770c01037e] -> [ID=discovery-guide-service-a][UID=20221026-220728-411-0772-370-576][T=service][P=Nacos][H=192.168.31.237:3001][V=1.0][R=dev][E=env1][Z=zone1][G=discovery-guide-group][A=true][TID=775868f091ec26d][SID=96fcc77d7d5e7767] -> [ID=discovery-guide-service-b][UID=20221026-220727-655-5472-259-437][T=service][P=Nacos][H=192.168.31.237:4001][V=1.0][R=qa][E=env1][Z=zone1][G=discovery-guide-group][A=false][TID=775868f091ec26d][SID=f80c1d9e20b6bdb9]"; + System.out.println(PluginInfoUtil.assembleAll(resultAll, (List) null)); + System.out.println(PluginInfoUtil.assembleAll(resultAll, (String) null)); + System.out.println(PluginInfoUtil.assembleAll(resultAll, Arrays.asList("ID", "V", "ABC"))); + System.out.println(PluginInfoUtil.assembleAll(resultAll, "ID,V,ABC")); + + System.out.println(PluginInfoUtil.extractAll(resultAll, (List) null)); + System.out.println(PluginInfoUtil.extractAll(resultAll, (String) null)); + System.out.println(PluginInfoUtil.extractAll(resultAll, Arrays.asList("ID", "V", "ABC"))); + System.out.println(PluginInfoUtil.extractAll(resultAll, "ID,V,ABC")); + } +} \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/test/java/com/nepxion/discovery/common/ReflectionUtilTest.java b/discovery-commons/discovery-common/src/test/java/com/nepxion/discovery/common/ReflectionUtilTest.java new file mode 100644 index 0000000000..985e81f26c --- /dev/null +++ b/discovery-commons/discovery-common/src/test/java/com/nepxion/discovery/common/ReflectionUtilTest.java @@ -0,0 +1,35 @@ +package com.nepxion.discovery.common; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import com.nepxion.discovery.common.util.ReflectionUtil; + +public class ReflectionUtilTest { + public static class User { + private String name = "zhangsan"; + + public String getName(String type1, int type2) { + if (type1.equals("a") && type2 == 0) { + return "lisi"; + } else { + return name; + } + } + } + + public static void main(String[] args) { + try { + System.out.println(ReflectionUtil.invoke(User.class, new User(), "getName", new Class[] { String.class, int.class }, new Object[] { "a", 0 })); + System.out.println(ReflectionUtil.getValue(User.class, new User(), "name")); + } catch (Exception e) { + e.printStackTrace(); + } + } +} \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/test/java/com/nepxion/discovery/common/StringUtilTest.java b/discovery-commons/discovery-common/src/test/java/com/nepxion/discovery/common/StringUtilTest.java new file mode 100644 index 0000000000..517875bb27 --- /dev/null +++ b/discovery-commons/discovery-common/src/test/java/com/nepxion/discovery/common/StringUtilTest.java @@ -0,0 +1,75 @@ +package com.nepxion.discovery.common; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import com.nepxion.discovery.common.constant.DiscoveryConstant; +import com.nepxion.discovery.common.util.StringUtil; + +public class StringUtilTest { + public static void main(String[] args) { + test1(); + test2(); + test3(); + } + + private static void test1() { + System.out.println(StringUtil.splitToList("")); + System.out.println(StringUtil.splitToList(null)); + + System.out.println(StringUtil.convertToString(new ArrayList())); + System.out.println(StringUtil.convertToString((List) null)); + + List list = StringUtil.splitToList("a->b->c", "->"); + System.out.println(list); + + String value = StringUtil.convertToString(list, "->"); + System.out.println(value); + } + + private static void test2() { + System.out.println(StringUtil.splitToMap("")); + System.out.println(StringUtil.splitToMap(null)); + + System.out.println(StringUtil.convertToString(new HashMap())); + System.out.println(StringUtil.convertToString((Map) null)); + + Map map = StringUtil.splitToMap("a==1&&b==2", "==", "&&"); + System.out.println(map); + + String value = StringUtil.convertToString(map, "==", "&&"); + System.out.println(value); + } + + private static void test3() { + Map> map1 = new LinkedHashMap>(); + map1.put("a", Arrays.asList("1", "2")); + map1.put("b", Arrays.asList("3", "4")); + + String value1 = StringUtil.convertToComplexString(map1); + + System.out.println(value1); + System.out.println(StringUtil.splitToComplexMap(value1)); + + Map> map2 = new LinkedHashMap>(); + map2.put(DiscoveryConstant.UNDEFINED, Arrays.asList("1", "2")); + + String value2 = StringUtil.convertToComplexString(map2); + + System.out.println(value2); + System.out.println(StringUtil.splitToComplexMap(value2)); + } +} \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/test/java/com/nepxion/discovery/common/UuidUtilTest.java b/discovery-commons/discovery-common/src/test/java/com/nepxion/discovery/common/UuidUtilTest.java new file mode 100644 index 0000000000..39c9d6c324 --- /dev/null +++ b/discovery-commons/discovery-common/src/test/java/com/nepxion/discovery/common/UuidUtilTest.java @@ -0,0 +1,40 @@ +package com.nepxion.discovery.common; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import com.nepxion.discovery.common.util.UuidUtil; + +public class UuidUtilTest { + public static void main(String[] args) { + System.out.println("Time UUID with default:"); + System.out.println(UuidUtil.getTimeUUID()); + System.out.println("--------------------"); + + System.out.println("Time UUID with prefix:"); + System.out.println(UuidUtil.getTimeUUID("nepxion")); + System.out.println("--------------------"); + + System.out.println("Time UUID with prefix and randomArray:"); + System.out.println(UuidUtil.getTimeUUID("nepxion", new int[] { 9, 99, 999, 9999 })); + System.out.println("--------------------"); + + System.out.println("Time UUID with all:"); + System.out.println(UuidUtil.getTimeUUID("nepxion", "yyyyMMdd-HHmmss", new int[] { 9, 99, 999, 9999 }, "-", "@")); + System.out.println("--------------------"); + + System.out.println("Random:"); + System.out.println(UuidUtil.random(999)); + System.out.println(UuidUtil.random(999, 5)); + System.out.println("--------------------"); + + System.out.println("UUID:"); + System.out.println(UuidUtil.getUUID()); + } +} \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/test/resources/sample.json b/discovery-commons/discovery-common/src/test/resources/sample.json new file mode 100644 index 0000000000..7969e7d5af --- /dev/null +++ b/discovery-commons/discovery-common/src/test/resources/sample.json @@ -0,0 +1,10 @@ +[ + { + "resource": "sentinel-resource", + "controlBehavior": 0, + "count": 1, + "grade": 1, + "limitApp": "default", + "strategy": 0 + } +] \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/test/resources/sample.properties b/discovery-commons/discovery-common/src/test/resources/sample.properties new file mode 100644 index 0000000000..60fbbe0bd4 --- /dev/null +++ b/discovery-commons/discovery-common/src/test/resources/sample.properties @@ -0,0 +1,2 @@ +spring.application.name=discovery-springcloud-example-a +server.port=1100 \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/test/resources/sample.xml b/discovery-commons/discovery-common/src/test/resources/sample.xml new file mode 100644 index 0000000000..8f0cfe99d1 --- /dev/null +++ b/discovery-commons/discovery-common/src/test/resources/sample.xml @@ -0,0 +1,6 @@ + + + + {"discovery-springcloud-example-a":"1.0", "discovery-springcloud-example-b":"1.0", "discovery-springcloud-example-c":"1.0;1.2"} + + \ No newline at end of file diff --git a/discovery-commons/discovery-common/src/test/resources/sample.yaml b/discovery-commons/discovery-common/src/test/resources/sample.yaml new file mode 100644 index 0000000000..f799f1ab19 --- /dev/null +++ b/discovery-commons/discovery-common/src/test/resources/sample.yaml @@ -0,0 +1,22 @@ +service: + - discovery-guide-service-a + - discovery-guide-service-b +blueGreen: + - expression: "#H['xyz'] == '1'" + route: green + - expression: "#H['xyz'] == '2'" + route: blue +gray: + - expression: "#H['xyz'] == '3'" + weight: + - 90 + - 10 + - expression: "#H['xyz'] == '4'" + weight: + - 70 + - 30 + - weight: + - 100 + - 0 +header: + xyz: 1 \ No newline at end of file diff --git a/discovery-commons/pom.xml b/discovery-commons/pom.xml new file mode 100644 index 0000000000..479f41d55f --- /dev/null +++ b/discovery-commons/pom.xml @@ -0,0 +1,26 @@ + + + discovery-commons + Nepxion Discovery Commons + pom + 4.0.0 + Nepxion Discovery is a solution for Spring Cloud with blue green, gray, weight, limitation, circuit breaker, degrade, isolation, monitor, tracing, dye, failover, async agent + http://www.nepxion.com + + + com.nepxion + discovery + 6.23.0 + + + + discovery-common + discovery-common-apollo + discovery-common-nacos + discovery-common-redis + discovery-common-zookeeper + discovery-common-consul + discovery-common-etcd + + \ No newline at end of file diff --git a/discovery-console-desktop/lib/jcalendar-1.3.4.200905090658.jar b/discovery-console-desktop/lib/jcalendar-1.3.4.200905090658.jar deleted file mode 100644 index 030a5b5415..0000000000 Binary files a/discovery-console-desktop/lib/jcalendar-1.3.4.200905090658.jar and /dev/null differ diff --git a/discovery-console-desktop/lib/jdesktop-swing-worker-1.2.jar b/discovery-console-desktop/lib/jdesktop-swing-worker-1.2.jar deleted file mode 100644 index 6953042eb4..0000000000 Binary files a/discovery-console-desktop/lib/jdesktop-swing-worker-1.2.jar and /dev/null differ diff --git a/discovery-console-desktop/lib/jdesktop-swingx-1.0.jar b/discovery-console-desktop/lib/jdesktop-swingx-1.0.jar deleted file mode 100644 index ee2273d97c..0000000000 Binary files a/discovery-console-desktop/lib/jdesktop-swingx-1.0.jar and /dev/null differ diff --git a/discovery-console-desktop/lib/jide-oss-2.9.7.jar b/discovery-console-desktop/lib/jide-oss-2.9.7.jar deleted file mode 100644 index 8bc20e1a62..0000000000 Binary files a/discovery-console-desktop/lib/jide-oss-2.9.7.jar and /dev/null differ diff --git a/discovery-console-desktop/lib/l2fprod-common-all-7.3.jar b/discovery-console-desktop/lib/l2fprod-common-all-7.3.jar deleted file mode 100644 index 45b58a7cd8..0000000000 Binary files a/discovery-console-desktop/lib/l2fprod-common-all-7.3.jar and /dev/null differ diff --git a/discovery-console-desktop/lib/nepxion-cots-1.0.0.jar b/discovery-console-desktop/lib/nepxion-cots-1.0.0.jar deleted file mode 100644 index 9c0d5553c9..0000000000 Binary files a/discovery-console-desktop/lib/nepxion-cots-1.0.0.jar and /dev/null differ diff --git a/discovery-console-desktop/lib/nepxion-swing-1.0.0.jar b/discovery-console-desktop/lib/nepxion-swing-1.0.0.jar deleted file mode 100644 index 0ed9cecb02..0000000000 Binary files a/discovery-console-desktop/lib/nepxion-swing-1.0.0.jar and /dev/null differ diff --git a/discovery-console-desktop/lib/nepxion-util-1.0.0.jar b/discovery-console-desktop/lib/nepxion-util-1.0.0.jar deleted file mode 100644 index 57a0f90663..0000000000 Binary files a/discovery-console-desktop/lib/nepxion-util-1.0.0.jar and /dev/null differ diff --git a/discovery-console-desktop/lib/twaver-3.7.jar b/discovery-console-desktop/lib/twaver-3.7.jar deleted file mode 100644 index d5035e8764..0000000000 Binary files a/discovery-console-desktop/lib/twaver-3.7.jar and /dev/null differ diff --git a/discovery-console-desktop/lib/twaver-gis-3.7.jar b/discovery-console-desktop/lib/twaver-gis-3.7.jar deleted file mode 100644 index 900ab413b8..0000000000 Binary files a/discovery-console-desktop/lib/twaver-gis-3.7.jar and /dev/null differ diff --git a/discovery-console-desktop/lib/twaver-layouter-3.7.jar b/discovery-console-desktop/lib/twaver-layouter-3.7.jar deleted file mode 100644 index 1a72791d4d..0000000000 Binary files a/discovery-console-desktop/lib/twaver-layouter-3.7.jar and /dev/null differ diff --git a/discovery-console-desktop/pom.xml b/discovery-console-desktop/pom.xml deleted file mode 100644 index 7bac3e76b1..0000000000 --- a/discovery-console-desktop/pom.xml +++ /dev/null @@ -1,182 +0,0 @@ - - - discovery-console-desktop - Nepxion Discovery Console Desktop - jar - 4.0.0 - Nepxion Discovery is an enhancement for Spring Cloud Discovery - http://www.nepxion.com - - - com.nepxion - discovery - 5.2.0-SNAPSHOT - - - - 1.10 - 1.2 - 1.0 - 2.9.7 - 7.3 - 1.3.4.200905090658 - 1.0.0 - 1.0.0 - 1.0.0 - 3.7 - - - - - ${project.groupId} - discovery-common - - - - commons-configuration - commons-configuration - ${commons.configuration.version} - - - - org.springframework - spring-web - - - - org.springframework - spring-web - - - - com.lmax - disruptor - ${disruptor.version} - - - - org.apache.logging.log4j - log4j-1.2-api - - - - org.apache.logging.log4j - log4j-slf4j-impl - - - - jdesktop - swing-worker - ${swing.worker.version} - system - ${project.basedir}/lib/jdesktop-swing-worker-${swing.worker.version}.jar - - - - jdesktop - swingx - ${swingx.version} - system - ${project.basedir}/lib/jdesktop-swingx-${swingx.version}.jar - - - - jide - oss - ${jide.version} - system - ${project.basedir}/lib/jide-oss-${jide.version}.jar - - - - l2fprod - common-all - ${l2fprod.version} - system - ${project.basedir}/lib/l2fprod-common-all-${l2fprod.version}.jar - - - - jcalendar - jcalendar - ${jcalendar.version} - system - ${project.basedir}/lib/jcalendar-${jcalendar.version}.jar - - - - com.nepxion - swing - ${nepxion.swing.version} - system - ${project.basedir}/lib/nepxion-swing-${nepxion.swing.version}.jar - - - - com.nepxion - util - ${nepxion.util.version} - system - ${project.basedir}/lib/nepxion-util-${nepxion.util.version}.jar - - - - com.nepxion - cots - ${nepxion.cots.version} - system - ${project.basedir}/lib/nepxion-cots-${nepxion.cots.version}.jar - - - - twaver - twaver - ${twaver.version} - system - ${project.basedir}/lib/twaver-${twaver.version}.jar - - - - twaver - twaver-gis - ${twaver.version} - system - ${project.basedir}/lib/twaver-gis-${twaver.version}.jar - - - - twaver - twaver-layouter - ${twaver.version} - system - ${project.basedir}/lib/twaver-layouter-${twaver.version}.jar - - - - - ${project.artifactId}-${project.version} - - - maven-assembly-plugin - - - src/assembly/dist.xml - - ${project.build.sourceEncoding} - true - true - - - - make-assembly - package - - single - - - - - - - \ No newline at end of file diff --git a/discovery-console-desktop/release/README.md b/discovery-console-desktop/release/README.md deleted file mode 100644 index 07529531f6..0000000000 --- a/discovery-console-desktop/release/README.md +++ /dev/null @@ -1 +0,0 @@ -执行maven clean install,将会在target目录下创建discovery-console-desktop-[version]-release和discovery-console-desktop-[version]-release.zip,点里面的bat运行即可 \ No newline at end of file diff --git "a/discovery-console-desktop/src/assembly/Discovery\347\201\260\345\272\246\345\217\221\345\270\203\346\216\247\345\210\266\345\217\260.bat" "b/discovery-console-desktop/src/assembly/Discovery\347\201\260\345\272\246\345\217\221\345\270\203\346\216\247\345\210\266\345\217\260.bat" deleted file mode 100644 index 9e993dec8d..0000000000 --- "a/discovery-console-desktop/src/assembly/Discovery\347\201\260\345\272\246\345\217\221\345\270\203\346\216\247\345\210\266\345\217\260.bat" +++ /dev/null @@ -1,42 +0,0 @@ -@echo on -@echo ============================================================= -@echo $ $ -@echo $ Nepxion Discovery $ -@echo $ $ -@echo $ $ -@echo $ $ -@echo $ Nepxion Studio All Right Reserved $ -@echo $ Copyright (C) 2017-2050 $ -@echo $ $ -@echo ============================================================= -@echo. -@echo off - -@title Nepxion Discovery -@color 0a - -@set CLASSPATH=./conf/;./lib/* -@set PATH= - -call:JAVA_HOME_CHECK - -:JAVA_HOME_CHECK -if "%JAVA_HOME%"=="" goto ECHO_JAVA_HOME_CHECK_EXIT - -@rem echo Found Java Home=%JAVA_HOME% -echo JAVA_HOME=%JAVA_HOME% -goto SET_CLASSPATH_AND_RUN - -:ECHO_JAVA_HOME_CHECK_EXIT -@rem echo Please set JAVA_HOME -echo JAVA_HOME -goto EXIT - -:SET_CLASSPATH_AND_RUN -"%JAVA_HOME%\bin\java" -Dfile.encoding=GBK -Ddefault.client.encoding=GBK -Duser.language=zh -Duser.region=CN -Djava.security.policy=java.policy -Djava.library.path=%PATH% -Xms128m -Xmx512m -classpath %CLASSPATH% com.nepxion.discovery.console.desktop.ConsoleLauncher - -:PAUSE -pause; - -:EXIT -exit; \ No newline at end of file diff --git a/discovery-console-desktop/src/assembly/dist.xml b/discovery-console-desktop/src/assembly/dist.xml deleted file mode 100644 index b20b6f7afe..0000000000 --- a/discovery-console-desktop/src/assembly/dist.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - release - - zip - dir - - false - - - lib - false - runtime - - - - - src/assembly - / - - *.bat - - 0744 - - - src/main/resources/config - /config - - *.properties - - 0744 - - - lib - /lib - - - \ No newline at end of file diff --git a/discovery-console-desktop/src/main/java/com/nepxion/discovery/console/desktop/ConsoleFrame.java b/discovery-console-desktop/src/main/java/com/nepxion/discovery/console/desktop/ConsoleFrame.java deleted file mode 100644 index 0959ca35df..0000000000 --- a/discovery-console-desktop/src/main/java/com/nepxion/discovery/console/desktop/ConsoleFrame.java +++ /dev/null @@ -1,55 +0,0 @@ -package com.nepxion.discovery.console.desktop; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import java.awt.Dimension; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.nepxion.discovery.console.desktop.controller.ServiceController; -import com.nepxion.discovery.console.desktop.icon.ConsoleIconFactory; -import com.nepxion.discovery.console.desktop.locale.ConsoleLocale; -import com.nepxion.swing.frame.JBasicFrame; -import com.nepxion.swing.framework.reflection.JReflectionHierarchy; -import com.nepxion.swing.style.texture.shrink.JBlackHeaderTextureStyle; -import com.nepxion.swing.style.texture.shrink.JGreenOutlookTextureStyle; - -public class ConsoleFrame extends JBasicFrame { - private static final long serialVersionUID = 1L; - private static final Logger LOG = LoggerFactory.getLogger(ConsoleFrame.class); - - public ConsoleFrame() { - super(ConsoleLocale.getString("title") + " " + getSubTitle(), ConsoleIconFactory.getSwingIcon("ribbon/navigator_nepxion.png"), new Dimension(1280, 900)); - } - - public void launch() { - ConsoleHierarchy deployHierarchy = new ConsoleHierarchy(new JBlackHeaderTextureStyle(), new JGreenOutlookTextureStyle()); - - JReflectionHierarchy reflectionHierarchy = new JReflectionHierarchy(20, 20); - reflectionHierarchy.setContentPane(deployHierarchy); - - getContentPane().add(reflectionHierarchy); - - setExtendedState(ConsoleFrame.MAXIMIZED_BOTH); - setVisible(true); - toFront(); - } - - private static String getSubTitle() { - try { - return "[" + ServiceController.getDiscoveryType() + " " + ConsoleLocale.getString("discovery_center") + "] [" + ServiceController.getConfigType() + " " + ConsoleLocale.getString("config_center") + "]"; - } catch (Exception e) { - LOG.error("Not connnect to Discovery Console", e); - - return "[" + ConsoleLocale.getString("not_connnect_to_console") + "]"; - } - } -} \ No newline at end of file diff --git a/discovery-console-desktop/src/main/java/com/nepxion/discovery/console/desktop/ConsoleHierarchy.java b/discovery-console-desktop/src/main/java/com/nepxion/discovery/console/desktop/ConsoleHierarchy.java deleted file mode 100644 index 3ad315c3b4..0000000000 --- a/discovery-console-desktop/src/main/java/com/nepxion/discovery/console/desktop/ConsoleHierarchy.java +++ /dev/null @@ -1,111 +0,0 @@ -package com.nepxion.discovery.console.desktop; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import java.awt.BorderLayout; -import java.awt.Dimension; -import java.awt.Font; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.util.ArrayList; -import java.util.List; - -import javax.swing.BorderFactory; -import javax.swing.JPanel; - -import com.nepxion.discovery.console.desktop.context.UIContext; -import com.nepxion.discovery.console.desktop.icon.ConsoleIconFactory; -import com.nepxion.discovery.console.desktop.locale.ConsoleLocale; -import com.nepxion.discovery.console.desktop.toggle.ConsoleToggleConstants; -import com.nepxion.discovery.console.desktop.toggle.ConsoleToggleListener; -import com.nepxion.swing.element.ElementNode; -import com.nepxion.swing.list.toggle.JToggleList; -import com.nepxion.swing.shrinkbar.JShrinkBar; -import com.nepxion.swing.shrinkbar.JShrinkOutlook; -import com.nepxion.swing.shrinkbar.JShrinkOutlookBar; -import com.nepxion.swing.shrinkbar.ShrinkListCellRenderer; -import com.nepxion.swing.shrinkbar.ShrinkOutlookSelectionListener; -import com.nepxion.swing.style.texture.shrink.IHeaderTextureStyle; -import com.nepxion.swing.style.texture.shrink.IOutlookTextureStyle; -import com.nepxion.util.data.CollectionUtil; - -public class ConsoleHierarchy extends JPanel { - private static final long serialVersionUID = 1L; - - private JShrinkBar shrinkContentBar; - private JShrinkOutlookBar shrinkOutlookBar; - - public ConsoleHierarchy(IHeaderTextureStyle headerTextureStyle, IOutlookTextureStyle outlookTextureStyle) { - shrinkContentBar = new JShrinkBar(JShrinkBar.PLACEMENT_EAST, JShrinkBar.CONTENT_PANE_TYPE_LABEL, headerTextureStyle); - shrinkContentBar.setShrinkable(false); - shrinkContentBar.setTitle(ConsoleLocale.getString("content_bar")); - shrinkContentBar.setToolTipText(ConsoleLocale.getString("content_bar")); - shrinkContentBar.setIcon(ConsoleIconFactory.getSwingIcon("paste.png")); - shrinkContentBar.setTitleFont(new Font(UIContext.getFontName(), Font.BOLD, UIContext.getLargeFontSize())); - shrinkContentBar.getShrinkHeader().getLabel().addMouseListener(new ShrinkContentBarMouseListener()); - - shrinkOutlookBar = new JShrinkOutlookBar(JShrinkBar.PLACEMENT_WEST, JShrinkBar.CONTENT_PANE_TYPE_LABEL, headerTextureStyle, outlookTextureStyle); - shrinkOutlookBar.setTitle(ConsoleLocale.getString("navigator_bar")); - shrinkOutlookBar.setToolTipText(ConsoleLocale.getString("navigator_bar")); - shrinkOutlookBar.setIcon(ConsoleIconFactory.getSwingIcon("hierarchy.png")); - shrinkOutlookBar.setTitleFont(new Font(UIContext.getFontName(), Font.BOLD, UIContext.getLargeFontSize())); - shrinkOutlookBar.setPreferredSize(new Dimension(210, shrinkOutlookBar.getPreferredSize().height)); - - createServiceControlShrinkOutlook(shrinkOutlookBar); - - shrinkOutlookBar.getShrinkOutlook(0).setSelected(true); - - setLayout(new BorderLayout(5, 5)); - add(shrinkContentBar, BorderLayout.CENTER); - add(shrinkOutlookBar, BorderLayout.WEST); - } - - private JShrinkOutlook createServiceControlShrinkOutlook(JShrinkOutlookBar shrinkOutlookBar) { - List elementNodes = new ArrayList(); - elementNodes.add(new ElementNode(ConsoleToggleConstants.SERVICE_TOPOLOGY, ConsoleLocale.getString(ConsoleToggleConstants.SERVICE_TOPOLOGY), ConsoleIconFactory.getSwingIcon("component/ui_16.png"), ConsoleLocale.getString(ConsoleToggleConstants.SERVICE_TOPOLOGY))); - - JToggleList list = createList(elementNodes); - list.setSelectedIndex(0); - - JShrinkOutlook shrinkOutlook = shrinkOutlookBar.addShrinkOutlook(ConsoleLocale.getString("service_control"), ConsoleIconFactory.getSwingIcon("stereo/favorite_16.png"), ConsoleIconFactory.getSwingIcon("stereo/favorite_add_16.png"), ConsoleLocale.getString("service_control"), new Font(UIContext.getFontName(), Font.BOLD, UIContext.getMiddleFontSize())); - shrinkOutlook.setContentPane(list); - shrinkOutlook.addPropertyChangeListener(new OutlookSelectionListener()); - - return shrinkOutlook; - } - - @SuppressWarnings("unchecked") - private JToggleList createList(List elementNodes) { - JToggleList list = new JToggleList(CollectionUtil.parseVector(elementNodes)); - list.setSelectionMode(JToggleList.SINGLE_SELECTION); - list.setBorder(BorderFactory.createEmptyBorder(5, 0, 5, 0)); - list.setCellRenderer(new ShrinkListCellRenderer(list, BorderFactory.createEmptyBorder(0, 10, 0, 0), 22)); - list.setToggleContentPanel(shrinkContentBar); - list.setToggleAdapter(new ConsoleToggleListener(list)); - - return list; - } - - private class ShrinkContentBarMouseListener extends MouseAdapter { - public void mouseClicked(MouseEvent e) { - if (e.getClickCount() > 1) { - boolean isShrinked = !shrinkOutlookBar.isShrinked(); - shrinkOutlookBar.setShrinked(isShrinked); - } - } - } - - private class OutlookSelectionListener extends ShrinkOutlookSelectionListener { - public void selectionStateChanged(JShrinkOutlook shrinkOutlook) { - JToggleList toggleList = (JToggleList) shrinkOutlook.getContentPane(); - toggleList.executeSelection(-1, toggleList.getSelectedIndex()); - } - } -} \ No newline at end of file diff --git a/discovery-console-desktop/src/main/java/com/nepxion/discovery/console/desktop/ConsoleLauncher.java b/discovery-console-desktop/src/main/java/com/nepxion/discovery/console/desktop/ConsoleLauncher.java deleted file mode 100644 index 8277b3d274..0000000000 --- a/discovery-console-desktop/src/main/java/com/nepxion/discovery/console/desktop/ConsoleLauncher.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.nepxion.discovery.console.desktop; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import javax.swing.SwingUtilities; - -import com.nepxion.discovery.console.desktop.context.ContextInitializer; - -public class ConsoleLauncher { - public static void main(String[] args) { - ContextInitializer.initialize(); - - SwingUtilities.invokeLater(new Runnable() { - public void run() { - ConsoleLogin consoleLogin = new ConsoleLogin(); - consoleLogin.launch(); - - ConsoleFrame consoleFrame = new ConsoleFrame(); - consoleFrame.launch(); - } - }); - } -} \ No newline at end of file diff --git a/discovery-console-desktop/src/main/java/com/nepxion/discovery/console/desktop/ConsoleLogin.java b/discovery-console-desktop/src/main/java/com/nepxion/discovery/console/desktop/ConsoleLogin.java deleted file mode 100644 index 6c38511846..0000000000 --- a/discovery-console-desktop/src/main/java/com/nepxion/discovery/console/desktop/ConsoleLogin.java +++ /dev/null @@ -1,127 +0,0 @@ -package com.nepxion.discovery.console.desktop; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import java.awt.Component; -import java.awt.Font; -import java.awt.Frame; -import java.util.Locale; -import java.util.Vector; - -import javax.swing.DefaultListCellRenderer; -import javax.swing.JList; -import javax.swing.JPanel; - -import org.apache.commons.lang3.StringUtils; - -import com.nepxion.discovery.common.entity.UserEntity; -import com.nepxion.discovery.console.desktop.controller.ServiceController; -import com.nepxion.discovery.console.desktop.locale.ConsoleLocale; -import com.nepxion.swing.combobox.JBasicComboBox; -import com.nepxion.swing.dialog.JLoginDialog; -import com.nepxion.swing.font.FontContext; -import com.nepxion.swing.label.JBasicLabel; -import com.nepxion.swing.layout.table.TableLayout; - -public class ConsoleLogin extends JLoginDialog { - private static final long serialVersionUID = 1L; - - private JBasicLabel urlLabel; - private JBasicComboBox urlComboBox; - - public ConsoleLogin() { - super(null); - } - - public ConsoleLogin(Frame parent) { - super(parent); - } - - @SuppressWarnings("unchecked") - @Override - protected void initEditorPanelLayout() { - urlLabel = new JBasicLabel(); - urlLabel.setFont(new Font(FontContext.getFontName(), FONT_STYLE, FONT_SIZE)); - - String url = null; - try { - url = ServiceController.getUrl(); - } catch (Exception e) { - - } - - Vector urls = new Vector(); - if (StringUtils.isNotEmpty(url)) { - urls.add(url); - } - - urlComboBox = new JBasicComboBox(urls); - urlComboBox.setEditable(true); - urlComboBox.setRenderer(new DefaultListCellRenderer() { - private static final long serialVersionUID = 1L; - - @SuppressWarnings("rawtypes") - public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { - super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); - - setToolTipText(value.toString()); - - return this; - } - }); - - double[][] size = { - { 80, 230 }, - { TableLayout.PREFERRED, TableLayout.PREFERRED, TableLayout.PREFERRED, TableLayout.PREFERRED } - }; - - TableLayout tableLayout = new TableLayout(size); - tableLayout.setVGap(10); - - editorPanel = new JPanel(); - editorPanel.setLayout(tableLayout); - editorPanel.add(urlLabel, "0, 0"); - editorPanel.add(urlComboBox, "1, 0"); - editorPanel.add(accountLabel, "0, 1"); - editorPanel.add(accountTextField, "1, 1"); - editorPanel.add(passwordLabel, "0, 2"); - editorPanel.add(passwordField, "1, 2"); - editorPanel.add(localeLabel, "0, 3"); - editorPanel.add(localeComboBox, "1, 3"); - } - - @Override - protected void initLocale(Locale locale) { - super.initLocale(locale); - - urlLabel.setText(ConsoleLocale.getString("url", locale)); - } - - @Override - public boolean login(String userId, String password, Locale locale) throws Exception { - Object url = urlComboBox.getSelectedItem(); - if (url == null || StringUtils.isEmpty(url.toString().trim())) { - throw new IllegalArgumentException("Console url can't be null or empty"); - } - - ServiceController.setUrl(url.toString().trim()); - - UserEntity userEntity = new UserEntity(); - userEntity.setUserId(userId); - userEntity.setPassword(password); - - return ServiceController.authenticate(userEntity); - } - - public void launch() { - setVisible(true); - toFront(); - } -} \ No newline at end of file diff --git a/discovery-console-desktop/src/main/java/com/nepxion/discovery/console/desktop/constant/ConsoleConstant.java b/discovery-console-desktop/src/main/java/com/nepxion/discovery/console/desktop/constant/ConsoleConstant.java deleted file mode 100644 index 222540f851..0000000000 --- a/discovery-console-desktop/src/main/java/com/nepxion/discovery/console/desktop/constant/ConsoleConstant.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.nepxion.discovery.console.desktop.constant; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -public class ConsoleConstant { - public static final String FILTER = "filter"; - public static final String PLUGIN = "plugin"; -} \ No newline at end of file diff --git a/discovery-console-desktop/src/main/java/com/nepxion/discovery/console/desktop/context/ContextInitializer.java b/discovery-console-desktop/src/main/java/com/nepxion/discovery/console/desktop/context/ContextInitializer.java deleted file mode 100644 index 59757215e3..0000000000 --- a/discovery-console-desktop/src/main/java/com/nepxion/discovery/console/desktop/context/ContextInitializer.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.nepxion.discovery.console.desktop.context; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -public class ContextInitializer { - public static void initialize() { - PropertiesContext.initialize(); - DataContext.initialize(); - UIContext.initialize(); - } -} \ No newline at end of file diff --git a/discovery-console-desktop/src/main/java/com/nepxion/discovery/console/desktop/context/DataContext.java b/discovery-console-desktop/src/main/java/com/nepxion/discovery/console/desktop/context/DataContext.java deleted file mode 100644 index 04714a17be..0000000000 --- a/discovery-console-desktop/src/main/java/com/nepxion/discovery/console/desktop/context/DataContext.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.nepxion.discovery.console.desktop.context; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import com.nepxion.swing.exception.ExceptionTracerContext; -import com.nepxion.util.encoder.EncoderContext; -import com.nepxion.util.locale.LocaleContext; - -public class DataContext { - public static final String CHARSET = "UTF-8"; - public static final String LOCALE = "zh_CN"; - - public static void initialize() { - initializeEncoder(); - initializeLocale(); - initializeTracer(); - } - - private static void initializeEncoder() { - EncoderContext.registerIOCharset(CHARSET); - } - - private static void initializeLocale() { - LocaleContext.registerLocale(LOCALE); - } - - private static void initializeTracer() { - ExceptionTracerContext.register(true); - } -} \ No newline at end of file diff --git a/discovery-console-desktop/src/main/java/com/nepxion/discovery/console/desktop/context/PropertiesContext.java b/discovery-console-desktop/src/main/java/com/nepxion/discovery/console/desktop/context/PropertiesContext.java deleted file mode 100644 index a8d133d815..0000000000 --- a/discovery-console-desktop/src/main/java/com/nepxion/discovery/console/desktop/context/PropertiesContext.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.nepxion.discovery.console.desktop.context; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import java.io.File; -import java.net.URL; - -import org.apache.commons.configuration.ConfigurationException; -import org.apache.commons.configuration.PropertiesConfiguration; - -public class PropertiesContext extends PropertiesConfiguration { - private static final String PATH = "config/console.properties"; - private static PropertiesContext propertiesContext; - - public static void initialize() { - try { - propertiesContext = new PropertiesContext(PATH); - } catch (ConfigurationException e) { - e.printStackTrace(); - } - } - - public static PropertiesContext getProperties() { - return propertiesContext; - } - - public PropertiesContext(String path) throws ConfigurationException { - super(path); - } - - public PropertiesContext(File file) throws ConfigurationException { - super(file); - } - - public PropertiesContext(URL url) throws ConfigurationException { - super(url); - } -} \ No newline at end of file diff --git a/discovery-console-desktop/src/main/java/com/nepxion/discovery/console/desktop/context/UIContext.java b/discovery-console-desktop/src/main/java/com/nepxion/discovery/console/desktop/context/UIContext.java deleted file mode 100644 index ff6f13bf22..0000000000 --- a/discovery-console-desktop/src/main/java/com/nepxion/discovery/console/desktop/context/UIContext.java +++ /dev/null @@ -1,80 +0,0 @@ -package com.nepxion.discovery.console.desktop.context; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import java.awt.Font; - -import com.nepxion.swing.font.FontContext; -import com.nepxion.swing.lookandfeel.LookAndFeelManager; -import com.nepxion.util.locale.LocaleContext; - -public class UIContext { - private static final String FONT_NAME_YAHEI = "\u5fae\u8f6f\u96c5\u9ed1"; // 微软雅黑 - private static final int FONT_SMALL_SIZE_YAHEI = 12; // 11 - private static final int FONT_MIDDLE_SIZE_YAHEI = FONT_SMALL_SIZE_YAHEI + 1; - private static final int FONT_LARGE_SIZE_YAHEI = FONT_SMALL_SIZE_YAHEI + 2; - - private static final String FONT_NAME_CALIBRI = "Calibri"; - private static final int FONT_SMALL_SIZE_CALIBRI = 12; - private static final int FONT_MIDDLE_SIZE_CALIBRI = FONT_SMALL_SIZE_CALIBRI + 1; - private static final int FONT_LARGE_SIZE_CALIBRI = FONT_SMALL_SIZE_CALIBRI + 2; - - public static void initialize() { - FontContext.registerFont(getFontName(), Font.PLAIN, getDefaultFontSize()); - - if (System.getProperty("os.name").toLowerCase().contains("windows")) { - LookAndFeelManager.setNimbusLookAndFeel(); - } - } - - public static String getFontName() { - if (LocaleContext.getLocale() == LocaleContext.LOCALE_ZH_CN) { - return FONT_NAME_YAHEI; - } - - return FONT_NAME_CALIBRI; - } - - public static int getDefaultFontSize() { - String fontName = getFontName(); - if (fontName.equals(FONT_NAME_YAHEI)) { - return FONT_MIDDLE_SIZE_YAHEI; - } else { - return FONT_MIDDLE_SIZE_CALIBRI; - } - } - - public static int getSmallFontSize() { - String fontName = getFontName(); - if (fontName.equals(FONT_NAME_YAHEI)) { - return FONT_SMALL_SIZE_YAHEI; - } else { - return FONT_SMALL_SIZE_CALIBRI; - } - } - - public static int getMiddleFontSize() { - String fontName = getFontName(); - if (fontName.equals(FONT_NAME_YAHEI)) { - return FONT_MIDDLE_SIZE_YAHEI; - } else { - return FONT_MIDDLE_SIZE_CALIBRI; - } - } - - public static int getLargeFontSize() { - String fontName = getFontName(); - if (fontName.equals(FONT_NAME_YAHEI)) { - return FONT_LARGE_SIZE_YAHEI; - } else { - return FONT_LARGE_SIZE_CALIBRI; - } - } -} \ No newline at end of file diff --git a/discovery-console-desktop/src/main/java/com/nepxion/discovery/console/desktop/controller/ServiceController.java b/discovery-console-desktop/src/main/java/com/nepxion/discovery/console/desktop/controller/ServiceController.java deleted file mode 100644 index c641b125c9..0000000000 --- a/discovery-console-desktop/src/main/java/com/nepxion/discovery/console/desktop/controller/ServiceController.java +++ /dev/null @@ -1,282 +0,0 @@ -package com.nepxion.discovery.console.desktop.controller; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import java.util.List; -import java.util.Map; - -import org.apache.commons.lang3.StringUtils; -import org.springframework.http.HttpEntity; -import org.springframework.http.HttpHeaders; -import org.springframework.http.MediaType; -import org.springframework.web.client.RestTemplate; - -import com.fasterxml.jackson.core.type.TypeReference; -import com.nepxion.discovery.common.constant.DiscoveryConstant; -import com.nepxion.discovery.common.entity.InstanceEntityWrapper; -import com.nepxion.discovery.common.entity.ResultEntity; -import com.nepxion.discovery.common.entity.RouterEntity; -import com.nepxion.discovery.common.entity.UserEntity; -import com.nepxion.discovery.common.handler.RestErrorHandler; -import com.nepxion.discovery.common.util.RestUtil; -import com.nepxion.discovery.common.util.UrlUtil; -import com.nepxion.discovery.console.desktop.context.PropertiesContext; -import com.nepxion.discovery.console.desktop.entity.Instance; - -public class ServiceController { - public static RestTemplate restTemplate; - - private static String consoleUrl; - - static { - restTemplate = new RestTemplate(); - restTemplate.setErrorHandler(new RestErrorHandler()); - } - - public static boolean authenticate(UserEntity userEntity) { - String url = getUrl() + "console/authenticate"; - - String result = restTemplate.postForEntity(url, userEntity, String.class).getBody(); - - return Boolean.valueOf(result); - } - - public static String getDiscoveryType() { - String url = getUrl() + "console/discovery-type"; - - String result = restTemplate.getForEntity(url, String.class).getBody(); - - return result; - } - - public static String getConfigType() { - String url = getUrl() + "console/config-type"; - - String result = restTemplate.getForEntity(url, String.class).getBody(); - - return result; - } - - public static List getGroups() { - String url = getUrl() + "console/groups"; - - String result = restTemplate.getForEntity(url, String.class).getBody(); - - return RestUtil.fromJson(restTemplate, result, new TypeReference>() { - }); - } - - public static Map> getInstanceMap(List groups) { - String url = getUrl() + "console/instance-map"; - - String result = restTemplate.postForEntity(url, groups, String.class).getBody(); - - return RestUtil.fromJson(restTemplate, result, new TypeReference>>() { - }); - } - - public static List getVersions(Instance instance) { - String url = getUrl(instance) + "version/view"; - - String result = restTemplate.getForEntity(url, String.class).getBody(); - - return RestUtil.fromJson(restTemplate, result, new TypeReference>() { - }); - } - - public static List getRules(Instance instance) { - String url = getUrl(instance) + "config/view"; - - String result = restTemplate.getForEntity(url, String.class).getBody(); - - return RestUtil.fromJson(restTemplate, result, new TypeReference>() { - }); - } - - public static List getRules(RouterEntity routerEntity) { - String url = getUrl(routerEntity) + "config/view"; - - String result = restTemplate.getForEntity(url, String.class).getBody(); - - return RestUtil.fromJson(restTemplate, result, new TypeReference>() { - }); - } - - public static RouterEntity routes(Instance instance, String routeServiceIds) { - String url = getUrl(instance) + "router/routes"; - - String result = restTemplate.postForEntity(url, routeServiceIds, String.class).getBody(); - - return RestUtil.fromJson(restTemplate, result, new TypeReference() { - }); - } - - public static String remoteConfigUpdate(String group, String serviceId, String config) { - String url = getUrl() + "console/remote-config/update/" + group + "/" + serviceId; - - // 解决中文乱码 - HttpHeaders headers = new HttpHeaders(); - headers.setContentType(MediaType.APPLICATION_JSON_UTF8); - HttpEntity entity = new HttpEntity(config, headers); - - String result = restTemplate.postForEntity(url, entity, String.class).getBody(); - - if (!StringUtils.equals(result, DiscoveryConstant.OK) && !StringUtils.equals(result, DiscoveryConstant.NO)) { - result = RestUtil.getCause(restTemplate); - } - - return result; - } - - public static String remoteConfigClear(String group, String serviceId) { - String url = getUrl() + "console/remote-config/clear/" + group + "/" + serviceId; - - String result = restTemplate.postForEntity(url, null, String.class).getBody(); - - if (!StringUtils.equals(result, DiscoveryConstant.OK) && !StringUtils.equals(result, DiscoveryConstant.NO)) { - result = RestUtil.getCause(restTemplate); - } - - return result; - } - - public static String remoteConfigView(String group, String serviceId) { - String url = getUrl() + "console/remote-config/view/" + group + "/" + serviceId; - - String result = restTemplate.getForEntity(url, String.class).getBody(); - - return result; - } - - public static List configUpdate(String serviceId, String config, boolean async) { - String url = getUrl() + "console/config/update-" + getInvokeType(async) + "/" + serviceId; - - // 解决中文乱码 - HttpHeaders headers = new HttpHeaders(); - headers.setContentType(MediaType.APPLICATION_JSON_UTF8); - HttpEntity entity = new HttpEntity(config, headers); - - String result = restTemplate.postForEntity(url, entity, String.class).getBody(); - - return RestUtil.fromJson(restTemplate, result, new TypeReference>() { - }); - } - - public static String configUpdate(Instance instance, String config, boolean async) { - String url = getUrl(instance) + "config/update-" + getInvokeType(async); - - // 解决中文乱码 - HttpHeaders headers = new HttpHeaders(); - headers.setContentType(MediaType.APPLICATION_JSON_UTF8); - HttpEntity entity = new HttpEntity(config, headers); - - String result = restTemplate.postForEntity(url, entity, String.class).getBody(); - - if (!StringUtils.equals(result, DiscoveryConstant.OK)) { - result = RestUtil.getCause(restTemplate); - } - - return result; - } - - public static List configClear(String serviceId, boolean async) { - String url = getUrl() + "console/config/clear-" + getInvokeType(async) + "/" + serviceId; - - String result = restTemplate.postForEntity(url, null, String.class).getBody(); - - return RestUtil.fromJson(restTemplate, result, new TypeReference>() { - }); - } - - public static String configClear(Instance instance, boolean async) { - String url = getUrl(instance) + "config/clear-" + getInvokeType(async); - - String result = restTemplate.postForEntity(url, null, String.class).getBody(); - - if (!StringUtils.equals(result, DiscoveryConstant.OK)) { - result = RestUtil.getCause(restTemplate); - } - - return result; - } - - public static List versionUpdate(String serviceId, String version, boolean async) { - String url = getUrl() + "console/version/update-" + getInvokeType(async) + "/" + serviceId; - - String result = restTemplate.postForEntity(url, version, String.class).getBody(); - - return RestUtil.fromJson(restTemplate, result, new TypeReference>() { - }); - } - - public static String versionUpdate(Instance instance, String version, boolean async) { - String url = getUrl(instance) + "version/update-" + getInvokeType(async); - - String result = restTemplate.postForEntity(url, version, String.class).getBody(); - - if (!StringUtils.equals(result, DiscoveryConstant.OK)) { - result = RestUtil.getCause(restTemplate); - } - - return result; - } - - public static List versionClear(String serviceId, boolean async) { - String url = getUrl() + "console/version/clear-" + getInvokeType(async) + "/" + serviceId; - - String result = restTemplate.postForEntity(url, null, String.class).getBody(); - - return RestUtil.fromJson(restTemplate, result, new TypeReference>() { - }); - } - - public static String versionClear(Instance instance, boolean async) { - String url = getUrl(instance) + "version/clear-" + getInvokeType(async); - - String result = restTemplate.postForEntity(url, null, String.class).getBody(); - - if (!StringUtils.equals(result, DiscoveryConstant.OK)) { - result = RestUtil.getCause(restTemplate); - } - - return result; - } - - public static String getUrl() { - String url = null; - if (StringUtils.isNotEmpty(consoleUrl)) { - url = consoleUrl; - } else { - url = PropertiesContext.getProperties().getString("url"); - } - - return UrlUtil.formatUrl(url); - } - - public static void setUrl(String url) { - consoleUrl = url; - } - - private static String getUrl(Instance instance) { - String url = "http://" + instance.getHost() + ":" + instance.getPort() + UrlUtil.formatContextPath(InstanceEntityWrapper.getContextPath(instance)); - - return url; - } - - private static String getUrl(RouterEntity routerEntity) { - String url = "http://" + routerEntity.getHost() + ":" + routerEntity.getPort() + UrlUtil.formatContextPath(routerEntity.getContextPath()); - - return url; - } - - private static String getInvokeType(boolean async) { - return async ? DiscoveryConstant.ASYNC : DiscoveryConstant.SYNC; - } -} \ No newline at end of file diff --git a/discovery-console-desktop/src/main/java/com/nepxion/discovery/console/desktop/entity/Instance.java b/discovery-console-desktop/src/main/java/com/nepxion/discovery/console/desktop/entity/Instance.java deleted file mode 100644 index 165782d9a8..0000000000 --- a/discovery-console-desktop/src/main/java/com/nepxion/discovery/console/desktop/entity/Instance.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.nepxion.discovery.console.desktop.entity; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import com.nepxion.discovery.common.entity.InstanceEntity; - -public class Instance extends InstanceEntity { - private static final long serialVersionUID = -3381928574242229614L; - - private String dynamicVersion; - private String rule; - private String dynamicRule; - - public String getDynamicVersion() { - return dynamicVersion; - } - - public void setDynamicVersion(String dynamicVersion) { - this.dynamicVersion = dynamicVersion; - } - - public String getRule() { - return rule; - } - - public void setRule(String rule) { - this.rule = rule; - } - - public String getDynamicRule() { - return dynamicRule; - } - - public void setDynamicRule(String dynamicRule) { - this.dynamicRule = dynamicRule; - } -} \ No newline at end of file diff --git a/discovery-console-desktop/src/main/java/com/nepxion/discovery/console/desktop/icon/ConsoleIconFactory.java b/discovery-console-desktop/src/main/java/com/nepxion/discovery/console/desktop/icon/ConsoleIconFactory.java deleted file mode 100644 index edac1de66a..0000000000 --- a/discovery-console-desktop/src/main/java/com/nepxion/discovery/console/desktop/icon/ConsoleIconFactory.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.nepxion.discovery.console.desktop.icon; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import javax.swing.ImageIcon; - -import com.nepxion.swing.icon.IconFactory; - -public class ConsoleIconFactory extends IconFactory { - public static final String ICON_FOLDER = "com/nepxion/discovery/console/desktop/icon/"; - - public static ImageIcon getContextIcon(String iconName) { - return getIcon(ICON_FOLDER + iconName); - } -} \ No newline at end of file diff --git a/discovery-console-desktop/src/main/java/com/nepxion/discovery/console/desktop/locale/ConsoleLocale.java b/discovery-console-desktop/src/main/java/com/nepxion/discovery/console/desktop/locale/ConsoleLocale.java deleted file mode 100644 index e7bb0ad40c..0000000000 --- a/discovery-console-desktop/src/main/java/com/nepxion/discovery/console/desktop/locale/ConsoleLocale.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.nepxion.discovery.console.desktop.locale; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import java.util.Locale; - -import com.nepxion.util.locale.LocaleManager; - -public class ConsoleLocale { - public static final Class BUNDLE_CLASS = ConsoleLocale.class; - - public static String getString(String key) { - return LocaleManager.getString(BUNDLE_CLASS, key); - } - - public static String getString(String key, Locale locale) { - return LocaleManager.getString(BUNDLE_CLASS, key, locale); - } -} \ No newline at end of file diff --git a/discovery-console-desktop/src/main/java/com/nepxion/discovery/console/desktop/toggle/ConsoleToggleConstants.java b/discovery-console-desktop/src/main/java/com/nepxion/discovery/console/desktop/toggle/ConsoleToggleConstants.java deleted file mode 100644 index 8ab1e1cc93..0000000000 --- a/discovery-console-desktop/src/main/java/com/nepxion/discovery/console/desktop/toggle/ConsoleToggleConstants.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.nepxion.discovery.console.desktop.toggle; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -public class ConsoleToggleConstants { - public static final String SERVICE_TOPOLOGY = "service_topology"; -} \ No newline at end of file diff --git a/discovery-console-desktop/src/main/java/com/nepxion/discovery/console/desktop/toggle/ConsoleToggleListener.java b/discovery-console-desktop/src/main/java/com/nepxion/discovery/console/desktop/toggle/ConsoleToggleListener.java deleted file mode 100644 index 00494ad26d..0000000000 --- a/discovery-console-desktop/src/main/java/com/nepxion/discovery/console/desktop/toggle/ConsoleToggleListener.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.nepxion.discovery.console.desktop.toggle; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import com.nepxion.swing.element.IElementNode; -import com.nepxion.swing.list.toggle.AbstractToggleAdapter; -import com.nepxion.swing.list.toggle.JToggleList; -import com.nepxion.swing.toggle.ITogglePanel; - -public class ConsoleToggleListener extends AbstractToggleAdapter { - public ConsoleToggleListener(JToggleList list) { - super(list); - } - - public ITogglePanel getTogglePanel(IElementNode elementNode) { - Object userObject = elementNode.getUserObject(); - if (userObject == null) { - userObject = new ConsoleTogglePanel(elementNode); - elementNode.setUserObject(userObject); - } - - return (ITogglePanel) userObject; - } -} \ No newline at end of file diff --git a/discovery-console-desktop/src/main/java/com/nepxion/discovery/console/desktop/toggle/ConsoleTogglePanel.java b/discovery-console-desktop/src/main/java/com/nepxion/discovery/console/desktop/toggle/ConsoleTogglePanel.java deleted file mode 100644 index ff83be6dbe..0000000000 --- a/discovery-console-desktop/src/main/java/com/nepxion/discovery/console/desktop/toggle/ConsoleTogglePanel.java +++ /dev/null @@ -1,63 +0,0 @@ -package com.nepxion.discovery.console.desktop.toggle; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import java.awt.BorderLayout; -import java.awt.Component; - -import com.nepxion.discovery.console.desktop.icon.ConsoleIconFactory; -import com.nepxion.discovery.console.desktop.locale.ConsoleLocale; -import com.nepxion.swing.element.IElementNode; -import com.nepxion.swing.locale.SwingLocale; -import com.nepxion.swing.toggle.JThreadTogglePanel; - -public class ConsoleTogglePanel extends JThreadTogglePanel { - private static final long serialVersionUID = 1L; - - private IElementNode listElementNode; - - private ConsoleToggleSpace toggleSpace; - - public ConsoleTogglePanel(IElementNode listElementNode) { - super(SwingLocale.getString("initialize_and_wait")); - - this.listElementNode = listElementNode; - - setToggleBannerIcon(ConsoleIconFactory.getSwingIcon("banner/edit.png")); - setInformationText(ConsoleLocale.getString("initialize_component")); - setInformationIcon(ConsoleIconFactory.getSwingIcon("banner/query_128.png")); - setErrorText(ConsoleLocale.getString("initialize_component_failure")); - setErrorIcon(ConsoleIconFactory.getSwingIcon("banner/error_128.png")); - setThreadPanelWidth(300); - - showInformation(); - - setLayout(new BorderLayout()); - } - - public Component getContentPane() { - return toggleSpace; - } - - public boolean isLoadCache() { - return toggleSpace != null; - } - - protected void loadForeground(Object data) throws Exception { - if (toggleSpace == null) { - toggleSpace = new ConsoleToggleSpace(listElementNode); - add(toggleSpace, BorderLayout.CENTER); - } - } - - protected Object loadBackground() throws Exception { - return null; - } -} \ No newline at end of file diff --git a/discovery-console-desktop/src/main/java/com/nepxion/discovery/console/desktop/toggle/ConsoleToggleSpace.java b/discovery-console-desktop/src/main/java/com/nepxion/discovery/console/desktop/toggle/ConsoleToggleSpace.java deleted file mode 100644 index 4e5a7f1d0c..0000000000 --- a/discovery-console-desktop/src/main/java/com/nepxion/discovery/console/desktop/toggle/ConsoleToggleSpace.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.nepxion.discovery.console.desktop.toggle; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import java.awt.BorderLayout; - -import javax.swing.JComponent; -import javax.swing.JPanel; - -import com.nepxion.discovery.console.desktop.workspace.ServiceTopology; -import com.nepxion.swing.element.IElementNode; - -public class ConsoleToggleSpace extends JPanel { - private static final long serialVersionUID = 1L; - - private IElementNode listElementNode; - private JPanel blankPane = new JPanel(); - - public ConsoleToggleSpace(IElementNode listElementNode) { - this.listElementNode = listElementNode; - - setLayout(new BorderLayout()); - add(createContentPane(), BorderLayout.CENTER); - } - - private JComponent createContentPane() { - JComponent contentPane = null; - - String name = listElementNode.getName(); - if (name.equals(ConsoleToggleConstants.SERVICE_TOPOLOGY)) { - contentPane = new ServiceTopology(); - } else { - contentPane = blankPane; - } - - return contentPane; - } -} \ No newline at end of file diff --git a/discovery-console-desktop/src/main/java/com/nepxion/discovery/console/desktop/ui/UIFactory.java b/discovery-console-desktop/src/main/java/com/nepxion/discovery/console/desktop/ui/UIFactory.java deleted file mode 100644 index 781d1df9a6..0000000000 --- a/discovery-console-desktop/src/main/java/com/nepxion/discovery/console/desktop/ui/UIFactory.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.nepxion.discovery.console.desktop.ui; - -/** - *

Title: Nepxion Thunder

- *

Description: Nepxion Thunder For Distribution

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import java.awt.Color; -import java.awt.Font; - -import javax.swing.BorderFactory; -import javax.swing.border.Border; -import javax.swing.border.TitledBorder; - -import com.nepxion.discovery.console.desktop.context.UIContext; -import com.nepxion.swing.separator.JBasicSeparator; - -public class UIFactory { - public static JBasicSeparator createSeparator() { - JBasicSeparator separator = new JBasicSeparator(JBasicSeparator.HORIZONTAL, JBasicSeparator.LOWERED_STYLE, -1); - separator.setBrightColor(new Color(197, 196, 198)); - separator.setDarkColor(new Color(153, 152, 154)); - - return separator; - } - - public static Border createTitledBorder(String title) { - return BorderFactory.createTitledBorder(null, title, TitledBorder.LEADING, TitledBorder.DEFAULT_POSITION, new Font(UIContext.getFontName(), Font.PLAIN, UIContext.getLargeFontSize()), new Color(64, 0, 0)); - } -} diff --git a/discovery-console-desktop/src/main/java/com/nepxion/discovery/console/desktop/workspace/RouterTopology.java b/discovery-console-desktop/src/main/java/com/nepxion/discovery/console/desktop/workspace/RouterTopology.java deleted file mode 100644 index daae679ef8..0000000000 --- a/discovery-console-desktop/src/main/java/com/nepxion/discovery/console/desktop/workspace/RouterTopology.java +++ /dev/null @@ -1,499 +0,0 @@ -package com.nepxion.discovery.console.desktop.workspace; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import twaver.Generator; - -import java.awt.BorderLayout; -import java.awt.Color; -import java.awt.Dimension; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.HierarchyEvent; -import java.awt.event.ItemEvent; -import java.awt.event.ItemListener; -import java.util.List; - -import javax.swing.BorderFactory; -import javax.swing.Box; -import javax.swing.DefaultComboBoxModel; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.JSlider; -import javax.swing.JToolBar; - -import org.apache.commons.collections4.CollectionUtils; -import org.apache.commons.lang3.StringUtils; - -import com.nepxion.cots.twaver.element.TElementManager; -import com.nepxion.cots.twaver.element.TLink; -import com.nepxion.cots.twaver.element.TNode; -import com.nepxion.cots.twaver.graph.TGraphBackground; -import com.nepxion.cots.twaver.graph.TGraphControlBar; -import com.nepxion.cots.twaver.graph.TGraphManager; -import com.nepxion.cots.twaver.graph.TLayoutPanel; -import com.nepxion.cots.twaver.graph.TLayouterBar; -import com.nepxion.discovery.common.entity.RouterEntity; -import com.nepxion.discovery.console.desktop.controller.ServiceController; -import com.nepxion.discovery.console.desktop.entity.Instance; -import com.nepxion.discovery.console.desktop.icon.ConsoleIconFactory; -import com.nepxion.discovery.console.desktop.locale.ConsoleLocale; -import com.nepxion.discovery.console.desktop.workspace.topology.AbstractTopology; -import com.nepxion.discovery.console.desktop.workspace.topology.LocationEntity; -import com.nepxion.discovery.console.desktop.workspace.topology.TopologyEntity; -import com.nepxion.discovery.console.desktop.workspace.topology.TopologyEntityType; -import com.nepxion.discovery.console.desktop.workspace.topology.TopologyStyleType; -import com.nepxion.swing.action.JSecurityAction; -import com.nepxion.swing.button.ButtonManager; -import com.nepxion.swing.button.JBasicButton; -import com.nepxion.swing.button.JBasicToggleButton; -import com.nepxion.swing.button.JClassicButton; -import com.nepxion.swing.combobox.JBasicComboBox; -import com.nepxion.swing.dialog.JExceptionDialog; -import com.nepxion.swing.handle.HandleManager; -import com.nepxion.swing.listener.DisplayAbilityListener; -import com.nepxion.swing.locale.SwingLocale; -import com.nepxion.swing.menuitem.JBasicMenuItem; -import com.nepxion.swing.optionpane.JBasicOptionPane; -import com.nepxion.swing.popupmenu.JBasicPopupMenu; -import com.nepxion.swing.scrollpane.JBasicScrollPane; -import com.nepxion.swing.tabbedpane.JBasicTabbedPane; -import com.nepxion.swing.textarea.JBasicTextArea; -import com.nepxion.swing.textfield.JBasicTextField; - -public class RouterTopology extends AbstractTopology { - private static final long serialVersionUID = 1L; - - private LocationEntity nodeLocationEntity = new LocationEntity(100, 200, 200, 0); - private TopologyEntity serviceNodeEntity = new TopologyEntity(TopologyEntityType.SERVICE, TopologyStyleType.MIDDLE, true); - - private TGraphBackground background; - private JBasicMenuItem showRuleMenuItem; - private JBasicComboBox comboBox; - private JBasicTextField textField; - private ActionListener layoutActionListener; - private RulePanel rulePanel; - - private Instance instance; - - public RouterTopology() { - initializeToolBar(); - initializeTopology(); - initializeListener(); - } - - @Override - protected void initializePopupMenu() { - super.initializePopupMenu(); - - showRuleMenuItem = new JBasicMenuItem(createShowRuleAction()); - popupMenu.add(showRuleMenuItem, 0); - } - - @Override - protected JBasicPopupMenu popupMenuGenerate() { - super.popupMenuGenerate(); - - TNode node = TElementManager.getSelectedNode(dataBox); - showRuleMenuItem.setVisible(node != null); - - if (node != null) { - return popupMenu; - } - - return null; - } - - private void initializeToolBar() { - JSecurityAction addServiceAction = createAddServiceAction(); - - comboBox = new JBasicComboBox(); - comboBox.setPreferredSize(new Dimension(300, comboBox.getPreferredSize().height)); - comboBox.addItemListener(new ItemListener() { - public void itemStateChanged(ItemEvent e) { - if (comboBox.getSelectedItem() != e.getItem()) { - addServiceAction.execute(null); - } - } - }); - - textField = new JBasicTextField(); - textField.setPreferredSize(new Dimension(650, textField.getPreferredSize().height)); - - JToolBar toolBar = getGraph().getToolbar(); - toolBar.addSeparator(); - toolBar.add(Box.createHorizontalStrut(5)); - toolBar.add(new JLabel(ConsoleLocale.getString("service_list"))); - toolBar.add(Box.createHorizontalStrut(5)); - toolBar.add(comboBox); - toolBar.add(new JClassicButton(addServiceAction)); - toolBar.add(new JClassicButton(createDeleteServiceAction())); - toolBar.add(textField); - toolBar.add(new JClassicButton(createExecuteRouterAction())); - toolBar.add(new JClassicButton(createClearRouterAction())); - toolBar.add(new JClassicButton(createShowRuleAction())); - - ButtonManager.updateUI(toolBar); - } - - private void initializeTopology() { - background = graph.getGraphBackground(); - background.setTitle(ConsoleLocale.getString("title_service_gray_router")); - graph.setElementStateOutlineColorGenerator(new Generator() { - public Object generate(Object object) { - return null; - } - }); - } - - private void initializeListener() { - addHierarchyListener(new DisplayAbilityListener() { - public void displayAbilityChanged(HierarchyEvent e) { - // Ugly code - TGraphControlBar graphControlBar = (TGraphControlBar) graph.getControlBarInternalFrame().getContent(); - JBasicToggleButton toggleButton = (JBasicToggleButton) graphControlBar.getViewToolBar().getViewOutlook().getComponent(10); - toggleButton.setSelected(true); - - TGraphManager.layout(graph); - - TLayouterBar layouterBar = (TLayouterBar) graph.getLayoutInternalFrame().getContent(); - JScrollPane scrollPane = (JScrollPane) layouterBar.getTabAt(layouterBar.getSelectedTitle()); - JPanel panel = (JPanel) scrollPane.getViewport().getView(); - TLayoutPanel layoutPanel = (TLayoutPanel) panel.getComponent(0); - - JPanel childPanel1 = (JPanel) layoutPanel.getComponent(0); - JBasicComboBox typeComboBox = (JBasicComboBox) childPanel1.getComponent(1); - typeComboBox.setSelectedIndex(2); - - JPanel childPanel2 = (JPanel) layoutPanel.getComponent(1); - JSlider yOffsetSlider = (JSlider) childPanel2.getComponent(11); - yOffsetSlider.setValue(0); - JSlider xGapSlider = (JSlider) childPanel2.getComponent(13); - xGapSlider.setValue(200); - JSlider yGapSlider = (JSlider) childPanel2.getComponent(15); - yGapSlider.setValue(150); - - JPanel childPanel3 = (JPanel) layoutPanel.getComponent(2); - JBasicButton runButton = (JBasicButton) childPanel3.getComponent(1); - layoutActionListener = runButton.getActionListeners()[0]; - - graph.getLayoutInternalFrame().setLocation(3000, 3000); - // graph.adjustComponentPosition(graph.getLayoutInternalFrame()); - - RouterTopology.this.setPreferredSize(new Dimension(RouterTopology.this.getPreferredSize().width - 100, 900)); - - removeHierarchyListener(this); - } - }); - } - - private void route(RouterEntity routerEntity) { - dataBox.clear(); - - int index = 0; - - TNode node = addNode(routerEntity, index); - - index++; - - route(routerEntity, node, index); - } - - private void route(RouterEntity routerEntity, TNode node, int index) { - List nexts = routerEntity.getNexts(); - if (CollectionUtils.isNotEmpty(nexts)) { - for (RouterEntity next : nexts) { - String nodeName = getNodeName(next); - TNode nextNode = TElementManager.getNode(dataBox, nodeName); - if (nextNode == null) { - nextNode = addNode(next, index); - - index++; - } - addLink(node, nextNode, next); - - route(next, nextNode, index); - } - } - - } - - private String getNodeName(Instance instance) { - StringBuilder stringBuilder = new StringBuilder(); - if (StringUtils.isNotEmpty(instance.getServiceType())) { - stringBuilder.append(ConsoleLocale.getString("type_" + instance.getServiceType())).append(" - "); - } - stringBuilder.append(instance.getServiceId()).append("\n"); - stringBuilder.append(instance.getHost()).append(":").append(instance.getPort()); - - if (StringUtils.isNotEmpty(instance.getVersion())) { - stringBuilder.append("\n [V").append(instance.getVersion()).append("]"); - } - - if (StringUtils.isNotEmpty(instance.getRegion())) { - stringBuilder.append("\n [Region=").append(instance.getRegion()).append("]"); - } - - return ButtonManager.getHtmlText(stringBuilder.toString()); - } - - private String getNodeName(RouterEntity routerEntity) { - StringBuilder stringBuilder = new StringBuilder(); - if (StringUtils.isNotEmpty(routerEntity.getServiceType())) { - stringBuilder.append(ConsoleLocale.getString("type_" + routerEntity.getServiceType())).append(" - "); - } - stringBuilder.append(routerEntity.getServiceId()).append("\n"); - stringBuilder.append(routerEntity.getHost()).append(":").append(routerEntity.getPort()); - - if (StringUtils.isNotEmpty(routerEntity.getVersion())) { - stringBuilder.append("\n [V").append(routerEntity.getVersion()).append("]"); - } - - if (StringUtils.isNotEmpty(routerEntity.getRegion())) { - stringBuilder.append("\n [Region=").append(routerEntity.getRegion()).append("]"); - } - - return ButtonManager.getHtmlText(stringBuilder.toString()); - } - - private TNode addNode(Instance instance) { - String nodeName = getNodeName(instance); - - TNode node = createNode(nodeName, serviceNodeEntity, nodeLocationEntity, 0); - node.setUserObject(instance); - - dataBox.addElement(node); - - return node; - } - - private TNode addNode(RouterEntity routerEntity, int index) { - String nodeName = getNodeName(routerEntity); - - TNode node = createNode(nodeName, serviceNodeEntity, nodeLocationEntity, index); - node.setUserObject(routerEntity); - - dataBox.addElement(node); - - return node; - } - - @SuppressWarnings("unchecked") - private void addLink(TNode fromNode, TNode toNode, RouterEntity routerEntity) { - List links = TElementManager.getLinks(dataBox); - for (TLink link : links) { - if (link.getFrom() == fromNode && link.getTo() == toNode) { - return; - } - } - - int weight = routerEntity.getWeight(); - - TLink link = createLink(fromNode, toNode, true); - link.putLinkToArrowColor(Color.yellow); - if (weight > -1) { - link.setName("weight=" + weight); - link.putLinkFlowing(true); - link.putLinkFlowingColor(new Color(255, 155, 85)); - link.putLinkFlowingWidth(3); - } - - dataBox.addElement(link); - } - - @SuppressWarnings({ "unchecked" }) - public void setServices(Object[] services) { - comboBox.setModel(new DefaultComboBoxModel<>(services)); - } - - public void setInstance(Instance instance) { - if (this.instance != instance) { - this.instance = instance; - - textField.setText(StringUtils.EMPTY); - dataBox.clear(); - - addNode(instance); - } - } - - private JSecurityAction createAddServiceAction() { - JSecurityAction action = new JSecurityAction(ConsoleIconFactory.getSwingIcon("add.png"), ConsoleLocale.getString("add_service")) { - private static final long serialVersionUID = 1L; - - public void execute(ActionEvent e) { - Object selectedItem = comboBox.getSelectedItem(); - if (selectedItem == null) { - return; - } - - String routerPath = textField.getText(); - String serviceId = selectedItem.toString(); - if (StringUtils.isNotEmpty(routerPath)) { - routerPath = routerPath + ";" + serviceId; - } else { - routerPath = serviceId; - } - textField.setText(routerPath); - } - }; - - return action; - } - - private JSecurityAction createDeleteServiceAction() { - JSecurityAction action = new JSecurityAction(ConsoleIconFactory.getSwingIcon("delete.png"), ConsoleLocale.getString("delete_service")) { - private static final long serialVersionUID = 1L; - - public void execute(ActionEvent e) { - String routerPath = textField.getText(); - if (StringUtils.isEmpty(routerPath)) { - return; - } - - if (routerPath.contains(";")) { - routerPath = routerPath.substring(0, routerPath.lastIndexOf(";")); - } else { - routerPath = StringUtils.EMPTY; - } - - textField.setText(routerPath); - } - }; - - return action; - } - - private JSecurityAction createExecuteRouterAction() { - JSecurityAction action = new JSecurityAction(ConsoleLocale.getString("execute_router"), ConsoleIconFactory.getSwingIcon("netbean/action_16.png"), ConsoleLocale.getString("execute_router")) { - private static final long serialVersionUID = 1L; - - public void execute(ActionEvent e) { - String routerPath = textField.getText(); - if (StringUtils.isEmpty(routerPath)) { - JBasicOptionPane.showMessageDialog(HandleManager.getFrame(RouterTopology.this), ConsoleLocale.getString("router_path_invalid"), SwingLocale.getString("warning"), JBasicOptionPane.WARNING_MESSAGE); - - return; - } - - RouterEntity routerEntity = null; - try { - routerEntity = ServiceController.routes(instance, routerPath); - } catch (Exception ex) { - JExceptionDialog.traceException(HandleManager.getFrame(RouterTopology.this), ConsoleLocale.getString("query_data_failure"), ex); - - return; - } - - route(routerEntity); - - layoutActionListener.actionPerformed(null); - } - }; - - return action; - } - - private JSecurityAction createClearRouterAction() { - JSecurityAction action = new JSecurityAction(ConsoleLocale.getString("clear_router"), ConsoleIconFactory.getSwingIcon("paint.png"), ConsoleLocale.getString("clear_router")) { - private static final long serialVersionUID = 1L; - - public void execute(ActionEvent e) { - textField.setText(StringUtils.EMPTY); - dataBox.clear(); - } - }; - - return action; - } - - private JSecurityAction createShowRuleAction() { - JSecurityAction action = new JSecurityAction(ConsoleLocale.getString("view_rule"), ConsoleIconFactory.getSwingIcon("component/file_chooser_16.png"), ConsoleLocale.getString("view_rule")) { - private static final long serialVersionUID = 1L; - - public void execute(ActionEvent e) { - TNode node = TElementManager.getSelectedNode(dataBox); - if (node == null) { - JBasicOptionPane.showMessageDialog(HandleManager.getFrame(RouterTopology.this), ConsoleLocale.getString("select_a_node"), SwingLocale.getString("warning"), JBasicOptionPane.WARNING_MESSAGE); - - return; - } - - Object userObject = node.getUserObject(); - List rules = null; - if (userObject instanceof Instance) { - Instance instance = (Instance) userObject; - rules = ServiceController.getRules(instance); - } else if (userObject instanceof RouterEntity) { - RouterEntity routerEntity = (RouterEntity) userObject; - rules = ServiceController.getRules(routerEntity); - } - String dynamicRule = rules.get(1); - String localRule = rules.get(0); - - if (rulePanel == null) { - rulePanel = new RulePanel(); - rulePanel.setPreferredSize(new Dimension(800, 600)); - } - - rulePanel.setDynamicRule(dynamicRule); - rulePanel.setLocalRule(localRule); - - JBasicOptionPane.showOptionDialog(HandleManager.getFrame(RouterTopology.this), rulePanel, ConsoleLocale.getString("view_rule"), JBasicOptionPane.DEFAULT_OPTION, JBasicOptionPane.PLAIN_MESSAGE, ConsoleIconFactory.getSwingIcon("banner/property.png"), new Object[] { SwingLocale.getString("close") }, null, true); - } - }; - - return action; - } - - private class RulePanel extends JPanel { - private static final long serialVersionUID = 1L; - - private JBasicTextArea dynamicRuleTextArea; - private JPanel dynamicRulePanel; - private JBasicTextArea localRuleTextArea; - private JPanel localRulePanel; - private JBasicTabbedPane ruleTabbedPane; - - public RulePanel() { - setLayout(new BorderLayout()); - add(createRuleTabbedPane(), BorderLayout.CENTER); - } - - private JBasicTabbedPane createRuleTabbedPane() { - dynamicRuleTextArea = new JBasicTextArea(); - dynamicRulePanel = new JPanel(); - dynamicRulePanel.setBorder(BorderFactory.createEmptyBorder(5, 0, 5, 0)); - dynamicRulePanel.setLayout(new BorderLayout()); - dynamicRulePanel.add(new JBasicScrollPane(dynamicRuleTextArea), BorderLayout.CENTER); - - localRuleTextArea = new JBasicTextArea(); - localRulePanel = new JPanel(); - localRulePanel.setBorder(BorderFactory.createEmptyBorder(5, 0, 5, 0)); - localRulePanel.setLayout(new BorderLayout()); - localRulePanel.add(new JBasicScrollPane(localRuleTextArea), BorderLayout.CENTER); - - ruleTabbedPane = new JBasicTabbedPane(); - ruleTabbedPane.addTab(ConsoleLocale.getString("label_dynamic_rule"), dynamicRulePanel, ConsoleLocale.getString("label_dynamic_rule")); - ruleTabbedPane.addTab(ConsoleLocale.getString("label_local_rule"), localRulePanel, ConsoleLocale.getString("label_local_rule")); - - return ruleTabbedPane; - } - - public void setDynamicRule(String dynamicRule) { - dynamicRuleTextArea.setText(dynamicRule); - } - - public void setLocalRule(String localRule) { - localRuleTextArea.setText(localRule); - } - } -} \ No newline at end of file diff --git a/discovery-console-desktop/src/main/java/com/nepxion/discovery/console/desktop/workspace/ServiceTopology.java b/discovery-console-desktop/src/main/java/com/nepxion/discovery/console/desktop/workspace/ServiceTopology.java deleted file mode 100644 index e21c64592c..0000000000 --- a/discovery-console-desktop/src/main/java/com/nepxion/discovery/console/desktop/workspace/ServiceTopology.java +++ /dev/null @@ -1,1509 +0,0 @@ -package com.nepxion.discovery.console.desktop.workspace; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import twaver.AlarmSeverity; -import twaver.BlinkingRule; -import twaver.Element; -import twaver.Generator; -import twaver.TWaverConst; - -import java.awt.BorderLayout; -import java.awt.Dimension; -import java.awt.Point; -import java.awt.event.ActionEvent; -import java.awt.event.MouseEvent; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.Vector; - -import javax.swing.BorderFactory; -import javax.swing.Box; -import javax.swing.BoxLayout; -import javax.swing.ButtonGroup; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JToolBar; -import javax.swing.SwingConstants; - -import org.apache.commons.collections4.CollectionUtils; -import org.apache.commons.lang3.StringUtils; - -import com.nepxion.cots.twaver.element.TElement; -import com.nepxion.cots.twaver.element.TElementManager; -import com.nepxion.cots.twaver.element.TGroup; -import com.nepxion.cots.twaver.element.TGroupType; -import com.nepxion.cots.twaver.element.TNode; -import com.nepxion.cots.twaver.graph.TGraphBackground; -import com.nepxion.cots.twaver.graph.TGraphManager; -import com.nepxion.discovery.common.entity.InstanceEntityWrapper; -import com.nepxion.discovery.common.entity.ResultEntity; -import com.nepxion.discovery.console.desktop.constant.ConsoleConstant; -import com.nepxion.discovery.console.desktop.controller.ServiceController; -import com.nepxion.discovery.console.desktop.entity.Instance; -import com.nepxion.discovery.console.desktop.icon.ConsoleIconFactory; -import com.nepxion.discovery.console.desktop.locale.ConsoleLocale; -import com.nepxion.discovery.console.desktop.ui.UIFactory; -import com.nepxion.discovery.console.desktop.workspace.topology.AbstractTopology; -import com.nepxion.discovery.console.desktop.workspace.topology.LocationEntity; -import com.nepxion.discovery.console.desktop.workspace.topology.TopologyEntity; -import com.nepxion.discovery.console.desktop.workspace.topology.TopologyEntityType; -import com.nepxion.discovery.console.desktop.workspace.topology.TopologyStyleType; -import com.nepxion.swing.action.JSecurityAction; -import com.nepxion.swing.button.ButtonManager; -import com.nepxion.swing.button.JClassicButton; -import com.nepxion.swing.button.JClassicMenuButton; -import com.nepxion.swing.dialog.JExceptionDialog; -import com.nepxion.swing.dialog.JOptionDialog; -import com.nepxion.swing.element.ElementNode; -import com.nepxion.swing.framework.dockable.JDockable; -import com.nepxion.swing.framework.dockable.JDockableView; -import com.nepxion.swing.handle.HandleManager; -import com.nepxion.swing.icon.IconFactory; -import com.nepxion.swing.label.JBasicLabel; -import com.nepxion.swing.layout.filed.FiledLayout; -import com.nepxion.swing.layout.table.TableLayout; -import com.nepxion.swing.list.BasicListModel; -import com.nepxion.swing.list.JBasicList; -import com.nepxion.swing.locale.SwingLocale; -import com.nepxion.swing.menuitem.JBasicMenuItem; -import com.nepxion.swing.menuitem.JBasicRadioButtonMenuItem; -import com.nepxion.swing.optionpane.JBasicOptionPane; -import com.nepxion.swing.popupmenu.JBasicPopupMenu; -import com.nepxion.swing.query.JQueryHierarchy; -import com.nepxion.swing.scrollpane.JBasicScrollPane; -import com.nepxion.swing.selector.checkbox.JCheckBoxSelector; -import com.nepxion.swing.tabbedpane.JBasicTabbedPane; -import com.nepxion.swing.textarea.JBasicTextArea; -import com.nepxion.swing.textfield.JBasicTextField; -import com.nepxion.swing.textfield.number.JNumberTextField; - -public class ServiceTopology extends AbstractTopology { - private static final long serialVersionUID = 1L; - - private LocationEntity groupLocationEntity = new LocationEntity(120, 250, 280, 0); - private LocationEntity nodeLocationEntity = new LocationEntity(0, 0, 120, 120); - private TopologyEntity serviceGroupEntity = new TopologyEntity(TopologyEntityType.SERVICE_GROUP, TopologyStyleType.LARGE, true); - private TopologyEntity notServiceGroupEntity = new TopologyEntity(TopologyEntityType.GATEWAY_GROUP, TopologyStyleType.LARGE, true); - private TopologyEntity serviceNodeEntity = new TopologyEntity(TopologyEntityType.SERVICE, TopologyStyleType.MIDDLE, false); - private TopologyEntity notServiceNodeEntity = new TopologyEntity(TopologyEntityType.GATEWAY, TopologyStyleType.MIDDLE, false); - private Map groupLocationMap = new HashMap(); - - private TGraphBackground background; - private JBasicMenuItem executeGrayReleaseMenuItem; - private JBasicMenuItem refreshGrayStateMenuItem; - private JBasicMenuItem executeGrayRouterMenuItem; - private JBasicMenuItem showMetadataMenuItem; - private JBasicRadioButtonMenuItem pushAsyncModeRadioButtonMenuItem; - private JBasicRadioButtonMenuItem pushSyncModeRadioButtonMenuItem; - private JBasicRadioButtonMenuItem ruleToConfigCenterRadioButtonMenuItem; - private JBasicRadioButtonMenuItem ruleToServiceRadioButtonMenuItem; - private GlobalGrayPanel globalGrayPanel; - private GrayPanel grayPanel; - private JBasicTextArea resultTextArea; - private JBasicTextArea metadataTextArea; - private RouterTopology routerTopology; - private LayoutDialog layoutDialog; - - private Map> globalInstanceMap; - - public ServiceTopology() { - initializeToolBar(); - initializeTopology(); - } - - @Override - protected void initializePopupMenu() { - super.initializePopupMenu(); - - executeGrayReleaseMenuItem = new JBasicMenuItem(createExecuteGrayReleaseAction()); - refreshGrayStateMenuItem = new JBasicMenuItem(createRefreshGrayStateAction()); - executeGrayRouterMenuItem = new JBasicMenuItem(createExecuteGrayRouterAction()); - showMetadataMenuItem = new JBasicMenuItem(createShowMetadataAction()); - popupMenu.add(executeGrayReleaseMenuItem, 0); - popupMenu.add(executeGrayRouterMenuItem, 1); - popupMenu.add(refreshGrayStateMenuItem, 2); - popupMenu.add(showMetadataMenuItem, 3); - } - - @Override - protected JBasicPopupMenu popupMenuGenerate() { - super.popupMenuGenerate(); - - TGroup group = TElementManager.getSelectedGroup(dataBox); - - TNode node = TElementManager.getSelectedNode(dataBox); - executeGrayRouterMenuItem.setVisible(node != null && isPlugin(node)); - - TElement element = TElementManager.getSelectedElement(dataBox); - executeGrayReleaseMenuItem.setVisible(element != null && isPlugin(element)); - refreshGrayStateMenuItem.setVisible(element != null && isPlugin(element)); - showMetadataMenuItem.setVisible(node != null); - - if (group != null || node != null || element != null) { - return popupMenu; - } - - return null; - } - - private void initializeToolBar() { - pushAsyncModeRadioButtonMenuItem = new JBasicRadioButtonMenuItem(ConsoleLocale.getString("push_async_mode"), ConsoleLocale.getString("push_async_mode"), true); - pushSyncModeRadioButtonMenuItem = new JBasicRadioButtonMenuItem(ConsoleLocale.getString("push_sync_mode"), ConsoleLocale.getString("push_sync_mode")); - ButtonGroup pushModeButtonGroup = new ButtonGroup(); - pushModeButtonGroup.add(pushAsyncModeRadioButtonMenuItem); - pushModeButtonGroup.add(pushSyncModeRadioButtonMenuItem); - - ruleToConfigCenterRadioButtonMenuItem = new JBasicRadioButtonMenuItem(ConsoleLocale.getString("rule_to_config_center"), ConsoleLocale.getString("rule_to_config_center"), true); - ruleToServiceRadioButtonMenuItem = new JBasicRadioButtonMenuItem(ConsoleLocale.getString("rule_to_service"), ConsoleLocale.getString("rule_to_service")); - ButtonGroup ruleToButtonGroup = new ButtonGroup(); - ruleToButtonGroup.add(ruleToConfigCenterRadioButtonMenuItem); - ruleToButtonGroup.add(ruleToServiceRadioButtonMenuItem); - - JBasicPopupMenu pushControlPopupMenu = new JBasicPopupMenu(); - pushControlPopupMenu.add(pushAsyncModeRadioButtonMenuItem); - pushControlPopupMenu.add(pushSyncModeRadioButtonMenuItem); - pushControlPopupMenu.addSeparator(); - pushControlPopupMenu.add(ruleToConfigCenterRadioButtonMenuItem); - pushControlPopupMenu.add(ruleToServiceRadioButtonMenuItem); - - JClassicMenuButton pushControllMenubutton = new JClassicMenuButton(ConsoleLocale.getString("push_control_mode"), ConsoleIconFactory.getSwingIcon("netbean/custom_node_16.png"), ConsoleLocale.getString("push_control_mode")); - pushControllMenubutton.setPopupMenu(pushControlPopupMenu); - - JToolBar toolBar = getGraph().getToolbar(); - toolBar.addSeparator(); - toolBar.add(Box.createHorizontalStrut(5)); - toolBar.add(new JClassicButton(createShowTopologyAction())); - toolBar.addSeparator(); - toolBar.add(new JClassicButton(createExecuteGrayReleaseAction())); - toolBar.add(new JClassicButton(createExecuteGrayRouterAction())); - toolBar.add(new JClassicButton(createRefreshGrayStateAction())); - toolBar.add(new JClassicButton(createShowMetadataAction())); - toolBar.add(new JClassicButton(createPushGlobalConfigAction())); - toolBar.add(pushControllMenubutton); - toolBar.addSeparator(); - toolBar.add(createConfigButton(true)); - - ButtonManager.updateUI(toolBar); - } - - private void initializeTopology() { - background = graph.getGraphBackground(); - background.setTitle(ConsoleLocale.getString("title_service_cluster_gray_release")); - graph.setBlinkingRule(new BlinkingRule() { - public boolean isBodyBlinking(Element element) { - return element.getAlarmState().getHighestNativeAlarmSeverity() != null || element.getClientProperty(TWaverConst.PROPERTYNAME_RENDER_COLOR) != null; - } - - public boolean isOutlineBlinking(Element element) { - return element.getAlarmState().getPropagateSeverity() != null || element.getClientProperty(TWaverConst.PROPERTYNAME_STATE_OUTLINE_COLOR) != null; - } - }); - graph.setElementStateOutlineColorGenerator(new Generator() { - public Object generate(Object object) { - return null; - } - }); - - setGroupAutoExpand(true); - setLinkAutoHide(true); - } - - private String getFilter(TElement element) { - return element.getClientProperty(ConsoleConstant.FILTER).toString(); - } - - private void setFilter(TElement element, String filter) { - element.putClientProperty(ConsoleConstant.FILTER, filter); - } - - private String getPlugin(TElement element) { - return element.getClientProperty(ConsoleConstant.PLUGIN).toString(); - } - - private void setPlugin(TElement element, String plugin) { - element.putClientProperty(ConsoleConstant.PLUGIN, plugin); - } - - private boolean isPlugin(TElement element) { - String plugin = getPlugin(element); - - return StringUtils.isNotEmpty(plugin); - } - - private void addServices() { - for (Map.Entry> entry : globalInstanceMap.entrySet()) { - String serviceId = entry.getKey(); - List instances = entry.getValue(); - addService(serviceId, instances); - } - } - - private void addService(String serviceId, List instances) { - String filter = getValidFilter(instances); - String plugin = getValidPlugin(instances); - - int count = groupLocationMap.size(); - String groupName = getGroupName(serviceId, instances.size(), filter); - - TGroup group = createGroup(groupName, StringUtils.isNotEmpty(plugin) ? serviceGroupEntity : notServiceGroupEntity, groupLocationEntity, count); - group.setGroupType(TGroupType.ELLIPSE_GROUP_TYPE.getType()); - group.setUserObject(serviceId); - setFilter(group, filter); - setPlugin(group, plugin); - - addInstances(group, serviceId, instances); - } - - private void addInstances(TGroup group, String serviceId, List instances) { - for (int i = 0; i < instances.size(); i++) { - Instance instance = instances.get(i); - String filter = InstanceEntityWrapper.getGroup(instance); - String plugin = InstanceEntityWrapper.getPlugin(instance); - String nodeName = getNodeName(instance); - - TNode node = createNode(nodeName, StringUtils.isNotEmpty(plugin) ? serviceNodeEntity : notServiceNodeEntity, nodeLocationEntity, i); - node.setUserObject(instance); - setFilter(node, filter); - setPlugin(node, plugin); - - group.addChild(node); - } - - updateGroup(group); - - groupLocationMap.put(serviceId, group.getLocation()); - - dataBox.addElement(group); - TElementManager.addGroupChildren(dataBox, group); - } - - private String getValidFilter(List instances) { - // 服务注册发现中心,必须有一个规范,即在同一个服务集群下,必须所有服务的metadata格式一致,例如一个服务配了group,另一个服务没有配group - // 只取有值的那个 - for (Instance instance : instances) { - String filter = InstanceEntityWrapper.getGroup(instance); - if (StringUtils.isNotEmpty(filter)) { - return filter; - } - } - - return StringUtils.EMPTY; - } - - private String getValidPlugin(List instances) { - for (Instance instance : instances) { - String plugin = InstanceEntityWrapper.getPlugin(instance); - if (StringUtils.isNotEmpty(plugin)) { - return plugin; - } - } - - return StringUtils.EMPTY; - } - - private Object[] filterServices(TNode node, Map> instanceMap) { - Set services = instanceMap.keySet(); - List filterServices = new ArrayList(); - for (String service : services) { - TGroup group = getGroup(service); - // node.getParent() != group 表示自己不能路由自己 - if (group != null && isPlugin(group) && node.getParent() != group) { - filterServices.add(service); - } - } - - return filterServices.toArray(); - } - - @SuppressWarnings("unchecked") - private TGroup getGroup(String serviceId) { - List elements = dataBox.getAllElements(); - for (TElement element : elements) { - if (element instanceof TGroup) { - if (StringUtils.equals(element.getUserObject().toString(), serviceId)) { - return (TGroup) element; - } - } - } - - return null; - } - - private String getGroupName(String serviceId, int count, String filter) { - return ButtonManager.getHtmlText(serviceId + " [" + count + "]" + (StringUtils.isNotEmpty(filter) ? "\n" + filter : StringUtils.EMPTY)); - } - - @SuppressWarnings("unchecked") - private void updateGroup(TGroup group) { - String name = getGroupName(group.getUserObject().toString(), group.childrenSize(), getFilter(group)); - group.setName(name); - - boolean hasDynamicRule = false; - boolean hasDynamicVersion = false; - List nodes = group.getChildren(); - Iterator iterator = nodes.iterator(); - while (iterator.hasNext()) { - TNode node = iterator.next(); - Instance instance = (Instance) node.getUserObject(); - if (StringUtils.isNotEmpty(instance.getDynamicRule())) { - hasDynamicRule = true; - } - - if (StringUtils.isNotEmpty(instance.getDynamicVersion())) { - hasDynamicVersion = true; - } - } - - group.getAlarmState().clear(); - if (hasDynamicRule) { - group.getAlarmState().addAcknowledgedAlarm(AlarmSeverity.MINOR); - } else if (hasDynamicVersion) { - group.getAlarmState().addAcknowledgedAlarm(AlarmSeverity.WARNING); - } - } - - private String getNodeName(Instance instance) { - StringBuilder stringBuilder = new StringBuilder(); - if (StringUtils.isNotEmpty(instance.getServiceType())) { - stringBuilder.append(ConsoleLocale.getString("type_" + instance.getServiceType())).append(" - "); - } - stringBuilder.append(instance.getHost()).append(":").append(instance.getPort()); - if (StringUtils.isNotEmpty(instance.getVersion())) { - stringBuilder.append("\n[V").append(instance.getVersion()); - if (StringUtils.isNotEmpty(instance.getDynamicVersion())) { - stringBuilder.append(" -> V").append(instance.getDynamicVersion()); - } - stringBuilder.append("]"); - } - if (StringUtils.isNotEmpty(instance.getRegion())) { - stringBuilder.append("\n [Region=").append(instance.getRegion()).append("]"); - } - - return ButtonManager.getHtmlText(stringBuilder.toString()); - } - - private void updateNode(TNode node, Instance instance) { - String name = getNodeName(instance); - node.setName(name); - - boolean hasDynamicRule = StringUtils.isNotEmpty(instance.getDynamicRule()); - boolean hasDynamicVersion = StringUtils.isNotEmpty(instance.getDynamicVersion()); - - node.getAlarmState().clear(); - if (hasDynamicRule) { - node.getAlarmState().addAcknowledgedAlarm(AlarmSeverity.MINOR); - } else if (hasDynamicVersion) { - node.getAlarmState().addAcknowledgedAlarm(AlarmSeverity.WARNING); - } - } - - @SuppressWarnings("unchecked") - private void locateGroups() { - List groups = TElementManager.getGroups(dataBox); - for (TGroup group : groups) { - String key = group.getUserObject().toString(); - if (groupLocationMap.containsKey(key)) { - group.setLocation(groupLocationMap.get(key)); - } - } - } - - private void showTopology() { - dataBox.clear(); - groupLocationMap.clear(); - - addServices(); - locateGroups(); - - TGraphManager.setGroupExpand(graph, isGroupAutoExpand()); - TGraphManager.setLinkVisible(graph, !isLinkAutoHide()); - } - - private void updateGrayState(TNode node) { - Instance instance = (Instance) node.getUserObject(); - List versions = ServiceController.getVersions(instance); - List rules = ServiceController.getRules(instance); - instance.setVersion(versions.get(0)); - instance.setDynamicVersion(versions.get(1)); - instance.setRule(rules.get(0)); - instance.setDynamicRule(rules.get(1)); - - updateNode(node, instance); - } - - private boolean refreshGrayState(TNode node) { - boolean hasException = false; - - TGroup group = (TGroup) node.getParent(); - try { - updateGrayState(node); - } catch (Exception e) { - JExceptionDialog.traceException(HandleManager.getFrame(this), ConsoleLocale.getString("query_data_failure"), e); - - group.removeChild(node); - dataBox.removeElement(node); - - hasException = true; - } - - updateGroup(group); - - return hasException; - } - - @SuppressWarnings("unchecked") - private boolean refreshGrayState(TGroup group) { - boolean hasException = false; - - List nodes = group.getChildren(); - Iterator iterator = nodes.iterator(); - while (iterator.hasNext()) { - TNode node = iterator.next(); - - try { - updateGrayState(node); - } catch (Exception e) { - JExceptionDialog.traceException(HandleManager.getFrame(this), ConsoleLocale.getString("query_data_failure"), e); - - iterator.remove(); - dataBox.removeElement(node); - - hasException = true; - } - } - - updateGroup(group); - - return hasException; - } - - private void showResult(Object result) { - if (resultTextArea == null) { - resultTextArea = new JBasicTextArea(); - resultTextArea.setLineWrap(true); - resultTextArea.setPreferredSize(new Dimension(800, 600)); - } - resultTextArea.setText(result.toString()); - - JBasicOptionPane.showOptionDialog(HandleManager.getFrame(this), new JBasicScrollPane(resultTextArea), ConsoleLocale.getString("execute_result"), JBasicOptionPane.DEFAULT_OPTION, JBasicOptionPane.PLAIN_MESSAGE, ConsoleIconFactory.getSwingIcon("banner/edit.png"), new Object[] { SwingLocale.getString("close") }, null, true); - } - - private void showMetadata(Instance instance) { - Map metadata = instance.getMetadata(); - - StringBuilder stringBuilder = new StringBuilder(); - for (Map.Entry entry : metadata.entrySet()) { - String key = entry.getKey(); - String value = entry.getValue(); - stringBuilder.append(key).append("=").append(value).append("\n"); - } - - if (metadataTextArea == null) { - metadataTextArea = new JBasicTextArea(); - metadataTextArea.setLineWrap(true); - metadataTextArea.setPreferredSize(new Dimension(800, 600)); - } - String result = stringBuilder.toString(); - if (StringUtils.isNotEmpty(result)) { - result = result.substring(0, result.lastIndexOf("\n")); - } - metadataTextArea.setText(result); - - JBasicOptionPane.showOptionDialog(HandleManager.getFrame(this), new JBasicScrollPane(metadataTextArea), ConsoleLocale.getString("show_metadata"), JBasicOptionPane.DEFAULT_OPTION, JBasicOptionPane.PLAIN_MESSAGE, ConsoleIconFactory.getSwingIcon("banner/property.png"), new Object[] { SwingLocale.getString("close") }, null, true); - } - - @Override - public void showLayout() { - if (layoutDialog == null) { - layoutDialog = new LayoutDialog(); - } - - layoutDialog.setToUI(); - layoutDialog.setVisible(true); - boolean confirmed = layoutDialog.isConfirmed(); - if (confirmed && !dataBox.isEmpty()) { - showTopology(); - } - } - - private JSecurityAction createShowTopologyAction() { - JSecurityAction action = new JSecurityAction(ConsoleLocale.getString("show_topology"), ConsoleIconFactory.getSwingIcon("component/ui_16.png"), ConsoleLocale.getString("show_topology")) { - private static final long serialVersionUID = 1L; - - @SuppressWarnings("unchecked") - public void execute(ActionEvent e) { - List groups = null; - try { - groups = ServiceController.getGroups(); - } catch (Exception ex) { - JExceptionDialog.traceException(HandleManager.getFrame(ServiceTopology.this), ConsoleLocale.getString("get_service_group_failure"), ex); - - return; - } - - List filterElementNodes = new ArrayList(); - for (String filter : groups) { - filterElementNodes.add(new ElementNode(filter, IconFactory.getSwingIcon("component/file_chooser_16.png"), filter)); - } - - JCheckBoxSelector checkBoxSelector = new JCheckBoxSelector(HandleManager.getFrame(ServiceTopology.this), ConsoleLocale.getString("service_cluster_filter"), new Dimension(400, 350), filterElementNodes); - checkBoxSelector.setVisible(true); - checkBoxSelector.dispose(); - - List filters = new ArrayList(); - if (checkBoxSelector.isConfirmed()) { - List selectedFilterElementNodes = checkBoxSelector.getSelectedElementNodes(); - for (ElementNode selectedFilterElementNode : selectedFilterElementNodes) { - filters.add(selectedFilterElementNode.getText()); - } - } - - Map> instanceMap = null; - try { - instanceMap = ServiceController.getInstanceMap(filters); - } catch (Exception ex) { - JExceptionDialog.traceException(HandleManager.getFrame(ServiceTopology.this), ConsoleLocale.getString("get_service_instances_failure"), ex); - - return; - } - - globalInstanceMap = instanceMap; - - String title = ConsoleLocale.getString("title_service_cluster_gray_release") + " " + (CollectionUtils.isNotEmpty(filters) ? filters : StringUtils.EMPTY); - background.setTitle(title); - - showTopology(); - } - }; - - return action; - } - - private JSecurityAction createExecuteGrayReleaseAction() { - JSecurityAction action = new JSecurityAction(ConsoleLocale.getString("execute_gray_release"), ConsoleIconFactory.getSwingIcon("netbean/action_16.png"), ConsoleLocale.getString("execute_gray_release")) { - private static final long serialVersionUID = 1L; - - public void execute(ActionEvent e) { - TGroup group = TElementManager.getSelectedGroup(dataBox); - TNode node = TElementManager.getSelectedNode(dataBox); - if (group == null && node == null) { - JBasicOptionPane.showMessageDialog(HandleManager.getFrame(ServiceTopology.this), ConsoleLocale.getString("select_a_group_or_node"), SwingLocale.getString("warning"), JBasicOptionPane.WARNING_MESSAGE); - - return; - } - - if (group != null && !isPlugin(group)) { - JBasicOptionPane.showMessageDialog(HandleManager.getFrame(ServiceTopology.this), ConsoleLocale.getString("group_not_for_gray_release"), SwingLocale.getString("warning"), JBasicOptionPane.WARNING_MESSAGE); - - return; - } - - if (node != null && !isPlugin(node)) { - JBasicOptionPane.showMessageDialog(HandleManager.getFrame(ServiceTopology.this), ConsoleLocale.getString("node_not_for_gray_release"), SwingLocale.getString("warning"), JBasicOptionPane.WARNING_MESSAGE); - - return; - } - - boolean hasException = false; - if (group != null) { - hasException = refreshGrayState(group); - } else if (node != null) { - hasException = refreshGrayState(node); - } - - if (hasException) { - return; - } - - if (grayPanel == null) { - grayPanel = new GrayPanel(); - grayPanel.setPreferredSize(new Dimension(1300, 800)); - } - - String description = null; - if (group != null) { - grayPanel.setGray(group); - - description = group.getUserObject().toString(); - } else if (node != null) { - grayPanel.setGray(node); - - Instance instance = (Instance) node.getUserObject(); - - description = instance.getServiceId() + " [" + instance.getHost() + ":" + instance.getPort() + "]"; - } - - JBasicOptionPane.showOptionDialog(HandleManager.getFrame(ServiceTopology.this), grayPanel, ConsoleLocale.getString("execute_gray_release") + " - " + description, JBasicOptionPane.DEFAULT_OPTION, JBasicOptionPane.PLAIN_MESSAGE, ConsoleIconFactory.getSwingIcon("banner/navigator.png"), new Object[] { SwingLocale.getString("close") }, null, true); - } - }; - - return action; - } - - private JSecurityAction createExecuteGrayRouterAction() { - JSecurityAction action = new JSecurityAction(ConsoleLocale.getString("execute_gray_router"), ConsoleIconFactory.getSwingIcon("netbean/close_path_16.png"), ConsoleLocale.getString("execute_gray_router")) { - private static final long serialVersionUID = 1L; - - public void execute(ActionEvent e) { - TNode node = TElementManager.getSelectedNode(dataBox); - if (node == null) { - JBasicOptionPane.showMessageDialog(HandleManager.getFrame(ServiceTopology.this), ConsoleLocale.getString("select_a_node"), SwingLocale.getString("warning"), JBasicOptionPane.WARNING_MESSAGE); - - return; - } - - if (node != null && !isPlugin(node)) { - JBasicOptionPane.showMessageDialog(HandleManager.getFrame(ServiceTopology.this), ConsoleLocale.getString("node_not_for_gray_router"), SwingLocale.getString("warning"), JBasicOptionPane.WARNING_MESSAGE); - - return; - } - - Instance instance = (Instance) node.getUserObject(); - - if (routerTopology == null) { - routerTopology = new RouterTopology(); - // routerTopology.setPreferredSize(new Dimension(1300, 800)); - } - - Object[] filterServices = filterServices(node, globalInstanceMap); - routerTopology.setServices(filterServices); - routerTopology.setInstance(instance); - - String description = instance.getServiceId() + " [" + instance.getHost() + ":" + instance.getPort() + "]"; - - JBasicOptionPane.showOptionDialog(HandleManager.getFrame(ServiceTopology.this), routerTopology, ConsoleLocale.getString("execute_gray_router") + " - " + description, JBasicOptionPane.DEFAULT_OPTION, JBasicOptionPane.PLAIN_MESSAGE, ConsoleIconFactory.getSwingIcon("banner/navigator.png"), new Object[] { SwingLocale.getString("close") }, null, true); - } - }; - - return action; - } - - private JSecurityAction createRefreshGrayStateAction() { - JSecurityAction action = new JSecurityAction(ConsoleLocale.getString("refresh_gray_state"), ConsoleIconFactory.getSwingIcon("netbean/rotate_16.png"), ConsoleLocale.getString("refresh_gray_state")) { - private static final long serialVersionUID = 1L; - - public void execute(ActionEvent e) { - TGroup group = TElementManager.getSelectedGroup(dataBox); - TNode node = TElementManager.getSelectedNode(dataBox); - if (group == null && node == null) { - JBasicOptionPane.showMessageDialog(HandleManager.getFrame(ServiceTopology.this), ConsoleLocale.getString("select_a_group_or_node"), SwingLocale.getString("warning"), JBasicOptionPane.WARNING_MESSAGE); - - return; - } - - if (group != null && !isPlugin(group)) { - JBasicOptionPane.showMessageDialog(HandleManager.getFrame(ServiceTopology.this), ConsoleLocale.getString("group_not_for_refresh_gray_state"), SwingLocale.getString("warning"), JBasicOptionPane.WARNING_MESSAGE); - - return; - } - - if (node != null && !isPlugin(node)) { - JBasicOptionPane.showMessageDialog(HandleManager.getFrame(ServiceTopology.this), ConsoleLocale.getString("node_not_for_refresh_gray_state"), SwingLocale.getString("warning"), JBasicOptionPane.WARNING_MESSAGE); - - return; - } - - if (group != null) { - refreshGrayState(group); - } else if (node != null) { - refreshGrayState(node); - } - } - }; - - return action; - } - - private JSecurityAction createShowMetadataAction() { - JSecurityAction action = new JSecurityAction(ConsoleLocale.getString("show_metadata"), ConsoleIconFactory.getSwingIcon("component/file_chooser_16.png"), ConsoleLocale.getString("show_metadata")) { - private static final long serialVersionUID = 1L; - - public void execute(ActionEvent e) { - TNode node = TElementManager.getSelectedNode(dataBox); - if (node == null) { - JBasicOptionPane.showMessageDialog(HandleManager.getFrame(ServiceTopology.this), ConsoleLocale.getString("select_a_node"), SwingLocale.getString("warning"), JBasicOptionPane.WARNING_MESSAGE); - - return; - } - - Object userObject = node.getUserObject(); - if (userObject == null || !(userObject instanceof Instance)) { - JBasicOptionPane.showMessageDialog(HandleManager.getFrame(ServiceTopology.this), ConsoleLocale.getString("node_has_no_metadata"), SwingLocale.getString("warning"), JBasicOptionPane.WARNING_MESSAGE); - - return; - } - - Instance instance = (Instance) userObject; - - showMetadata(instance); - } - }; - - return action; - } - - private JSecurityAction createPushGlobalConfigAction() { - JSecurityAction action = new JSecurityAction(ConsoleLocale.getString("push_global_config"), ConsoleIconFactory.getSwingIcon("netbean/ease_both_16.png"), ConsoleLocale.getString("push_global_config")) { - private static final long serialVersionUID = 1L; - - public void execute(ActionEvent e) { - if (!ruleToConfigCenterRadioButtonMenuItem.isSelected()) { - JBasicOptionPane.showMessageDialog(HandleManager.getFrame(ServiceTopology.this), ConsoleLocale.getString("not_for_push_global_config"), SwingLocale.getString("warning"), JBasicOptionPane.WARNING_MESSAGE); - - return; - } - - List groups = null; - try { - groups = ServiceController.getGroups(); - } catch (Exception ex) { - JExceptionDialog.traceException(HandleManager.getFrame(ServiceTopology.this), ConsoleLocale.getString("get_service_group_failure"), ex); - - return; - } - - Vector globalFilterVector = new Vector(groups); - - if (globalGrayPanel == null) { - globalGrayPanel = new GlobalGrayPanel(); - globalGrayPanel.setPreferredSize(new Dimension(1300, 800)); - } - - globalGrayPanel.setFilters(globalFilterVector); - - JBasicOptionPane.showOptionDialog(HandleManager.getFrame(ServiceTopology.this), globalGrayPanel, ConsoleLocale.getString("push_global_config"), JBasicOptionPane.DEFAULT_OPTION, JBasicOptionPane.PLAIN_MESSAGE, ConsoleIconFactory.getSwingIcon("banner/navigator.png"), new Object[] { SwingLocale.getString("close") }, null, true); - } - }; - - return action; - } - - private class GlobalGrayPanel extends JQueryHierarchy { - private static final long serialVersionUID = 1L; - - private JBasicList filterList; - private JBasicTextArea ruleTextArea; - private JClassicButton updateRuleButton; - private JClassicButton clearRuleButton; - - public GlobalGrayPanel() { - filterList = new JBasicList() { - private static final long serialVersionUID = 1L; - - @Override - public void mousePressed(MouseEvent e) { - int selectedRow = getSelectedIndex(); - if (selectedRow < 0) { - return; - } - - String filter = getListData().get(selectedRow).toString(); - String config = ServiceController.remoteConfigView(filter, filter); - ruleTextArea.setText(config); - } - }; - filterList.setSelectionMode(JBasicList.SINGLE_SELECTION); - - JPanel filterPanel = new JPanel(); - filterPanel.setLayout(new BorderLayout()); - filterPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); - filterPanel.add(new JBasicScrollPane(filterList), BorderLayout.CENTER); - - ruleTextArea = new JBasicTextArea(); - - updateRuleButton = new JClassicButton(createUpdateRuleAction()); - updateRuleButton.setPreferredSize(new Dimension(updateRuleButton.getPreferredSize().width, 30)); - - clearRuleButton = new JClassicButton(createClearRuleAction()); - updateRuleButton.setPreferredSize(new Dimension(clearRuleButton.getPreferredSize().width, 30)); - - JPanel toolBar = new JPanel(); - toolBar.setLayout(new BoxLayout(toolBar, BoxLayout.X_AXIS)); - toolBar.add(updateRuleButton); - toolBar.add(clearRuleButton); - ButtonManager.updateUI(toolBar); - - JPanel rulePanel = new JPanel(); - rulePanel.setLayout(new BorderLayout()); - rulePanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); - rulePanel.add(new JBasicScrollPane(ruleTextArea), BorderLayout.CENTER); - rulePanel.add(toolBar, BorderLayout.SOUTH); - - JDockable dockable = (JDockable) getDockableContainer().getContentPane(); - - JDockableView filterView = (JDockableView) dockable.getPaneAt(0); - filterView.setTitle(ConsoleLocale.getString("global_group")); - filterView.setIcon(ConsoleIconFactory.getSwingIcon("netbean/stack_16.png")); - filterView.setToolTipText(ConsoleLocale.getString("global_group")); - filterView.add(filterPanel); - - JDockableView ruleView = (JDockableView) dockable.getPaneAt(1); - ruleView.setTitle(ConsoleLocale.getString("global_rule")); - ruleView.setIcon(ConsoleIconFactory.getSwingIcon("netbean/custom_node_16.png")); - ruleView.setToolTipText(ConsoleLocale.getString("global_rule")); - ruleView.add(rulePanel); - } - - @SuppressWarnings("unchecked") - public void setFilters(Vector filters) { - filterList.setModel(new BasicListModel(filters)); - ruleTextArea.setText(StringUtils.EMPTY); - } - - private JSecurityAction createUpdateRuleAction() { - JSecurityAction action = new JSecurityAction(ConsoleLocale.getString("button_update_rule"), ConsoleIconFactory.getSwingIcon("save.png"), ConsoleLocale.getString("button_update_rule")) { - private static final long serialVersionUID = 1L; - - public void execute(ActionEvent e) { - int selectedRow = filterList.getSelectedIndex(); - if (selectedRow < 0) { - JBasicOptionPane.showMessageDialog(HandleManager.getFrame(ServiceTopology.this), ConsoleLocale.getString("select_a_global_group"), SwingLocale.getString("warning"), JBasicOptionPane.WARNING_MESSAGE); - - return; - } - - String rule = ruleTextArea.getText(); - if (StringUtils.isEmpty(rule)) { - JBasicOptionPane.showMessageDialog(HandleManager.getFrame(ServiceTopology.this), ConsoleLocale.getString("gray_rule_not_null"), SwingLocale.getString("warning"), JBasicOptionPane.WARNING_MESSAGE); - - return; - } - - String filter = filterList.getListData().get(selectedRow).toString(); - - String result = null; - try { - result = ServiceController.remoteConfigUpdate(filter, filter, rule); - } catch (Exception ex) { - JExceptionDialog.traceException(HandleManager.getFrame(ServiceTopology.this), ConsoleLocale.getString("query_data_failure"), ex); - - return; - } - - showResult(result); - } - }; - - return action; - } - - private JSecurityAction createClearRuleAction() { - JSecurityAction action = new JSecurityAction(ConsoleLocale.getString("button_clear_rule"), ConsoleIconFactory.getSwingIcon("paint.png"), ConsoleLocale.getString("button_clear_rule")) { - private static final long serialVersionUID = 1L; - - public void execute(ActionEvent e) { - int selectedRow = filterList.getSelectedIndex(); - if (selectedRow < 0) { - JBasicOptionPane.showMessageDialog(HandleManager.getFrame(ServiceTopology.this), ConsoleLocale.getString("select_a_global_group"), SwingLocale.getString("warning"), JBasicOptionPane.WARNING_MESSAGE); - - return; - } - - String filter = filterList.getListData().get(selectedRow).toString(); - - String result = null; - try { - result = ServiceController.remoteConfigClear(filter, filter); - } catch (Exception ex) { - JExceptionDialog.traceException(HandleManager.getFrame(ServiceTopology.this), ConsoleLocale.getString("query_data_failure"), ex); - - return; - } - - showResult(result); - } - }; - - return action; - } - } - - private class GrayPanel extends JPanel { - private static final long serialVersionUID = 1L; - - private JBasicTextField dynamicVersionTextField; - private JPanel dynamicVersionPanel; - private JBasicTextField localVersionTextField; - private JPanel localVersionPanel; - private JLabel versionInfoLabel; - private JBasicTabbedPane versionTabbedPane; - private JClassicButton updateVersionButton; - private JClassicButton clearVersionButton; - - private JBasicTextArea dynamicRuleTextArea; - private JPanel dynamicRulePanel; - private JBasicTextArea localRuleTextArea; - private JPanel localRulePanel; - private JLabel ruleInfoLabel; - private JBasicTabbedPane ruleTabbedPane; - private JClassicButton updateRuleButton; - private JClassicButton clearRuleButton; - - private TGroup group; - private TNode node; - - public GrayPanel() { - setLayout(new BorderLayout()); - add(createVersionPanel(), BorderLayout.NORTH); - add(createRulePanel(), BorderLayout.CENTER); - } - - private JPanel createVersionPanel() { - dynamicVersionTextField = new JBasicTextField(); - dynamicVersionPanel = new JPanel(); - dynamicVersionPanel.setBorder(BorderFactory.createEmptyBorder(5, 0, 5, 0)); - dynamicVersionPanel.setLayout(new BorderLayout()); - dynamicVersionPanel.add(dynamicVersionTextField, BorderLayout.CENTER); - - localVersionTextField = new JBasicTextField(); - localVersionTextField.setEditable(false); - localVersionPanel = new JPanel(); - localVersionPanel.setBorder(BorderFactory.createEmptyBorder(5, 0, 5, 0)); - localVersionPanel.setLayout(new BorderLayout()); - localVersionPanel.add(localVersionTextField, BorderLayout.CENTER); - - versionTabbedPane = new JBasicTabbedPane(); - versionTabbedPane.setPreferredSize(new Dimension(versionTabbedPane.getPreferredSize().width, 75)); - versionTabbedPane.addTab(ConsoleLocale.getString("label_dynamic_version"), dynamicVersionPanel, ConsoleLocale.getString("label_dynamic_version")); - versionTabbedPane.addTab(ConsoleLocale.getString("label_local_version"), localVersionPanel, ConsoleLocale.getString("label_local_version")); - - updateVersionButton = new JClassicButton(createUpdateVersionAction()); - updateVersionButton.setPreferredSize(new Dimension(updateVersionButton.getPreferredSize().width, 30)); - - clearVersionButton = new JClassicButton(createClearVersionAction()); - clearVersionButton.setPreferredSize(new Dimension(clearVersionButton.getPreferredSize().width, 30)); - - JPanel toolBar = new JPanel(); - toolBar.setLayout(new BoxLayout(toolBar, BoxLayout.X_AXIS)); - toolBar.add(updateVersionButton); - toolBar.add(clearVersionButton); - ButtonManager.updateUI(toolBar); - - versionInfoLabel = new JLabel(ConsoleLocale.getString("description_gray_version"), IconFactory.getSwingIcon("question_message.png"), SwingConstants.LEADING); - - JPanel layoutPanel = new JPanel(); - layoutPanel.setLayout(new FiledLayout(FiledLayout.COLUMN, FiledLayout.FULL, 5)); - layoutPanel.add(versionInfoLabel); - layoutPanel.add(toolBar); - - JPanel panel = new JPanel(); - panel.setBorder(UIFactory.createTitledBorder(ConsoleLocale.getString("title_gray_version_operation"))); - panel.setLayout(new BorderLayout()); - panel.add(versionTabbedPane, BorderLayout.CENTER); - panel.add(layoutPanel, BorderLayout.SOUTH); - - return panel; - } - - private JPanel createRulePanel() { - dynamicRuleTextArea = new JBasicTextArea(); - dynamicRulePanel = new JPanel(); - dynamicRulePanel.setBorder(BorderFactory.createEmptyBorder(5, 0, 5, 0)); - dynamicRulePanel.setLayout(new BorderLayout()); - dynamicRulePanel.add(new JBasicScrollPane(dynamicRuleTextArea), BorderLayout.CENTER); - - localRuleTextArea = new JBasicTextArea(); - localRuleTextArea.setEditable(false); - localRulePanel = new JPanel(); - localRulePanel.setBorder(BorderFactory.createEmptyBorder(5, 0, 5, 0)); - localRulePanel.setLayout(new BorderLayout()); - localRulePanel.add(new JBasicScrollPane(localRuleTextArea), BorderLayout.CENTER); - - ruleTabbedPane = new JBasicTabbedPane(); - ruleTabbedPane.addTab(ConsoleLocale.getString("label_dynamic_rule"), dynamicRulePanel, ConsoleLocale.getString("label_dynamic_rule")); - ruleTabbedPane.addTab(ConsoleLocale.getString("label_local_rule"), localRulePanel, ConsoleLocale.getString("label_local_rule")); - - updateRuleButton = new JClassicButton(createUpdateRuleAction()); - updateRuleButton.setPreferredSize(new Dimension(updateRuleButton.getPreferredSize().width, 30)); - - clearRuleButton = new JClassicButton(createClearRuleAction()); - updateRuleButton.setPreferredSize(new Dimension(clearRuleButton.getPreferredSize().width, 30)); - - JPanel toolBar = new JPanel(); - toolBar.setLayout(new BoxLayout(toolBar, BoxLayout.X_AXIS)); - toolBar.add(updateRuleButton); - toolBar.add(clearRuleButton); - ButtonManager.updateUI(toolBar); - - ruleInfoLabel = new JLabel(ConsoleLocale.getString("description_gray_rule_to_config_center"), IconFactory.getSwingIcon("question_message.png"), SwingConstants.LEADING); - - JPanel layoutPanel = new JPanel(); - layoutPanel.setLayout(new FiledLayout(FiledLayout.COLUMN, FiledLayout.FULL, 5)); - layoutPanel.add(ruleInfoLabel); - layoutPanel.add(toolBar); - - JPanel panel = new JPanel(); - panel.setBorder(UIFactory.createTitledBorder(ConsoleLocale.getString("title_gray_rule_operation"))); - panel.setLayout(new BorderLayout()); - panel.add(ruleTabbedPane, BorderLayout.CENTER); - panel.add(layoutPanel, BorderLayout.SOUTH); - - return panel; - } - - @SuppressWarnings("unchecked") - public void setGray(TGroup group) { - this.group = group; - this.node = null; - - boolean versionControlEnabled = ruleToConfigCenterRadioButtonMenuItem.isSelected(); - boolean ruleControlEnabled = ruleToConfigCenterRadioButtonMenuItem.isSelected(); - if (!versionControlEnabled && !ruleControlEnabled) { - for (Iterator iterator = group.children(); iterator.hasNext();) { - TNode node = iterator.next(); - Instance instance = (Instance) node.getUserObject(); - - boolean versionEnabled = InstanceEntityWrapper.isDiscoveryControlEnabled(instance); - if (versionEnabled) { - versionControlEnabled = true; - } - boolean ruleEnabled = InstanceEntityWrapper.isDiscoveryControlEnabled(instance) && InstanceEntityWrapper.isConfigRestControlEnabled(instance); - if (ruleEnabled) { - ruleControlEnabled = true; - } - } - } - - if (versionTabbedPane.getTabCount() == 2) { - versionTabbedPane.remove(localVersionPanel); - } - if (ruleTabbedPane.getTabCount() == 2) { - ruleTabbedPane.remove(localRulePanel); - } - - dynamicVersionTextField.setText(StringUtils.EMPTY); - localVersionTextField.setText(StringUtils.EMPTY); - updateVersionButton.setText(ConsoleLocale.getString("button_batch_update_version")); - clearVersionButton.setText(ConsoleLocale.getString("button_batch_clear_version")); - updateVersionButton.setEnabled(versionControlEnabled); - clearVersionButton.setEnabled(versionControlEnabled); - - dynamicRuleTextArea.setText(StringUtils.EMPTY); - localRuleTextArea.setText(StringUtils.EMPTY); - updateRuleButton.setText(ConsoleLocale.getString("button_batch_update_rule")); - clearRuleButton.setText(ConsoleLocale.getString("button_batch_clear_rule")); - updateRuleButton.setEnabled(ruleControlEnabled); - clearRuleButton.setEnabled(ruleControlEnabled); - - String ruleInfo = null; - if (ruleToConfigCenterRadioButtonMenuItem.isSelected()) { - String filter = getFilter(group); - String serviceId = group.getUserObject().toString(); - String config = ServiceController.remoteConfigView(filter, serviceId); - dynamicRuleTextArea.setText(config); - ruleInfo = ConsoleLocale.getString("description_gray_rule_to_config_center"); - } else { - ruleInfo = ConsoleLocale.getString("description_gray_rule_to_service"); - } - - ruleInfoLabel.setText(ruleInfo); - } - - public void setGray(TNode node) { - this.group = null; - this.node = node; - Instance instance = (Instance) node.getUserObject(); - - boolean versionControlEnabled = InstanceEntityWrapper.isDiscoveryControlEnabled(instance); - boolean ruleControlEnabled = InstanceEntityWrapper.isDiscoveryControlEnabled(instance) && InstanceEntityWrapper.isConfigRestControlEnabled(instance) && !ruleToConfigCenterRadioButtonMenuItem.isSelected(); - - if (versionTabbedPane.getTabCount() == 1) { - versionTabbedPane.addTab(ConsoleLocale.getString("label_local_version"), localVersionPanel, ConsoleLocale.getString("label_local_version")); - } - if (ruleTabbedPane.getTabCount() == 1) { - ruleTabbedPane.addTab(ConsoleLocale.getString("label_local_rule"), localRulePanel, ConsoleLocale.getString("label_local_rule")); - } - - dynamicVersionTextField.setText(instance.getDynamicVersion()); - localVersionTextField.setText(instance.getVersion()); - updateVersionButton.setText(ConsoleLocale.getString("button_update_version")); - clearVersionButton.setText(ConsoleLocale.getString("button_clear_version")); - updateVersionButton.setEnabled(versionControlEnabled); - clearVersionButton.setEnabled(versionControlEnabled); - - dynamicRuleTextArea.setText(instance.getDynamicRule()); - localRuleTextArea.setText(instance.getRule()); - updateRuleButton.setText(ConsoleLocale.getString("button_update_rule")); - clearRuleButton.setText(ConsoleLocale.getString("button_clear_rule")); - updateRuleButton.setEnabled(ruleControlEnabled); - clearRuleButton.setEnabled(ruleControlEnabled); - - String ruleInfo = null; - if (ruleToConfigCenterRadioButtonMenuItem.isSelected()) { - ruleInfo = ConsoleLocale.getString("description_gray_rule_to_config_center"); - } else { - ruleInfo = ConsoleLocale.getString("description_gray_rule_to_service"); - } - - ruleInfoLabel.setText(ruleInfo); - } - - private JSecurityAction createUpdateVersionAction() { - JSecurityAction action = new JSecurityAction(ConsoleLocale.getString("button_update_version"), ConsoleIconFactory.getSwingIcon("save.png"), ConsoleLocale.getString("button_update_version")) { - private static final long serialVersionUID = 1L; - - public void execute(ActionEvent e) { - String dynamicVersion = dynamicVersionTextField.getText(); - if (StringUtils.isEmpty(dynamicVersion)) { - JBasicOptionPane.showMessageDialog(HandleManager.getFrame(ServiceTopology.this), ConsoleLocale.getString("gray_version_not_null"), SwingLocale.getString("warning"), JBasicOptionPane.WARNING_MESSAGE); - - return; - } - - if (group != null) { - String serviceId = group.getUserObject().toString(); - List results = null; - try { - results = ServiceController.versionUpdate(serviceId, dynamicVersion, pushAsyncModeRadioButtonMenuItem.isSelected()); - } catch (Exception ex) { - JExceptionDialog.traceException(HandleManager.getFrame(ServiceTopology.this), ConsoleLocale.getString("query_data_failure"), ex); - - refreshGrayState(group); - - return; - } - - showResult(results); - - refreshGrayState(group); - } else if (node != null) { - Instance instance = (Instance) node.getUserObject(); - - String result = null; - try { - result = ServiceController.versionUpdate(instance, dynamicVersion, pushAsyncModeRadioButtonMenuItem.isSelected()); - } catch (Exception ex) { - JExceptionDialog.traceException(HandleManager.getFrame(ServiceTopology.this), ConsoleLocale.getString("query_data_failure"), ex); - - refreshGrayState(node); - - return; - } - - showResult(result); - - refreshGrayState(node); - } - } - }; - - return action; - } - - private JSecurityAction createClearVersionAction() { - JSecurityAction action = new JSecurityAction(ConsoleLocale.getString("button_clear_version"), ConsoleIconFactory.getSwingIcon("paint.png"), ConsoleLocale.getString("button_clear_version")) { - private static final long serialVersionUID = 1L; - - public void execute(ActionEvent e) { - if (group != null) { - String serviceId = group.getUserObject().toString(); - List results = null; - try { - results = ServiceController.versionClear(serviceId, pushAsyncModeRadioButtonMenuItem.isSelected()); - } catch (Exception ex) { - JExceptionDialog.traceException(HandleManager.getFrame(ServiceTopology.this), ConsoleLocale.getString("query_data_failure"), ex); - - refreshGrayState(group); - - return; - } - - showResult(results); - - refreshGrayState(group); - } else if (node != null) { - Instance instance = (Instance) node.getUserObject(); - - String result = null; - try { - result = ServiceController.versionClear(instance, pushAsyncModeRadioButtonMenuItem.isSelected()); - } catch (Exception ex) { - JExceptionDialog.traceException(HandleManager.getFrame(ServiceTopology.this), ConsoleLocale.getString("query_data_failure"), ex); - - refreshGrayState(node); - - return; - } - - showResult(result); - - refreshGrayState(node); - } - } - }; - - return action; - } - - private JSecurityAction createUpdateRuleAction() { - JSecurityAction action = new JSecurityAction(ConsoleLocale.getString("button_update_rule"), ConsoleIconFactory.getSwingIcon("save.png"), ConsoleLocale.getString("button_update_rule")) { - private static final long serialVersionUID = 1L; - - public void execute(ActionEvent e) { - String dynamicRule = dynamicRuleTextArea.getText(); - if (StringUtils.isEmpty(dynamicRule)) { - JBasicOptionPane.showMessageDialog(HandleManager.getFrame(ServiceTopology.this), ConsoleLocale.getString("gray_rule_not_null"), SwingLocale.getString("warning"), JBasicOptionPane.WARNING_MESSAGE); - - return; - } - - if (group != null) { - String serviceId = group.getUserObject().toString(); - - if (ruleToConfigCenterRadioButtonMenuItem.isSelected()) { - String filter = getFilter(group); - String result = null; - try { - result = ServiceController.remoteConfigUpdate(filter, serviceId, dynamicRule); - } catch (Exception ex) { - JExceptionDialog.traceException(HandleManager.getFrame(ServiceTopology.this), ConsoleLocale.getString("query_data_failure"), ex); - - refreshGrayState(group); - - return; - } - - showResult(result); - } else { - List results = null; - try { - results = ServiceController.configUpdate(serviceId, dynamicRule, pushAsyncModeRadioButtonMenuItem.isSelected()); - } catch (Exception ex) { - JExceptionDialog.traceException(HandleManager.getFrame(ServiceTopology.this), ConsoleLocale.getString("query_data_failure"), ex); - - refreshGrayState(group); - - return; - } - - showResult(results); - } - - refreshGrayState(group); - } else if (node != null) { - Instance instance = (Instance) node.getUserObject(); - - String result = null; - try { - result = ServiceController.configUpdate(instance, dynamicRule, pushAsyncModeRadioButtonMenuItem.isSelected()); - } catch (Exception ex) { - JExceptionDialog.traceException(HandleManager.getFrame(ServiceTopology.this), ConsoleLocale.getString("query_data_failure"), ex); - - refreshGrayState(node); - - return; - } - - showResult(result); - - refreshGrayState(node); - } - } - }; - - return action; - } - - private JSecurityAction createClearRuleAction() { - JSecurityAction action = new JSecurityAction(ConsoleLocale.getString("button_clear_rule"), ConsoleIconFactory.getSwingIcon("paint.png"), ConsoleLocale.getString("button_clear_rule")) { - private static final long serialVersionUID = 1L; - - public void execute(ActionEvent e) { - if (group != null) { - String serviceId = group.getUserObject().toString(); - if (ruleToConfigCenterRadioButtonMenuItem.isSelected()) { - String filter = getFilter(group); - String result = null; - try { - result = ServiceController.remoteConfigClear(filter, serviceId); - } catch (Exception ex) { - JExceptionDialog.traceException(HandleManager.getFrame(ServiceTopology.this), ConsoleLocale.getString("query_data_failure"), ex); - - refreshGrayState(group); - - return; - } - - showResult(result); - } else { - List results = null; - try { - results = ServiceController.configClear(serviceId, pushAsyncModeRadioButtonMenuItem.isSelected()); - } catch (Exception ex) { - JExceptionDialog.traceException(HandleManager.getFrame(ServiceTopology.this), ConsoleLocale.getString("query_data_failure"), ex); - - refreshGrayState(group); - - return; - } - - showResult(results); - } - - refreshGrayState(group); - } else if (node != null) { - Instance instance = (Instance) node.getUserObject(); - - String result = null; - try { - result = ServiceController.configClear(instance, pushAsyncModeRadioButtonMenuItem.isSelected()); - } catch (Exception ex) { - JExceptionDialog.traceException(HandleManager.getFrame(ServiceTopology.this), ConsoleLocale.getString("query_data_failure"), ex); - - refreshGrayState(node); - - return; - } - - showResult(result); - - refreshGrayState(node); - } - } - }; - - return action; - } - } - - private class LayoutDialog extends JOptionDialog { - private static final long serialVersionUID = 1L; - - private JNumberTextField groupStartXTextField; - private JNumberTextField groupStartYTextField; - private JNumberTextField groupHorizontalGapTextField; - private JNumberTextField groupVerticalGapTextField; - - private JNumberTextField nodeStartXTextField; - private JNumberTextField nodeStartYTextField; - private JNumberTextField nodeHorizontalGapTextField; - private JNumberTextField nodeVerticalGapTextField; - - public LayoutDialog() { - super(HandleManager.getFrame(ServiceTopology.this), SwingLocale.getString("layout"), new Dimension(500, 330), true, false, true); - - groupStartXTextField = new JNumberTextField(4, 0, 0, 10000); - groupStartYTextField = new JNumberTextField(4, 0, 0, 10000); - groupHorizontalGapTextField = new JNumberTextField(4, 0, 0, 10000); - groupVerticalGapTextField = new JNumberTextField(4, 0, 0, 10000); - - nodeStartXTextField = new JNumberTextField(4, 0, 0, 10000); - nodeStartYTextField = new JNumberTextField(4, 0, 0, 10000); - nodeHorizontalGapTextField = new JNumberTextField(4, 0, 0, 10000); - nodeVerticalGapTextField = new JNumberTextField(4, 0, 0, 10000); - - double[][] size = { - { 100, TableLayout.FILL, 100, TableLayout.FILL }, - { TableLayout.PREFERRED, TableLayout.PREFERRED } - }; - - TableLayout tableLayout = new TableLayout(size); - tableLayout.setHGap(5); - tableLayout.setVGap(5); - - JPanel groupPanel = new JPanel(); - groupPanel.setLayout(tableLayout); - groupPanel.setBorder(UIFactory.createTitledBorder(ConsoleLocale.getString("group_layout"))); - groupPanel.add(new JBasicLabel(ConsoleLocale.getString("start_x")), "0, 0"); - groupPanel.add(groupStartXTextField, "1, 0"); - groupPanel.add(new JBasicLabel(ConsoleLocale.getString("start_y")), "2, 0"); - groupPanel.add(groupStartYTextField, "3, 0"); - groupPanel.add(new JBasicLabel(ConsoleLocale.getString("horizontal_gap")), "0, 1"); - groupPanel.add(groupHorizontalGapTextField, "1, 1"); - groupPanel.add(new JBasicLabel(ConsoleLocale.getString("vertical_gap")), "2, 1"); - groupPanel.add(groupVerticalGapTextField, "3, 1"); - - JPanel nodePanel = new JPanel(); - nodePanel.setLayout(tableLayout); - nodePanel.setBorder(UIFactory.createTitledBorder(ConsoleLocale.getString("node_layout"))); - nodePanel.add(new JBasicLabel(ConsoleLocale.getString("start_x")), "0, 0"); - nodePanel.add(nodeStartXTextField, "1, 0"); - nodePanel.add(new JBasicLabel(ConsoleLocale.getString("start_y")), "2, 0"); - nodePanel.add(nodeStartYTextField, "3, 0"); - nodePanel.add(new JBasicLabel(ConsoleLocale.getString("horizontal_gap")), "0, 1"); - nodePanel.add(nodeHorizontalGapTextField, "1, 1"); - nodePanel.add(new JBasicLabel(ConsoleLocale.getString("vertical_gap")), "2, 1"); - nodePanel.add(nodeVerticalGapTextField, "3, 1"); - - JPanel panel = new JPanel(); - panel.setLayout(new FiledLayout(FiledLayout.COLUMN, FiledLayout.FULL, 5)); - panel.add(groupPanel); - panel.add(nodePanel); - - setOption(YES_NO_OPTION); - setIcon(IconFactory.getSwingIcon("banner/navigator.png")); - setContent(panel); - } - - @Override - public boolean confirm() { - return setFromUI(); - } - - @Override - public boolean cancel() { - return true; - } - - public void setToUI() { - groupStartXTextField.setText(groupLocationEntity.getStartX() + StringUtils.EMPTY); - groupStartYTextField.setText(groupLocationEntity.getStartY() + StringUtils.EMPTY); - groupHorizontalGapTextField.setText(groupLocationEntity.getHorizontalGap() + StringUtils.EMPTY); - groupVerticalGapTextField.setText(groupLocationEntity.getVerticalGap() + StringUtils.EMPTY); - - nodeStartXTextField.setText(nodeLocationEntity.getStartX() + StringUtils.EMPTY); - nodeStartYTextField.setText(nodeLocationEntity.getStartY() + StringUtils.EMPTY); - nodeHorizontalGapTextField.setText(nodeLocationEntity.getHorizontalGap() + StringUtils.EMPTY); - nodeVerticalGapTextField.setText(nodeLocationEntity.getVerticalGap() + StringUtils.EMPTY); - } - - public boolean setFromUI() { - int groupStartX = 0; - int groupStartY = 0; - int groupHorizontalGap = 0; - int groupVerticalGap = 0; - int nodeStartX = 0; - int nodeStartY = 0; - int nodeHorizontalGap = 0; - int nodeVerticalGap = 0; - - try { - groupStartX = Integer.parseInt(groupStartXTextField.getText()); - groupStartY = Integer.parseInt(groupStartYTextField.getText()); - groupHorizontalGap = Integer.parseInt(groupHorizontalGapTextField.getText()); - groupVerticalGap = Integer.parseInt(groupVerticalGapTextField.getText()); - - nodeStartX = Integer.parseInt(nodeStartXTextField.getText()); - nodeStartY = Integer.parseInt(nodeStartYTextField.getText()); - nodeHorizontalGap = Integer.parseInt(nodeHorizontalGapTextField.getText()); - nodeVerticalGap = Integer.parseInt(nodeVerticalGapTextField.getText()); - } catch (NumberFormatException e) { - return false; - } - - groupLocationEntity.setStartX(groupStartX); - groupLocationEntity.setStartY(groupStartY); - groupLocationEntity.setHorizontalGap(groupHorizontalGap); - groupLocationEntity.setVerticalGap(groupVerticalGap); - - nodeLocationEntity.setStartX(nodeStartX); - nodeLocationEntity.setStartY(nodeStartY); - nodeLocationEntity.setHorizontalGap(nodeHorizontalGap); - nodeLocationEntity.setVerticalGap(nodeVerticalGap); - - return true; - } - } -} \ No newline at end of file diff --git a/discovery-console-desktop/src/main/java/com/nepxion/discovery/console/desktop/workspace/topology/AbstractTopology.java b/discovery-console-desktop/src/main/java/com/nepxion/discovery/console/desktop/workspace/topology/AbstractTopology.java deleted file mode 100644 index c5ef14532f..0000000000 --- a/discovery-console-desktop/src/main/java/com/nepxion/discovery/console/desktop/workspace/topology/AbstractTopology.java +++ /dev/null @@ -1,304 +0,0 @@ -package com.nepxion.discovery.console.desktop.workspace.topology; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import twaver.GeoCoordinate; -import twaver.Node; -import twaver.TDataBox; -import twaver.TView; -import twaver.gis.GeographyMap; - -import java.awt.BorderLayout; -import java.awt.Color; -import java.awt.Font; -import java.awt.Point; -import java.awt.event.ActionEvent; -import java.awt.event.MouseEvent; - -import javax.swing.JPanel; -import javax.swing.JPopupMenu; - -import com.nepxion.cots.twaver.element.TElementManager; -import com.nepxion.cots.twaver.element.TGroup; -import com.nepxion.cots.twaver.element.TLink; -import com.nepxion.cots.twaver.element.TNode; -import com.nepxion.cots.twaver.gis.TGisGraph; -import com.nepxion.cots.twaver.graph.TGraph; -import com.nepxion.cots.twaver.graph.TGraphBackground; -import com.nepxion.cots.twaver.graph.TGraphController; -import com.nepxion.cots.twaver.graph.TGraphPointBackground; -import com.nepxion.cots.twaver.graph.TGraphPopupMenuGenerator; -import com.nepxion.cots.twaver.locale.TLocale; -import com.nepxion.discovery.console.desktop.context.UIContext; -import com.nepxion.discovery.console.desktop.icon.ConsoleIconFactory; -import com.nepxion.swing.action.JSecurityAction; -import com.nepxion.swing.button.JClassicMenuButton; -import com.nepxion.swing.locale.SwingLocale; -import com.nepxion.swing.menuitem.JBasicMenuItem; -import com.nepxion.swing.menuitem.JBasicRadioButtonMenuItem; -import com.nepxion.swing.popupmenu.JBasicPopupMenu; - -public abstract class AbstractTopology extends JPanel { - private static final long serialVersionUID = 1L; - - public static final String IMAGE_FOLDER = "/" + ConsoleIconFactory.ICON_FOLDER; - - protected TGraph graph; - protected TDataBox dataBox = new TDataBox(); - - protected JBasicPopupMenu popupMenu; - protected JBasicMenuItem pinSelectedGroupMenuItem; - protected JBasicMenuItem pinSelectedNodeMenuItem; - - protected JBasicRadioButtonMenuItem groupAutoExpandRadioButtonMenuItem; - protected JBasicRadioButtonMenuItem linkAutoHideRadioButtonMenuItem; - - public AbstractTopology() { - setLayout(new BorderLayout()); - add(createGraph()); - // add(createGisGraph()); - - initializePopupMenu(); - } - - protected TGraph createGraph() { - if (graph == null) { - graph = new TGraph(); - graph.setDataBox(dataBox); - graph.setGraphBackground(createBackground()); - graph.getControlBarInternalFrame().setVisible(false); - } - - return graph; - } - - protected TGraph createGisGraph() { - if (graph == null) { - graph = new TGisGraph(); - graph.setDataBox(dataBox); - graph.getControlBarInternalFrame().setVisible(false); - - final TGisGraph gisGraph = (TGisGraph) graph; - GeographyMap map = gisGraph.getMap(); - map.setZoom(16); - map.setCenterPoint(new GeoCoordinate(118.795896, 32.088683)); - } - - return graph; - } - - protected TGraph getGraph() { - return graph; - } - - protected TGraphBackground createBackground() { - return createBackground(null); - } - - protected TGraphBackground createBackground(String title) { - TGraphBackground background = new TGraphBackground(Color.white, TGraphBackground.BLUE_STYLE_COLOR); - // TGraphBackground background = new TGraphBackground(Color.cyan, Color.black); - // background.setGradientFactory(TWaverConst.GRADIENT_LINE_S); - background.setTitleAlignment(TGraphPointBackground.TOP); - background.setTitle(title); - - return background; - } - - protected void initializePopupMenu() { - popupMenu = new JBasicPopupMenu(); - - pinSelectedGroupMenuItem = new JBasicMenuItem(TGraphController.getPinSelectedGroupAction(dataBox)); - popupMenu.add(pinSelectedGroupMenuItem); - - pinSelectedNodeMenuItem = new JBasicMenuItem(TGraphController.getPinSelectedNodeAction(dataBox)); - popupMenu.add(pinSelectedNodeMenuItem); - - new TGraphPopupMenuGenerator(graph) { - @Override - public JPopupMenu generate(TView view, MouseEvent event) { - return popupMenuGenerate(); - } - }; - } - - protected JBasicPopupMenu popupMenuGenerate() { - TGroup group = TElementManager.getSelectedGroup(dataBox); - pinSelectedGroupMenuItem.setVisible(group != null); - - TNode node = TElementManager.getSelectedNode(dataBox); - pinSelectedNodeMenuItem.setVisible(node != null); - - if (group != null || node != null) { - return popupMenu; - } - - return null; - } - - protected JClassicMenuButton createConfigButton(boolean linkConfig) { - JBasicPopupMenu popupMenu = new JBasicPopupMenu(); - - JSecurityAction showLayoutAction = createShowLayoutAction(); - popupMenu.add(new JBasicMenuItem(showLayoutAction)); - - popupMenu.addSeparator(); - - JSecurityAction groupExpandAction = TGraphController.getGroupExpandAction(graph); - groupExpandAction.setIcon(ConsoleIconFactory.getSwingIcon("rectangle_multi.png")); - popupMenu.add(new JBasicMenuItem(groupExpandAction)); - - JSecurityAction groupCollapseAction = TGraphController.getGroupCollapseAction(graph); - groupCollapseAction.setIcon(ConsoleIconFactory.getSwingIcon("rectangle_single.png")); - popupMenu.add(new JBasicMenuItem(groupCollapseAction)); - - groupAutoExpandRadioButtonMenuItem = new JBasicRadioButtonMenuItem(TLocale.getString("group_expand_auto"), TLocale.getString("group_expand_auto")); - popupMenu.add(groupAutoExpandRadioButtonMenuItem); - - if (linkConfig) { - popupMenu.addSeparator(); - - JSecurityAction linkShowAction = TGraphController.getLinkShowAction(graph); - linkShowAction.setIcon(ConsoleIconFactory.getSwingIcon("netbean/arc_16.png")); - popupMenu.add(new JBasicMenuItem(linkShowAction)); - - JSecurityAction linkHideAction = TGraphController.getLinkHideAction(graph); - linkHideAction.setIcon(ConsoleIconFactory.getSwingIcon("netbean/arc_to_16.png")); - popupMenu.add(new JBasicMenuItem(linkHideAction)); - - linkAutoHideRadioButtonMenuItem = new JBasicRadioButtonMenuItem(TLocale.getString("link_hide_auto"), TLocale.getString("link_hide_auto")); - popupMenu.add(linkAutoHideRadioButtonMenuItem); - } - - JClassicMenuButton menuButton = new JClassicMenuButton(SwingLocale.getString("setting"), ConsoleIconFactory.getSwingIcon("property.png"), SwingLocale.getString("setting")); - menuButton.setPopupMenu(popupMenu); - - return menuButton; - } - - private JSecurityAction createShowLayoutAction() { - JSecurityAction action = new JSecurityAction(SwingLocale.getString("layout"), ConsoleIconFactory.getSwingIcon("netbean/clip_view_16.png"), SwingLocale.getString("layout")) { - private static final long serialVersionUID = 1L; - - public void execute(ActionEvent e) { - showLayout(); - } - }; - - return action; - } - - protected void showLayout() { - - } - - protected boolean isGroupAutoExpand() { - if (groupAutoExpandRadioButtonMenuItem == null) { - return false; - } - - return groupAutoExpandRadioButtonMenuItem.isSelected(); - } - - protected void setGroupAutoExpand(boolean expand) { - if (groupAutoExpandRadioButtonMenuItem == null) { - return; - } - - groupAutoExpandRadioButtonMenuItem.setSelected(expand); - } - - protected boolean isLinkAutoHide() { - if (linkAutoHideRadioButtonMenuItem == null) { - return false; - } - - return linkAutoHideRadioButtonMenuItem.isSelected(); - } - - protected void setLinkAutoHide(boolean hide) { - if (linkAutoHideRadioButtonMenuItem == null) { - return; - } - - linkAutoHideRadioButtonMenuItem.setSelected(hide); - } - - protected TGroup createGroup(String name, TopologyEntity topologyEntity, LocationEntity locationEntity, int index) { - String image = topologyEntity.getImage(); - - int startX = locationEntity.getStartX(); - int startY = locationEntity.getStartY(); - int horizontalGap = locationEntity.getHorizontalGap(); - int verticalGap = locationEntity.getVerticalGap(); - Point location = new Point(topologyEntity.isHorizontalPile() ? startX + index * horizontalGap : startX, topologyEntity.isHorizontalPile() ? startY : startY + index * verticalGap); - - return createGroup(name, image, location); - } - - protected TGroup createGroup(String name, TopologyEntity topologyEntity) { - String image = topologyEntity.getImage(); - Point location = topologyEntity.getLocation(); - - return createGroup(name, image, location); - } - - protected TGroup createGroup(String name, String image, Point location) { - TGroup group = new TGroup(); - group.setName(name); - group.setImage(IMAGE_FOLDER + image); - group.putLabelFont(new Font(UIContext.getFontName(), Font.PLAIN, UIContext.getDefaultFontSize())); - group.setLocation(location); - - return group; - } - - protected TNode createNode(String name, TopologyEntity topologyEntity, LocationEntity locationEntity, int index) { - String image = topologyEntity.getImage(); - - int startX = locationEntity.getStartX(); - int startY = locationEntity.getStartY(); - int horizontalGap = locationEntity.getHorizontalGap(); - int verticalGap = locationEntity.getVerticalGap(); - Point location = new Point(topologyEntity.isHorizontalPile() ? startX + index * horizontalGap : startX, topologyEntity.isHorizontalPile() ? startY : startY + index * verticalGap); - - return createNode(name, image, location); - } - - protected TNode createNode(String name, TopologyEntity topologyEntity) { - String image = topologyEntity.getImage(); - Point location = topologyEntity.getLocation(); - - return createNode(name, image, location); - } - - protected TNode createNode(String name, String image, Point location) { - TNode node = new TNode(); - node.setName(name); - node.setImage(IMAGE_FOLDER + image); - node.putLabelFont(new Font(UIContext.getFontName(), Font.PLAIN, UIContext.getSmallFontSize())); - node.setLocation(location); - - return node; - } - - protected TLink createLink(Node fromNode, Node toNode) { - return createLink(fromNode, toNode, false); - } - - protected TLink createLink(Node fromNode, Node toNode, boolean toArrow) { - TLink link = new TLink(fromNode, toNode); - link.putLinkToArrow(toArrow); - link.putLabelYOffset(-2); - link.putLabelFont(new Font(UIContext.getFontName(), Font.PLAIN, UIContext.getSmallFontSize())); - - return link; - } -} \ No newline at end of file diff --git a/discovery-console-desktop/src/main/java/com/nepxion/discovery/console/desktop/workspace/topology/LocationEntity.java b/discovery-console-desktop/src/main/java/com/nepxion/discovery/console/desktop/workspace/topology/LocationEntity.java deleted file mode 100644 index ff1e5e5a0b..0000000000 --- a/discovery-console-desktop/src/main/java/com/nepxion/discovery/console/desktop/workspace/topology/LocationEntity.java +++ /dev/null @@ -1,56 +0,0 @@ -package com.nepxion.discovery.console.desktop.workspace.topology; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -public class LocationEntity { - private int startX; - private int startY; - private int horizontalGap; - private int verticalGap; - - public LocationEntity(int startX, int startY, int horizontalGap, int verticalGap) { - this.startX = startX; - this.startY = startY; - this.horizontalGap = horizontalGap; - this.verticalGap = verticalGap; - } - - public int getStartX() { - return startX; - } - - public void setStartX(int startX) { - this.startX = startX; - } - - public int getStartY() { - return startY; - } - - public void setStartY(int startY) { - this.startY = startY; - } - - public int getHorizontalGap() { - return horizontalGap; - } - - public void setHorizontalGap(int horizontalGap) { - this.horizontalGap = horizontalGap; - } - - public int getVerticalGap() { - return verticalGap; - } - - public void setVerticalGap(int verticalGap) { - this.verticalGap = verticalGap; - } -} \ No newline at end of file diff --git a/discovery-console-desktop/src/main/java/com/nepxion/discovery/console/desktop/workspace/topology/TopologyEntity.java b/discovery-console-desktop/src/main/java/com/nepxion/discovery/console/desktop/workspace/topology/TopologyEntity.java deleted file mode 100644 index d1626ef1fd..0000000000 --- a/discovery-console-desktop/src/main/java/com/nepxion/discovery/console/desktop/workspace/topology/TopologyEntity.java +++ /dev/null @@ -1,163 +0,0 @@ -package com.nepxion.discovery.console.desktop.workspace.topology; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import java.awt.Point; - -public class TopologyEntity { - public static final String THEME_DIRECTORY = "theme_1/"; - - public static final String SERVICE_GROUP_LARGE_IMAGE = "service_group_80.png"; - public static final String SERVICE_GROUP_MIDDLE_IMAGE = "service_group_64.png"; - public static final String SERVICE_GROUP_SMALL_IMAGE = "service_group_48.png"; - - public static final String REFERENCE_GROUP_LARGE_IMAGE = "reference_group_80.png"; - public static final String REFERENCE_GROUP_MIDDLE_IMAGE = "reference_group_64.png"; - public static final String REFERENCE_GROUP_SMALL_IMAGE = "reference_group_48.png"; - - public static final String GATEWAY_GROUP_LARGE_IMAGE = "gateway_group_80.png"; - public static final String GATEWAY_GROUP_MIDDLE_IMAGE = "gateway_group_64.png"; - public static final String GATEWAY_GROUP_SMALL_IMAGE = "gateway_group_48.png"; - - public static final String SERVICE_LARGE_IMAGE = THEME_DIRECTORY + "service_64.png"; - public static final String SERVICE_MIDDLE_IMAGE = THEME_DIRECTORY + "service_48.png"; - public static final String SERVICE_SMALL_IMAGE = THEME_DIRECTORY + "service_32.png"; - - public static final String REFERENCE_LARGE_IMAGE = THEME_DIRECTORY + "reference_64.png"; - public static final String REFERENCE_MIDDLE_IMAGE = THEME_DIRECTORY + "reference_48.png"; - public static final String REFERENCE_SMALL_IMAGE = THEME_DIRECTORY + "reference_32.png"; - - public static final String GATEWAY_LARGE_IMAGE = THEME_DIRECTORY + "gateway_64.png"; - public static final String GATEWAY_MIDDLE_IMAGE = THEME_DIRECTORY + "gateway_48.png"; - public static final String GATEWAY_SMALL_IMAGE = THEME_DIRECTORY + "gateway_32.png"; - - private TopologyEntityType entityType; - private TopologyStyleType styleType; - private String image; - private Point location; - private boolean horizontalPile; - - public TopologyEntity(TopologyEntityType entityType, TopologyStyleType styleType, Point location) { - initialize(entityType, styleType); - - this.location = location; - } - - public TopologyEntity(TopologyEntityType entityType, TopologyStyleType styleType, boolean horizontalPile) { - initialize(entityType, styleType); - - this.horizontalPile = horizontalPile; - } - - private void initialize(TopologyEntityType entityType, TopologyStyleType styleType) { - this.entityType = entityType; - this.styleType = styleType; - switch (entityType) { - case SERVICE_GROUP: - switch (styleType) { - case LARGE: - image = SERVICE_GROUP_LARGE_IMAGE; - break; - case MIDDLE: - image = SERVICE_GROUP_MIDDLE_IMAGE; - break; - case SMALL: - image = SERVICE_GROUP_SMALL_IMAGE; - break; - } - break; - case REFERENCE_GROUP: - switch (styleType) { - case LARGE: - image = REFERENCE_GROUP_LARGE_IMAGE; - break; - case MIDDLE: - image = REFERENCE_GROUP_MIDDLE_IMAGE; - break; - case SMALL: - image = REFERENCE_GROUP_SMALL_IMAGE; - break; - } - break; - case GATEWAY_GROUP: - switch (styleType) { - case LARGE: - image = GATEWAY_GROUP_LARGE_IMAGE; - break; - case MIDDLE: - image = GATEWAY_GROUP_MIDDLE_IMAGE; - break; - case SMALL: - image = GATEWAY_GROUP_SMALL_IMAGE; - break; - } - break; - case SERVICE: - switch (styleType) { - case LARGE: - image = SERVICE_LARGE_IMAGE; - break; - case MIDDLE: - image = SERVICE_MIDDLE_IMAGE; - break; - case SMALL: - image = SERVICE_SMALL_IMAGE; - break; - } - break; - case REFERENCE: - switch (styleType) { - case LARGE: - image = REFERENCE_LARGE_IMAGE; - break; - case MIDDLE: - image = REFERENCE_MIDDLE_IMAGE; - break; - case SMALL: - image = REFERENCE_SMALL_IMAGE; - break; - } - break; - case GATEWAY: - switch (styleType) { - case LARGE: - image = GATEWAY_LARGE_IMAGE; - break; - case MIDDLE: - image = GATEWAY_MIDDLE_IMAGE; - break; - case SMALL: - image = GATEWAY_SMALL_IMAGE; - break; - } - break; - } - } - - public TopologyEntityType getEntityType() { - return entityType; - } - - public TopologyStyleType getStyleType() { - return styleType; - } - - public String getImage() { - return image; - } - - public Point getLocation() { - return location; - } - - public boolean isHorizontalPile() { - return horizontalPile; - } -} \ No newline at end of file diff --git a/discovery-console-desktop/src/main/java/com/nepxion/discovery/console/desktop/workspace/topology/TopologyEntityType.java b/discovery-console-desktop/src/main/java/com/nepxion/discovery/console/desktop/workspace/topology/TopologyEntityType.java deleted file mode 100644 index 9f66fce947..0000000000 --- a/discovery-console-desktop/src/main/java/com/nepxion/discovery/console/desktop/workspace/topology/TopologyEntityType.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.nepxion.discovery.console.desktop.workspace.topology; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -public enum TopologyEntityType { - SERVICE_GROUP, - REFERENCE_GROUP, - GATEWAY_GROUP, - SERVICE, - REFERENCE, - GATEWAY -} \ No newline at end of file diff --git a/discovery-console-desktop/src/main/java/com/nepxion/discovery/console/desktop/workspace/topology/TopologyStyleType.java b/discovery-console-desktop/src/main/java/com/nepxion/discovery/console/desktop/workspace/topology/TopologyStyleType.java deleted file mode 100644 index e641bf49ef..0000000000 --- a/discovery-console-desktop/src/main/java/com/nepxion/discovery/console/desktop/workspace/topology/TopologyStyleType.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.nepxion.discovery.console.desktop.workspace.topology; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -public enum TopologyStyleType { - LARGE, - MIDDLE, - SMALL -} \ No newline at end of file diff --git a/discovery-console-desktop/src/main/resources/com/nepxion/discovery/console/desktop/icon/gateway_group_32.png b/discovery-console-desktop/src/main/resources/com/nepxion/discovery/console/desktop/icon/gateway_group_32.png deleted file mode 100644 index 50c14c5d35..0000000000 Binary files a/discovery-console-desktop/src/main/resources/com/nepxion/discovery/console/desktop/icon/gateway_group_32.png and /dev/null differ diff --git a/discovery-console-desktop/src/main/resources/com/nepxion/discovery/console/desktop/icon/gateway_group_48.png b/discovery-console-desktop/src/main/resources/com/nepxion/discovery/console/desktop/icon/gateway_group_48.png deleted file mode 100644 index ddb163db3b..0000000000 Binary files a/discovery-console-desktop/src/main/resources/com/nepxion/discovery/console/desktop/icon/gateway_group_48.png and /dev/null differ diff --git a/discovery-console-desktop/src/main/resources/com/nepxion/discovery/console/desktop/icon/gateway_group_64.png b/discovery-console-desktop/src/main/resources/com/nepxion/discovery/console/desktop/icon/gateway_group_64.png deleted file mode 100644 index 164d08ed63..0000000000 Binary files a/discovery-console-desktop/src/main/resources/com/nepxion/discovery/console/desktop/icon/gateway_group_64.png and /dev/null differ diff --git a/discovery-console-desktop/src/main/resources/com/nepxion/discovery/console/desktop/icon/gateway_group_80.png b/discovery-console-desktop/src/main/resources/com/nepxion/discovery/console/desktop/icon/gateway_group_80.png deleted file mode 100644 index 64fe9761e0..0000000000 Binary files a/discovery-console-desktop/src/main/resources/com/nepxion/discovery/console/desktop/icon/gateway_group_80.png and /dev/null differ diff --git a/discovery-console-desktop/src/main/resources/com/nepxion/discovery/console/desktop/icon/reference_group_32.png b/discovery-console-desktop/src/main/resources/com/nepxion/discovery/console/desktop/icon/reference_group_32.png deleted file mode 100644 index 2a86a3f1d0..0000000000 Binary files a/discovery-console-desktop/src/main/resources/com/nepxion/discovery/console/desktop/icon/reference_group_32.png and /dev/null differ diff --git a/discovery-console-desktop/src/main/resources/com/nepxion/discovery/console/desktop/icon/reference_group_48.png b/discovery-console-desktop/src/main/resources/com/nepxion/discovery/console/desktop/icon/reference_group_48.png deleted file mode 100644 index 1510961ec8..0000000000 Binary files a/discovery-console-desktop/src/main/resources/com/nepxion/discovery/console/desktop/icon/reference_group_48.png and /dev/null differ diff --git a/discovery-console-desktop/src/main/resources/com/nepxion/discovery/console/desktop/icon/reference_group_64.png b/discovery-console-desktop/src/main/resources/com/nepxion/discovery/console/desktop/icon/reference_group_64.png deleted file mode 100644 index 38288bad36..0000000000 Binary files a/discovery-console-desktop/src/main/resources/com/nepxion/discovery/console/desktop/icon/reference_group_64.png and /dev/null differ diff --git a/discovery-console-desktop/src/main/resources/com/nepxion/discovery/console/desktop/icon/reference_group_80.png b/discovery-console-desktop/src/main/resources/com/nepxion/discovery/console/desktop/icon/reference_group_80.png deleted file mode 100644 index 1eb98d8582..0000000000 Binary files a/discovery-console-desktop/src/main/resources/com/nepxion/discovery/console/desktop/icon/reference_group_80.png and /dev/null differ diff --git a/discovery-console-desktop/src/main/resources/com/nepxion/discovery/console/desktop/icon/service_group_32.png b/discovery-console-desktop/src/main/resources/com/nepxion/discovery/console/desktop/icon/service_group_32.png deleted file mode 100644 index 2a86a3f1d0..0000000000 Binary files a/discovery-console-desktop/src/main/resources/com/nepxion/discovery/console/desktop/icon/service_group_32.png and /dev/null differ diff --git a/discovery-console-desktop/src/main/resources/com/nepxion/discovery/console/desktop/icon/service_group_48.png b/discovery-console-desktop/src/main/resources/com/nepxion/discovery/console/desktop/icon/service_group_48.png deleted file mode 100644 index 1510961ec8..0000000000 Binary files a/discovery-console-desktop/src/main/resources/com/nepxion/discovery/console/desktop/icon/service_group_48.png and /dev/null differ diff --git a/discovery-console-desktop/src/main/resources/com/nepxion/discovery/console/desktop/icon/service_group_64.png b/discovery-console-desktop/src/main/resources/com/nepxion/discovery/console/desktop/icon/service_group_64.png deleted file mode 100644 index 38288bad36..0000000000 Binary files a/discovery-console-desktop/src/main/resources/com/nepxion/discovery/console/desktop/icon/service_group_64.png and /dev/null differ diff --git a/discovery-console-desktop/src/main/resources/com/nepxion/discovery/console/desktop/icon/service_group_80.png b/discovery-console-desktop/src/main/resources/com/nepxion/discovery/console/desktop/icon/service_group_80.png deleted file mode 100644 index 1eb98d8582..0000000000 Binary files a/discovery-console-desktop/src/main/resources/com/nepxion/discovery/console/desktop/icon/service_group_80.png and /dev/null differ diff --git a/discovery-console-desktop/src/main/resources/com/nepxion/discovery/console/desktop/icon/theme_1/gateway_32.png b/discovery-console-desktop/src/main/resources/com/nepxion/discovery/console/desktop/icon/theme_1/gateway_32.png deleted file mode 100644 index 2013a378f4..0000000000 Binary files a/discovery-console-desktop/src/main/resources/com/nepxion/discovery/console/desktop/icon/theme_1/gateway_32.png and /dev/null differ diff --git a/discovery-console-desktop/src/main/resources/com/nepxion/discovery/console/desktop/icon/theme_1/gateway_48.png b/discovery-console-desktop/src/main/resources/com/nepxion/discovery/console/desktop/icon/theme_1/gateway_48.png deleted file mode 100644 index 43283426aa..0000000000 Binary files a/discovery-console-desktop/src/main/resources/com/nepxion/discovery/console/desktop/icon/theme_1/gateway_48.png and /dev/null differ diff --git a/discovery-console-desktop/src/main/resources/com/nepxion/discovery/console/desktop/icon/theme_1/gateway_64.png b/discovery-console-desktop/src/main/resources/com/nepxion/discovery/console/desktop/icon/theme_1/gateway_64.png deleted file mode 100644 index c0618778ba..0000000000 Binary files a/discovery-console-desktop/src/main/resources/com/nepxion/discovery/console/desktop/icon/theme_1/gateway_64.png and /dev/null differ diff --git a/discovery-console-desktop/src/main/resources/com/nepxion/discovery/console/desktop/icon/theme_1/reference_32.png b/discovery-console-desktop/src/main/resources/com/nepxion/discovery/console/desktop/icon/theme_1/reference_32.png deleted file mode 100644 index c5c0cb4abd..0000000000 Binary files a/discovery-console-desktop/src/main/resources/com/nepxion/discovery/console/desktop/icon/theme_1/reference_32.png and /dev/null differ diff --git a/discovery-console-desktop/src/main/resources/com/nepxion/discovery/console/desktop/icon/theme_1/reference_48.png b/discovery-console-desktop/src/main/resources/com/nepxion/discovery/console/desktop/icon/theme_1/reference_48.png deleted file mode 100644 index 7adf4b1514..0000000000 Binary files a/discovery-console-desktop/src/main/resources/com/nepxion/discovery/console/desktop/icon/theme_1/reference_48.png and /dev/null differ diff --git a/discovery-console-desktop/src/main/resources/com/nepxion/discovery/console/desktop/icon/theme_1/reference_64.png b/discovery-console-desktop/src/main/resources/com/nepxion/discovery/console/desktop/icon/theme_1/reference_64.png deleted file mode 100644 index 9cd8cd96e0..0000000000 Binary files a/discovery-console-desktop/src/main/resources/com/nepxion/discovery/console/desktop/icon/theme_1/reference_64.png and /dev/null differ diff --git a/discovery-console-desktop/src/main/resources/com/nepxion/discovery/console/desktop/icon/theme_1/service_32.png b/discovery-console-desktop/src/main/resources/com/nepxion/discovery/console/desktop/icon/theme_1/service_32.png deleted file mode 100644 index e8623f438a..0000000000 Binary files a/discovery-console-desktop/src/main/resources/com/nepxion/discovery/console/desktop/icon/theme_1/service_32.png and /dev/null differ diff --git a/discovery-console-desktop/src/main/resources/com/nepxion/discovery/console/desktop/icon/theme_1/service_48.png b/discovery-console-desktop/src/main/resources/com/nepxion/discovery/console/desktop/icon/theme_1/service_48.png deleted file mode 100644 index 643e1536b8..0000000000 Binary files a/discovery-console-desktop/src/main/resources/com/nepxion/discovery/console/desktop/icon/theme_1/service_48.png and /dev/null differ diff --git a/discovery-console-desktop/src/main/resources/com/nepxion/discovery/console/desktop/icon/theme_1/service_64.png b/discovery-console-desktop/src/main/resources/com/nepxion/discovery/console/desktop/icon/theme_1/service_64.png deleted file mode 100644 index 5ad30eb558..0000000000 Binary files a/discovery-console-desktop/src/main/resources/com/nepxion/discovery/console/desktop/icon/theme_1/service_64.png and /dev/null differ diff --git a/discovery-console-desktop/src/main/resources/com/nepxion/discovery/console/desktop/icon/theme_2/gateway_32.png b/discovery-console-desktop/src/main/resources/com/nepxion/discovery/console/desktop/icon/theme_2/gateway_32.png deleted file mode 100644 index 0cce2a9815..0000000000 Binary files a/discovery-console-desktop/src/main/resources/com/nepxion/discovery/console/desktop/icon/theme_2/gateway_32.png and /dev/null differ diff --git a/discovery-console-desktop/src/main/resources/com/nepxion/discovery/console/desktop/icon/theme_2/gateway_48.png b/discovery-console-desktop/src/main/resources/com/nepxion/discovery/console/desktop/icon/theme_2/gateway_48.png deleted file mode 100644 index a46628d270..0000000000 Binary files a/discovery-console-desktop/src/main/resources/com/nepxion/discovery/console/desktop/icon/theme_2/gateway_48.png and /dev/null differ diff --git a/discovery-console-desktop/src/main/resources/com/nepxion/discovery/console/desktop/icon/theme_2/gateway_64.png b/discovery-console-desktop/src/main/resources/com/nepxion/discovery/console/desktop/icon/theme_2/gateway_64.png deleted file mode 100644 index 0b84e35bce..0000000000 Binary files a/discovery-console-desktop/src/main/resources/com/nepxion/discovery/console/desktop/icon/theme_2/gateway_64.png and /dev/null differ diff --git a/discovery-console-desktop/src/main/resources/com/nepxion/discovery/console/desktop/icon/theme_2/reference_32.png b/discovery-console-desktop/src/main/resources/com/nepxion/discovery/console/desktop/icon/theme_2/reference_32.png deleted file mode 100644 index 731cd4781b..0000000000 Binary files a/discovery-console-desktop/src/main/resources/com/nepxion/discovery/console/desktop/icon/theme_2/reference_32.png and /dev/null differ diff --git a/discovery-console-desktop/src/main/resources/com/nepxion/discovery/console/desktop/icon/theme_2/reference_48.png b/discovery-console-desktop/src/main/resources/com/nepxion/discovery/console/desktop/icon/theme_2/reference_48.png deleted file mode 100644 index b412298eb7..0000000000 Binary files a/discovery-console-desktop/src/main/resources/com/nepxion/discovery/console/desktop/icon/theme_2/reference_48.png and /dev/null differ diff --git a/discovery-console-desktop/src/main/resources/com/nepxion/discovery/console/desktop/icon/theme_2/reference_64.png b/discovery-console-desktop/src/main/resources/com/nepxion/discovery/console/desktop/icon/theme_2/reference_64.png deleted file mode 100644 index 2eb51ffa24..0000000000 Binary files a/discovery-console-desktop/src/main/resources/com/nepxion/discovery/console/desktop/icon/theme_2/reference_64.png and /dev/null differ diff --git a/discovery-console-desktop/src/main/resources/com/nepxion/discovery/console/desktop/icon/theme_2/service_32.png b/discovery-console-desktop/src/main/resources/com/nepxion/discovery/console/desktop/icon/theme_2/service_32.png deleted file mode 100644 index 289ad54a0b..0000000000 Binary files a/discovery-console-desktop/src/main/resources/com/nepxion/discovery/console/desktop/icon/theme_2/service_32.png and /dev/null differ diff --git a/discovery-console-desktop/src/main/resources/com/nepxion/discovery/console/desktop/icon/theme_2/service_48.png b/discovery-console-desktop/src/main/resources/com/nepxion/discovery/console/desktop/icon/theme_2/service_48.png deleted file mode 100644 index c10d02dd05..0000000000 Binary files a/discovery-console-desktop/src/main/resources/com/nepxion/discovery/console/desktop/icon/theme_2/service_48.png and /dev/null differ diff --git a/discovery-console-desktop/src/main/resources/com/nepxion/discovery/console/desktop/icon/theme_2/service_64.png b/discovery-console-desktop/src/main/resources/com/nepxion/discovery/console/desktop/icon/theme_2/service_64.png deleted file mode 100644 index 0b383968de..0000000000 Binary files a/discovery-console-desktop/src/main/resources/com/nepxion/discovery/console/desktop/icon/theme_2/service_64.png and /dev/null differ diff --git a/discovery-console-desktop/src/main/resources/com/nepxion/discovery/console/desktop/locale/Locale.bat b/discovery-console-desktop/src/main/resources/com/nepxion/discovery/console/desktop/locale/Locale.bat deleted file mode 100644 index 93dd778d2d..0000000000 --- a/discovery-console-desktop/src/main/resources/com/nepxion/discovery/console/desktop/locale/Locale.bat +++ /dev/null @@ -1,26 +0,0 @@ -@echo on -@echo ============================================================= -@echo $ $ -@echo $ Encoding localizer $ -@echo $ $ -@echo $ $ -@echo $ $ -@echo $ Nepxion Technologies All Right Reserved $ -@echo $ Copyright(C) 2015 $ -@echo $ $ -@echo ============================================================= -@echo. -@echo off - -@rem ====================================== -@rem DOS Batch file to invoke the Swing UI -@rem ====================================== - -@title Encoding localizer -@color 0a - -rem if "%JAVA_HOME%"=="" goto noJava - -if "%JAVA_HOME%"=="" set JAVA_HOME=D:\JDK1.6.0 - -%JAVA_HOME%\bin\native2ascii -encoding gbk Locale.properties Locale_zh_CN.properties \ No newline at end of file diff --git a/discovery-console-desktop/src/main/resources/com/nepxion/discovery/console/desktop/locale/Locale.properties b/discovery-console-desktop/src/main/resources/com/nepxion/discovery/console/desktop/locale/Locale.properties deleted file mode 100644 index 80d118b757..0000000000 --- a/discovery-console-desktop/src/main/resources/com/nepxion/discovery/console/desktop/locale/Locale.properties +++ /dev/null @@ -1,89 +0,0 @@ -url=ַ̨ - -title=Discovery Ҷȷ̨ -navigator_bar= -content_bar= - -service_control= -service_topology= - -type_service= -type_gateway= - -show_topology=ʾ -execute_gray_release=ִлҶȷ -execute_gray_router=ִлҶ· -refresh_gray_state=ˢ»Ҷ״̬ -push_global_config=ȫ·Ҷȷ -show_metadata=鿴Ԫ -push_control_mode=ģʽ -push_async_mode=첽 -push_sync_mode=ͬ -discovery_center=עᷢ -config_center=Զ -rule_to_config_center=͵Զ -rule_to_service=͵߷Ⱥ - -title_service_cluster_gray_release=ȺҶȷ -service_cluster_filter=Ⱥ - -title_service_gray_router=Ҷ· -service_list=б -add_service=һ -delete_service=ɾһ -execute_router=ִ· -clear_router=· -view_rule=鿴 -router_path_invalid=··Ϊ - -global_group=Ⱥ -global_rule=ȫֹ - -title_gray_version_operation=ҶȰ汾 - ֧͵񣨲־û -title_gray_rule_operation=Ҷȹ - ֧͵񣨲־û֧͵Զģ־û -label_dynamic_version=Ҷȣ̬汾 -label_local_version=ʼأ汾 -label_dynamic_rule=Ҷȣ̬ -label_local_rule=ʼأ -button_update_version=»ҶȰ汾 -button_clear_version=ҶȰ汾 -button_batch_update_version=»ҶȰ汾 -button_batch_clear_version=ҶȰ汾 -button_update_rule=»Ҷȹ -button_clear_rule=Ҷȹ -description_gray_rule_to_config_center=ҶȹĸʽΪXMLĿǰõģʽ [͵Զ]ַֻ֧Ⱥ -description_gray_rule_to_service=ҶȹĸʽΪXMLĿǰõģʽ [͵]ַ֧߷Ⱥ -button_batch_update_rule=»Ҷȹ -button_batch_clear_rule=Ҷȹ -description_gray_version=ҶȰ汾ĸʽΪ[dynamicVersion][dynamicVersion];[localVersion]1.11.1;1.0ǰֱӸ»ҶȰ汾Ϊ1.1ֻǰʼ汾Ϊ1.0ķ»ҶȰ汾Ϊ1.1 -gray_version_not_null=ҶȰ汾Ϊ -gray_rule_not_null=ҶȹΪ - -execute_result=ִн - -get_service_group_failure=ȡбʧ -get_service_instances_failure=ȡʵбʧ -query_data_failure=ѯʧܣʵ -group_not_for_gray_release=÷ȺִлҶȷ -node_not_for_gray_release=÷ִлҶȷ -node_not_for_gray_router=÷ִִлҶ· -group_not_for_refresh_gray_state=÷Ⱥˢ»Ҷ״̬ -node_not_for_refresh_gray_state=÷ˢ»Ҷ״̬ -node_has_no_metadata=÷񲻰Ԫ -not_for_push_global_config=ȫ·Ҷȷֻڡ͵Զġģʽ - -select_a_global_group=ѡһȺ -select_a_group=ѡһȺ -select_a_node=ѡһ -select_a_group_or_node=ѡһ߷Ⱥ - -group_layout=鲼 -node_layout=ڵ㲼 -start_x=ʼX -start_y=ʼY -horizontal_gap=ˮƽ -vertical_gap=ֱ - -not_connnect_to_console=޷ӵƽ̨ -initialize_component=ʼ -initialize_component_failure=ʼʧ \ No newline at end of file diff --git a/discovery-console-desktop/src/main/resources/com/nepxion/discovery/console/desktop/locale/Locale_en_US.properties b/discovery-console-desktop/src/main/resources/com/nepxion/discovery/console/desktop/locale/Locale_en_US.properties deleted file mode 100644 index d4b9bb9761..0000000000 --- a/discovery-console-desktop/src/main/resources/com/nepxion/discovery/console/desktop/locale/Locale_en_US.properties +++ /dev/null @@ -1 +0,0 @@ -url=Console Url \ No newline at end of file diff --git a/discovery-console-desktop/src/main/resources/com/nepxion/discovery/console/desktop/locale/Locale_zh_CN.properties b/discovery-console-desktop/src/main/resources/com/nepxion/discovery/console/desktop/locale/Locale_zh_CN.properties deleted file mode 100644 index 43ba70bd72..0000000000 --- a/discovery-console-desktop/src/main/resources/com/nepxion/discovery/console/desktop/locale/Locale_zh_CN.properties +++ /dev/null @@ -1,89 +0,0 @@ -url=\u63a7\u5236\u53f0\u5730\u5740 - -title=Discovery \u7070\u5ea6\u53d1\u5e03\u63a7\u5236\u53f0 -navigator_bar=\u5bfc\u822a\u533a -content_bar=\u5de5\u4f5c\u533a - -service_control=\u670d\u52a1\u6cbb\u7406 -service_topology=\u670d\u52a1\u62d3\u6251 - -type_service=\u670d\u52a1 -type_gateway=\u7f51\u5173 - -show_topology=\u663e\u793a\u670d\u52a1\u62d3\u6251 -execute_gray_release=\u6267\u884c\u7070\u5ea6\u53d1\u5e03 -execute_gray_router=\u6267\u884c\u7070\u5ea6\u8def\u7531 -refresh_gray_state=\u5237\u65b0\u7070\u5ea6\u72b6\u6001 -push_global_config=\u5168\u94fe\u8def\u7070\u5ea6\u53d1\u5e03 -show_metadata=\u67e5\u770b\u5143\u6570\u636e -push_control_mode=\u63a8\u9001\u6a21\u5f0f\u8bbe\u7f6e -push_async_mode=\u5f02\u6b65\u63a8\u9001 -push_sync_mode=\u540c\u6b65\u63a8\u9001 -discovery_center=\u6ce8\u518c\u53d1\u73b0\u4e2d\u5fc3 -config_center=\u8fdc\u7a0b\u914d\u7f6e\u4e2d\u5fc3 -rule_to_config_center=\u89c4\u5219\u63a8\u9001\u5230\u8fdc\u7a0b\u914d\u7f6e\u4e2d\u5fc3 -rule_to_service=\u89c4\u5219\u63a8\u9001\u5230\u670d\u52a1\u6216\u8005\u670d\u52a1\u96c6\u7fa4 - -title_service_cluster_gray_release=\u670d\u52a1\u96c6\u7fa4\u7070\u5ea6\u53d1\u5e03 -service_cluster_filter=\u670d\u52a1\u96c6\u7fa4\u7ec4\u8fc7\u6ee4 - -title_service_gray_router=\u670d\u52a1\u7070\u5ea6\u8def\u7531 -service_list=\u670d\u52a1\u5217\u8868 -add_service=\u6dfb\u52a0\u4e00\u4e2a\u670d\u52a1 -delete_service=\u5220\u9664\u4e00\u4e2a\u670d\u52a1 -execute_router=\u6267\u884c\u8def\u7531 -clear_router=\u6e05\u9664\u8def\u7531 -view_rule=\u67e5\u770b\u89c4\u5219 -router_path_invalid=\u8def\u7531\u8def\u5f84\u4e0d\u80fd\u4e3a\u7a7a - -global_group=\u670d\u52a1\u96c6\u7fa4\u7ec4 -global_rule=\u5168\u5c40\u89c4\u5219 - -title_gray_version_operation=\u7070\u5ea6\u7248\u672c\u64cd\u4f5c - \u652f\u6301\u63a8\u9001\u5230\u670d\u52a1\uff08\u4e0d\u6301\u4e45\u5316\uff09 -title_gray_rule_operation=\u7070\u5ea6\u89c4\u5219\u64cd\u4f5c - \u652f\u6301\u63a8\u9001\u5230\u670d\u52a1\uff08\u4e0d\u6301\u4e45\u5316\uff09\uff0c\u652f\u6301\u63a8\u9001\u5230\u8fdc\u7a0b\u914d\u7f6e\u4e2d\u5fc3\uff08\u6301\u4e45\u5316\uff09 -label_dynamic_version=\u7070\u5ea6\uff08\u52a8\u6001\uff09\u7248\u672c -label_local_version=\u521d\u59cb\uff08\u672c\u5730\uff09\u7248\u672c -label_dynamic_rule=\u7070\u5ea6\uff08\u52a8\u6001\uff09\u89c4\u5219 -label_local_rule=\u521d\u59cb\uff08\u672c\u5730\uff09\u89c4\u5219 -button_update_version=\u66f4\u65b0\u7070\u5ea6\u7248\u672c -button_clear_version=\u6e05\u9664\u7070\u5ea6\u7248\u672c -button_batch_update_version=\u6279\u91cf\u66f4\u65b0\u7070\u5ea6\u7248\u672c -button_batch_clear_version=\u6279\u91cf\u6e05\u9664\u7070\u5ea6\u7248\u672c -button_update_rule=\u66f4\u65b0\u7070\u5ea6\u89c4\u5219 -button_clear_rule=\u6e05\u9664\u7070\u5ea6\u89c4\u5219 -description_gray_rule_to_config_center=\u7070\u5ea6\u89c4\u5219\uff0c\u8f93\u5165\u7684\u683c\u5f0f\u4e3aXML\u3002\u76ee\u524d\u91c7\u7528\u7684\u63a8\u9001\u6a21\u5f0f\u662f [\u63a8\u9001\u5230\u8fdc\u7a0b\u914d\u7f6e\u4e2d\u5fc3]\uff0c\u53ea\u652f\u6301\u670d\u52a1\u96c6\u7fa4\u63a8\u9001 -description_gray_rule_to_service=\u7070\u5ea6\u89c4\u5219\uff0c\u8f93\u5165\u7684\u683c\u5f0f\u4e3aXML\u3002\u76ee\u524d\u91c7\u7528\u7684\u63a8\u9001\u6a21\u5f0f\u662f [\u63a8\u9001\u5230\u670d\u52a1]\uff0c\u652f\u6301\u670d\u52a1\u6216\u8005\u670d\u52a1\u96c6\u7fa4\u63a8\u9001 -button_batch_update_rule=\u6279\u91cf\u66f4\u65b0\u7070\u5ea6\u89c4\u5219 -button_batch_clear_rule=\u6279\u91cf\u6e05\u9664\u7070\u5ea6\u89c4\u5219 -description_gray_version=\u7070\u5ea6\u7248\u672c\uff0c\u8f93\u5165\u7684\u683c\u5f0f\u4e3a[dynamicVersion]\u6216\u8005[dynamicVersion];[localVersion]\uff0c\u4f8b\u59821.1\u6216\u80051.1;1.0\uff0c\u524d\u8005\u76f4\u63a5\u66f4\u65b0\u7070\u5ea6\u7248\u672c\u4e3a1.1\uff0c\u540e\u8005\u53ea\u662f\u628a\u6ee1\u8db3\u521d\u59cb\u7248\u672c\u4e3a1.0\u6761\u4ef6\u7684\u670d\u52a1\u66f4\u65b0\u7070\u5ea6\u7248\u672c\u4e3a1.1 -gray_version_not_null=\u7070\u5ea6\u7248\u672c\u4e0d\u80fd\u4e3a\u7a7a -gray_rule_not_null=\u7070\u5ea6\u89c4\u5219\u4e0d\u80fd\u4e3a\u7a7a - -execute_result=\u6267\u884c\u7ed3\u679c - -get_service_group_failure=\u83b7\u53d6\u670d\u52a1\u7ec4\u5217\u8868\u5931\u8d25 -get_service_instances_failure=\u83b7\u53d6\u670d\u52a1\u548c\u5b9e\u4f8b\u5217\u8868\u5931\u8d25 -query_data_failure=\u67e5\u8be2\u6570\u636e\u5931\u8d25\uff0c\u53ef\u80fd\u76f8\u5173\u5b9e\u4f8b\u5df2\u4e0b\u7ebf -group_not_for_gray_release=\u8be5\u670d\u52a1\u96c6\u7fa4\u4e0d\u80fd\u6267\u884c\u7070\u5ea6\u53d1\u5e03 -node_not_for_gray_release=\u8be5\u670d\u52a1\u4e0d\u80fd\u6267\u884c\u7070\u5ea6\u53d1\u5e03 -node_not_for_gray_router=\u8be5\u670d\u52a1\u4e0d\u80fd\u6267\u884c\u6267\u884c\u7070\u5ea6\u8def\u7531 -group_not_for_refresh_gray_state=\u8be5\u670d\u52a1\u96c6\u7fa4\u4e0d\u80fd\u5237\u65b0\u7070\u5ea6\u72b6\u6001 -node_not_for_refresh_gray_state=\u8be5\u670d\u52a1\u4e0d\u80fd\u5237\u65b0\u7070\u5ea6\u72b6\u6001 -node_has_no_metadata=\u8be5\u670d\u52a1\u4e0d\u5305\u542b\u5143\u6570\u636e -not_for_push_global_config=\u5168\u94fe\u8def\u7070\u5ea6\u53d1\u5e03\uff0c\u53ea\u80fd\u5728\u201c\u89c4\u5219\u63a8\u9001\u5230\u8fdc\u7a0b\u914d\u7f6e\u4e2d\u5fc3\u201d\u6a21\u5f0f\u4e0b\u8fd0\u884c - -select_a_global_group=\u8bf7\u9009\u62e9\u4e00\u4e2a\u670d\u52a1\u96c6\u7fa4\u7ec4 -select_a_group=\u8bf7\u9009\u62e9\u4e00\u4e2a\u670d\u52a1\u96c6\u7fa4 -select_a_node=\u8bf7\u9009\u62e9\u4e00\u4e2a\u670d\u52a1 -select_a_group_or_node=\u8bf7\u9009\u62e9\u4e00\u4e2a\u670d\u52a1\u6216\u8005\u670d\u52a1\u96c6\u7fa4 - -group_layout=\u7ec4\u5e03\u5c40 -node_layout=\u8282\u70b9\u5e03\u5c40 -start_x=\u8d77\u59cb\u70b9X\u5750\u6807 -start_y=\u8d77\u59cb\u70b9Y\u5750\u6807 -horizontal_gap=\u6c34\u5e73\u95f4\u8ddd -vertical_gap=\u5782\u76f4\u95f4\u8ddd - -not_connnect_to_console=\u65e0\u6cd5\u8fde\u63a5\u5230\u63a7\u5236\u5e73\u53f0 -initialize_component=\u521d\u59cb\u5316\u754c\u9762 -initialize_component_failure=\u521d\u59cb\u5316\u754c\u9762\u5931\u8d25 diff --git a/discovery-console-desktop/src/main/resources/config/console.properties b/discovery-console-desktop/src/main/resources/config/console.properties deleted file mode 100644 index 8577a7e03e..0000000000 --- a/discovery-console-desktop/src/main/resources/config/console.properties +++ /dev/null @@ -1 +0,0 @@ -url=http://localhost:2222/ \ No newline at end of file diff --git a/discovery-console-desktop/src/main/resources/log4j2.xml b/discovery-console-desktop/src/main/resources/log4j2.xml deleted file mode 100644 index 490e2d60a0..0000000000 --- a/discovery-console-desktop/src/main/resources/log4j2.xml +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/discovery-console-starter-apollo/pom.xml b/discovery-console-starter-apollo/pom.xml deleted file mode 100644 index 44aa95737b..0000000000 --- a/discovery-console-starter-apollo/pom.xml +++ /dev/null @@ -1,28 +0,0 @@ - - - discovery-console-starter-apollo - Nepxion Discovery Console Starter Apollo - jar - 4.0.0 - Nepxion Discovery is an enhancement for Spring Cloud Discovery - http://www.nepxion.com - - - com.nepxion - discovery - 5.2.0-SNAPSHOT - - - - - ${project.groupId} - discovery-console - - - - com.ctrip.framework.apollo - apollo-openapi - - - \ No newline at end of file diff --git a/discovery-console-starter-apollo/src/main/java/com/nepxion/discovery/console/apollo/adapter/ApolloConfigAdapter.java b/discovery-console-starter-apollo/src/main/java/com/nepxion/discovery/console/apollo/adapter/ApolloConfigAdapter.java deleted file mode 100644 index 4bbc873f8c..0000000000 --- a/discovery-console-starter-apollo/src/main/java/com/nepxion/discovery/console/apollo/adapter/ApolloConfigAdapter.java +++ /dev/null @@ -1,133 +0,0 @@ -package com.nepxion.discovery.console.apollo.adapter; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import java.text.SimpleDateFormat; -import java.util.Date; - -import org.apache.commons.lang3.StringUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.core.env.Environment; - -import com.ctrip.framework.apollo.openapi.client.ApolloOpenApiClient; -import com.ctrip.framework.apollo.openapi.dto.NamespaceReleaseDTO; -import com.ctrip.framework.apollo.openapi.dto.OpenItemDTO; -import com.nepxion.discovery.console.adapter.ConfigAdapter; -import com.nepxion.discovery.console.apollo.constant.ApolloConstant; - -public class ApolloConfigAdapter implements ConfigAdapter { - @Autowired - private Environment environment; - - @Autowired - private ApolloOpenApiClient apolloOpenApiClient; - - @Override - public boolean updateConfig(String group, String serviceId, String config) throws Exception { - String appId = environment.getProperty(ApolloConstant.APOLLO_PLUGIN_APP_ID); - if (StringUtils.isEmpty(appId)) { - throw new IllegalArgumentException(ApolloConstant.APOLLO_PLUGIN_APP_ID + " can't be null or empty"); - } - - String env = environment.getProperty(ApolloConstant.APOLLO_PLUGIN_ENV); - if (StringUtils.isEmpty(env)) { - throw new IllegalArgumentException(ApolloConstant.APOLLO_PLUGIN_ENV + " can't be null or empty"); - } - - String operator = environment.getProperty(ApolloConstant.APOLLO_OPERATOR); - if (StringUtils.isEmpty(operator)) { - throw new IllegalArgumentException(ApolloConstant.APOLLO_OPERATOR + " can't be null or empty"); - } - - String cluster = environment.getProperty(ApolloConstant.APOLLO_PLUGIN_CLUSTER, String.class, ApolloConstant.DEFAULT_CLUSTER); - String namespace = environment.getProperty(ApolloConstant.APOLLO_PLUGIN_NAMESPACE, String.class, ApolloConstant.DEFAULT_NAMESPACE); - - Date now = new Date(); - - OpenItemDTO openItemDTO = new OpenItemDTO(); - openItemDTO.setKey(group + "-" + serviceId); - openItemDTO.setValue(config); - openItemDTO.setComment("Operated by Nepxion Discovery Console"); - openItemDTO.setDataChangeCreatedBy(operator); - openItemDTO.setDataChangeLastModifiedBy(operator); - openItemDTO.setDataChangeCreatedTime(now); - openItemDTO.setDataChangeLastModifiedTime(now); - - apolloOpenApiClient.createOrUpdateItem(appId, env, cluster, namespace, openItemDTO); - - NamespaceReleaseDTO namespaceReleaseDTO = new NamespaceReleaseDTO(); - namespaceReleaseDTO.setReleaseTitle(new SimpleDateFormat("yyyyMMddHHmmss").format(now) + "-release"); - namespaceReleaseDTO.setReleasedBy(operator); - namespaceReleaseDTO.setReleaseComment("Released by Nepxion Discovery Console"); - namespaceReleaseDTO.setEmergencyPublish(true); - - apolloOpenApiClient.publishNamespace(appId, env, cluster, namespace, namespaceReleaseDTO); - - return true; - } - - @Override - public boolean clearConfig(String group, String serviceId) throws Exception { - String appId = environment.getProperty(ApolloConstant.APOLLO_PLUGIN_APP_ID); - if (StringUtils.isEmpty(appId)) { - throw new IllegalArgumentException(ApolloConstant.APOLLO_PLUGIN_APP_ID + " can't be null or empty"); - } - - String env = environment.getProperty(ApolloConstant.APOLLO_PLUGIN_ENV); - if (StringUtils.isEmpty(env)) { - throw new IllegalArgumentException(ApolloConstant.APOLLO_PLUGIN_ENV + " can't be null or empty"); - } - - String operator = environment.getProperty(ApolloConstant.APOLLO_OPERATOR); - if (StringUtils.isEmpty(operator)) { - throw new IllegalArgumentException(ApolloConstant.APOLLO_OPERATOR + " can't be null or empty"); - } - - String cluster = environment.getProperty(ApolloConstant.APOLLO_PLUGIN_CLUSTER, String.class, ApolloConstant.DEFAULT_CLUSTER); - String namespace = environment.getProperty(ApolloConstant.APOLLO_PLUGIN_NAMESPACE, String.class, ApolloConstant.DEFAULT_NAMESPACE); - - apolloOpenApiClient.removeItem(appId, env, cluster, namespace, group + "-" + serviceId, operator); - - Date now = new Date(); - - NamespaceReleaseDTO namespaceReleaseDTO = new NamespaceReleaseDTO(); - namespaceReleaseDTO.setReleaseTitle(new SimpleDateFormat("yyyyMMddHHmmss").format(now) + "-release"); - namespaceReleaseDTO.setReleasedBy(operator); - namespaceReleaseDTO.setReleaseComment("Deleted by Nepxion Discovery Console"); - namespaceReleaseDTO.setEmergencyPublish(true); - - apolloOpenApiClient.publishNamespace(appId, env, cluster, namespace, namespaceReleaseDTO); - - return true; - } - - @Override - public String getConfig(String group, String serviceId) throws Exception { - String appId = environment.getProperty(ApolloConstant.APOLLO_PLUGIN_APP_ID); - if (StringUtils.isEmpty(appId)) { - throw new IllegalArgumentException(ApolloConstant.APOLLO_PLUGIN_APP_ID + " can't be null or empty"); - } - - String env = environment.getProperty(ApolloConstant.APOLLO_PLUGIN_ENV); - if (StringUtils.isEmpty(env)) { - throw new IllegalArgumentException(ApolloConstant.APOLLO_PLUGIN_ENV + " can't be null or empty"); - } - - String cluster = environment.getProperty(ApolloConstant.APOLLO_PLUGIN_CLUSTER, String.class, ApolloConstant.DEFAULT_CLUSTER); - String namespace = environment.getProperty(ApolloConstant.APOLLO_PLUGIN_NAMESPACE, String.class, ApolloConstant.DEFAULT_NAMESPACE); - - return apolloOpenApiClient.getLatestActiveRelease(appId, env, cluster, namespace).getConfigurations().get(group + "-" + serviceId); - } - - @Override - public String getConfigType() { - return ApolloConstant.TYPE; - } -} \ No newline at end of file diff --git a/discovery-console-starter-apollo/src/main/java/com/nepxion/discovery/console/apollo/configuration/ApolloConfigAutoConfiguration.java b/discovery-console-starter-apollo/src/main/java/com/nepxion/discovery/console/apollo/configuration/ApolloConfigAutoConfiguration.java deleted file mode 100644 index c407353262..0000000000 --- a/discovery-console-starter-apollo/src/main/java/com/nepxion/discovery/console/apollo/configuration/ApolloConfigAutoConfiguration.java +++ /dev/null @@ -1,76 +0,0 @@ -package com.nepxion.discovery.console.apollo.configuration; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import org.apache.commons.lang3.StringUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.core.env.Environment; - -import com.ctrip.framework.apollo.openapi.client.ApolloOpenApiClient; -import com.nepxion.banner.BannerConstant; -import com.nepxion.banner.Description; -import com.nepxion.banner.LogoBanner; -import com.nepxion.banner.NepxionBanner; -import com.nepxion.discovery.console.adapter.ConfigAdapter; -import com.nepxion.discovery.console.apollo.adapter.ApolloConfigAdapter; -import com.nepxion.discovery.console.apollo.constant.ApolloConstant; -import com.taobao.text.Color; - -@Configuration -public class ApolloConfigAutoConfiguration { - static { - /*String bannerShown = System.getProperty(BannerConstant.BANNER_SHOWN, "true"); - if (Boolean.valueOf(bannerShown)) { - System.out.println(""); - System.out.println("╔═══╗ ╔╗╔╗"); - System.out.println("║╔═╗║ ║║║║"); - System.out.println("║║ ║╠══╦══╣║║║╔══╗"); - System.out.println("║╚═╝║╔╗║╔╗║║║║║╔╗║"); - System.out.println("║╔═╗║╚╝║╚╝║╚╣╚╣╚╝║"); - System.out.println("╚╝ ╚╣╔═╩══╩═╩═╩══╝"); - System.out.println(" ║║"); - System.out.println(" ╚╝"); - System.out.println(ApolloConstant.TYPE + " Config"); - System.out.println(""); - }*/ - - LogoBanner logoBanner = new LogoBanner(ApolloConfigAutoConfiguration.class, "/com/nepxion/apollo/resource/logo.txt", "Welcome to Nepxion", 6, 5, new Color[] { Color.red, Color.green, Color.cyan, Color.blue, Color.yellow, Color.magenta }, true); - - NepxionBanner.show(logoBanner, new Description("Config:", ApolloConstant.TYPE, 0, 1), new Description(BannerConstant.GITHUB + ":", BannerConstant.NEPXION_GITHUB + "/Discovery", 0, 1)); - } - - @Autowired - private Environment environment; - - @Bean - public ApolloOpenApiClient openApiClient() { - String portalUrl = environment.getProperty(ApolloConstant.APOLLO_PORTAL_URL); - if (StringUtils.isEmpty(portalUrl)) { - throw new IllegalArgumentException(ApolloConstant.APOLLO_PORTAL_URL + " can't be null or empty"); - } - - String token = environment.getProperty(ApolloConstant.APOLLO_TOKEN); - if (StringUtils.isEmpty(token)) { - throw new IllegalArgumentException(ApolloConstant.APOLLO_TOKEN + " can't be null or empty"); - } - - int connectTimeout = environment.getProperty(ApolloConstant.APOLLO_CONNECT_TIMEOUT, Integer.class, ApolloConstant.DEFAULT_CONNECT_TIMEOUT); - int readTimeout = environment.getProperty(ApolloConstant.APOLLO_READ_TIMEOUT, Integer.class, ApolloConstant.DEFAULT_READ_TIMEOUT); - - return ApolloOpenApiClient.newBuilder().withPortalUrl(portalUrl).withToken(token).withConnectTimeout(connectTimeout).withReadTimeout(readTimeout).build(); - } - - @Bean - public ConfigAdapter configAdapter() { - return new ApolloConfigAdapter(); - } -} \ No newline at end of file diff --git a/discovery-console-starter-apollo/src/main/java/com/nepxion/discovery/console/apollo/constant/ApolloConstant.java b/discovery-console-starter-apollo/src/main/java/com/nepxion/discovery/console/apollo/constant/ApolloConstant.java deleted file mode 100644 index c3ea770567..0000000000 --- a/discovery-console-starter-apollo/src/main/java/com/nepxion/discovery/console/apollo/constant/ApolloConstant.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.nepxion.discovery.console.apollo.constant; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import com.ctrip.framework.apollo.openapi.client.constant.ApolloOpenApiConstants; - -public class ApolloConstant implements ApolloOpenApiConstants { - public static final String TYPE = "Apollo"; - public static final String APOLLO_PORTAL_URL = "apollo.portal-url"; - public static final String APOLLO_TOKEN = "apollo.token"; - public static final String APOLLO_OPERATOR = "apollo.operator"; - public static final String APOLLO_READ_TIMEOUT = "apollo.read-timeout"; - public static final String APOLLO_CONNECT_TIMEOUT = "apollo.connect-timeout"; - public static final String APOLLO_PLUGIN_APP_ID = "apollo.plugin.app.id"; - public static final String APOLLO_PLUGIN_ENV = "apollo.plugin.env"; - public static final String APOLLO_PLUGIN_CLUSTER = "apollo.plugin.cluster"; - public static final String APOLLO_PLUGIN_NAMESPACE = "apollo.plugin.namespace"; - - public static final String DEFAULT_CLUSTER = "default"; - public static final String DEFAULT_NAMESPACE = "application"; -} \ No newline at end of file diff --git a/discovery-console-starter-nacos/pom.xml b/discovery-console-starter-nacos/pom.xml deleted file mode 100644 index 54585e072a..0000000000 --- a/discovery-console-starter-nacos/pom.xml +++ /dev/null @@ -1,28 +0,0 @@ - - - discovery-console-starter-nacos - Nepxion Discovery Console Starter Nacos - jar - 4.0.0 - Nepxion Discovery is an enhancement for Spring Cloud Discovery - http://www.nepxion.com - - - com.nepxion - discovery - 5.2.0-SNAPSHOT - - - - - ${project.groupId} - discovery-console - - - - ${project.groupId} - discovery-common-nacos - - - \ No newline at end of file diff --git a/discovery-console-starter-nacos/src/main/java/com/nepxion/discovery/console/nacos/adapter/NacosConfigAdapter.java b/discovery-console-starter-nacos/src/main/java/com/nepxion/discovery/console/nacos/adapter/NacosConfigAdapter.java deleted file mode 100644 index 2a4b942380..0000000000 --- a/discovery-console-starter-nacos/src/main/java/com/nepxion/discovery/console/nacos/adapter/NacosConfigAdapter.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.nepxion.discovery.console.nacos.adapter; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import org.springframework.beans.factory.annotation.Autowired; - -import com.nepxion.discovery.common.nacos.constant.NacosConstant; -import com.nepxion.discovery.common.nacos.operation.NacosOperation; -import com.nepxion.discovery.console.adapter.ConfigAdapter; - -public class NacosConfigAdapter implements ConfigAdapter { - @Autowired - private NacosOperation nacosOperation; - - @Override - public boolean updateConfig(String group, String serviceId, String config) throws Exception { - return nacosOperation.publishConfig(group, serviceId, config); - } - - @Override - public boolean clearConfig(String group, String serviceId) throws Exception { - return nacosOperation.removeConfig(group, serviceId); - } - - @Override - public String getConfig(String group, String serviceId) throws Exception { - return nacosOperation.getConfig(group, serviceId); - } - - @Override - public String getConfigType() { - return NacosConstant.TYPE; - } -} \ No newline at end of file diff --git a/discovery-console-starter-nacos/src/main/java/com/nepxion/discovery/console/nacos/configuration/NacosConfigAutoConfiguration.java b/discovery-console-starter-nacos/src/main/java/com/nepxion/discovery/console/nacos/configuration/NacosConfigAutoConfiguration.java deleted file mode 100644 index 2923374e8d..0000000000 --- a/discovery-console-starter-nacos/src/main/java/com/nepxion/discovery/console/nacos/configuration/NacosConfigAutoConfiguration.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.nepxion.discovery.console.nacos.configuration; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -import com.nepxion.banner.BannerConstant; -import com.nepxion.banner.Description; -import com.nepxion.banner.LogoBanner; -import com.nepxion.banner.NepxionBanner; -import com.nepxion.discovery.common.nacos.constant.NacosConstant; -import com.nepxion.discovery.console.adapter.ConfigAdapter; -import com.nepxion.discovery.console.nacos.adapter.NacosConfigAdapter; -import com.taobao.text.Color; - -@Configuration -public class NacosConfigAutoConfiguration { - static { - /*String bannerShown = System.getProperty(BannerConstant.BANNER_SHOWN, "true"); - if (Boolean.valueOf(bannerShown)) { - System.out.println(""); - System.out.println("╔═╗ ╔╗"); - System.out.println("║║╚╗║║"); - System.out.println("║╔╗╚╝╠══╦══╦══╦══╗"); - System.out.println("║║╚╗║║╔╗║╔═╣╔╗║══╣"); - System.out.println("║║ ║║║╔╗║╚═╣╚╝╠══║"); - System.out.println("╚╝ ╚═╩╝╚╩══╩══╩══╝"); - System.out.println(NacosConstant.TYPE + " Config"); - System.out.println(""); - }*/ - - LogoBanner logoBanner = new LogoBanner(NacosConfigAutoConfiguration.class, "/com/nepxion/nacos/resource/logo.txt", "Welcome to Nepxion", 5, 5, new Color[] { Color.red, Color.green, Color.cyan, Color.blue, Color.yellow }, true); - - NepxionBanner.show(logoBanner, new Description("Config:", NacosConstant.TYPE, 0, 1), new Description(BannerConstant.GITHUB + ":", BannerConstant.NEPXION_GITHUB + "/Discovery", 0, 1)); - } - - @Bean - public ConfigAdapter configAdapter() { - return new NacosConfigAdapter(); - } -} \ No newline at end of file diff --git a/discovery-console-starter-nacos/src/main/resources/META-INF/spring.factories b/discovery-console-starter-nacos/src/main/resources/META-INF/spring.factories deleted file mode 100644 index 44f62e04f7..0000000000 --- a/discovery-console-starter-nacos/src/main/resources/META-INF/spring.factories +++ /dev/null @@ -1,3 +0,0 @@ -org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ -com.nepxion.discovery.common.nacos.configuration.NacosAutoConfiguration,\ -com.nepxion.discovery.console.nacos.configuration.NacosConfigAutoConfiguration \ No newline at end of file diff --git a/discovery-console-starter-redis/pom.xml b/discovery-console-starter-redis/pom.xml deleted file mode 100644 index 9735003388..0000000000 --- a/discovery-console-starter-redis/pom.xml +++ /dev/null @@ -1,28 +0,0 @@ - - - discovery-console-starter-redis - Nepxion Discovery Console Starter Redis - jar - 4.0.0 - Nepxion Discovery is an enhancement for Spring Cloud Discovery - http://www.nepxion.com - - - com.nepxion - discovery - 5.2.0-SNAPSHOT - - - - - ${project.groupId} - discovery-console - - - - ${project.groupId} - discovery-common-redis - - - \ No newline at end of file diff --git a/discovery-console-starter-redis/src/main/java/com/nepxion/discovery/console/redis/adapter/RedisConfigAdapter.java b/discovery-console-starter-redis/src/main/java/com/nepxion/discovery/console/redis/adapter/RedisConfigAdapter.java deleted file mode 100644 index da65a45789..0000000000 --- a/discovery-console-starter-redis/src/main/java/com/nepxion/discovery/console/redis/adapter/RedisConfigAdapter.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.nepxion.discovery.console.redis.adapter; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @author JiKai Sun - * @version 1.0 - */ - -import org.springframework.beans.factory.annotation.Autowired; - -import com.nepxion.discovery.common.redis.constant.RedisConstant; -import com.nepxion.discovery.common.redis.operation.RedisOperation; -import com.nepxion.discovery.console.adapter.ConfigAdapter; - -public class RedisConfigAdapter implements ConfigAdapter { - @Autowired - private RedisOperation redisOperation; - - @Override - public boolean updateConfig(String group, String serviceId, String config) throws Exception { - return redisOperation.publishConfig(group, serviceId, config); - } - - @Override - public boolean clearConfig(String group, String serviceId) throws Exception { - return redisOperation.removeConfig(group, serviceId); - } - - @Override - public String getConfig(String group, String serviceId) throws Exception { - return redisOperation.getConfig(group, serviceId); - } - - @Override - public String getConfigType() { - return RedisConstant.TYPE; - } -} \ No newline at end of file diff --git a/discovery-console-starter-redis/src/main/java/com/nepxion/discovery/console/redis/configuration/RedisConfigAutoConfiguration.java b/discovery-console-starter-redis/src/main/java/com/nepxion/discovery/console/redis/configuration/RedisConfigAutoConfiguration.java deleted file mode 100644 index 747d920953..0000000000 --- a/discovery-console-starter-redis/src/main/java/com/nepxion/discovery/console/redis/configuration/RedisConfigAutoConfiguration.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.nepxion.discovery.console.redis.configuration; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @author JiKai Sun - * @version 1.0 - */ - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -import com.nepxion.banner.BannerConstant; -import com.nepxion.banner.Description; -import com.nepxion.banner.LogoBanner; -import com.nepxion.banner.NepxionBanner; -import com.nepxion.discovery.common.redis.constant.RedisConstant; -import com.nepxion.discovery.console.adapter.ConfigAdapter; -import com.nepxion.discovery.console.redis.adapter.RedisConfigAdapter; -import com.taobao.text.Color; - -@Configuration -public class RedisConfigAutoConfiguration { - static { - /*String bannerShown = System.getProperty(BannerConstant.BANNER_SHOWN, "true"); - if (Boolean.valueOf(bannerShown)) { - System.out.println(""); - System.out.println("╔═══╗ ╔╗"); - System.out.println("║╔═╗║ ║║"); - System.out.println("║╚═╝╠══╦═╝╠╦══╗"); - System.out.println("║╔╗╔╣║═╣╔╗╠╣══╣"); - System.out.println("║║║╚╣║═╣╚╝║╠══║"); - System.out.println("╚╝╚═╩══╩══╩╩══╝"); - System.out.println(RedisConstant.TYPE + " Config"); - System.out.println(""); - }*/ - - LogoBanner logoBanner = new LogoBanner(RedisConfigAutoConfiguration.class, "/com/nepxion/redis/resource/logo.txt", "Welcome to Nepxion", 5, 5, new Color[] { Color.red, Color.green, Color.cyan, Color.blue, Color.yellow }, true); - - NepxionBanner.show(logoBanner, new Description("Config:", RedisConstant.TYPE, 0, 1), new Description(BannerConstant.GITHUB + ":", BannerConstant.NEPXION_GITHUB + "/Discovery", 0, 1)); - } - - @Bean - public ConfigAdapter configAdapter() { - return new RedisConfigAdapter(); - } -} \ No newline at end of file diff --git a/discovery-console-starter-redis/src/main/resources/META-INF/spring.factories b/discovery-console-starter-redis/src/main/resources/META-INF/spring.factories deleted file mode 100644 index 4658b74673..0000000000 --- a/discovery-console-starter-redis/src/main/resources/META-INF/spring.factories +++ /dev/null @@ -1,3 +0,0 @@ -org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ -com.nepxion.discovery.common.redis.configuration.RedisAutoConfiguration,\ -com.nepxion.discovery.console.redis.configuration.RedisConfigAutoConfiguration \ No newline at end of file diff --git a/discovery-console/discovery-console-starter-apollo/pom.xml b/discovery-console/discovery-console-starter-apollo/pom.xml new file mode 100644 index 0000000000..02aa2805c3 --- /dev/null +++ b/discovery-console/discovery-console-starter-apollo/pom.xml @@ -0,0 +1,28 @@ + + + discovery-console-starter-apollo + Nepxion Discovery Console Starter Apollo + jar + 4.0.0 + Nepxion Discovery is a solution for Spring Cloud with blue green, gray, weight, limitation, circuit breaker, degrade, isolation, monitor, tracing, dye, failover, async agent + http://www.nepxion.com + + + com.nepxion + discovery-console + 6.23.0 + + + + + ${project.groupId} + discovery-console-starter + + + + com.ctrip.framework.apollo + apollo-openapi + + + \ No newline at end of file diff --git a/discovery-console/discovery-console-starter-apollo/src/main/java/com/nepxion/discovery/console/apollo/adapter/ApolloConfigAdapter.java b/discovery-console/discovery-console-starter-apollo/src/main/java/com/nepxion/discovery/console/apollo/adapter/ApolloConfigAdapter.java new file mode 100644 index 0000000000..8179d85cfc --- /dev/null +++ b/discovery-console/discovery-console-starter-apollo/src/main/java/com/nepxion/discovery/console/apollo/adapter/ApolloConfigAdapter.java @@ -0,0 +1,135 @@ +package com.nepxion.discovery.console.apollo.adapter; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.text.SimpleDateFormat; +import java.util.Date; + +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.env.Environment; + +import com.ctrip.framework.apollo.openapi.client.ApolloOpenApiClient; +import com.ctrip.framework.apollo.openapi.dto.NamespaceReleaseDTO; +import com.ctrip.framework.apollo.openapi.dto.OpenItemDTO; +import com.nepxion.discovery.common.entity.ConfigType; +import com.nepxion.discovery.common.exception.DiscoveryException; +import com.nepxion.discovery.console.adapter.ConfigAdapter; +import com.nepxion.discovery.console.apollo.constant.ApolloConstant; + +public class ApolloConfigAdapter implements ConfigAdapter { + @Autowired + private Environment environment; + + @Autowired + private ApolloOpenApiClient apolloOpenApiClient; + + @Override + public boolean updateConfig(String group, String serviceId, String config) throws Exception { + String appId = environment.getProperty(ApolloConstant.APOLLO_APP_ID); + if (StringUtils.isEmpty(appId)) { + throw new DiscoveryException(ApolloConstant.APOLLO_APP_ID + " can't be null or empty"); + } + + String env = environment.getProperty(ApolloConstant.APOLLO_ENV); + if (StringUtils.isEmpty(env)) { + throw new DiscoveryException(ApolloConstant.APOLLO_ENV + " can't be null or empty"); + } + + String operator = environment.getProperty(ApolloConstant.APOLLO_OPERATOR); + if (StringUtils.isEmpty(operator)) { + throw new DiscoveryException(ApolloConstant.APOLLO_OPERATOR + " can't be null or empty"); + } + + String cluster = environment.getProperty(ApolloConstant.APOLLO_CLUSTER, String.class, ApolloConstant.APOLLO_DEFAULT_CLUSTER); + String namespace = environment.getProperty(ApolloConstant.APOLLO_NAMESPACE, String.class, ApolloConstant.APOLLO_DEFAULT_NAMESPACE); + + Date now = new Date(); + + OpenItemDTO openItemDTO = new OpenItemDTO(); + openItemDTO.setKey(group + "-" + serviceId); + openItemDTO.setValue(config); + openItemDTO.setComment("Operated by Nepxion Discovery Console"); + openItemDTO.setDataChangeCreatedBy(operator); + openItemDTO.setDataChangeLastModifiedBy(operator); + openItemDTO.setDataChangeCreatedTime(now); + openItemDTO.setDataChangeLastModifiedTime(now); + + apolloOpenApiClient.createOrUpdateItem(appId, env, cluster, namespace, openItemDTO); + + NamespaceReleaseDTO namespaceReleaseDTO = new NamespaceReleaseDTO(); + namespaceReleaseDTO.setReleaseTitle(new SimpleDateFormat("yyyyMMddHHmmss").format(now) + "-release"); + namespaceReleaseDTO.setReleasedBy(operator); + namespaceReleaseDTO.setReleaseComment("Released by Nepxion Discovery Console"); + namespaceReleaseDTO.setEmergencyPublish(true); + + apolloOpenApiClient.publishNamespace(appId, env, cluster, namespace, namespaceReleaseDTO); + + return true; + } + + @Override + public boolean clearConfig(String group, String serviceId) throws Exception { + String appId = environment.getProperty(ApolloConstant.APOLLO_APP_ID); + if (StringUtils.isEmpty(appId)) { + throw new DiscoveryException(ApolloConstant.APOLLO_APP_ID + " can't be null or empty"); + } + + String env = environment.getProperty(ApolloConstant.APOLLO_ENV); + if (StringUtils.isEmpty(env)) { + throw new DiscoveryException(ApolloConstant.APOLLO_ENV + " can't be null or empty"); + } + + String operator = environment.getProperty(ApolloConstant.APOLLO_OPERATOR); + if (StringUtils.isEmpty(operator)) { + throw new DiscoveryException(ApolloConstant.APOLLO_OPERATOR + " can't be null or empty"); + } + + String cluster = environment.getProperty(ApolloConstant.APOLLO_CLUSTER, String.class, ApolloConstant.APOLLO_DEFAULT_CLUSTER); + String namespace = environment.getProperty(ApolloConstant.APOLLO_NAMESPACE, String.class, ApolloConstant.APOLLO_DEFAULT_NAMESPACE); + + apolloOpenApiClient.removeItem(appId, env, cluster, namespace, group + "-" + serviceId, operator); + + Date now = new Date(); + + NamespaceReleaseDTO namespaceReleaseDTO = new NamespaceReleaseDTO(); + namespaceReleaseDTO.setReleaseTitle(new SimpleDateFormat("yyyyMMddHHmmss").format(now) + "-release"); + namespaceReleaseDTO.setReleasedBy(operator); + namespaceReleaseDTO.setReleaseComment("Deleted by Nepxion Discovery Console"); + namespaceReleaseDTO.setEmergencyPublish(true); + + apolloOpenApiClient.publishNamespace(appId, env, cluster, namespace, namespaceReleaseDTO); + + return true; + } + + @Override + public String getConfig(String group, String serviceId) throws Exception { + String appId = environment.getProperty(ApolloConstant.APOLLO_APP_ID); + if (StringUtils.isEmpty(appId)) { + throw new DiscoveryException(ApolloConstant.APOLLO_APP_ID + " can't be null or empty"); + } + + String env = environment.getProperty(ApolloConstant.APOLLO_ENV); + if (StringUtils.isEmpty(env)) { + throw new DiscoveryException(ApolloConstant.APOLLO_ENV + " can't be null or empty"); + } + + String cluster = environment.getProperty(ApolloConstant.APOLLO_CLUSTER, String.class, ApolloConstant.APOLLO_DEFAULT_CLUSTER); + String namespace = environment.getProperty(ApolloConstant.APOLLO_NAMESPACE, String.class, ApolloConstant.APOLLO_DEFAULT_NAMESPACE); + + return apolloOpenApiClient.getLatestActiveRelease(appId, env, cluster, namespace).getConfigurations().get(group + "-" + serviceId); + } + + @Override + public ConfigType getConfigType() { + return ConfigType.APOLLO; + } +} \ No newline at end of file diff --git a/discovery-console/discovery-console-starter-apollo/src/main/java/com/nepxion/discovery/console/apollo/configuration/ApolloConfigAutoConfiguration.java b/discovery-console/discovery-console-starter-apollo/src/main/java/com/nepxion/discovery/console/apollo/configuration/ApolloConfigAutoConfiguration.java new file mode 100644 index 0000000000..4c095edbe1 --- /dev/null +++ b/discovery-console/discovery-console-starter-apollo/src/main/java/com/nepxion/discovery/console/apollo/configuration/ApolloConfigAutoConfiguration.java @@ -0,0 +1,78 @@ +package com.nepxion.discovery.console.apollo.configuration; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.env.Environment; + +import com.ctrip.framework.apollo.openapi.client.ApolloOpenApiClient; +import com.nepxion.banner.BannerConstant; +import com.nepxion.banner.Description; +import com.nepxion.banner.LogoBanner; +import com.nepxion.banner.NepxionBanner; +import com.nepxion.discovery.common.entity.ConfigType; +import com.nepxion.discovery.common.exception.DiscoveryException; +import com.nepxion.discovery.console.adapter.ConfigAdapter; +import com.nepxion.discovery.console.apollo.adapter.ApolloConfigAdapter; +import com.nepxion.discovery.console.apollo.constant.ApolloConstant; +import com.taobao.text.Color; + +@Configuration +public class ApolloConfigAutoConfiguration { + static { + /*String bannerShown = System.getProperty(BannerConstant.BANNER_SHOWN, "true"); + if (Boolean.valueOf(bannerShown)) { + System.out.println(""); + System.out.println("╔═══╗ ╔╗╔╗"); + System.out.println("║╔═╗║ ║║║║"); + System.out.println("║║ ║╠══╦══╣║║║╔══╗"); + System.out.println("║╚═╝║╔╗║╔╗║║║║║╔╗║"); + System.out.println("║╔═╗║╚╝║╚╝║╚╣╚╣╚╝║"); + System.out.println("╚╝ ╚╣╔═╩══╩═╩═╩══╝"); + System.out.println(" ║║"); + System.out.println(" ╚╝"); + System.out.println(ApolloConstant.TYPE + " Config"); + System.out.println(""); + }*/ + + LogoBanner logoBanner = new LogoBanner(ApolloConfigAutoConfiguration.class, "/com/nepxion/apollo/resource/logo.txt", "Welcome to Nepxion", 6, 5, new Color[] { Color.red, Color.green, Color.cyan, Color.blue, Color.yellow, Color.magenta }, true); + + NepxionBanner.show(logoBanner, new Description("Config:", ConfigType.APOLLO.toString(), 0, 1), new Description(BannerConstant.GITHUB + ":", BannerConstant.NEPXION_GITHUB + "/Discovery", 0, 1)); + } + + @Autowired + private Environment environment; + + @Bean + public ApolloOpenApiClient openApiClient() { + String portalUrl = environment.getProperty(ApolloConstant.APOLLO_PORTAL_URL); + if (StringUtils.isEmpty(portalUrl)) { + throw new DiscoveryException(ApolloConstant.APOLLO_PORTAL_URL + " can't be null or empty"); + } + + String token = environment.getProperty(ApolloConstant.APOLLO_TOKEN); + if (StringUtils.isEmpty(token)) { + throw new DiscoveryException(ApolloConstant.APOLLO_TOKEN + " can't be null or empty"); + } + + int connectTimeout = environment.getProperty(ApolloConstant.APOLLO_CONNECT_TIMEOUT, Integer.class, ApolloConstant.DEFAULT_CONNECT_TIMEOUT); + int readTimeout = environment.getProperty(ApolloConstant.APOLLO_READ_TIMEOUT, Integer.class, ApolloConstant.DEFAULT_READ_TIMEOUT); + + return ApolloOpenApiClient.newBuilder().withPortalUrl(portalUrl).withToken(token).withConnectTimeout(connectTimeout).withReadTimeout(readTimeout).build(); + } + + @Bean + public ConfigAdapter configAdapter() { + return new ApolloConfigAdapter(); + } +} \ No newline at end of file diff --git a/discovery-console/discovery-console-starter-apollo/src/main/java/com/nepxion/discovery/console/apollo/constant/ApolloConstant.java b/discovery-console/discovery-console-starter-apollo/src/main/java/com/nepxion/discovery/console/apollo/constant/ApolloConstant.java new file mode 100644 index 0000000000..03e912c404 --- /dev/null +++ b/discovery-console/discovery-console-starter-apollo/src/main/java/com/nepxion/discovery/console/apollo/constant/ApolloConstant.java @@ -0,0 +1,26 @@ +package com.nepxion.discovery.console.apollo.constant; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import com.ctrip.framework.apollo.openapi.client.constant.ApolloOpenApiConstants; + +public class ApolloConstant implements ApolloOpenApiConstants { + public static final String APOLLO_PORTAL_URL = "apollo.portal-url"; + public static final String APOLLO_TOKEN = "apollo.token"; + public static final String APOLLO_OPERATOR = "apollo.operator"; + public static final String APOLLO_READ_TIMEOUT = "apollo.read-timeout"; + public static final String APOLLO_CONNECT_TIMEOUT = "apollo.connect-timeout"; + public static final String APOLLO_APP_ID = "apollo.app.id"; + public static final String APOLLO_ENV = "apollo.env"; + public static final String APOLLO_CLUSTER = "apollo.cluster"; + public static final String APOLLO_NAMESPACE = "apollo.namespace"; + public static final String APOLLO_DEFAULT_CLUSTER = "default"; + public static final String APOLLO_DEFAULT_NAMESPACE = "application"; +} \ No newline at end of file diff --git a/discovery-console/discovery-console-starter-apollo/src/main/resources/META-INF/additional-spring-configuration-metadata.json b/discovery-console/discovery-console-starter-apollo/src/main/resources/META-INF/additional-spring-configuration-metadata.json new file mode 100644 index 0000000000..252d60cce6 --- /dev/null +++ b/discovery-console/discovery-console-starter-apollo/src/main/resources/META-INF/additional-spring-configuration-metadata.json @@ -0,0 +1,53 @@ +{ + "properties": [ + { + "name": "apollo.portal-url", + "type": "java.lang.String", + "description": "Apollo portal url." + }, + { + "name": "apollo.token", + "type": "java.lang.String", + "description": "Apollo token." + }, + { + "name": "apollo.operator", + "type": "java.lang.String", + "description": "Apollo operator." + }, + { + "name": "apollo.read-timeout", + "type": "java.lang.Integer", + "defaultValue": 5000, + "description": "Apollo read timeout." + }, + { + "name": "apollo.connect-timeout", + "type": "java.lang.Integer", + "defaultValue": 1000, + "description": "Apollo connect timeout." + }, + { + "name": "apollo.app.id", + "type": "java.lang.String", + "description": "Apollo app id." + }, + { + "name": "apollo.env", + "type": "java.lang.String", + "description": "Apollo env." + }, + { + "name": "apollo.cluster", + "type": "java.lang.String", + "defaultValue": "default", + "description": "Apollo cluster." + }, + { + "name": "apollo.namespace", + "type": "java.lang.String", + "defaultValue": "application", + "description": "Apollo namespace." + } + ] +} \ No newline at end of file diff --git a/discovery-console-starter-apollo/src/main/resources/META-INF/spring.factories b/discovery-console/discovery-console-starter-apollo/src/main/resources/META-INF/spring.factories similarity index 100% rename from discovery-console-starter-apollo/src/main/resources/META-INF/spring.factories rename to discovery-console/discovery-console-starter-apollo/src/main/resources/META-INF/spring.factories diff --git a/discovery-console/discovery-console-starter-consul/pom.xml b/discovery-console/discovery-console-starter-consul/pom.xml new file mode 100644 index 0000000000..433ca319df --- /dev/null +++ b/discovery-console/discovery-console-starter-consul/pom.xml @@ -0,0 +1,28 @@ + + + discovery-console-starter-consul + Nepxion Discovery Console Starter Consul + jar + 4.0.0 + Nepxion Discovery is a solution for Spring Cloud with blue green, gray, weight, limitation, circuit breaker, degrade, isolation, monitor, tracing, dye, failover, async agent + http://www.nepxion.com + + + com.nepxion + discovery-console + 6.23.0 + + + + + ${project.groupId} + discovery-console-starter + + + + ${project.groupId} + discovery-common-consul + + + \ No newline at end of file diff --git a/discovery-console/discovery-console-starter-consul/src/main/java/com/nepxion/discovery/console/consul/adapter/ConsulConfigAdapter.java b/discovery-console/discovery-console-starter-consul/src/main/java/com/nepxion/discovery/console/consul/adapter/ConsulConfigAdapter.java new file mode 100644 index 0000000000..0825a20b9d --- /dev/null +++ b/discovery-console/discovery-console-starter-consul/src/main/java/com/nepxion/discovery/console/consul/adapter/ConsulConfigAdapter.java @@ -0,0 +1,41 @@ +package com.nepxion.discovery.console.consul.adapter; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Congwei Xu + * @version 1.0 + */ + +import org.springframework.beans.factory.annotation.Autowired; + +import com.nepxion.discovery.common.consul.operation.ConsulOperation; +import com.nepxion.discovery.common.entity.ConfigType; +import com.nepxion.discovery.console.adapter.ConfigAdapter; + +public class ConsulConfigAdapter implements ConfigAdapter { + @Autowired + private ConsulOperation consulOperation; + + @Override + public boolean updateConfig(String group, String serviceId, String config) throws Exception { + return consulOperation.publishConfig(group, serviceId, config); + } + + @Override + public boolean clearConfig(String group, String serviceId) throws Exception { + return consulOperation.removeConfig(group, serviceId); + } + + @Override + public String getConfig(String group, String serviceId) throws Exception { + return consulOperation.getConfig(group, serviceId); + } + + @Override + public ConfigType getConfigType() { + return ConfigType.CONSUL; + } +} \ No newline at end of file diff --git a/discovery-console/discovery-console-starter-consul/src/main/java/com/nepxion/discovery/console/consul/configuration/ConsulConfigAutoConfiguration.java b/discovery-console/discovery-console-starter-consul/src/main/java/com/nepxion/discovery/console/consul/configuration/ConsulConfigAutoConfiguration.java new file mode 100644 index 0000000000..ca0302095c --- /dev/null +++ b/discovery-console/discovery-console-starter-consul/src/main/java/com/nepxion/discovery/console/consul/configuration/ConsulConfigAutoConfiguration.java @@ -0,0 +1,35 @@ +package com.nepxion.discovery.console.consul.configuration; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Congwei Xu + * @version 1.0 + */ + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import com.nepxion.banner.BannerConstant; +import com.nepxion.banner.Description; +import com.nepxion.banner.LogoBanner; +import com.nepxion.banner.NepxionBanner; +import com.nepxion.discovery.common.entity.ConfigType; +import com.nepxion.discovery.console.adapter.ConfigAdapter; +import com.nepxion.discovery.console.consul.adapter.ConsulConfigAdapter; +import com.taobao.text.Color; + +@Configuration +public class ConsulConfigAutoConfiguration { + static { + LogoBanner logoBanner = new LogoBanner(ConsulConfigAutoConfiguration.class, "/com/nepxion/consul/resource/logo.txt", "Welcome to Nepxion", 6, 5, new Color[] { Color.red, Color.green, Color.cyan, Color.blue, Color.yellow, Color.magenta }, true); + NepxionBanner.show(logoBanner, new Description("Config:", ConfigType.CONSUL.toString(), 0, 1), new Description(BannerConstant.GITHUB + ":", BannerConstant.NEPXION_GITHUB + "/Discovery", 0, 1)); + } + + @Bean + public ConfigAdapter configAdapter() { + return new ConsulConfigAdapter(); + } +} \ No newline at end of file diff --git a/discovery-console/discovery-console-starter-consul/src/main/resources/META-INF/spring.factories b/discovery-console/discovery-console-starter-consul/src/main/resources/META-INF/spring.factories new file mode 100644 index 0000000000..7ec6c32715 --- /dev/null +++ b/discovery-console/discovery-console-starter-consul/src/main/resources/META-INF/spring.factories @@ -0,0 +1,2 @@ +org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ +com.nepxion.discovery.console.consul.configuration.ConsulConfigAutoConfiguration \ No newline at end of file diff --git a/discovery-console/discovery-console-starter-etcd/pom.xml b/discovery-console/discovery-console-starter-etcd/pom.xml new file mode 100644 index 0000000000..b4101a9b76 --- /dev/null +++ b/discovery-console/discovery-console-starter-etcd/pom.xml @@ -0,0 +1,28 @@ + + + discovery-console-starter-etcd + Nepxion Discovery Console Starter Etcd + jar + 4.0.0 + Nepxion Discovery is a solution for Spring Cloud with blue green, gray, weight, limitation, circuit breaker, degrade, isolation, monitor, tracing, dye, failover, async agent + http://www.nepxion.com + + + com.nepxion + discovery-console + 6.23.0 + + + + + ${project.groupId} + discovery-console-starter + + + + ${project.groupId} + discovery-common-etcd + + + \ No newline at end of file diff --git a/discovery-console/discovery-console-starter-etcd/src/main/java/com/nepxion/discovery/console/etcd/adapter/EtcdConfigAdapter.java b/discovery-console/discovery-console-starter-etcd/src/main/java/com/nepxion/discovery/console/etcd/adapter/EtcdConfigAdapter.java new file mode 100644 index 0000000000..93c4049c35 --- /dev/null +++ b/discovery-console/discovery-console-starter-etcd/src/main/java/com/nepxion/discovery/console/etcd/adapter/EtcdConfigAdapter.java @@ -0,0 +1,41 @@ +package com.nepxion.discovery.console.etcd.adapter; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Congwei Xu + * @version 1.0 + */ + +import org.springframework.beans.factory.annotation.Autowired; + +import com.nepxion.discovery.common.entity.ConfigType; +import com.nepxion.discovery.common.etcd.operation.EtcdOperation; +import com.nepxion.discovery.console.adapter.ConfigAdapter; + +public class EtcdConfigAdapter implements ConfigAdapter { + @Autowired + private EtcdOperation etcdOperation; + + @Override + public boolean updateConfig(String group, String serviceId, String config) throws Exception { + return etcdOperation.publishConfig(group, serviceId, config); + } + + @Override + public boolean clearConfig(String group, String serviceId) throws Exception { + return etcdOperation.removeConfig(group, serviceId); + } + + @Override + public String getConfig(String group, String serviceId) throws Exception { + return etcdOperation.getConfig(group, serviceId); + } + + @Override + public ConfigType getConfigType() { + return ConfigType.ETCD; + } +} \ No newline at end of file diff --git a/discovery-console/discovery-console-starter-etcd/src/main/java/com/nepxion/discovery/console/etcd/configuration/EtcdConfigAutoConfiguration.java b/discovery-console/discovery-console-starter-etcd/src/main/java/com/nepxion/discovery/console/etcd/configuration/EtcdConfigAutoConfiguration.java new file mode 100644 index 0000000000..d65ad82010 --- /dev/null +++ b/discovery-console/discovery-console-starter-etcd/src/main/java/com/nepxion/discovery/console/etcd/configuration/EtcdConfigAutoConfiguration.java @@ -0,0 +1,35 @@ +package com.nepxion.discovery.console.etcd.configuration; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Congwei Xu + * @version 1.0 + */ + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import com.nepxion.banner.BannerConstant; +import com.nepxion.banner.Description; +import com.nepxion.banner.LogoBanner; +import com.nepxion.banner.NepxionBanner; +import com.nepxion.discovery.common.entity.ConfigType; +import com.nepxion.discovery.console.adapter.ConfigAdapter; +import com.nepxion.discovery.console.etcd.adapter.EtcdConfigAdapter; +import com.taobao.text.Color; + +@Configuration +public class EtcdConfigAutoConfiguration { + static { + LogoBanner logoBanner = new LogoBanner(EtcdConfigAutoConfiguration.class, "/com/nepxion/etcd/resource/logo.txt", "Welcome to Nepxion", 4, 5, new Color[] { Color.red, Color.green, Color.cyan, Color.blue }, true); + NepxionBanner.show(logoBanner, new Description("Config:", ConfigType.ETCD.toString(), 0, 1), new Description(BannerConstant.GITHUB + ":", BannerConstant.NEPXION_GITHUB + "/Discovery", 0, 1)); + } + + @Bean + public ConfigAdapter configAdapter() { + return new EtcdConfigAdapter(); + } +} \ No newline at end of file diff --git a/discovery-console/discovery-console-starter-etcd/src/main/resources/META-INF/spring.factories b/discovery-console/discovery-console-starter-etcd/src/main/resources/META-INF/spring.factories new file mode 100644 index 0000000000..ac65d6d04e --- /dev/null +++ b/discovery-console/discovery-console-starter-etcd/src/main/resources/META-INF/spring.factories @@ -0,0 +1,2 @@ +org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ +com.nepxion.discovery.console.etcd.configuration.EtcdConfigAutoConfiguration \ No newline at end of file diff --git a/discovery-console/discovery-console-starter-nacos/pom.xml b/discovery-console/discovery-console-starter-nacos/pom.xml new file mode 100644 index 0000000000..46b90eda02 --- /dev/null +++ b/discovery-console/discovery-console-starter-nacos/pom.xml @@ -0,0 +1,28 @@ + + + discovery-console-starter-nacos + Nepxion Discovery Console Starter Nacos + jar + 4.0.0 + Nepxion Discovery is a solution for Spring Cloud with blue green, gray, weight, limitation, circuit breaker, degrade, isolation, monitor, tracing, dye, failover, async agent + http://www.nepxion.com + + + com.nepxion + discovery-console + 6.23.0 + + + + + ${project.groupId} + discovery-console-starter + + + + ${project.groupId} + discovery-common-nacos + + + \ No newline at end of file diff --git a/discovery-console/discovery-console-starter-nacos/src/main/java/com/nepxion/discovery/console/nacos/adapter/NacosConfigAdapter.java b/discovery-console/discovery-console-starter-nacos/src/main/java/com/nepxion/discovery/console/nacos/adapter/NacosConfigAdapter.java new file mode 100644 index 0000000000..60ed498398 --- /dev/null +++ b/discovery-console/discovery-console-starter-nacos/src/main/java/com/nepxion/discovery/console/nacos/adapter/NacosConfigAdapter.java @@ -0,0 +1,47 @@ +package com.nepxion.discovery.console.nacos.adapter; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.springframework.beans.factory.annotation.Autowired; + +import com.nepxion.discovery.common.entity.ConfigType; +import com.nepxion.discovery.common.entity.FormatType; +import com.nepxion.discovery.common.nacos.operation.NacosOperation; +import com.nepxion.discovery.console.adapter.ConfigAdapter; + +public class NacosConfigAdapter implements ConfigAdapter { + @Autowired + private NacosOperation nacosOperation; + + @Override + public boolean updateConfig(String group, String serviceId, String config) throws Exception { + return nacosOperation.publishConfig(group, serviceId, config); + } + + @Override + public boolean updateConfig(String group, String serviceId, String config, FormatType formatType) throws Exception { + return nacosOperation.publishConfig(group, serviceId, config, formatType); + } + + @Override + public boolean clearConfig(String group, String serviceId) throws Exception { + return nacosOperation.removeConfig(group, serviceId); + } + + @Override + public String getConfig(String group, String serviceId) throws Exception { + return nacosOperation.getConfig(group, serviceId); + } + + @Override + public ConfigType getConfigType() { + return ConfigType.NACOS; + } +} \ No newline at end of file diff --git a/discovery-console/discovery-console-starter-nacos/src/main/java/com/nepxion/discovery/console/nacos/configuration/NacosConfigAutoConfiguration.java b/discovery-console/discovery-console-starter-nacos/src/main/java/com/nepxion/discovery/console/nacos/configuration/NacosConfigAutoConfiguration.java new file mode 100644 index 0000000000..3156cd5e8e --- /dev/null +++ b/discovery-console/discovery-console-starter-nacos/src/main/java/com/nepxion/discovery/console/nacos/configuration/NacosConfigAutoConfiguration.java @@ -0,0 +1,49 @@ +package com.nepxion.discovery.console.nacos.configuration; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import com.nepxion.banner.BannerConstant; +import com.nepxion.banner.Description; +import com.nepxion.banner.LogoBanner; +import com.nepxion.banner.NepxionBanner; +import com.nepxion.discovery.common.entity.ConfigType; +import com.nepxion.discovery.console.adapter.ConfigAdapter; +import com.nepxion.discovery.console.nacos.adapter.NacosConfigAdapter; +import com.taobao.text.Color; + +@Configuration +public class NacosConfigAutoConfiguration { + static { + /*String bannerShown = System.getProperty(BannerConstant.BANNER_SHOWN, "true"); + if (Boolean.valueOf(bannerShown)) { + System.out.println(""); + System.out.println("╔═╗ ╔╗"); + System.out.println("║║╚╗║║"); + System.out.println("║╔╗╚╝╠══╦══╦══╦══╗"); + System.out.println("║║╚╗║║╔╗║╔═╣╔╗║══╣"); + System.out.println("║║ ║║║╔╗║╚═╣╚╝╠══║"); + System.out.println("╚╝ ╚═╩╝╚╩══╩══╩══╝"); + System.out.println(NacosConstant.TYPE + " Config"); + System.out.println(""); + }*/ + + LogoBanner logoBanner = new LogoBanner(NacosConfigAutoConfiguration.class, "/com/nepxion/nacos/resource/logo.txt", "Welcome to Nepxion", 5, 5, new Color[] { Color.red, Color.green, Color.cyan, Color.blue, Color.yellow }, true); + + NepxionBanner.show(logoBanner, new Description("Config:", ConfigType.NACOS.toString(), 0, 1), new Description(BannerConstant.GITHUB + ":", BannerConstant.NEPXION_GITHUB + "/Discovery", 0, 1)); + } + + @Bean + public ConfigAdapter configAdapter() { + return new NacosConfigAdapter(); + } +} \ No newline at end of file diff --git a/discovery-console/discovery-console-starter-nacos/src/main/resources/META-INF/spring.factories b/discovery-console/discovery-console-starter-nacos/src/main/resources/META-INF/spring.factories new file mode 100644 index 0000000000..846863ee66 --- /dev/null +++ b/discovery-console/discovery-console-starter-nacos/src/main/resources/META-INF/spring.factories @@ -0,0 +1,2 @@ +org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ +com.nepxion.discovery.console.nacos.configuration.NacosConfigAutoConfiguration \ No newline at end of file diff --git a/discovery-console/discovery-console-starter-redis/pom.xml b/discovery-console/discovery-console-starter-redis/pom.xml new file mode 100644 index 0000000000..95833be548 --- /dev/null +++ b/discovery-console/discovery-console-starter-redis/pom.xml @@ -0,0 +1,28 @@ + + + discovery-console-starter-redis + Nepxion Discovery Console Starter Redis + jar + 4.0.0 + Nepxion Discovery is a solution for Spring Cloud with blue green, gray, weight, limitation, circuit breaker, degrade, isolation, monitor, tracing, dye, failover, async agent + http://www.nepxion.com + + + com.nepxion + discovery-console + 6.23.0 + + + + + ${project.groupId} + discovery-console-starter + + + + ${project.groupId} + discovery-common-redis + + + \ No newline at end of file diff --git a/discovery-console/discovery-console-starter-redis/src/main/java/com/nepxion/discovery/console/redis/adapter/RedisConfigAdapter.java b/discovery-console/discovery-console-starter-redis/src/main/java/com/nepxion/discovery/console/redis/adapter/RedisConfigAdapter.java new file mode 100644 index 0000000000..9f8d21d0e9 --- /dev/null +++ b/discovery-console/discovery-console-starter-redis/src/main/java/com/nepxion/discovery/console/redis/adapter/RedisConfigAdapter.java @@ -0,0 +1,42 @@ +package com.nepxion.discovery.console.redis.adapter; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @author JiKai Sun + * @version 1.0 + */ + +import org.springframework.beans.factory.annotation.Autowired; + +import com.nepxion.discovery.common.entity.ConfigType; +import com.nepxion.discovery.common.redis.operation.RedisOperation; +import com.nepxion.discovery.console.adapter.ConfigAdapter; + +public class RedisConfigAdapter implements ConfigAdapter { + @Autowired + private RedisOperation redisOperation; + + @Override + public boolean updateConfig(String group, String serviceId, String config) throws Exception { + return redisOperation.publishConfig(group, serviceId, config); + } + + @Override + public boolean clearConfig(String group, String serviceId) throws Exception { + return redisOperation.removeConfig(group, serviceId); + } + + @Override + public String getConfig(String group, String serviceId) throws Exception { + return redisOperation.getConfig(group, serviceId); + } + + @Override + public ConfigType getConfigType() { + return ConfigType.REDIS; + } +} \ No newline at end of file diff --git a/discovery-console/discovery-console-starter-redis/src/main/java/com/nepxion/discovery/console/redis/configuration/RedisConfigAutoConfiguration.java b/discovery-console/discovery-console-starter-redis/src/main/java/com/nepxion/discovery/console/redis/configuration/RedisConfigAutoConfiguration.java new file mode 100644 index 0000000000..9175d1f832 --- /dev/null +++ b/discovery-console/discovery-console-starter-redis/src/main/java/com/nepxion/discovery/console/redis/configuration/RedisConfigAutoConfiguration.java @@ -0,0 +1,50 @@ +package com.nepxion.discovery.console.redis.configuration; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @author JiKai Sun + * @version 1.0 + */ + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import com.nepxion.banner.BannerConstant; +import com.nepxion.banner.Description; +import com.nepxion.banner.LogoBanner; +import com.nepxion.banner.NepxionBanner; +import com.nepxion.discovery.common.entity.ConfigType; +import com.nepxion.discovery.console.adapter.ConfigAdapter; +import com.nepxion.discovery.console.redis.adapter.RedisConfigAdapter; +import com.taobao.text.Color; + +@Configuration +public class RedisConfigAutoConfiguration { + static { + /*String bannerShown = System.getProperty(BannerConstant.BANNER_SHOWN, "true"); + if (Boolean.valueOf(bannerShown)) { + System.out.println(""); + System.out.println("╔═══╗ ╔╗"); + System.out.println("║╔═╗║ ║║"); + System.out.println("║╚═╝╠══╦═╝╠╦══╗"); + System.out.println("║╔╗╔╣║═╣╔╗╠╣══╣"); + System.out.println("║║║╚╣║═╣╚╝║╠══║"); + System.out.println("╚╝╚═╩══╩══╩╩══╝"); + System.out.println(RedisConstant.TYPE + " Config"); + System.out.println(""); + }*/ + + LogoBanner logoBanner = new LogoBanner(RedisConfigAutoConfiguration.class, "/com/nepxion/redis/resource/logo.txt", "Welcome to Nepxion", 5, 5, new Color[] { Color.red, Color.green, Color.cyan, Color.blue, Color.yellow }, true); + + NepxionBanner.show(logoBanner, new Description("Config:", ConfigType.REDIS.toString(), 0, 1), new Description(BannerConstant.GITHUB + ":", BannerConstant.NEPXION_GITHUB + "/Discovery", 0, 1)); + } + + @Bean + public ConfigAdapter configAdapter() { + return new RedisConfigAdapter(); + } +} \ No newline at end of file diff --git a/discovery-console/discovery-console-starter-redis/src/main/resources/META-INF/spring.factories b/discovery-console/discovery-console-starter-redis/src/main/resources/META-INF/spring.factories new file mode 100644 index 0000000000..a01c5fb3b6 --- /dev/null +++ b/discovery-console/discovery-console-starter-redis/src/main/resources/META-INF/spring.factories @@ -0,0 +1,2 @@ +org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ +com.nepxion.discovery.console.redis.configuration.RedisConfigAutoConfiguration \ No newline at end of file diff --git a/discovery-console/discovery-console-starter-zookeeper/pom.xml b/discovery-console/discovery-console-starter-zookeeper/pom.xml new file mode 100644 index 0000000000..90043d31c4 --- /dev/null +++ b/discovery-console/discovery-console-starter-zookeeper/pom.xml @@ -0,0 +1,28 @@ + + + discovery-console-starter-zookeeper + Nepxion Discovery Console Starter Zookeeper + jar + 4.0.0 + Nepxion Discovery is a solution for Spring Cloud with blue green, gray, weight, limitation, circuit breaker, degrade, isolation, monitor, tracing, dye, failover, async agent + http://www.nepxion.com + + + com.nepxion + discovery-console + 6.23.0 + + + + + ${project.groupId} + discovery-console-starter + + + + ${project.groupId} + discovery-common-zookeeper + + + \ No newline at end of file diff --git a/discovery-console/discovery-console-starter-zookeeper/src/main/java/com/nepxion/discovery/console/zookeeper/adapter/ZookeeperConfigAdapter.java b/discovery-console/discovery-console-starter-zookeeper/src/main/java/com/nepxion/discovery/console/zookeeper/adapter/ZookeeperConfigAdapter.java new file mode 100644 index 0000000000..cdbd714bd0 --- /dev/null +++ b/discovery-console/discovery-console-starter-zookeeper/src/main/java/com/nepxion/discovery/console/zookeeper/adapter/ZookeeperConfigAdapter.java @@ -0,0 +1,41 @@ +package com.nepxion.discovery.console.zookeeper.adapter; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author rotten + * @version 1.0 + */ + +import org.springframework.beans.factory.annotation.Autowired; + +import com.nepxion.discovery.common.entity.ConfigType; +import com.nepxion.discovery.common.zookeeper.operation.ZookeeperOperation; +import com.nepxion.discovery.console.adapter.ConfigAdapter; + +public class ZookeeperConfigAdapter implements ConfigAdapter { + @Autowired + private ZookeeperOperation zookeeperOperation; + + @Override + public boolean updateConfig(String group, String serviceId, String config) throws Exception { + return zookeeperOperation.publishConfig(group, serviceId, config); + } + + @Override + public boolean clearConfig(String group, String serviceId) throws Exception { + return zookeeperOperation.removeConfig(group, serviceId); + } + + @Override + public String getConfig(String group, String serviceId) throws Exception { + return zookeeperOperation.getConfig(group, serviceId); + } + + @Override + public ConfigType getConfigType() { + return ConfigType.ZOOKEEPER; + } +} \ No newline at end of file diff --git a/discovery-console/discovery-console-starter-zookeeper/src/main/java/com/nepxion/discovery/console/zookeeper/configuration/ZookeeperConfigAutoConfiguration.java b/discovery-console/discovery-console-starter-zookeeper/src/main/java/com/nepxion/discovery/console/zookeeper/configuration/ZookeeperConfigAutoConfiguration.java new file mode 100644 index 0000000000..8d6945d96f --- /dev/null +++ b/discovery-console/discovery-console-starter-zookeeper/src/main/java/com/nepxion/discovery/console/zookeeper/configuration/ZookeeperConfigAutoConfiguration.java @@ -0,0 +1,50 @@ +package com.nepxion.discovery.console.zookeeper.configuration; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author rotten + * @version 1.0 + */ + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import com.nepxion.banner.BannerConstant; +import com.nepxion.banner.Description; +import com.nepxion.banner.LogoBanner; +import com.nepxion.banner.NepxionBanner; +import com.nepxion.discovery.common.entity.ConfigType; +import com.nepxion.discovery.console.adapter.ConfigAdapter; +import com.nepxion.discovery.console.zookeeper.adapter.ZookeeperConfigAdapter; +import com.taobao.text.Color; + +@Configuration +public class ZookeeperConfigAutoConfiguration { + static { + /*String bannerShown = System.getProperty(BannerConstant.BANNER_SHOWN, "true"); + if (Boolean.valueOf(bannerShown)) { + System.out.println(""); + System.out.println("╔════╗ ╔╗"); + System.out.println("╚══╗═║ ║║"); + System.out.println(" ╔╝╔╬══╦══╣║╔╦══╦══╦══╦══╦═╗"); + System.out.println(" ╔╝╔╝║╔╗║╔╗║╚╝╣║═╣║═╣╔╗║║═╣╔╝"); + System.out.println("╔╝═╚═╣╚╝║╚╝║╔╗╣║═╣║═╣╚╝║║═╣║"); + System.out.println("╚════╩══╩══╩╝╚╩══╩══╣╔═╩══╩╝"); + System.out.println(" ║║"); + System.out.println(" ╚╝"); + System.out.println(ZookeeperConstant.DISCOVERY_PLUGIN + " Discovery"); + System.out.println(""); + }*/ + + LogoBanner logoBanner = new LogoBanner(ZookeeperConfigAutoConfiguration.class, "/com/nepxion/zookeeper/resource/logo.txt", "Welcome to Nepxion", 9, 5, new Color[] { Color.red, Color.green, Color.cyan, Color.blue, Color.yellow, Color.magenta, Color.red, Color.green, Color.cyan }, true); + NepxionBanner.show(logoBanner, new Description("Config:", ConfigType.ZOOKEEPER.toString(), 0, 1), new Description(BannerConstant.GITHUB + ":", BannerConstant.NEPXION_GITHUB + "/Discovery", 0, 1)); + } + + @Bean + public ConfigAdapter configAdapter() { + return new ZookeeperConfigAdapter(); + } +} \ No newline at end of file diff --git a/discovery-console/discovery-console-starter-zookeeper/src/main/resources/META-INF/spring.factories b/discovery-console/discovery-console-starter-zookeeper/src/main/resources/META-INF/spring.factories new file mode 100644 index 0000000000..f704d0b61d --- /dev/null +++ b/discovery-console/discovery-console-starter-zookeeper/src/main/resources/META-INF/spring.factories @@ -0,0 +1,2 @@ +org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ +com.nepxion.discovery.console.zookeeper.configuration.ZookeeperConfigAutoConfiguration \ No newline at end of file diff --git a/discovery-console/discovery-console-starter/pom.xml b/discovery-console/discovery-console-starter/pom.xml new file mode 100644 index 0000000000..900d568899 --- /dev/null +++ b/discovery-console/discovery-console-starter/pom.xml @@ -0,0 +1,63 @@ + + + discovery-console-starter + Nepxion Discovery Console Starter + jar + 4.0.0 + Nepxion Discovery is a solution for Spring Cloud with blue green, gray, weight, limitation, circuit breaker, degrade, isolation, monitor, tracing, dye, failover, async agent + http://www.nepxion.com + + + com.nepxion + discovery-console + 6.23.0 + + + + + ${project.groupId} + discovery-plugin-framework-starter-parser + + + + ${project.groupId} + banner + + + + org.springframework.cloud + spring-cloud-starter + + + + org.springframework.cloud + spring-cloud-starter-netflix-ribbon + + + + org.springframework.boot + spring-boot-starter-web + + + + io.swagger + swagger-annotations + + + + io.swagger + swagger-models + + + + io.springfox + springfox-swagger2 + + + + io.springfox + springfox-swagger-ui + + + \ No newline at end of file diff --git a/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/adapter/ConfigAdapter.java b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/adapter/ConfigAdapter.java new file mode 100644 index 0000000000..e568e60273 --- /dev/null +++ b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/adapter/ConfigAdapter.java @@ -0,0 +1,28 @@ +package com.nepxion.discovery.console.adapter; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import com.nepxion.discovery.common.entity.ConfigType; +import com.nepxion.discovery.common.entity.FormatType; + +public interface ConfigAdapter { + boolean updateConfig(String group, String serviceId, String config) throws Exception; + + // 除了Nacos,其它配置中心不需要FormatType + default boolean updateConfig(String group, String serviceId, String config, FormatType formatType) throws Exception { + return updateConfig(group, serviceId, config); + } + + boolean clearConfig(String group, String serviceId) throws Exception; + + String getConfig(String group, String serviceId) throws Exception; + + ConfigType getConfigType(); +} \ No newline at end of file diff --git a/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/configuration/ConsoleAutoConfiguration.java b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/configuration/ConsoleAutoConfiguration.java new file mode 100644 index 0000000000..99e56b6180 --- /dev/null +++ b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/configuration/ConsoleAutoConfiguration.java @@ -0,0 +1,202 @@ +package com.nepxion.discovery.console.configuration; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.cloud.client.loadbalancer.LoadBalanced; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Import; +import org.springframework.web.client.RestTemplate; + +import com.nepxion.discovery.common.handler.DiscoveryResponseErrorHandler; +import com.nepxion.discovery.console.constant.ConsoleConstant; +import com.nepxion.discovery.console.endpoint.AuthenticationEndpoint; +import com.nepxion.discovery.console.endpoint.BlacklistEndpoint; +import com.nepxion.discovery.console.endpoint.ConfigEndpoint; +import com.nepxion.discovery.console.endpoint.FailoverEndpoint; +import com.nepxion.discovery.console.endpoint.InspectorEndpoint; +import com.nepxion.discovery.console.endpoint.RouteEndpoint; +import com.nepxion.discovery.console.endpoint.SentinelEndpoint; +import com.nepxion.discovery.console.endpoint.ServiceEndpoint; +import com.nepxion.discovery.console.endpoint.StrategyEndpoint; +import com.nepxion.discovery.console.endpoint.VersionEndpoint; +import com.nepxion.discovery.console.resource.AuthenticationResource; +import com.nepxion.discovery.console.resource.AuthenticationResourceImpl; +import com.nepxion.discovery.console.resource.BlacklistResource; +import com.nepxion.discovery.console.resource.BlacklistResourceImpl; +import com.nepxion.discovery.console.resource.ConfigResource; +import com.nepxion.discovery.console.resource.ConfigResourceImpl; +import com.nepxion.discovery.console.resource.FailoverResource; +import com.nepxion.discovery.console.resource.FailoverResourceImpl; +import com.nepxion.discovery.console.resource.InspectorResource; +import com.nepxion.discovery.console.resource.InspectorResourceImpl; +import com.nepxion.discovery.console.resource.RouteResource; +import com.nepxion.discovery.console.resource.RouteResourceImpl; +import com.nepxion.discovery.console.resource.SentinelResource; +import com.nepxion.discovery.console.resource.SentinelResourceImpl; +import com.nepxion.discovery.console.resource.ServiceResource; +import com.nepxion.discovery.console.resource.ServiceResourceImpl; +import com.nepxion.discovery.console.resource.StrategyResource; +import com.nepxion.discovery.console.resource.StrategyResourceImpl; +import com.nepxion.discovery.console.resource.VersionResource; +import com.nepxion.discovery.console.resource.VersionResourceImpl; + +@Configuration +@Import({ SwaggerConfiguration.class, CorsRegistryConfiguration.class }) +public class ConsoleAutoConfiguration { + @ConditionalOnProperty(value = ConsoleConstant.SPRING_APPLICATION_CONSOLE_AUTHENTICATION_ENDPOINT_ENABLED, matchIfMissing = true) + protected static class AuthenticationEndpointConfiguration { + @Bean + @ConditionalOnMissingBean + public AuthenticationResource authenticationResource() { + return new AuthenticationResourceImpl(); + } + + @Bean + public AuthenticationEndpoint authenticationEndpoint() { + return new AuthenticationEndpoint(); + } + } + + @ConditionalOnProperty(value = ConsoleConstant.SPRING_APPLICATION_CONSOLE_SERVICE_ENDPOINT_ENABLED, matchIfMissing = true) + protected static class ServiceEndpointConfiguration { + @Bean + public ServiceResource serviceResource() { + return new ServiceResourceImpl(); + } + + @Bean + public ServiceEndpoint serviceEndpoint() { + return new ServiceEndpoint(); + } + } + + @ConditionalOnProperty(value = ConsoleConstant.SPRING_APPLICATION_CONSOLE_CONFIG_ENDPOINT_ENABLED, matchIfMissing = true) + protected static class ConfigEndpointConfiguration { + @Bean + public ConfigResource configResource() { + return new ConfigResourceImpl(); + } + + @Bean + public ConfigEndpoint configEndpoint() { + return new ConfigEndpoint(); + } + } + + @ConditionalOnProperty(value = ConsoleConstant.SPRING_APPLICATION_CONSOLE_VERSION_ENDPOINT_ENABLED, matchIfMissing = true) + protected static class VersionEndpointConfiguration { + @Bean + public VersionResource versionResource() { + return new VersionResourceImpl(); + } + + @Bean + public VersionEndpoint versionEndpoint() { + return new VersionEndpoint(); + } + } + + @ConditionalOnProperty(value = ConsoleConstant.SPRING_APPLICATION_CONSOLE_SENTINEL_ENDPOINT_ENABLED, matchIfMissing = true) + protected static class SentinelEndpointConfiguration { + @Bean + public SentinelResource sentinelResource() { + return new SentinelResourceImpl(); + } + + @Bean + public SentinelEndpoint sentinelEndpoint() { + return new SentinelEndpoint(); + } + } + + @ConditionalOnProperty(value = ConsoleConstant.SPRING_APPLICATION_CONSOLE_ROUTE_ENDPOINT_ENABLED, matchIfMissing = true) + protected static class RouteEndpointConfiguration { + @Bean + public RouteResource routeResource() { + return new RouteResourceImpl(); + } + + @Bean + public RouteEndpoint routeEndpoint() { + return new RouteEndpoint(); + } + } + + @ConditionalOnProperty(value = ConsoleConstant.SPRING_APPLICATION_CONSOLE_STRATEGY_ENDPOINT_ENABLED, matchIfMissing = true) + protected static class StrategyEndpointConfiguration { + @Bean + public StrategyResource strategyResource() { + return new StrategyResourceImpl(); + } + + @Bean + public StrategyEndpoint strategyEndpoint() { + return new StrategyEndpoint(); + } + } + + @ConditionalOnProperty(value = ConsoleConstant.SPRING_APPLICATION_CONSOLE_FAILOVER_ENDPOINT_ENABLED, matchIfMissing = true) + protected static class FailoverEndpointConfiguration { + @Bean + public FailoverResource failoverResource() { + return new FailoverResourceImpl(); + } + + @Bean + public FailoverEndpoint failoverEndpoint() { + return new FailoverEndpoint(); + } + } + + @ConditionalOnProperty(value = ConsoleConstant.SPRING_APPLICATION_CONSOLE_BLACKLIST_ENDPOINT_ENABLED, matchIfMissing = true) + protected static class BlacklistEndpointConfiguration { + @Bean + public BlacklistResource blacklistResource() { + return new BlacklistResourceImpl(); + } + + @Bean + public BlacklistEndpoint blacklistEndpoint() { + return new BlacklistEndpoint(); + } + } + + @ConditionalOnProperty(value = ConsoleConstant.SPRING_APPLICATION_CONSOLE_INSPECTOR_ENDPOINT_ENABLED, matchIfMissing = true) + protected static class InspectorEndpointConfiguration { + @Bean + public InspectorResource inspectorResource() { + return new InspectorResourceImpl(); + } + + @Bean + public InspectorEndpoint inspectorEndpoint() { + return new InspectorEndpoint(); + } + } + + protected static class RestTemplateEndpointConfiguration { + @Bean + public RestTemplate consoleRestTemplate() { + RestTemplate consoleRestTemplate = new RestTemplate(); + consoleRestTemplate.setErrorHandler(new DiscoveryResponseErrorHandler()); + + return consoleRestTemplate; + } + + @Bean + @LoadBalanced + public RestTemplate loadBalancedRestTemplate() { + return new RestTemplate(); + } + } +} \ No newline at end of file diff --git a/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/configuration/CorsRegistryConfiguration.java b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/configuration/CorsRegistryConfiguration.java new file mode 100644 index 0000000000..5cadade3f2 --- /dev/null +++ b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/configuration/CorsRegistryConfiguration.java @@ -0,0 +1,28 @@ +package com.nepxion.discovery.console.configuration; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.CorsRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +@Configuration +@ConditionalOnProperty(value = "cors.registry.enabled", matchIfMissing = false) +public class CorsRegistryConfiguration implements WebMvcConfigurer { + // 解决跨域问题 + @Override + public void addCorsMappings(CorsRegistry registry) { + registry.addMapping("/**") + .allowedHeaders("*") + .allowedMethods("*") + .allowedOrigins("*"); + } +} \ No newline at end of file diff --git a/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/configuration/SwaggerConfiguration.java b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/configuration/SwaggerConfiguration.java new file mode 100644 index 0000000000..af28365369 --- /dev/null +++ b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/configuration/SwaggerConfiguration.java @@ -0,0 +1,188 @@ +package com.nepxion.discovery.console.configuration; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import springfox.documentation.RequestHandler; +import springfox.documentation.builders.ApiInfoBuilder; +import springfox.documentation.builders.PathSelectors; +import springfox.documentation.service.ApiInfo; +import springfox.documentation.service.Contact; +import springfox.documentation.service.Parameter; +import springfox.documentation.service.SecurityScheme; +import springfox.documentation.spi.DocumentationType; +import springfox.documentation.spi.service.contexts.SecurityContext; +import springfox.documentation.spring.web.plugins.Docket; +import springfox.documentation.swagger2.annotations.EnableSwagger2; + +import java.util.Collections; +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import com.google.common.base.Function; +import com.google.common.base.Optional; +import com.google.common.base.Predicate; +import com.nepxion.discovery.common.constant.DiscoveryConstant; +import com.nepxion.discovery.common.constant.DiscoverySwaggerConstant; + +@Configuration +@EnableSwagger2 +@ConditionalOnProperty(value = DiscoverySwaggerConstant.SWAGGER_ENABLED, matchIfMissing = true) +public class SwaggerConfiguration { + private String discoveryGroup = DiscoverySwaggerConstant.SWAGGER_DEFAULT_GROUP_VALUE; + private String discoveryPackages = "com.nepxion.discovery.console.endpoint"; + private String discoveryDescription = "Console Restful APIs"; + private String discoveryVersion = DiscoverySwaggerConstant.SWAGGER_DEFAULT_VERSION_VALUE; + private String discoveryLicenseName = DiscoverySwaggerConstant.SWAGGER_DEFAULT_LICENSE_NAME_VALUE; + private String discoveryLicenseUrl = DiscoverySwaggerConstant.SWAGGER_DEFAULT_LICENSE_URL_VALUE; + private String discoveryContactName = DiscoverySwaggerConstant.SWAGGER_DEFAULT_CONTACT_NAME_VALUE; + private String discoveryContactUrl = DiscoverySwaggerConstant.SWAGGER_DEFAULT_CONTACT_URL_VALUE; + private String discoveryContactEmail = DiscoverySwaggerConstant.SWAGGER_DEFAULT_CONTACT_EMAIL_VALUE; + private String discoveryTermsOfServiceUrl = DiscoverySwaggerConstant.SWAGGER_DEFAULT_TERMSOFSERVICE_URL_VALUE; + + @Value("${" + DiscoverySwaggerConstant.SWAGGER_SERVICE_GROUP + ":}") + private String serviceGroup; + + @Value("${" + DiscoverySwaggerConstant.SWAGGER_SERVICE_PACKAGES + ":}") + private String servicePackages; + + @Value("${" + DiscoverySwaggerConstant.SWAGGER_SERVICE_DESCRIPTION + ":}") + private String serviceDescription; + + @Value("${" + DiscoverySwaggerConstant.SWAGGER_SERVICE_VERSION + ":}") + private String serviceVersion; + + @Value("${" + DiscoverySwaggerConstant.SWAGGER_SERVICE_LICENSE_NAME + ":" + DiscoverySwaggerConstant.SWAGGER_DEFAULT_LICENSE_NAME_VALUE + "}") + private String serviceLicenseName; + + @Value("${" + DiscoverySwaggerConstant.SWAGGER_SERVICE_LICENSE_URL + ":" + DiscoverySwaggerConstant.SWAGGER_DEFAULT_LICENSE_URL_VALUE + "}") + private String serviceLicenseUrl; + + @Value("${" + DiscoverySwaggerConstant.SWAGGER_SERVICE_CONTACT_NAME + ":" + DiscoverySwaggerConstant.SWAGGER_DEFAULT_CONTACT_NAME_VALUE + "}") + private String serviceContactName; + + @Value("${" + DiscoverySwaggerConstant.SWAGGER_SERVICE_CONTACT_URL + ":" + DiscoverySwaggerConstant.SWAGGER_DEFAULT_CONTACT_URL_VALUE + "}") + private String serviceContactUrl; + + @Value("${" + DiscoverySwaggerConstant.SWAGGER_SERVICE_CONTACT_EMAIL + ":" + DiscoverySwaggerConstant.SWAGGER_DEFAULT_CONTACT_EMAIL_VALUE + "}") + private String serviceContactEmail; + + @Value("${" + DiscoverySwaggerConstant.SWAGGER_SERVICE_TERMSOFSERVICE_URL + ":" + DiscoverySwaggerConstant.SWAGGER_DEFAULT_TERMSOFSERVICE_URL_VALUE + "}") + private String serviceTermsOfServiceUrl; + + @Value("${" + DiscoveryConstant.SPRING_APPLICATION_NAME + "}") + private String serviceName; + + @Autowired(required = false) + private List swaggerHeaderParameters; + + @Autowired(required = false) + private List swaggerSecuritySchemes; + + @Autowired(required = false) + private List swaggerSecurityContexts; + + @Bean("discoveryDocket") + public Docket discoveryDocket() { + return new Docket(DocumentationType.SWAGGER_2) + .groupName(discoveryGroup) + .apiInfo(apiInfo(discoveryDescription, + discoveryVersion, + discoveryLicenseName, + discoveryLicenseUrl, + discoveryContactName, + discoveryContactUrl, + discoveryContactEmail, + discoveryTermsOfServiceUrl)) + .select() + .apis(SwaggerConfiguration.basePackage(discoveryPackages)) // 扫描该包下的所有需要在Swagger中展示的API,@ApiIgnore注解标注的除外 + .paths(PathSelectors.any()) + .build() + .globalOperationParameters(swaggerHeaderParameters) + .securitySchemes(swaggerSecuritySchemes) + .securityContexts(swaggerSecurityContexts != null ? swaggerSecurityContexts : Collections.emptyList()); + } + + @Bean("serviceDocket") + @ConditionalOnProperty(name = DiscoverySwaggerConstant.SWAGGER_SERVICE_GROUP) + public Docket serviceDocket() { + return new Docket(DocumentationType.SWAGGER_2) + .groupName(serviceGroup) + .apiInfo(apiInfo(serviceDescription, + serviceVersion, + serviceLicenseName, + serviceLicenseUrl, + serviceContactName, + serviceContactUrl, + serviceContactEmail, + serviceTermsOfServiceUrl)) + .select() + .apis(SwaggerConfiguration.basePackage(servicePackages)) // 扫描该包下的所有需要在Swagger中展示的API,@ApiIgnore注解标注的除外 + .paths(PathSelectors.any()) + .build() + .globalOperationParameters(swaggerHeaderParameters) + .securitySchemes(swaggerSecuritySchemes) + .securityContexts(swaggerSecurityContexts != null ? swaggerSecurityContexts : Collections.emptyList()); + } + + private ApiInfo apiInfo(String description, + String version, + String licenseName, + String licenseUrl, + String contactName, + String contactUrl, + String contactEmail, + String termsOfServiceUrl) { + return new ApiInfoBuilder() + .title(serviceName) + .description(description) + .version(version) + .license(licenseName) + .licenseUrl(licenseUrl) + .contact(new Contact(contactName, contactUrl, contactEmail)) + .termsOfServiceUrl(termsOfServiceUrl) + .build(); + } + + public static Predicate basePackage(String basePackage) { + return new Predicate() { + @Override + public boolean apply(RequestHandler input) { + return declaringClass(input).transform(handlerPackage(basePackage)).or(true); + } + }; + } + + private static Function, Boolean> handlerPackage(String basePackage) { + return new Function, Boolean>() { + @Override + public Boolean apply(Class input) { + String[] subPackages = basePackage.split(DiscoveryConstant.SEPARATE); + for (String subPackage : subPackages) { + boolean matched = input.getPackage().getName().startsWith(subPackage.trim()); + if (matched) { + return true; + } + } + + return false; + } + }; + } + + @SuppressWarnings("deprecation") + private static Optional> declaringClass(RequestHandler input) { + return Optional.fromNullable(input.declaringClass()); + } +} \ No newline at end of file diff --git a/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/constant/ConsoleConstant.java b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/constant/ConsoleConstant.java new file mode 100644 index 0000000000..5cdbf37caf --- /dev/null +++ b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/constant/ConsoleConstant.java @@ -0,0 +1,25 @@ +package com.nepxion.discovery.console.constant; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +public class ConsoleConstant { + public static final String SPRING_APPLICATION_CONSOLE_SERVICE_ENDPOINT_ENABLED = "spring.application.console.service.endpoint.enabled"; + public static final String SPRING_APPLICATION_CONSOLE_CONFIG_ENDPOINT_ENABLED = "spring.application.console.config.endpoint.enabled"; + public static final String SPRING_APPLICATION_CONSOLE_VERSION_ENDPOINT_ENABLED = "spring.application.console.version.endpoint.enabled"; + public static final String SPRING_APPLICATION_CONSOLE_INSPECTOR_ENDPOINT_ENABLED = "spring.application.console.inspector.endpoint.enabled"; + public static final String SPRING_APPLICATION_CONSOLE_ROUTE_ENDPOINT_ENABLED = "spring.application.console.route.endpoint.enabled"; + public static final String SPRING_APPLICATION_CONSOLE_STRATEGY_ENDPOINT_ENABLED = "spring.application.console.strategy.endpoint.enabled"; + public static final String SPRING_APPLICATION_CONSOLE_SENTINEL_ENDPOINT_ENABLED = "spring.application.console.sentinel.endpoint.enabled"; + public static final String SPRING_APPLICATION_CONSOLE_BLACKLIST_ENDPOINT_ENABLED = "spring.application.console.blacklist.endpoint.enabled"; + public static final String SPRING_APPLICATION_CONSOLE_FAILOVER_ENDPOINT_ENABLED = "spring.application.console.failover.endpoint.enabled"; + public static final String SPRING_APPLICATION_CONSOLE_AUTHENTICATION_ENDPOINT_ENABLED = "spring.application.console.authentication.endpoint.enabled"; + + public static final String SPRING_APPLICATION_CONSOLE_STRATEGY_ENDPOINT_VALIDATE_EXPRESSION_ENABLED = "spring.application.console.strategy.endpoint.validate-expression.enabled"; +} \ No newline at end of file diff --git a/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/context/ConsoleApplicationContextInitializer.java b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/context/ConsoleApplicationContextInitializer.java new file mode 100644 index 0000000000..b0bec920c5 --- /dev/null +++ b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/context/ConsoleApplicationContextInitializer.java @@ -0,0 +1,47 @@ +package com.nepxion.discovery.console.context; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.springframework.context.ApplicationContextInitializer; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; + +import com.nepxion.banner.BannerConstant; +import com.nepxion.banner.Description; +import com.nepxion.banner.LogoBanner; +import com.nepxion.banner.NepxionBanner; +import com.nepxion.discovery.common.constant.DiscoveryConstant; +import com.taobao.text.Color; + +public class ConsoleApplicationContextInitializer implements ApplicationContextInitializer { + @Override + public void initialize(ConfigurableApplicationContext applicationContext) { + if (!(applicationContext instanceof AnnotationConfigApplicationContext)) { + /*String bannerShown = System.getProperty(BannerConstant.BANNER_SHOWN, "true"); + if (Boolean.valueOf(bannerShown)) { + System.out.println(""); + System.out.println("╔═══╗"); + System.out.println("╚╗╔╗║"); + System.out.println(" ║║║╠╦══╦══╦══╦╗╔╦══╦═╦╗ ╔╗"); + System.out.println(" ║║║╠╣══╣╔═╣╔╗║╚╝║║═╣╔╣║ ║║"); + System.out.println("╔╝╚╝║╠══║╚═╣╚╝╠╗╔╣║═╣║║╚═╝║"); + System.out.println("╚═══╩╩══╩══╩══╝╚╝╚══╩╝╚═╗╔╝"); + System.out.println(" ╔═╝║"); + System.out.println(" ╚══╝"); + System.out.println("Nepxion Discovery - Console v" + DiscoveryConstant.DISCOVERY_VERSION); + System.out.println(""); + }*/ + + LogoBanner logoBanner = new LogoBanner(ConsoleApplicationContextInitializer.class, "/com/nepxion/discovery/resource/logo.txt", "Welcome to Nepxion", 9, 5, new Color[] { Color.red, Color.green, Color.cyan, Color.blue, Color.yellow, Color.magenta, Color.red, Color.green, Color.cyan }, true); + + NepxionBanner.show(logoBanner, new Description(BannerConstant.VERSION + ":", DiscoveryConstant.DISCOVERY_VERSION, 0, 1), new Description(BannerConstant.PLUGIN + ":", "Console", 0, 1), new Description(BannerConstant.GITHUB + ":", BannerConstant.NEPXION_GITHUB + "/Discovery", 0, 1)); + } + } +} \ No newline at end of file diff --git a/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/context/ConsoleEnvironmentPostProcessor.java b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/context/ConsoleEnvironmentPostProcessor.java new file mode 100644 index 0000000000..99751415bd --- /dev/null +++ b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/context/ConsoleEnvironmentPostProcessor.java @@ -0,0 +1,33 @@ +package com.nepxion.discovery.console.context; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.env.EnvironmentPostProcessor; +import org.springframework.core.Ordered; +import org.springframework.core.env.ConfigurableEnvironment; + +import com.nepxion.discovery.common.constant.DiscoveryConstant; +import com.nepxion.discovery.common.entity.ServiceType; +import com.nepxion.discovery.common.util.EnvironmentUtil; + +public class ConsoleEnvironmentPostProcessor implements EnvironmentPostProcessor, Ordered { + @Override + public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { + if (EnvironmentUtil.isStandardEnvironment(environment)) { + System.setProperty(DiscoveryConstant.SPRING_APPLICATION_TYPE, ServiceType.CONSOLE.toString()); + } + } + + @Override + public int getOrder() { + return Ordered.HIGHEST_PRECEDENCE; + } +} \ No newline at end of file diff --git a/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/delegate/ConsoleResourceDelegate.java b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/delegate/ConsoleResourceDelegate.java new file mode 100644 index 0000000000..7cc9d81bac --- /dev/null +++ b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/delegate/ConsoleResourceDelegate.java @@ -0,0 +1,18 @@ +package com.nepxion.discovery.console.delegate; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import com.nepxion.discovery.common.entity.RuleEntity; + +public interface ConsoleResourceDelegate { + RuleEntity getRemoteRuleEntity(String group, String serviceId); + + boolean updateRemoteRuleEntity(String group, String serviceId, RuleEntity ruleEntity); +} \ No newline at end of file diff --git a/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/delegate/ConsoleResourceDelegateImpl.java b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/delegate/ConsoleResourceDelegateImpl.java new file mode 100644 index 0000000000..8d9140690e --- /dev/null +++ b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/delegate/ConsoleResourceDelegateImpl.java @@ -0,0 +1,53 @@ +package com.nepxion.discovery.console.delegate; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; + +import com.nepxion.discovery.common.entity.RuleEntity; +import com.nepxion.discovery.common.exception.DiscoveryException; +import com.nepxion.discovery.console.resource.ConfigResource; + +public class ConsoleResourceDelegateImpl implements ConsoleResourceDelegate { + private static final Logger LOG = LoggerFactory.getLogger(ConsoleResourceDelegateImpl.class); + + @Autowired + private ConfigResource configResource; + + @Override + public RuleEntity getRemoteRuleEntity(String group, String serviceId) { + String subscriptionServiceId = StringUtils.isEmpty(serviceId) ? group : serviceId; + + RuleEntity ruleEntity = null; + try { + ruleEntity = configResource.getRemoteRuleEntity(group, subscriptionServiceId); + } catch (Exception e) { + ruleEntity = new RuleEntity(); + + LOG.warn("Get remote RuleEntity failed, group={}, serviceId={}", group, subscriptionServiceId, e); + } + + return ruleEntity; + } + + @Override + public boolean updateRemoteRuleEntity(String group, String serviceId, RuleEntity ruleEntity) { + String subscriptionServiceId = StringUtils.isEmpty(serviceId) ? group : serviceId; + + try { + return configResource.updateRemoteRuleEntity(group, subscriptionServiceId, ruleEntity); + } catch (Exception e) { + throw new DiscoveryException("Update remote RuleEntity failed, group=" + group + ", serviceId=" + subscriptionServiceId, e); + } + } +} \ No newline at end of file diff --git a/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/endpoint/AuthenticationEndpoint.java b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/endpoint/AuthenticationEndpoint.java new file mode 100644 index 0000000000..086c6b2788 --- /dev/null +++ b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/endpoint/AuthenticationEndpoint.java @@ -0,0 +1,52 @@ +package com.nepxion.discovery.console.endpoint; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.RestController; + +import com.nepxion.discovery.common.entity.AuthenticationEntity; +import com.nepxion.discovery.common.entity.UserEntity; +import com.nepxion.discovery.common.util.ResponseUtil; +import com.nepxion.discovery.console.resource.AuthenticationResource; + +@RestController +@RequestMapping(path = "/authentication") +@Api(tags = { "认证接口" }) +public class AuthenticationEndpoint { + @Autowired + private AuthenticationResource authenticationResource; + + @RequestMapping(path = "/authenticate", method = RequestMethod.POST) + @ApiOperation(value = "登录认证", notes = "", response = ResponseEntity.class, httpMethod = "POST") + @ResponseBody + public ResponseEntity authenticate(@RequestBody @ApiParam(value = "UserEntity实例", required = true) UserEntity userEntity) { + return doAuthenticate(userEntity); + } + + private ResponseEntity doAuthenticate(UserEntity userEntity) { + try { + AuthenticationEntity authenticationEntity = authenticationResource.authenticate(userEntity); + + return ResponseUtil.getSuccessResponse(authenticationEntity); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } +} \ No newline at end of file diff --git a/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/endpoint/BlacklistEndpoint.java b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/endpoint/BlacklistEndpoint.java new file mode 100644 index 0000000000..b15cf2ab80 --- /dev/null +++ b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/endpoint/BlacklistEndpoint.java @@ -0,0 +1,171 @@ +package com.nepxion.discovery.console.endpoint; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.RestController; + +import com.nepxion.discovery.common.entity.AddressEntity; +import com.nepxion.discovery.common.util.ResponseUtil; +import com.nepxion.discovery.console.resource.BlacklistResource; + +@RestController +@RequestMapping(path = "/blacklist") +@Api(tags = { "无损下线黑名单接口" }) +public class BlacklistEndpoint { + @Autowired + private BlacklistResource blacklistResource; + + @RequestMapping(path = "/add-address/{group}/{targetServiceId}", method = RequestMethod.POST) + @ApiOperation(value = "全局订阅方式,根据服务实例IP地址和端口,添加下线的服务实例到黑名单", notes = "", response = ResponseEntity.class, httpMethod = "POST") + @ResponseBody + public ResponseEntity addBlacklist(@PathVariable(value = "group") @ApiParam(value = "组名", required = true) String group, @PathVariable(value = "targetServiceId") @ApiParam(value = "待下线实例的服务名", required = true) String targetServiceId, @RequestBody @ApiParam(value = "待下线实例的IP地址和端口", required = true) AddressEntity targetAddressEntity) { + return doAddBlacklist(group, targetServiceId, targetAddressEntity); + } + + @RequestMapping(path = "/add-uuid/{group}/{targetServiceId}", method = RequestMethod.POST) + @ApiOperation(value = "全局订阅方式,根据服务实例UUId,添加下线的服务实例到黑名单", notes = "", response = ResponseEntity.class, httpMethod = "POST") + @ResponseBody + public ResponseEntity addBlacklist(@PathVariable(value = "group") @ApiParam(value = "组名", required = true) String group, @PathVariable(value = "targetServiceId") @ApiParam(value = "待下线实例的服务名", required = true) String targetServiceId, @RequestBody @ApiParam(value = "待下线实例的UUId", required = true) String targetServiceUUId) { + return doAddBlacklist(group, targetServiceId, targetServiceUUId); + } + + @RequestMapping(path = "/delete/{group}/{targetServiceId}/{targetServiceUUId}", method = RequestMethod.DELETE) + @ApiOperation(value = "全局订阅方式,根据服务实例UUId,从黑名单删除过期的服务实例", notes = "", response = ResponseEntity.class, httpMethod = "DELETE") + @ResponseBody + public ResponseEntity deleteBlacklist(@PathVariable(value = "group") @ApiParam(value = "组名", required = true) String group, @PathVariable(value = "targetServiceId") @ApiParam(value = "已下线实例的服务名", required = true) String targetServiceId, @PathVariable(value = "targetServiceUUId") @ApiParam(value = "已下线实例的UUId", required = true) String targetServiceUUId) { + return doDeleteBlacklist(group, targetServiceId, targetServiceUUId); + } + + @RequestMapping(path = "/clear/{group}", method = RequestMethod.POST) + @ApiOperation(value = "全局订阅方式,从黑名单清除所有过期的服务实例", notes = "", response = ResponseEntity.class, httpMethod = "POST") + @ResponseBody + public ResponseEntity clearBlacklist(@PathVariable(value = "group") @ApiParam(value = "组名", required = true) String group) { + return doClearBlacklist(group); + } + + @RequestMapping(path = "/add-address/{group}/{serviceId}/{targetServiceId}", method = RequestMethod.POST) + @ApiOperation(value = "局部订阅方式,根据服务实例IP地址和端口,添加下线的服务实例到黑名单", notes = "", response = ResponseEntity.class, httpMethod = "POST") + @ResponseBody + public ResponseEntity addBlacklist(@PathVariable(value = "group") @ApiParam(value = "组名", required = true) String group, @PathVariable(value = "serviceId") @ApiParam(value = "服务名", required = true) String serviceId, @PathVariable(value = "targetServiceId") @ApiParam(value = "待下线实例的服务名", required = true) String targetServiceId, @RequestBody @ApiParam(value = "待下线实例的IP地址和端口", required = true) AddressEntity targetAddressEntity) { + return doAddBlacklist(group, serviceId, targetServiceId, targetAddressEntity); + } + + @RequestMapping(path = "/add-uuid/{group}/{serviceId}/{targetServiceId}", method = RequestMethod.POST) + @ApiOperation(value = "局部订阅方式,根据服务实例UUId,添加下线的服务实例到黑名单", notes = "", response = ResponseEntity.class, httpMethod = "POST") + @ResponseBody + public ResponseEntity addBlacklist(@PathVariable(value = "group") @ApiParam(value = "组名", required = true) String group, @PathVariable(value = "serviceId") @ApiParam(value = "服务名", required = true) String serviceId, @PathVariable(value = "targetServiceId") @ApiParam(value = "待下线实例的服务名", required = true) String targetServiceId, @RequestBody @ApiParam(value = "待下线实例的UUId", required = true) String targetServiceUUId) { + return doAddBlacklist(group, serviceId, targetServiceId, targetServiceUUId); + } + + @RequestMapping(path = "/delete/{group}/{serviceId}/{targetServiceId}/{targetServiceUUId}", method = RequestMethod.DELETE) + @ApiOperation(value = "局部订阅方式,根据服务实例UUId,从黑名单删除过期的服务实例", notes = "", response = ResponseEntity.class, httpMethod = "DELETE") + @ResponseBody + public ResponseEntity deleteBlacklist(@PathVariable(value = "group") @ApiParam(value = "组名", required = true) String group, @PathVariable(value = "serviceId") @ApiParam(value = "服务名", required = true) String serviceId, @PathVariable(value = "targetServiceId") @ApiParam(value = "已下线实例的服务名", required = true) String targetServiceId, @PathVariable(value = "targetServiceUUId") @ApiParam(value = "已下线实例的UUId", required = true) String targetServiceUUId) { + return doDeleteBlacklist(group, serviceId, targetServiceId, targetServiceUUId); + } + + @RequestMapping(path = "/clear/{group}/{serviceId}", method = RequestMethod.POST) + @ApiOperation(value = "局部订阅方式,从黑名单清除所有过期的服务实例", notes = "", response = ResponseEntity.class, httpMethod = "POST") + @ResponseBody + public ResponseEntity clearBlacklist(@PathVariable(value = "group") @ApiParam(value = "组名", required = true) String group, @PathVariable(value = "serviceId") @ApiParam(value = "服务名", required = true) String serviceId) { + return doClearBlacklist(group, serviceId); + } + + private ResponseEntity doAddBlacklist(String group, String targetServiceId, AddressEntity targetAddressEntity) { + try { + String result = blacklistResource.addBlacklist(group, targetServiceId, targetAddressEntity.getHost(), targetAddressEntity.getPort()); + + return ResponseUtil.getSuccessResponse(result); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doAddBlacklist(String group, String targetServiceId, String targetServiceUUId) { + try { + String result = blacklistResource.addBlacklist(group, targetServiceId, targetServiceUUId); + + return ResponseUtil.getSuccessResponse(result); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doDeleteBlacklist(String group, String targetServiceId, String targetServiceUUId) { + try { + boolean result = blacklistResource.deleteBlacklist(group, targetServiceId, targetServiceUUId); + + return ResponseUtil.getSuccessResponse(result); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doClearBlacklist(String group) { + try { + boolean result = blacklistResource.clearBlacklist(group); + + return ResponseUtil.getSuccessResponse(result); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doAddBlacklist(String group, String serviceId, String targetServiceId, AddressEntity targetAddressEntity) { + try { + String result = blacklistResource.addBlacklist(group, serviceId, targetServiceId, targetAddressEntity.getHost(), targetAddressEntity.getPort()); + + return ResponseUtil.getSuccessResponse(result); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doAddBlacklist(String group, String serviceId, String targetServiceId, String targetServiceUUId) { + try { + String result = blacklistResource.addBlacklist(group, serviceId, targetServiceId, targetServiceUUId); + + return ResponseUtil.getSuccessResponse(result); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doDeleteBlacklist(String group, String serviceId, String targetServiceId, String targetServiceUUId) { + try { + boolean result = blacklistResource.deleteBlacklist(group, serviceId, targetServiceId, targetServiceUUId); + + return ResponseUtil.getSuccessResponse(result); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doClearBlacklist(String group, String serviceId) { + try { + boolean result = blacklistResource.clearBlacklist(group, serviceId); + + return ResponseUtil.getSuccessResponse(result); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } +} \ No newline at end of file diff --git a/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/endpoint/ConfigEndpoint.java b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/endpoint/ConfigEndpoint.java new file mode 100644 index 0000000000..73009741ab --- /dev/null +++ b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/endpoint/ConfigEndpoint.java @@ -0,0 +1,257 @@ +package com.nepxion.discovery.console.endpoint; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; + +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.RestController; + +import com.nepxion.discovery.common.entity.FormatType; +import com.nepxion.discovery.common.entity.ResultEntity; +import com.nepxion.discovery.common.entity.RuleEntity; +import com.nepxion.discovery.common.util.ResponseUtil; +import com.nepxion.discovery.console.resource.ConfigResource; + +@RestController +@RequestMapping(path = "/config") +@Api(tags = { "配置接口" }) +public class ConfigEndpoint { + @Autowired + private ConfigResource configResource; + + @RequestMapping(path = "/config-type", method = RequestMethod.GET) + @ApiOperation(value = "获取配置中心类型", notes = "", response = ResponseEntity.class, httpMethod = "GET") + @ResponseBody + public ResponseEntity configType() { + return doConfigType(); + } + + @RequestMapping(path = "/remote/update/{group}/{serviceId}", method = RequestMethod.POST) + @ApiOperation(value = "更新规则配置到远程配置中心", notes = "", response = ResponseEntity.class, httpMethod = "POST") + @ResponseBody + public ResponseEntity remoteConfigUpdate(@PathVariable(value = "group") @ApiParam(value = "组名", required = true) String group, @PathVariable(value = "serviceId") @ApiParam(value = "服务名。当全局推送模式下,服务名必须由组名来代替", required = true) String serviceId, @RequestBody @ApiParam(value = "规则配置内容", required = true) String config) { + return doRemoteConfigUpdate(group, serviceId, config); + } + + @RequestMapping(path = "/remote/update/{group}/{serviceId}/{formatType}", method = RequestMethod.POST) + @ApiOperation(value = "更新规则配置到远程配置中心", notes = "", response = ResponseEntity.class, httpMethod = "POST") + @ResponseBody + public ResponseEntity remoteConfigUpdate(@PathVariable(value = "group") @ApiParam(value = "组名", required = true) String group, @PathVariable(value = "serviceId") @ApiParam(value = "服务名。当全局推送模式下,服务名必须由组名来代替", required = true) String serviceId, @PathVariable(value = "formatType") @ApiParam(value = "配置类型(Nacos专用)。取值: xml | json | yaml | properties | html | text", defaultValue = "text", required = true) String formatType, @RequestBody @ApiParam(value = "规则配置内容", required = true) String config) { + return doRemoteConfigUpdate(group, serviceId, config, formatType); + } + + @RequestMapping(path = "/remote/update-rule-entity/{group}/{serviceId}", method = RequestMethod.POST) + @ApiOperation(value = "更新规则配置对象到远程配置中心", notes = "", response = ResponseEntity.class, httpMethod = "POST") + @ResponseBody + public ResponseEntity remoteRuleEntityUpdate(@PathVariable(value = "group") @ApiParam(value = "组名", required = true) String group, @PathVariable(value = "serviceId") @ApiParam(value = "服务名。当全局推送模式下,服务名必须由组名来代替", required = true) String serviceId, @RequestBody @ApiParam(value = "规则配置对象", required = true) RuleEntity ruleEntity) { + return doRemoteRuleEntityUpdate(group, serviceId, ruleEntity); + } + + @RequestMapping(path = "/remote/clear/{group}/{serviceId}", method = RequestMethod.POST) + @ApiOperation(value = "清除规则配置到远程配置中心", notes = "", response = ResponseEntity.class, httpMethod = "POST") + @ResponseBody + public ResponseEntity remoteConfigClear(@PathVariable(value = "group") @ApiParam(value = "组名", required = true) String group, @PathVariable(value = "serviceId") @ApiParam(value = "服务名。当全局推送模式下,服务名必须由组名来代替", required = true) String serviceId) { + return doRemoteConfigClear(group, serviceId); + } + + @RequestMapping(path = "/remote/view/{group}/{serviceId}", method = RequestMethod.GET) + @ApiOperation(value = "查看远程配置中心的规则配置", notes = "", response = ResponseEntity.class, httpMethod = "GET") + @ResponseBody + public ResponseEntity remoteConfigView(@PathVariable(value = "group") @ApiParam(value = "组名", required = true) String group, @PathVariable(value = "serviceId") @ApiParam(value = "服务名。当全局推送模式下,服务名必须由组名来代替", required = true) String serviceId) { + return doRemoteConfigView(group, serviceId); + } + + @RequestMapping(path = "/remote/view-rule-entity/{group}/{serviceId}", method = RequestMethod.GET) + @ApiOperation(value = "查看远程配置中心的规则配置对象", notes = "", response = ResponseEntity.class, httpMethod = "GET") + @ResponseBody + public ResponseEntity remoteRuleEntityView(@PathVariable(value = "group") @ApiParam(value = "组名", required = true) String group, @PathVariable(value = "serviceId") @ApiParam(value = "服务名。当全局推送模式下,服务名必须由组名来代替", required = true) String serviceId) { + return doRemoteRuleEntityView(group, serviceId); + } + + @RequestMapping(path = "/update-async/{serviceId}", method = RequestMethod.POST) + @ApiOperation(value = "批量异步更新规则配置", notes = "", response = ResponseEntity.class, httpMethod = "POST") + @ResponseBody + public ResponseEntity configUpdateAsync(@PathVariable(value = "serviceId") @ApiParam(value = "服务名", required = true) String serviceId, @RequestBody @ApiParam(value = "规则配置内容", required = true) String config) { + return doConfigUpdate(serviceId, config, true); + } + + @RequestMapping(path = "/update-sync/{serviceId}", method = RequestMethod.POST) + @ApiOperation(value = "批量同步更新规则配置", notes = "", response = ResponseEntity.class, httpMethod = "POST") + @ResponseBody + public ResponseEntity configUpdateSync(@PathVariable(value = "serviceId") @ApiParam(value = "服务名", required = true) String serviceId, @RequestBody @ApiParam(value = "规则配置内容", required = true) String config) { + return doConfigUpdate(serviceId, config, false); + } + + @RequestMapping(path = "/clear-async/{serviceId}", method = RequestMethod.POST) + @ApiOperation(value = "批量异步清除规则配置", notes = "", response = ResponseEntity.class, httpMethod = "POST") + @ResponseBody + public ResponseEntity configClearAsync(@PathVariable(value = "serviceId") @ApiParam(value = "服务名", required = true) String serviceId) { + return doConfigClear(serviceId, true); + } + + @RequestMapping(path = "/clear-sync/{serviceId}", method = RequestMethod.POST) + @ApiOperation(value = "批量同步清除规则配置", notes = "", response = ResponseEntity.class, httpMethod = "POST") + @ResponseBody + public ResponseEntity configClearSync(@PathVariable(value = "serviceId") @ApiParam(value = "服务名", required = true) String serviceId) { + return doConfigClear(serviceId, false); + } + + @RequestMapping(path = "/view/{serviceId}", method = RequestMethod.GET) + @ApiOperation(value = "批量查看规则配置", notes = "", response = ResponseEntity.class, httpMethod = "GET") + @ResponseBody + public ResponseEntity configView(@PathVariable(value = "serviceId") @ApiParam(value = "服务名", required = true) String serviceId) { + return doConfigView(serviceId); + } + + @RequestMapping(path = "/parse", method = RequestMethod.POST) + @ApiOperation(value = "解析规则配置内容成对象", notes = "", response = ResponseEntity.class, httpMethod = "POST") + @ResponseBody + public ResponseEntity configParse(@RequestBody @ApiParam(value = "规则配置内容", required = true) String config) { + return doConfigParse(config); + } + + @RequestMapping(path = "/deparse", method = RequestMethod.POST) + @ApiOperation(value = "反解析规则配置对象成内容", notes = "", response = ResponseEntity.class, httpMethod = "POST") + @ResponseBody + public ResponseEntity configDeparse(@RequestBody @ApiParam(value = "规则配置对象,RuleEntity格式", required = true) RuleEntity ruleEntity) { + return doConfigDeparse(ruleEntity); + } + + private ResponseEntity doConfigType() { + try { + String configType = configResource.getConfigType().toString(); + + return ResponseUtil.getSuccessResponse(configType); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doRemoteConfigUpdate(String group, String serviceId, String config) { + try { + boolean result = configResource.updateRemoteConfig(group, serviceId, config); + + return ResponseUtil.getSuccessResponse(result); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doRemoteConfigUpdate(String group, String serviceId, String config, String formatType) { + try { + boolean result = configResource.updateRemoteConfig(group, serviceId, config, FormatType.fromString(formatType)); + + return ResponseUtil.getSuccessResponse(result); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doRemoteRuleEntityUpdate(String group, String serviceId, RuleEntity ruleEntity) { + try { + boolean result = configResource.updateRemoteRuleEntity(group, serviceId, ruleEntity); + + return ResponseUtil.getSuccessResponse(result); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doRemoteConfigClear(String group, String serviceId) { + try { + boolean result = configResource.clearRemoteConfig(group, serviceId); + + return ResponseUtil.getSuccessResponse(result); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doRemoteConfigView(String group, String serviceId) { + try { + String config = configResource.getRemoteConfig(group, serviceId); + + return ResponseUtil.getSuccessResponse(config); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doRemoteRuleEntityView(String group, String serviceId) { + try { + RuleEntity ruleEntity = configResource.getRemoteRuleEntity(group, serviceId); + + return ResponseUtil.getSuccessResponse(ruleEntity); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doConfigUpdate(String serviceId, String config, boolean async) { + try { + List resultEntityList = configResource.updateConfig(serviceId, config, async); + + return ResponseUtil.getSuccessResponse(resultEntityList); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doConfigClear(String serviceId, boolean async) { + try { + List resultEntityList = configResource.clearConfig(serviceId, async); + + return ResponseUtil.getSuccessResponse(resultEntityList); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doConfigView(String serviceId) { + try { + List resultEntityList = configResource.viewConfig(serviceId); + + return ResponseUtil.getSuccessResponse(resultEntityList); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doConfigParse(String config) { + try { + RuleEntity ruleEntity = configResource.toRuleEntity(config); + + return ResponseUtil.getSuccessResponse(ruleEntity); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doConfigDeparse(RuleEntity ruleEntity) { + try { + String config = configResource.fromRuleEntity(ruleEntity); + + return ResponseUtil.getSuccessResponse(config); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } +} \ No newline at end of file diff --git a/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/endpoint/FailoverEndpoint.java b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/endpoint/FailoverEndpoint.java new file mode 100644 index 0000000000..13433ae51c --- /dev/null +++ b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/endpoint/FailoverEndpoint.java @@ -0,0 +1,103 @@ +package com.nepxion.discovery.console.endpoint; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.RestController; + +import com.nepxion.discovery.common.entity.FailoverType; +import com.nepxion.discovery.common.util.ResponseUtil; +import com.nepxion.discovery.console.resource.FailoverResource; + +@RestController +@RequestMapping(path = "/failover") +@Api(tags = { "故障转移接口" }) +public class FailoverEndpoint { + @Autowired + private FailoverResource failoverResource; + + @RequestMapping(path = "/create/{failoverType}/{group}", method = RequestMethod.POST) + @ApiOperation(value = "全局订阅方式,创建故障转移", notes = "", response = ResponseEntity.class, httpMethod = "POST") + @ResponseBody + public ResponseEntity createFailover(@PathVariable(value = "failoverType") @ApiParam(value = "故障转移类型。取值:version-prefer | version-failover | region-transfer | region-failover | env-failover | zone-failover | address-failover", defaultValue = "version-failover", required = true) String failoverType, @PathVariable(value = "group") @ApiParam(value = "组名", required = true) String group, @RequestBody @ApiParam(value = "故障转移值,Json格式或者非Json格式", required = true) String failoverValue) { + return doCreateFailover(failoverType, group, failoverValue); + } + + @RequestMapping(path = "/clear/{failoverType}/{group}", method = RequestMethod.POST) + @ApiOperation(value = "全局订阅方式,清除故障转移", notes = "", response = ResponseEntity.class, httpMethod = "POST") + @ResponseBody + public ResponseEntity clearFailover(@PathVariable(value = "failoverType") @ApiParam(value = "故障转移类型。取值:version-prefer | version-failover | region-transfer | region-failover | env-failover | zone-failover | address-failover", defaultValue = "version-failover", required = true) String failoverType, @PathVariable(value = "group") @ApiParam(value = "组名", required = true) String group) { + return doClearFailover(failoverType, group); + } + + @RequestMapping(path = "/create/{failoverType}/{group}/{serviceId}", method = RequestMethod.POST) + @ApiOperation(value = "局部订阅方式,创建故障转移", notes = "", response = ResponseEntity.class, httpMethod = "POST") + @ResponseBody + public ResponseEntity createFailover(@PathVariable(value = "failoverType") @ApiParam(value = "故障转移类型。取值:version-prefer | version-failover | region-transfer | region-failover | env-failover | zone-failover | address-failover", defaultValue = "version-failover", required = true) String failoverType, @PathVariable(value = "group") @ApiParam(value = "组名", required = true) String group, @PathVariable(value = "serviceId") @ApiParam(value = "服务名", required = true) String serviceId, @RequestBody @ApiParam(value = "故障转移值,Json格式或者非Json格式", required = true) String failoverValue) { + return doCreateFailover(failoverType, group, serviceId, failoverValue); + } + + @RequestMapping(path = "/clear/{failoverType}/{group}/{serviceId}", method = RequestMethod.POST) + @ApiOperation(value = "局部订阅方式,清除故障转移", notes = "", response = ResponseEntity.class, httpMethod = "POST") + @ResponseBody + public ResponseEntity clearFailover(@PathVariable(value = "failoverType") @ApiParam(value = "故障转移类型。取值:version-prefer | version-failover | region-transfer | region-failover | env-failover | zone-failover | address-failover", defaultValue = "version-failover", required = true) String failoverType, @PathVariable(value = "group") @ApiParam(value = "组名", required = true) String group, @PathVariable(value = "serviceId") @ApiParam(value = "服务名", required = true) String serviceId) { + return doClearFailover(failoverType, group, serviceId); + } + + private ResponseEntity doCreateFailover(String failoverType, String group, String failoverValue) { + try { + String result = failoverResource.createFailover(FailoverType.fromString(failoverType), group, failoverValue); + + return ResponseUtil.getSuccessResponse(result); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doClearFailover(String failoverType, String group) { + try { + String result = failoverResource.clearFailover(FailoverType.fromString(failoverType), group); + + return ResponseUtil.getSuccessResponse(result); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doCreateFailover(String failoverType, String group, String serviceId, String failoverValue) { + try { + String result = failoverResource.createFailover(FailoverType.fromString(failoverType), group, serviceId, failoverValue); + + return ResponseUtil.getSuccessResponse(result); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doClearFailover(String failoverType, String group, String serviceId) { + try { + String result = failoverResource.clearFailover(FailoverType.fromString(failoverType), group, serviceId); + + return ResponseUtil.getSuccessResponse(result); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } +} \ No newline at end of file diff --git a/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/endpoint/InspectorEndpoint.java b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/endpoint/InspectorEndpoint.java new file mode 100644 index 0000000000..c07fe6212a --- /dev/null +++ b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/endpoint/InspectorEndpoint.java @@ -0,0 +1,71 @@ +package com.nepxion.discovery.console.endpoint; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; + +import java.util.List; +import java.util.Map; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.RestController; + +import com.nepxion.discovery.common.entity.InspectorDebugEntity; +import com.nepxion.discovery.common.util.ResponseUtil; +import com.nepxion.discovery.console.resource.InspectorResource; + +@RestController +@RequestMapping(path = "/inspector") +@Api(tags = { "侦测接口" }) +public class InspectorEndpoint { + @Autowired + private InspectorResource inspectorResource; + + @RequestMapping(path = "/inspect", method = RequestMethod.POST) + @ApiOperation(value = "侦测调试全链路路由,返回字符串格式", notes = "", response = ResponseEntity.class, httpMethod = "POST") + @ResponseBody + public ResponseEntity inspect(@RequestBody @ApiParam(value = "侦测调试对象", required = true) InspectorDebugEntity inspectorDebugEntity) { + return doInspect(inspectorDebugEntity); + } + + @RequestMapping(path = "/inspect-to-list", method = RequestMethod.POST) + @ApiOperation(value = "侦测调试全链路路由,返回结构化格式", notes = "", response = ResponseEntity.class, httpMethod = "POST") + @ResponseBody + public ResponseEntity inspectToList(@RequestBody @ApiParam(value = "侦测调试对象", required = true) InspectorDebugEntity inspectorDebugEntity) { + return doInspectToList(inspectorDebugEntity); + } + + private ResponseEntity doInspect(InspectorDebugEntity inspectorDebugEntity) { + try { + String result = inspectorResource.inspect(inspectorDebugEntity.getProtocol(), inspectorDebugEntity.getPortal(), inspectorDebugEntity.getPath(), inspectorDebugEntity.getService(), inspectorDebugEntity.getHeader(), inspectorDebugEntity.getFilter()); + + return ResponseUtil.getSuccessResponse(result); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doInspectToList(InspectorDebugEntity inspectorDebugEntity) { + try { + List> result = inspectorResource.inspectToList(inspectorDebugEntity.getProtocol(), inspectorDebugEntity.getPortal(), inspectorDebugEntity.getPath(), inspectorDebugEntity.getService(), inspectorDebugEntity.getHeader(), inspectorDebugEntity.getFilter()); + + return ResponseUtil.getSuccessResponse(result); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } +} \ No newline at end of file diff --git a/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/endpoint/RouteEndpoint.java b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/endpoint/RouteEndpoint.java new file mode 100644 index 0000000000..e524894112 --- /dev/null +++ b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/endpoint/RouteEndpoint.java @@ -0,0 +1,175 @@ +package com.nepxion.discovery.console.endpoint; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Ning Zhang + * @author Haojun Ren + * @version 1.0 + */ + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; + +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.RestController; + +import com.nepxion.discovery.common.entity.GatewayType; +import com.nepxion.discovery.common.entity.ResultEntity; +import com.nepxion.discovery.common.util.ResponseUtil; +import com.nepxion.discovery.console.resource.RouteResource; + +@RestController +@RequestMapping(path = "/route") +@Api(tags = { "网关动态路由接口" }) +public class RouteEndpoint { + @Autowired + private RouteResource routeResource; + + @RequestMapping(path = "/remote/update/{gatewayType}/{group}/{serviceId}", method = RequestMethod.POST) + @ApiOperation(value = "更新网关路由到远程配置中心", notes = "", response = ResponseEntity.class, httpMethod = "POST") + @ResponseBody + public ResponseEntity remoteRouteUpdate(@PathVariable(value = "gatewayType") @ApiParam(value = "网关类型。取值: spring-cloud-gateway | zuul。spring-cloud-gateway指Spring Cloud Gateway, zuul指Netflix Zuul", defaultValue = "spring-cloud-gateway", required = true) String gatewayType, @PathVariable(value = "group") @ApiParam(value = "组名", required = true) String group, @PathVariable(value = "serviceId") @ApiParam(value = "网关服务名", required = true) String serviceId, @RequestBody @ApiParam(value = "网关路由对象内容,Json格式", required = true) String route) { + return doRemoteRouteUpdate(gatewayType, group, serviceId, route); + } + + @RequestMapping(path = "/remote/clear/{gatewayType}/{group}/{serviceId}", method = RequestMethod.POST) + @ApiOperation(value = "清除网关路由到远程配置中心", notes = "", response = ResponseEntity.class, httpMethod = "POST") + @ResponseBody + public ResponseEntity remoteRouteClear(@PathVariable(value = "gatewayType") @ApiParam(value = "网关类型。取值: spring-cloud-gateway | zuul。spring-cloud-gateway指Spring Cloud Gateway, zuul指Netflix Zuul", defaultValue = "spring-cloud-gateway", required = true) String gatewayType, @PathVariable(value = "group") @ApiParam(value = "组名", required = true) String group, @PathVariable(value = "serviceId") @ApiParam(value = "网关服务名", required = true) String serviceId) { + return doRemoteRouteClear(gatewayType, group, serviceId); + } + + @RequestMapping(path = "/remote/view/{gatewayType}/{group}/{serviceId}", method = RequestMethod.GET) + @ApiOperation(value = "查看远程配置中心的网关路由", notes = "", response = ResponseEntity.class, httpMethod = "GET") + @ResponseBody + public ResponseEntity remoteSentinelView(@PathVariable(value = "gatewayType") @ApiParam(value = "网关类型。取值: spring-cloud-gateway | zuul。spring-cloud-gateway指Spring Cloud Gateway, zuul指Netflix Zuul", defaultValue = "spring-cloud-gateway", required = true) String gatewayType, @PathVariable(value = "group") @ApiParam(value = "组名", required = true) String group, @PathVariable(value = "serviceId") @ApiParam(value = "网关服务名", required = true) String serviceId) { + return doRemoteRouteView(gatewayType, group, serviceId); + } + + @RequestMapping(path = "/add/{gatewayType}/{serviceId}", method = RequestMethod.POST) + @ApiOperation(value = "批量增加网关路由", notes = "", response = ResponseEntity.class, httpMethod = "POST") + @ResponseBody + public ResponseEntity routeAdd(@PathVariable(value = "gatewayType") @ApiParam(value = "网关类型。取值: spring-cloud-gateway | zuul。spring-cloud-gateway指Spring Cloud Gateway, zuul指Netflix Zuul", defaultValue = "spring-cloud-gateway", required = true) String gatewayType, @PathVariable(value = "serviceId") @ApiParam(value = "网关服务名", required = true) String serviceId, @RequestBody @ApiParam(value = "网关路由对象内容,Json格式", required = true) String route) { + return doRouteAdd(gatewayType, serviceId, route); + } + + @RequestMapping(path = "/modify/{gatewayType}/{serviceId}", method = RequestMethod.POST) + @ApiOperation(value = "批量修改网关路由", notes = "", response = ResponseEntity.class, httpMethod = "POST") + @ResponseBody + public ResponseEntity routeModify(@PathVariable(value = "gatewayType") @ApiParam(value = "网关类型。取值: spring-cloud-gateway | zuul。spring-cloud-gateway指Spring Cloud Gateway, zuul指Netflix Zuul", defaultValue = "spring-cloud-gateway", required = true) String gatewayType, @PathVariable(value = "serviceId") @ApiParam(value = "网关服务名", required = true) String serviceId, @RequestBody @ApiParam(value = "网关路由对象内容,Json格式", required = true) String route) { + return doRouteModify(gatewayType, serviceId, route); + } + + @RequestMapping(path = "/delete/{gatewayType}/{serviceId}/{routeId}", method = RequestMethod.DELETE) + @ApiOperation(value = "批量删除网关路由", notes = "", response = ResponseEntity.class, httpMethod = "DELETE") + @ResponseBody + public ResponseEntity routeDelete(@PathVariable(value = "gatewayType") @ApiParam(value = "网关类型。取值: spring-cloud-gateway | zuul。spring-cloud-gateway指Spring Cloud Gateway, zuul指Netflix Zuul", defaultValue = "spring-cloud-gateway", required = true) String gatewayType, @PathVariable(value = "serviceId") @ApiParam(value = "网关服务名", required = true) String serviceId, @PathVariable(value = "routeId") @ApiParam(value = "路由Id", required = true) String routeId) { + return doRouteDelete(gatewayType, serviceId, routeId); + } + + @RequestMapping(path = "/update-all/{gatewayType}/{serviceId}", method = RequestMethod.POST) + @ApiOperation(value = "批量更新全部网关路由", notes = "", response = ResponseEntity.class, httpMethod = "POST") + @ResponseBody + public ResponseEntity routeUpdateAll(@PathVariable(value = "gatewayType") @ApiParam(value = "网关类型。取值: spring-cloud-gateway | zuul。spring-cloud-gateway指Spring Cloud Gateway, zuul指Netflix Zuul", defaultValue = "spring-cloud-gateway", required = true) String gatewayType, @PathVariable(value = "serviceId") @ApiParam(value = "网关服务名", required = true) String serviceId, @RequestBody @ApiParam(value = "网关路由对象列表内容,Json格式", required = true) String route) { + return doRouteUpdateAll(gatewayType, serviceId, route); + } + + @RequestMapping(path = "/view-all/{gatewayType}/{serviceId}", method = RequestMethod.GET) + @ApiOperation(value = "批量查看全部网关路由", notes = "", response = ResponseEntity.class, httpMethod = "GET") + @ResponseBody + public ResponseEntity routeViewAll(@PathVariable(value = "gatewayType") @ApiParam(value = "网关类型。取值: spring-cloud-gateway | zuul。spring-cloud-gateway指Spring Cloud Gateway, zuul指Netflix Zuul", defaultValue = "spring-cloud-gateway", required = true) String gatewayType, @PathVariable(value = "serviceId") @ApiParam(value = "网关服务名", required = true) String serviceId) { + return doRouteViewAll(gatewayType, serviceId); + } + + private ResponseEntity doRemoteRouteUpdate(String gatewayType, String group, String serviceId, String rule) { + try { + boolean result = routeResource.updateRemoteRoute(GatewayType.fromString(gatewayType), group, serviceId, rule); + + return ResponseUtil.getSuccessResponse(result); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doRemoteRouteClear(String gatewayType, String group, String serviceId) { + try { + boolean result = routeResource.clearRemoteRoute(GatewayType.fromString(gatewayType), group, serviceId); + + return ResponseUtil.getSuccessResponse(result); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doRemoteRouteView(String gatewayType, String group, String serviceId) { + try { + String result = routeResource.getRemoteRoute(GatewayType.fromString(gatewayType), group, serviceId); + + return ResponseUtil.getSuccessResponse(result); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doRouteAdd(String gatewayType, String serviceId, String route) { + try { + List resultEntityList = routeResource.addRoute(GatewayType.fromString(gatewayType), serviceId, route); + + return ResponseUtil.getSuccessResponse(resultEntityList); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doRouteModify(String gatewayType, String serviceId, String route) { + try { + List resultEntityList = routeResource.modifyRoute(GatewayType.fromString(gatewayType), serviceId, route); + + return ResponseUtil.getSuccessResponse(resultEntityList); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doRouteDelete(String gatewayType, String serviceId, String routeId) { + try { + List resultEntityList = routeResource.deleteRoute(GatewayType.fromString(gatewayType), serviceId, routeId); + + return ResponseUtil.getSuccessResponse(resultEntityList); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doRouteUpdateAll(String gatewayType, String serviceId, String route) { + try { + List resultEntityList = routeResource.updateAllRoute(GatewayType.fromString(gatewayType), serviceId, route); + + return ResponseUtil.getSuccessResponse(resultEntityList); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doRouteViewAll(String gatewayType, String serviceId) { + try { + List resultEntityList = routeResource.viewAllRoute(GatewayType.fromString(gatewayType), serviceId); + + return ResponseUtil.getSuccessResponse(resultEntityList); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } +} \ No newline at end of file diff --git a/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/endpoint/SentinelEndpoint.java b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/endpoint/SentinelEndpoint.java new file mode 100644 index 0000000000..bac7749492 --- /dev/null +++ b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/endpoint/SentinelEndpoint.java @@ -0,0 +1,140 @@ +package com.nepxion.discovery.console.endpoint; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; + +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.RestController; + +import com.nepxion.discovery.common.entity.ResultEntity; +import com.nepxion.discovery.common.entity.SentinelRuleType; +import com.nepxion.discovery.common.util.ResponseUtil; +import com.nepxion.discovery.console.resource.SentinelResource; + +@RestController +@RequestMapping(path = "/sentinel") +@Api(tags = { "哨兵接口" }) +public class SentinelEndpoint { + @Autowired + private SentinelResource sentinelResource; + + @RequestMapping(path = "/remote/update/{ruleType}/{group}/{serviceId}", method = RequestMethod.POST) + @ApiOperation(value = "更新哨兵规则到远程配置中心", notes = "", response = ResponseEntity.class, httpMethod = "POST") + @ResponseBody + public ResponseEntity remoteSentinelUpdate(@PathVariable(value = "ruleType") @ApiParam(value = "哨兵规则类型。取值: flow | degrade | authority | system | param-flow", defaultValue = "flow", required = true) String ruleType, @PathVariable(value = "group") @ApiParam(value = "组名", required = true) String group, @PathVariable(value = "serviceId") @ApiParam(value = "服务名", required = true) String serviceId, @RequestBody @ApiParam(value = "哨兵规则内容,Json格式", required = true) String rule) { + return doRemoteSentinelUpdate(ruleType, group, serviceId, rule); + } + + @RequestMapping(path = "/remote/clear/{ruleType}/{group}/{serviceId}", method = RequestMethod.POST) + @ApiOperation(value = "清除哨兵规则到远程配置中心", notes = "", response = ResponseEntity.class, httpMethod = "POST") + @ResponseBody + public ResponseEntity remoteSentinelClear(@PathVariable(value = "ruleType") @ApiParam(value = "哨兵规则类型。取值: flow | degrade | authority | system | param-flow", defaultValue = "flow", required = true) String ruleType, @PathVariable(value = "group") @ApiParam(value = "组名", required = true) String group, @PathVariable(value = "serviceId") @ApiParam(value = "服务名", required = true) String serviceId) { + return doRemoteSentinelClear(ruleType, group, serviceId); + } + + @RequestMapping(path = "/remote/view/{ruleType}/{group}/{serviceId}", method = RequestMethod.GET) + @ApiOperation(value = "查看远程配置中心的哨兵规则", notes = "", response = ResponseEntity.class, httpMethod = "GET") + @ResponseBody + public ResponseEntity remoteSentinelView(@PathVariable(value = "ruleType") @ApiParam(value = "哨兵规则类型。取值: flow | degrade | authority | system | param-flow", defaultValue = "flow", required = true) String ruleType, @PathVariable(value = "group") @ApiParam(value = "组名", required = true) String group, @PathVariable(value = "serviceId") @ApiParam(value = "服务名", required = true) String serviceId) { + return doRemoteSentinelView(ruleType, group, serviceId); + } + + @RequestMapping(path = "/update/{ruleType}/{serviceId}", method = RequestMethod.POST) + @ApiOperation(value = "批量更新哨兵规则列表", notes = "", response = ResponseEntity.class, httpMethod = "POST") + @ResponseBody + public ResponseEntity sentinelUpdate(@PathVariable(value = "ruleType") @ApiParam(value = "哨兵规则类型。取值: flow | degrade | authority | system | param-flow", defaultValue = "flow", required = true) String ruleType, @PathVariable(value = "serviceId") @ApiParam(value = "服务名", required = true) String serviceId, @RequestBody @ApiParam(value = "哨兵规则内容,Json格式", required = true) String rule) { + return doSentinelUpdate(ruleType, serviceId, rule); + } + + @RequestMapping(path = "/clear/{ruleType}/{serviceId}", method = RequestMethod.POST) + @ApiOperation(value = "批量清除哨兵规则列表", notes = "", response = ResponseEntity.class, httpMethod = "POST") + @ResponseBody + public ResponseEntity sentinelClear(@PathVariable(value = "ruleType") @ApiParam(value = "哨兵规则类型。取值: flow | degrade | authority | system | param-flow", defaultValue = "flow", required = true) String ruleType, @PathVariable(value = "serviceId") @ApiParam(value = "服务名", required = true) String serviceId) { + return doSentinelClear(ruleType, serviceId); + } + + @RequestMapping(path = "/view/{ruleType}/{serviceId}", method = RequestMethod.GET) + @ApiOperation(value = "批量查看哨兵规则列表", notes = "", response = ResponseEntity.class, httpMethod = "GET") + @ResponseBody + public ResponseEntity sentinelView(@PathVariable(value = "ruleType") @ApiParam(value = "哨兵规则类型。取值: flow | degrade | authority | system | param-flow", defaultValue = "flow", required = true) String ruleType, @PathVariable(value = "serviceId") @ApiParam(value = "服务名", required = true) String serviceId) { + return doSentinelView(ruleType, serviceId); + } + + private ResponseEntity doRemoteSentinelUpdate(String ruleType, String group, String serviceId, String rule) { + try { + boolean result = sentinelResource.updateRemoteSentinel(SentinelRuleType.fromString(ruleType), group, serviceId, rule); + + return ResponseUtil.getSuccessResponse(result); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doRemoteSentinelClear(String ruleType, String group, String serviceId) { + try { + boolean result = sentinelResource.clearRemoteSentinel(SentinelRuleType.fromString(ruleType), group, serviceId); + + return ResponseUtil.getSuccessResponse(result); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doRemoteSentinelView(String ruleType, String group, String serviceId) { + try { + String result = sentinelResource.getRemoteSentinel(SentinelRuleType.fromString(ruleType), group, serviceId); + + return ResponseUtil.getSuccessResponse(result); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doSentinelUpdate(String ruleType, String serviceId, String rule) { + try { + List resultEntityList = sentinelResource.updateSentinel(SentinelRuleType.fromString(ruleType), serviceId, rule); + + return ResponseUtil.getSuccessResponse(resultEntityList); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doSentinelClear(String ruleType, String serviceId) { + try { + List resultEntityList = sentinelResource.clearSentinel(SentinelRuleType.fromString(ruleType), serviceId); + + return ResponseUtil.getSuccessResponse(resultEntityList); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doSentinelView(String ruleType, String serviceId) { + try { + List resultEntityList = sentinelResource.viewSentinel(SentinelRuleType.fromString(ruleType), serviceId); + + return ResponseUtil.getSuccessResponse(resultEntityList); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } +} \ No newline at end of file diff --git a/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/endpoint/ServiceEndpoint.java b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/endpoint/ServiceEndpoint.java new file mode 100644 index 0000000000..141bcd5708 --- /dev/null +++ b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/endpoint/ServiceEndpoint.java @@ -0,0 +1,279 @@ +package com.nepxion.discovery.console.endpoint; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cloud.client.ServiceInstance; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.RestController; + +import com.nepxion.discovery.common.entity.GatewayType; +import com.nepxion.discovery.common.entity.InstanceEntity; +import com.nepxion.discovery.common.entity.MetadataParameter; +import com.nepxion.discovery.common.entity.ServiceType; +import com.nepxion.discovery.common.util.ResponseUtil; +import com.nepxion.discovery.console.resource.ServiceResource; + +@RestController +@RequestMapping(path = "/service") +@Api(tags = { "服务接口" }) +public class ServiceEndpoint { + @Autowired + private ServiceResource serviceResource; + + @RequestMapping(path = "/discovery-type", method = RequestMethod.GET) + @ApiOperation(value = "获取注册发现中心类型", notes = "", response = ResponseEntity.class, httpMethod = "GET") + @ResponseBody + public ResponseEntity discoveryType() { + return doDiscoveryType(); + } + + @RequestMapping(path = "/groups", method = RequestMethod.GET) + @ApiOperation(value = "获取注册中心的服务组名列表", notes = "", response = ResponseEntity.class, httpMethod = "GET") + @ResponseBody + public ResponseEntity groups() { + return doGroups(); + } + + @RequestMapping(path = "/group/{serviceId}", method = RequestMethod.GET) + @ApiOperation(value = "获取注册中心的服务组名", notes = "", response = ResponseEntity.class, httpMethod = "GET") + @ResponseBody + public ResponseEntity group(@PathVariable(value = "serviceId") @ApiParam(value = "服务名", required = true) String serviceId) { + return doGroup(serviceId); + } + + @RequestMapping(path = "/services", method = RequestMethod.GET) + @ApiOperation(value = "获取注册中心的服务名列表", notes = "", response = ResponseEntity.class, httpMethod = "GET") + @ResponseBody + public ResponseEntity services() { + return doServices(); + } + + @RequestMapping(path = "/service-list", method = RequestMethod.POST) + @ApiOperation(value = "获取注册中心的服务名列表", notes = "", response = ResponseEntity.class, httpMethod = "POST") + @ResponseBody + public ResponseEntity serviceList(@RequestBody @ApiParam(value = "服务类型列表。取值: service | gateway", required = true) List serviceTypes) { + return doServiceList(serviceTypes); + } + + @RequestMapping(path = "/service-list/{group}", method = RequestMethod.POST) + @ApiOperation(value = "获取注册中心的组下服务名列表", notes = "", response = ResponseEntity.class, httpMethod = "POST") + @ResponseBody + public ResponseEntity serviceList(@PathVariable(value = "group") @ApiParam(value = "组名", required = true) String group, @RequestBody @ApiParam(value = "服务类型列表。取值: service | gateway", required = true) List serviceTypes) { + return doServiceList(group, serviceTypes); + } + + @RequestMapping(path = "/gateways", method = RequestMethod.GET) + @ApiOperation(value = "获取注册中心的网关名列表", notes = "", response = ResponseEntity.class, httpMethod = "GET") + @ResponseBody + public ResponseEntity gateways() { + return doGateways(); + } + + @RequestMapping(path = "/gateway-list", method = RequestMethod.POST) + @ApiOperation(value = "获取注册中心的网关名列表", notes = "", response = ResponseEntity.class, httpMethod = "POST") + @ResponseBody + public ResponseEntity gatewayList(@RequestBody @ApiParam(value = "网关类型列表。取值: spring-cloud-gateway | zuul。spring-cloud-gateway指Spring Cloud Gateway, zuul指Netflix Zuul", required = true) List gatewayTypes) { + return doGatewayList(gatewayTypes); + } + + @RequestMapping(path = "/instances/{serviceId}", method = RequestMethod.GET) + @ApiOperation(value = "获取注册中心的服务实例列表", notes = "", response = ResponseEntity.class, httpMethod = "GET") + @ResponseBody + public ResponseEntity instances(@PathVariable(value = "serviceId") @ApiParam(value = "服务名", required = true) String serviceId) { + return doInstances(serviceId); + } + + @RequestMapping(path = "/instance-list/{serviceId}", method = RequestMethod.GET) + @ApiOperation(value = "获取注册中心的服务实例列表(精简数据)", notes = "", response = ResponseEntity.class, httpMethod = "GET") + @ResponseBody + public ResponseEntity instanceList(@PathVariable(value = "serviceId") @ApiParam(value = "服务名", required = true) String serviceId) { + return doInstanceList(serviceId); + } + + @RequestMapping(path = "/instance-map", method = RequestMethod.POST) + @ApiOperation(value = "获取注册中心的服务实例的Map(精简数据)", notes = "", response = ResponseEntity.class, httpMethod = "POST") + @ResponseBody + public ResponseEntity instanceMap(@RequestBody @ApiParam(value = "服务组名列表,传入空列则可以获取全部服务实例数据", required = true) List groups) { + return doInstanceMap(groups); + } + + @RequestMapping(path = "/metadata-map/{metadataKey}", method = RequestMethod.POST) + @ApiOperation(value = "获取注册中心的服务实例元数据值列表的Map(值包含单个元数据)", notes = "", response = ResponseEntity.class, httpMethod = "POST") + @ResponseBody + public ResponseEntity metadataMap(@PathVariable(value = "metadataKey") @ApiParam(value = "元数据键名", required = true) String metadataKey, @RequestBody @ApiParam(value = "服务名列表", required = true) List serviceIds) { + return doMetadataMap(metadataKey, serviceIds); + } + + @RequestMapping(path = "/metadata-map", method = RequestMethod.POST) + @ApiOperation(value = "获取注册中心的服务实例元数据值列表的Map(值包含多个元数据,通过分隔符分隔)", notes = "", response = ResponseEntity.class, httpMethod = "POST") + @ResponseBody + public ResponseEntity metadataMap(@RequestBody @ApiParam(value = "元数据查询参数对象", required = true) MetadataParameter metadataParameter) { + return doMetadataMap(metadataParameter); + } + + private ResponseEntity doDiscoveryType() { + try { + String discoveryType = serviceResource.getDiscoveryType().toString(); + + return ResponseUtil.getSuccessResponse(discoveryType); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doGroups() { + try { + List groups = serviceResource.getGroups(); + + return ResponseUtil.getSuccessResponse(groups); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doGroup(String serviceId) { + try { + String group = serviceResource.getGroup(serviceId); + + return ResponseUtil.getSuccessResponse(group); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doServices() { + try { + List services = serviceResource.getServices(); + + return ResponseUtil.getSuccessResponse(services); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doServiceList(List serviceTypes) { + try { + List types = new ArrayList(); + for (String serviceType : serviceTypes) { + types.add(ServiceType.fromString(serviceType)); + } + + List services = serviceResource.getServiceList(types); + + return ResponseUtil.getSuccessResponse(services); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doServiceList(String group, List serviceTypes) { + try { + List types = new ArrayList(); + for (String serviceType : serviceTypes) { + types.add(ServiceType.fromString(serviceType)); + } + + List services = serviceResource.getServiceList(group, types); + + return ResponseUtil.getSuccessResponse(services); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doGateways() { + try { + List gateways = serviceResource.getGateways(); + + return ResponseUtil.getSuccessResponse(gateways); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doGatewayList(List gatewayTypes) { + try { + List types = new ArrayList(); + for (String gatewayType : gatewayTypes) { + types.add(GatewayType.fromString(gatewayType)); + } + + List gatewayList = serviceResource.getGatewayList(types); + + return ResponseUtil.getSuccessResponse(gatewayList); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doInstances(String serviceId) { + try { + List instances = serviceResource.getInstances(serviceId); + + return ResponseUtil.getSuccessResponse(instances); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doInstanceList(String serviceId) { + try { + List instanceList = serviceResource.getInstanceList(serviceId); + + return ResponseUtil.getSuccessResponse(instanceList); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doInstanceMap(List groups) { + try { + Map> instanceMaps = serviceResource.getInstanceMap(groups); + + return ResponseUtil.getSuccessResponse(instanceMaps); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doMetadataMap(String metadataKey, List serviceIds) { + try { + Map> metadataMap = serviceResource.getMetadataMap(metadataKey, serviceIds); + + return ResponseUtil.getSuccessResponse(metadataMap); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doMetadataMap(MetadataParameter metadataParameter) { + try { + Map> metadataMap = serviceResource.getMetadataMap(metadataParameter); + + return ResponseUtil.getSuccessResponse(metadataMap); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } +} \ No newline at end of file diff --git a/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/endpoint/StrategyEndpoint.java b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/endpoint/StrategyEndpoint.java new file mode 100644 index 0000000000..cc3bd79dcd --- /dev/null +++ b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/endpoint/StrategyEndpoint.java @@ -0,0 +1,360 @@ +package com.nepxion.discovery.console.endpoint; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.RestController; + +import com.nepxion.discovery.common.entity.ConditionRouteStrategy; +import com.nepxion.discovery.common.entity.ConditionStrategy; +import com.nepxion.discovery.common.util.ResponseUtil; +import com.nepxion.discovery.console.resource.StrategyResource; + +@RestController +@RequestMapping(path = "/strategy") +@Api(tags = { "策略接口" }) +public class StrategyEndpoint { + @Autowired + private StrategyResource strategyResource; + + @RequestMapping(path = "/get-version-release/{group}", method = RequestMethod.GET) + @ApiOperation(value = "全局订阅方式,获取Json格式的蓝绿灰度发布", notes = "", response = ResponseEntity.class, httpMethod = "GET") + @ResponseBody + public ResponseEntity getVersionRelease(@PathVariable(value = "group") @ApiParam(value = "组名", required = true) String group) { + return doGetVersionRelease(group); + } + + @RequestMapping(path = "/create-version-release-yaml/{group}", method = RequestMethod.POST) + @ApiOperation(value = "全局订阅方式,根据Yaml格式,创建版本蓝绿灰度发布", notes = "", response = ResponseEntity.class, httpMethod = "POST") + @ResponseBody + public ResponseEntity createVersionRelease(@PathVariable(value = "group") @ApiParam(value = "组名", required = true) String group, @RequestBody @ApiParam(value = "蓝绿灰度策略Yaml", required = true) String conditionStrategyYaml) { + return doCreateVersionRelease(group, conditionStrategyYaml); + } + + @RequestMapping(path = "/create-version-release-json/{group}", method = RequestMethod.POST) + @ApiOperation(value = "全局订阅方式,根据Json格式,创建版本蓝绿灰度发布", notes = "", response = ResponseEntity.class, httpMethod = "POST") + @ResponseBody + public ResponseEntity createVersionRelease(@PathVariable(value = "group") @ApiParam(value = "组名", required = true) String group, @RequestBody @ApiParam(value = "蓝绿灰度策略Json", required = true) ConditionStrategy conditionStrategy) { + return doCreateVersionRelease(group, conditionStrategy); + } + + @RequestMapping(path = "/recreate-version-release-yaml/{group}", method = RequestMethod.POST) + @ApiOperation(value = "全局订阅方式,根据Yaml格式,重新创建版本蓝绿灰度发布(创建链路智能编排,不创建条件表达式)", notes = "", response = ResponseEntity.class, httpMethod = "POST") + @ResponseBody + public ResponseEntity recreateVersionRelease(@PathVariable(value = "group") @ApiParam(value = "组名", required = true) String group, @RequestBody @ApiParam(value = "蓝绿灰度路由策略Yaml", required = true) String conditionRouteStrategyYaml) { + return doRecreateVersionRelease(group, conditionRouteStrategyYaml); + } + + @RequestMapping(path = "/recreate-version-release-json/{group}", method = RequestMethod.POST) + @ApiOperation(value = "全局订阅方式,根据Json格式,重新创建版本蓝绿灰度发布(创建链路智能编排,不创建条件表达式)", notes = "", response = ResponseEntity.class, httpMethod = "POST") + @ResponseBody + public ResponseEntity recreateVersionRelease(@PathVariable(value = "group") @ApiParam(value = "组名", required = true) String group, @RequestBody @ApiParam(value = "蓝绿灰度路由策略Json", required = true) ConditionRouteStrategy conditionRouteStrategy) { + return doRecreateVersionRelease(group, conditionRouteStrategy); + } + + @RequestMapping(path = "/reset-release/{group}", method = RequestMethod.POST) + @ApiOperation(value = "全局订阅方式,重置蓝绿灰度发布(清除链路智能编排,不清除条件表达式)", notes = "", response = ResponseEntity.class, httpMethod = "POST") + @ResponseBody + public ResponseEntity resetRelease(@PathVariable(value = "group") @ApiParam(value = "组名", required = true) String group) { + return doResetRelease(group); + } + + @RequestMapping(path = "/clear-release/{group}", method = RequestMethod.POST) + @ApiOperation(value = "全局订阅方式,清除蓝绿灰度发布", notes = "", response = ResponseEntity.class, httpMethod = "POST") + @ResponseBody + public ResponseEntity clearRelease(@PathVariable(value = "group") @ApiParam(value = "组名", required = true) String group) { + return doClearRelease(group); + } + + @RequestMapping(path = "/get-version-release/{group}/{serviceId}", method = RequestMethod.GET) + @ApiOperation(value = "局部订阅方式,获取Json格式的蓝绿灰度发布", notes = "", response = ResponseEntity.class, httpMethod = "GET") + @ResponseBody + public ResponseEntity getVersionRelease(@PathVariable(value = "group") @ApiParam(value = "组名", required = true) String group, @PathVariable(value = "serviceId") @ApiParam(value = "服务名", required = true) String serviceId) { + return doGetVersionRelease(group, serviceId); + } + + @RequestMapping(path = "/create-version-release-yaml/{group}/{serviceId}", method = RequestMethod.POST) + @ApiOperation(value = "局部订阅方式,根据Yaml格式,创建版本蓝绿灰度发布", notes = "", response = ResponseEntity.class, httpMethod = "POST") + @ResponseBody + public ResponseEntity createVersionRelease(@PathVariable(value = "group") @ApiParam(value = "组名", required = true) String group, @PathVariable(value = "serviceId") @ApiParam(value = "服务名", required = true) String serviceId, @RequestBody @ApiParam(value = "蓝绿灰度策略Yaml", required = true) String conditionStrategyYaml) { + return doCreateVersionRelease(group, serviceId, conditionStrategyYaml); + } + + @RequestMapping(path = "/create-version-release-json/{group}/{serviceId}", method = RequestMethod.POST) + @ApiOperation(value = "局部订阅方式,根据Json格式,创建版本蓝绿灰度发布", notes = "", response = ResponseEntity.class, httpMethod = "POST") + @ResponseBody + public ResponseEntity createVersionRelease(@PathVariable(value = "group") @ApiParam(value = "组名", required = true) String group, @PathVariable(value = "serviceId") @ApiParam(value = "服务名", required = true) String serviceId, @RequestBody @ApiParam(value = "蓝绿灰度策略Json", required = true) ConditionStrategy conditionStrategy) { + return doCreateVersionRelease(group, serviceId, conditionStrategy); + } + + @RequestMapping(path = "/recreate-version-release-yaml/{group}/{serviceId}", method = RequestMethod.POST) + @ApiOperation(value = "局部订阅方式,根据Yaml格式,重新创建版本蓝绿灰度发布(创建链路智能编排,不创建条件表达式)", notes = "", response = ResponseEntity.class, httpMethod = "POST") + @ResponseBody + public ResponseEntity recreateVersionRelease(@PathVariable(value = "group") @ApiParam(value = "组名", required = true) String group, @PathVariable(value = "serviceId") @ApiParam(value = "服务名", required = true) String serviceId, @RequestBody @ApiParam(value = "蓝绿灰度路由策略Yaml", required = true) String conditionRouteStrategyYaml) { + return doRecreateVersionRelease(group, serviceId, conditionRouteStrategyYaml); + } + + @RequestMapping(path = "/recreate-version-release-json/{group}/{serviceId}", method = RequestMethod.POST) + @ApiOperation(value = "局部订阅方式,根据Json格式,重新创建版本蓝绿灰度发布(创建链路智能编排,不创建条件表达式)", notes = "", response = ResponseEntity.class, httpMethod = "POST") + @ResponseBody + public ResponseEntity recreateVersionRelease(@PathVariable(value = "group") @ApiParam(value = "组名", required = true) String group, @PathVariable(value = "serviceId") @ApiParam(value = "服务名", required = true) String serviceId, @RequestBody @ApiParam(value = "蓝绿灰度路由策略Json", required = true) ConditionRouteStrategy conditionRouteStrategy) { + return doRecreateVersionRelease(group, serviceId, conditionRouteStrategy); + } + + @RequestMapping(path = "/reset-release/{group}/{serviceId}", method = RequestMethod.POST) + @ApiOperation(value = "局部订阅方式,重置蓝绿灰度发布(清除链路智能编排,不清除条件表达式)", notes = "", response = ResponseEntity.class, httpMethod = "POST") + @ResponseBody + public ResponseEntity resetRelease(@PathVariable(value = "group") @ApiParam(value = "组名", required = true) String group, @PathVariable(value = "serviceId") @ApiParam(value = "服务名", required = true) String serviceId) { + return doResetRelease(group, serviceId); + } + + @RequestMapping(path = "/clear-release/{group}/{serviceId}", method = RequestMethod.POST) + @ApiOperation(value = "局部订阅方式,清除蓝绿灰度发布", notes = "", response = ResponseEntity.class, httpMethod = "POST") + @ResponseBody + public ResponseEntity clearRelease(@PathVariable(value = "group") @ApiParam(value = "组名", required = true) String group, @PathVariable(value = "serviceId") @ApiParam(value = "服务名", required = true) String serviceId) { + return doClearRelease(group, serviceId); + } + + @RequestMapping(path = "/parse-version-release-yaml", method = RequestMethod.POST) + @ApiOperation(value = "根据Yaml格式,解析版本蓝绿灰度发布策略为Xml格式", notes = "", response = ResponseEntity.class, httpMethod = "POST") + @ResponseBody + public ResponseEntity parseVersionRelease(@RequestBody @ApiParam(value = "蓝绿灰度策略Yaml", required = true) String conditionStrategyYaml) { + return doParseVersionRelease(conditionStrategyYaml); + } + + @RequestMapping(path = "/parse-version-release-json", method = RequestMethod.POST) + @ApiOperation(value = "根据Json格式,解析版本蓝绿灰度发布策略为Xml格式", notes = "", response = ResponseEntity.class, httpMethod = "POST") + @ResponseBody + public ResponseEntity parseVersionRelease(@RequestBody @ApiParam(value = "蓝绿灰度策略Json", required = true) ConditionStrategy conditionStrategy) { + return doParseVersionRelease(conditionStrategy); + } + + @RequestMapping(path = "/deparse-version-release-xml", method = RequestMethod.POST) + @ApiOperation(value = "根据Xml格式,反解析版本蓝绿灰度发布策略为Json格式", notes = "", response = ResponseEntity.class, httpMethod = "POST") + @ResponseBody + public ResponseEntity deparseVersionRelease(@RequestBody @ApiParam(value = "蓝绿灰度策略Xml", required = true) String ruleXml) { + return doDeparseVersionReleaseXml(ruleXml); + } + + @RequestMapping(path = "/deparse-version-release-yaml", method = RequestMethod.POST) + @ApiOperation(value = "根据Yaml格式,反解析版本蓝绿灰度发布策略为Json格式", notes = "", response = ResponseEntity.class, httpMethod = "POST") + @ResponseBody + public ResponseEntity convertVersionRelease(@RequestBody @ApiParam(value = "蓝绿灰度策略Yaml", required = true) String conditionStrategyYaml) { + return doDeparseVersionReleaseYaml(conditionStrategyYaml); + } + + @RequestMapping(path = "/validate-expression", method = RequestMethod.GET) + @ApiOperation(value = "校验策略的条件表达式", notes = "", response = ResponseEntity.class, httpMethod = "GET") + @ResponseBody + public ResponseEntity validateExpression(@RequestParam @ApiParam(value = "条件表达式,格式示例:#H['a'] == '1' && #H['b'] != '2'。注意,引号是否为中文格式", defaultValue = "#H['a'] == '1' && #H['b'] != '2'", required = true) String expression, @RequestParam(defaultValue = "", required = false) @ApiParam(value = "校验参数,格式示例:a=1;b=1。如果多个用“;”分隔,不允许出现空格。允许为空", defaultValue = "a=1;b=1") String validation) { + return doValidateExpression(expression, validation); + } + + private ResponseEntity doGetVersionRelease(String group) { + try { + ConditionStrategy result = strategyResource.getVersionRelease(group); + + return ResponseUtil.getSuccessResponse(result); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doCreateVersionRelease(String group, String conditionStrategyYaml) { + try { + String result = strategyResource.createVersionRelease(group, conditionStrategyYaml); + + return ResponseUtil.getSuccessResponse(result); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doCreateVersionRelease(String group, ConditionStrategy conditionStrategy) { + try { + String result = strategyResource.createVersionRelease(group, conditionStrategy); + + return ResponseUtil.getSuccessResponse(result); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doRecreateVersionRelease(String group, String conditionRouteStrategyYaml) { + try { + String result = strategyResource.recreateVersionRelease(group, conditionRouteStrategyYaml); + + return ResponseUtil.getSuccessResponse(result); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doRecreateVersionRelease(String group, ConditionRouteStrategy conditionRouteStrategy) { + try { + String result = strategyResource.recreateVersionRelease(group, conditionRouteStrategy); + + return ResponseUtil.getSuccessResponse(result); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doResetRelease(String group) { + try { + String result = strategyResource.resetRelease(group); + + return ResponseUtil.getSuccessResponse(result); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doClearRelease(String group) { + try { + String result = strategyResource.clearRelease(group); + + return ResponseUtil.getSuccessResponse(result); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doGetVersionRelease(String group, String serviceId) { + try { + ConditionStrategy result = strategyResource.getVersionRelease(group, serviceId); + + return ResponseUtil.getSuccessResponse(result); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doCreateVersionRelease(String group, String serviceId, String conditionStrategyYaml) { + try { + String result = strategyResource.createVersionRelease(group, serviceId, conditionStrategyYaml); + + return ResponseUtil.getSuccessResponse(result); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doCreateVersionRelease(String group, String serviceId, ConditionStrategy conditionStrategy) { + try { + String result = strategyResource.createVersionRelease(group, serviceId, conditionStrategy); + + return ResponseUtil.getSuccessResponse(result); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doRecreateVersionRelease(String group, String serviceId, String conditionRouteStrategyYaml) { + try { + String result = strategyResource.recreateVersionRelease(group, serviceId, conditionRouteStrategyYaml); + + return ResponseUtil.getSuccessResponse(result); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doRecreateVersionRelease(String group, String serviceId, ConditionRouteStrategy conditionRouteStrategy) { + try { + String result = strategyResource.recreateVersionRelease(group, serviceId, conditionRouteStrategy); + + return ResponseUtil.getSuccessResponse(result); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doResetRelease(String group, String serviceId) { + try { + String result = strategyResource.resetRelease(group, serviceId); + + return ResponseUtil.getSuccessResponse(result); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doClearRelease(String group, String serviceId) { + try { + String result = strategyResource.clearRelease(group, serviceId); + + return ResponseUtil.getSuccessResponse(result); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doParseVersionRelease(String conditionStrategyYaml) { + try { + String result = strategyResource.parseVersionRelease(conditionStrategyYaml); + + return ResponseUtil.getSuccessResponse(result); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doParseVersionRelease(ConditionStrategy conditionStrategy) { + try { + String result = strategyResource.parseVersionRelease(conditionStrategy); + + return ResponseUtil.getSuccessResponse(result); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doDeparseVersionReleaseXml(String ruleXml) { + try { + ConditionStrategy conditionStrategy = strategyResource.deparseVersionReleaseXml(ruleXml); + + return ResponseUtil.getSuccessResponse(conditionStrategy); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doDeparseVersionReleaseYaml(String conditionStrategyYaml) { + try { + ConditionStrategy result = strategyResource.deparseVersionReleaseYaml(conditionStrategyYaml); + + return ResponseUtil.getSuccessResponse(result); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doValidateExpression(String expression, String validation) { + try { + boolean result = strategyResource.validateExpression(expression, validation); + + return ResponseUtil.getSuccessResponse(result); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } +} \ No newline at end of file diff --git a/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/endpoint/VersionEndpoint.java b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/endpoint/VersionEndpoint.java new file mode 100644 index 0000000000..ec6e8bb985 --- /dev/null +++ b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/endpoint/VersionEndpoint.java @@ -0,0 +1,102 @@ +package com.nepxion.discovery.console.endpoint; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; + +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.RestController; + +import com.nepxion.discovery.common.entity.ResultEntity; +import com.nepxion.discovery.common.util.ResponseUtil; +import com.nepxion.discovery.console.resource.VersionResource; + +@RestController +@RequestMapping(path = "/version") +@Api(tags = { "版本接口" }) +public class VersionEndpoint { + @Autowired + private VersionResource versionResource; + + @RequestMapping(path = "/update-async/{serviceId}", method = RequestMethod.POST) + @ApiOperation(value = "批量异步更新动态版本", notes = "根据指定的localVersion更新服务的dynamicVersion。如果输入的localVersion不匹配服务的localVersion,则忽略;如果如果输入的localVersion为空,则直接更新服务的dynamicVersion", response = ResponseEntity.class, httpMethod = "POST") + @ResponseBody + public ResponseEntity versionUpdateAsync(@PathVariable(value = "serviceId") @ApiParam(value = "服务名", required = true) String serviceId, @RequestBody @ApiParam(value = "版本号,格式为${dynamicVersion}或者${dynamicVersion};${localVersion}", required = true) String version) { + return doVersionUpdate(serviceId, version, true); + } + + @RequestMapping(path = "/update-sync/{serviceId}", method = RequestMethod.POST) + @ApiOperation(value = "批量同步更新动态版本", notes = "根据指定的localVersion更新服务的dynamicVersion。如果输入的localVersion不匹配服务的localVersion,则忽略;如果如果输入的localVersion为空,则直接更新服务的dynamicVersion", response = ResponseEntity.class, httpMethod = "POST") + @ResponseBody + public ResponseEntity versionUpdateSync(@PathVariable(value = "serviceId") @ApiParam(value = "服务名", required = true) String serviceId, @RequestBody @ApiParam(value = "版本号,格式为${dynamicVersion}或者${dynamicVersion};${localVersion}", required = true) String version) { + return doVersionUpdate(serviceId, version, false); + } + + @RequestMapping(path = "/clear-async/{serviceId}", method = RequestMethod.POST) + @ApiOperation(value = "批量异步清除动态版本", notes = "根据指定的localVersion清除服务的dynamicVersion。如果输入的localVersion不匹配服务的localVersion,则忽略;如果如果输入的localVersion为空,则直接清除服务的dynamicVersion", response = ResponseEntity.class, httpMethod = "POST") + @ResponseBody + public ResponseEntity versionClearAsync(@PathVariable(value = "serviceId") @ApiParam(value = "服务名", required = true) String serviceId, @RequestBody(required = false) @ApiParam(value = "版本号,指localVersion,可以为空") String version) { + return doVersionClear(serviceId, version, true); + } + + @RequestMapping(path = "/clear-sync/{serviceId}", method = RequestMethod.POST) + @ApiOperation(value = "批量同步清除动态版本", notes = "根据指定的localVersion清除服务的dynamicVersion。如果输入的localVersion不匹配服务的localVersion,则忽略;如果如果输入的localVersion为空,则直接清除服务的dynamicVersion", response = ResponseEntity.class, httpMethod = "POST") + @ResponseBody + public ResponseEntity versionClearSync(@PathVariable(value = "serviceId") @ApiParam(value = "服务名", required = true) String serviceId, @RequestBody(required = false) @ApiParam(value = "版本号,指localVersion,可以为空") String version) { + return doVersionClear(serviceId, version, false); + } + + @RequestMapping(path = "/view/{serviceId}", method = RequestMethod.GET) + @ApiOperation(value = "批量查看版本", notes = "", response = ResponseEntity.class, httpMethod = "GET") + @ResponseBody + public ResponseEntity versionView(@PathVariable(value = "serviceId") @ApiParam(value = "服务名", required = true) String serviceId) { + return doVersionView(serviceId); + } + + private ResponseEntity doVersionUpdate(String serviceId, String version, boolean async) { + try { + List resultEntityList = versionResource.updateVersion(serviceId, version, async); + + return ResponseUtil.getSuccessResponse(resultEntityList); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doVersionClear(String serviceId, String version, boolean async) { + try { + List resultEntityList = versionResource.clearVersion(serviceId, version, async); + + return ResponseUtil.getSuccessResponse(resultEntityList); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doVersionView(String serviceId) { + try { + List resultEntityList = versionResource.viewVersion(serviceId); + + return ResponseUtil.getSuccessResponse(resultEntityList); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } +} \ No newline at end of file diff --git a/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/resource/AuthenticationResource.java b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/resource/AuthenticationResource.java new file mode 100644 index 0000000000..61100c2911 --- /dev/null +++ b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/resource/AuthenticationResource.java @@ -0,0 +1,17 @@ +package com.nepxion.discovery.console.resource; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import com.nepxion.discovery.common.entity.AuthenticationEntity; +import com.nepxion.discovery.common.entity.UserEntity; + +public interface AuthenticationResource { + AuthenticationEntity authenticate(UserEntity userEntity); +} \ No newline at end of file diff --git a/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/resource/AuthenticationResourceImpl.java b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/resource/AuthenticationResourceImpl.java new file mode 100644 index 0000000000..4c87dcadaa --- /dev/null +++ b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/resource/AuthenticationResourceImpl.java @@ -0,0 +1,43 @@ +package com.nepxion.discovery.console.resource; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.env.Environment; + +import com.nepxion.discovery.common.entity.AuthenticationEntity; +import com.nepxion.discovery.common.entity.UserEntity; + +public class AuthenticationResourceImpl implements AuthenticationResource { + @Autowired + private Environment environment; + + @Override + public AuthenticationEntity authenticate(UserEntity userEntity) { + AuthenticationEntity authenticationEntity = new AuthenticationEntity(); + + String userId = userEntity.getUserId().trim(); + String password = userEntity.getPassword().trim(); + + String passwordValue = environment.getProperty(userId); + if (StringUtils.isNotEmpty(passwordValue)) { + if (StringUtils.equals(password, passwordValue)) { + authenticationEntity.setPassed(true); + } else { + authenticationEntity.setError("Password is mismatched"); + } + } else { + authenticationEntity.setError("Account doesn't exist"); + } + + return authenticationEntity; + } +} \ No newline at end of file diff --git a/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/resource/BlacklistResource.java b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/resource/BlacklistResource.java new file mode 100644 index 0000000000..a36bf82f53 --- /dev/null +++ b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/resource/BlacklistResource.java @@ -0,0 +1,28 @@ +package com.nepxion.discovery.console.resource; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +public interface BlacklistResource { + String addBlacklist(String group, String targetServiceId, String targetHost, int targetPort); + + String addBlacklist(String group, String targetServiceId, String targetServiceUUId); + + boolean deleteBlacklist(String group, String targetServiceId, String targetServiceUUId); + + boolean clearBlacklist(String group); + + String addBlacklist(String group, String serviceId, String targetServiceId, String targetHost, int targetPort); + + String addBlacklist(String group, String serviceId, String targetServiceId, String targetServiceUUId); + + boolean deleteBlacklist(String group, String serviceId, String targetServiceId, String targetServiceUUId); + + boolean clearBlacklist(String group, String serviceId); +} \ No newline at end of file diff --git a/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/resource/BlacklistResourceImpl.java b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/resource/BlacklistResourceImpl.java new file mode 100644 index 0000000000..de4a20f6b2 --- /dev/null +++ b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/resource/BlacklistResourceImpl.java @@ -0,0 +1,218 @@ +package com.nepxion.discovery.console.resource; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import org.apache.commons.collections4.CollectionUtils; +import org.apache.commons.collections4.MapUtils; +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; + +import com.nepxion.discovery.common.entity.InstanceEntity; +import com.nepxion.discovery.common.entity.RuleEntity; +import com.nepxion.discovery.common.entity.StrategyBlacklistEntity; +import com.nepxion.discovery.common.exception.DiscoveryException; +import com.nepxion.discovery.common.util.StringUtil; +import com.nepxion.discovery.console.delegate.ConsoleResourceDelegateImpl; + +public class BlacklistResourceImpl extends ConsoleResourceDelegateImpl implements BlacklistResource { + @Autowired + private ServiceResource serviceResource; + + @Override + public String addBlacklist(String group, String targetServiceId, String targetHost, int targetPort) { + return addBlacklist(group, null, targetServiceId, targetHost, targetPort); + } + + @Override + public String addBlacklist(String group, String targetServiceId, String targetServiceUUId) { + return addBlacklist(group, null, targetServiceId, targetServiceUUId); + } + + @Override + public boolean deleteBlacklist(String group, String targetServiceId, String targetServiceUUId) { + return deleteBlacklist(group, null, targetServiceId, targetServiceUUId); + } + + @Override + public boolean clearBlacklist(String group) { + return clearBlacklist(group, null); + } + + @Override + public String addBlacklist(String group, String serviceId, String targetServiceId, String targetHost, int targetPort) { + InstanceEntity instanceEntity = getInstanceEntity(targetServiceId, targetHost, targetPort); + if (instanceEntity == null) { + throw new DiscoveryException("Not found the instance with serviceId=" + targetServiceId + " host=" + targetHost + ", port=" + targetPort); + } + + String targetServiceUUId = instanceEntity.getServiceUUId(); + if (StringUtils.isEmpty(targetServiceUUId)) { + throw new DiscoveryException("Not found UUID in the instance with serviceId=" + targetServiceId + " host=" + targetHost + ", port=" + targetPort); + } + + return addBlacklist(group, serviceId, targetServiceId, targetServiceUUId); + } + + @Override + public String addBlacklist(String group, String serviceId, String targetServiceId, String targetServiceUUId) { + RuleEntity ruleEntity = getRemoteRuleEntity(group, serviceId); + + addBlacklistId(ruleEntity, targetServiceId, targetServiceUUId); + + updateRemoteRuleEntity(group, serviceId, ruleEntity); + + return targetServiceUUId; + } + + @Override + public boolean deleteBlacklist(String group, String serviceId, String targetServiceId, String targetServiceUUId) { + RuleEntity ruleEntity = getRemoteRuleEntity(group, serviceId); + + deleteBlacklistId(ruleEntity, targetServiceId, targetServiceUUId); + + return updateRemoteRuleEntity(group, serviceId, ruleEntity); + } + + @Override + public boolean clearBlacklist(String group, String serviceId) { + RuleEntity ruleEntity = getRemoteRuleEntity(group, serviceId); + + clearBlacklistId(ruleEntity); + + return updateRemoteRuleEntity(group, serviceId, ruleEntity); + } + + private void addBlacklistId(RuleEntity ruleEntity, String serviceId, String serviceUUId) { + StrategyBlacklistEntity strategyBlacklistEntity = ruleEntity.getStrategyBlacklistEntity(); + if (strategyBlacklistEntity != null) { + String idValue = strategyBlacklistEntity.getIdValue(); + if (StringUtils.isNotEmpty(idValue)) { + String addIdValue = addBlacklistId(idValue, serviceId, serviceUUId); + strategyBlacklistEntity.setIdValue(addIdValue); + } else { + String addIdValue = addBlacklistId((String) null, serviceId, serviceUUId); + strategyBlacklistEntity.setIdValue(addIdValue); + } + } else { + strategyBlacklistEntity = new StrategyBlacklistEntity(); + ruleEntity.setStrategyBlacklistEntity(strategyBlacklistEntity); + + String addIdValue = addBlacklistId((String) null, serviceId, serviceUUId); + strategyBlacklistEntity.setIdValue(addIdValue); + } + } + + // 添加新的UUId到下线黑名单idValue中,并产生新的idValue格式返回 + // idValue的格式为{"discovery-guide-service-a":"20210601-222214-909-1146-372-698", "discovery-guide-service-b":"20210601-222623-277-4978-633-279"} + private String addBlacklistId(String idValue, String serviceId, String serviceUUId) { + Map> idMap = StringUtil.splitToComplexMap(idValue); + if (MapUtils.isNotEmpty(idMap)) { + if (idMap.containsKey(serviceId)) { + List idList = idMap.get(serviceId); + if (!idList.contains(serviceUUId)) { + List newIdList = new ArrayList(); + newIdList.addAll(idList); + newIdList.add(serviceUUId); + + idMap.put(serviceId, newIdList); + } + } else { + List idList = new ArrayList(); + idList.add(serviceUUId); + + idMap.put(serviceId, idList); + } + } else { + idMap = new LinkedHashMap>(); + + List idList = new ArrayList(); + idList.add(serviceUUId); + + idMap.put(serviceId, idList); + } + + return StringUtil.convertToComplexString(idMap); + } + + private void deleteBlacklistId(RuleEntity ruleEntity, String serviceId, String serviceUUId) { + StrategyBlacklistEntity strategyBlacklistEntity = ruleEntity.getStrategyBlacklistEntity(); + if (strategyBlacklistEntity != null) { + String idValue = strategyBlacklistEntity.getIdValue(); + if (StringUtils.isNotEmpty(idValue)) { + String deletedIdValue = deleteBlacklistId(idValue, serviceId, serviceUUId); + strategyBlacklistEntity.setIdValue(deletedIdValue); + } else { + throw new DiscoveryException("Not found UUId=" + serviceUUId + " with serviceId=" + serviceId + " in blacklist"); + } + } else { + throw new DiscoveryException("Not found UUId=" + serviceUUId + " with serviceId=" + serviceId + " in blacklist"); + } + } + + // 删除旧的UUId到下线黑名单idValue中,并产生新的idValue格式返回 + // idValue的格式为{"discovery-guide-service-a":"20210601-222214-909-1146-372-698", "discovery-guide-service-b":"20210601-222623-277-4978-633-279"} + private String deleteBlacklistId(String idValue, String serviceId, String serviceUUId) { + Map> idMap = StringUtil.splitToComplexMap(idValue); + if (MapUtils.isNotEmpty(idMap)) { + List idList = idMap.get(serviceId); + if (CollectionUtils.isEmpty(idList)) { + throw new DiscoveryException("Not found UUId=" + serviceUUId + " with serviceId=" + serviceId + " in blacklist"); + } + + if (idList.contains(serviceUUId)) { + if (idList.size() == 1) { + idMap.remove(serviceId); + } else { + List newIdList = new ArrayList(); + newIdList.addAll(idList); + newIdList.remove(serviceUUId); + + idMap.put(serviceId, newIdList); + } + } else { + throw new DiscoveryException("Not found UUId=" + serviceUUId + " with serviceId=" + serviceId + " in blacklist"); + } + + return StringUtil.convertToComplexString(idMap); + } + + return null; + } + + private void clearBlacklistId(RuleEntity ruleEntity) { + StrategyBlacklistEntity strategyBlacklistEntity = ruleEntity.getStrategyBlacklistEntity(); + if (strategyBlacklistEntity != null) { + String idValue = strategyBlacklistEntity.getIdValue(); + if (StringUtils.isNotEmpty(idValue)) { + strategyBlacklistEntity.setIdValue(null); + } else { + throw new DiscoveryException("No UUId blacklist found"); + } + } else { + throw new DiscoveryException("No UUId blacklist found"); + } + } + + private InstanceEntity getInstanceEntity(String serviceId, String host, int port) { + List instanceEntityList = serviceResource.getInstanceList(serviceId); + for (InstanceEntity instanceEntity : instanceEntityList) { + if (StringUtils.equals(instanceEntity.getHost(), host) && instanceEntity.getPort() == port) { + return instanceEntity; + } + } + + return null; + } +} \ No newline at end of file diff --git a/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/resource/ConfigResource.java b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/resource/ConfigResource.java new file mode 100644 index 0000000000..5a56b2af94 --- /dev/null +++ b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/resource/ConfigResource.java @@ -0,0 +1,49 @@ +package com.nepxion.discovery.console.resource; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.List; + +import com.nepxion.discovery.common.entity.ConfigType; +import com.nepxion.discovery.common.entity.FormatType; +import com.nepxion.discovery.common.entity.ResultEntity; +import com.nepxion.discovery.common.entity.RuleEntity; + +public interface ConfigResource { + ConfigType getConfigType(); + + boolean updateRemoteConfig(String group, String serviceId, String config) throws Exception; + + boolean updateRemoteConfig(String group, String serviceId, String config, FormatType formatType) throws Exception; + + boolean updateRemoteRuleEntity(String group, String serviceId, RuleEntity ruleEntity) throws Exception; + + boolean clearRemoteConfig(String group, String serviceId) throws Exception; + + String getRemoteConfig(String group, String serviceId) throws Exception; + + RuleEntity getRemoteRuleEntity(String group, String serviceId) throws Exception; + + List updateConfig(String serviceId, String config, boolean async); + + List updateRuleEntity(String serviceId, RuleEntity ruleEntity, boolean async); + + List clearConfig(String serviceId, boolean async); + + List viewConfig(String serviceId); + + RuleEntity toRuleEntity(String config); + + String fromRuleEntity(RuleEntity ruleEntity); + + RuleEntity parse(String config); + + String deparse(RuleEntity ruleEntity); +} \ No newline at end of file diff --git a/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/resource/ConfigResourceImpl.java b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/resource/ConfigResourceImpl.java new file mode 100644 index 0000000000..af83255f2e --- /dev/null +++ b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/resource/ConfigResourceImpl.java @@ -0,0 +1,187 @@ +package com.nepxion.discovery.console.resource; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.List; + +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.env.Environment; +import org.springframework.web.client.RestTemplate; + +import com.nepxion.discovery.common.constant.DiscoveryConstant; +import com.nepxion.discovery.common.entity.ConfigFormatType; +import com.nepxion.discovery.common.entity.ConfigType; +import com.nepxion.discovery.common.entity.FormatType; +import com.nepxion.discovery.common.entity.ResultEntity; +import com.nepxion.discovery.common.entity.RuleEntity; +import com.nepxion.discovery.common.exception.DiscoveryException; +import com.nepxion.discovery.console.adapter.ConfigAdapter; +import com.nepxion.discovery.console.rest.ConfigClearRestInvoker; +import com.nepxion.discovery.console.rest.ConfigUpdateRestInvoker; +import com.nepxion.discovery.console.rest.ConfigViewRestInvoker; +import com.nepxion.discovery.plugin.framework.parser.PluginConfigDeparser; +import com.nepxion.discovery.plugin.framework.parser.PluginConfigParser; + +public class ConfigResourceImpl implements ConfigResource { + private static final Logger LOG = LoggerFactory.getLogger(ConfigResourceImpl.class); + + @Autowired(required = false) + private ConfigAdapter configAdapter; + + @Autowired + private ServiceResource serviceResource; + + @Autowired + private RestTemplate consoleRestTemplate; + + @Autowired + private PluginConfigParser pluginConfigParser; + + @Autowired + private PluginConfigDeparser pluginConfigDeparser; + + @Autowired + private Environment environment; + + @Override + public ConfigType getConfigType() { + if (configAdapter == null) { + LOG.error("Remote config adapter isn't provided"); + + throw new DiscoveryException("Remote config adapter isn't provided"); + } + + return configAdapter.getConfigType(); + } + + @Override + public boolean updateRemoteConfig(String group, String serviceId, String config) throws Exception { + if (configAdapter == null) { + LOG.error("Remote config adapter isn't provided"); + + throw new DiscoveryException("Remote config adapter isn't provided"); + } + + return configAdapter.updateConfig(group, serviceId, config); + } + + @Override + public boolean updateRemoteConfig(String group, String serviceId, String config, FormatType formatType) throws Exception { + if (configAdapter == null) { + LOG.error("Remote config adapter isn't provided"); + + throw new DiscoveryException("Remote config adapter isn't provided"); + } + + return configAdapter.updateConfig(group, serviceId, config, formatType); + } + + @Override + public boolean updateRemoteRuleEntity(String group, String serviceId, RuleEntity ruleEntity) throws Exception { + String config = fromRuleEntity(ruleEntity); + String configFormat = environment.getProperty(DiscoveryConstant.SPRING_APPLICATION_CONFIG_FORMAT, String.class, DiscoveryConstant.XML_FORMAT); + FormatType formatType = FormatType.fromString(configFormat); + + return updateRemoteConfig(group, serviceId, config, formatType); + } + + @Override + public boolean clearRemoteConfig(String group, String serviceId) throws Exception { + if (configAdapter == null) { + LOG.error("Remote config adapter isn't provided"); + + throw new DiscoveryException("Remote config adapter isn't provided"); + } + + return configAdapter.clearConfig(group, serviceId); + } + + @Override + public String getRemoteConfig(String group, String serviceId) throws Exception { + if (configAdapter == null) { + LOG.error("Remote config adapter isn't provided"); + + throw new DiscoveryException("Remote config adapter isn't provided"); + } + + return configAdapter.getConfig(group, serviceId); + } + + @Override + public RuleEntity getRemoteRuleEntity(String group, String serviceId) throws Exception { + String config = getRemoteConfig(group, serviceId); + + return toRuleEntity(config); + } + + @Override + public List updateConfig(String serviceId, String config, boolean async) { + ConfigUpdateRestInvoker configUpdateRestInvoker = new ConfigUpdateRestInvoker(serviceResource, serviceId, consoleRestTemplate, async, config); + + return configUpdateRestInvoker.invoke(); + } + + @Override + public List updateRuleEntity(String serviceId, RuleEntity ruleEntity, boolean async) { + String config = fromRuleEntity(ruleEntity); + + return updateConfig(serviceId, config, async); + } + + @Override + public List clearConfig(String serviceId, boolean async) { + ConfigClearRestInvoker configClearRestInvoker = new ConfigClearRestInvoker(serviceResource, serviceId, consoleRestTemplate, async); + + return configClearRestInvoker.invoke(); + } + + @Override + public List viewConfig(String serviceId) { + ConfigViewRestInvoker configViewRestInvoker = new ConfigViewRestInvoker(serviceResource, serviceId, consoleRestTemplate); + + return configViewRestInvoker.invoke(); + } + + @Override + public RuleEntity toRuleEntity(String config) { + return StringUtils.isNotEmpty(config) ? parse(config) : new RuleEntity(); + } + + @Override + public String fromRuleEntity(RuleEntity ruleEntity) { + if (ruleEntity != null) { + return deparse(ruleEntity); + } + + String configFormat = environment.getProperty(DiscoveryConstant.SPRING_APPLICATION_CONFIG_FORMAT, String.class, DiscoveryConstant.XML_FORMAT); + ConfigFormatType configFormatType = ConfigFormatType.fromString(configFormat); + switch (configFormatType) { + case XML_FORMAT: + return DiscoveryConstant.EMPTY_XML_RULE; + case JSON_FORMAT: + return DiscoveryConstant.EMPTY_JSON_RULE_SINGLE; + } + + return StringUtils.EMPTY; + } + + @Override + public RuleEntity parse(String config) { + return pluginConfigParser.parse(config); + } + + @Override + public String deparse(RuleEntity ruleEntity) { + return pluginConfigDeparser.deparse(ruleEntity); + } +} \ No newline at end of file diff --git a/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/resource/FailoverResource.java b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/resource/FailoverResource.java new file mode 100644 index 0000000000..7da9e0d2b2 --- /dev/null +++ b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/resource/FailoverResource.java @@ -0,0 +1,22 @@ +package com.nepxion.discovery.console.resource; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import com.nepxion.discovery.common.entity.FailoverType; + +public interface FailoverResource { + String createFailover(FailoverType failoverType, String group, String failoverValue); + + String clearFailover(FailoverType failoverType, String group); + + String createFailover(FailoverType failoverType, String group, String serviceId, String failoverValue); + + String clearFailover(FailoverType failoverType, String group, String serviceId); +} \ No newline at end of file diff --git a/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/resource/FailoverResourceImpl.java b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/resource/FailoverResourceImpl.java new file mode 100644 index 0000000000..ff3d0f9785 --- /dev/null +++ b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/resource/FailoverResourceImpl.java @@ -0,0 +1,97 @@ +package com.nepxion.discovery.console.resource; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.springframework.beans.factory.annotation.Autowired; + +import com.nepxion.discovery.common.entity.FailoverType; +import com.nepxion.discovery.common.entity.RuleEntity; +import com.nepxion.discovery.common.entity.StrategyFailoverEntity; +import com.nepxion.discovery.console.delegate.ConsoleResourceDelegateImpl; + +public class FailoverResourceImpl extends ConsoleResourceDelegateImpl implements FailoverResource { + @Autowired + private ConfigResource configResource; + + @Override + public String createFailover(FailoverType failoverType, String group, String failoverValue) { + return createFailover(failoverType, group, null, failoverValue); + } + + @Override + public String clearFailover(FailoverType failoverType, String group) { + return clearFailover(failoverType, group, null); + } + + @Override + public String createFailover(FailoverType failoverType, String group, String serviceId, String failoverValue) { + RuleEntity ruleEntity = getRemoteRuleEntity(group, serviceId); + + createFailover(failoverType, ruleEntity, failoverValue); + + updateRemoteRuleEntity(group, serviceId, ruleEntity); + + return configResource.fromRuleEntity(ruleEntity); + } + + @Override + public String clearFailover(FailoverType failoverType, String group, String serviceId) { + RuleEntity ruleEntity = getRemoteRuleEntity(group, serviceId); + + clearFailover(failoverType, ruleEntity); + + updateRemoteRuleEntity(group, serviceId, ruleEntity); + + return configResource.fromRuleEntity(ruleEntity); + } + + private void createFailover(FailoverType failoverType, RuleEntity ruleEntity, String failoverValue) { + StrategyFailoverEntity strategyFailoverEntity = ruleEntity.getStrategyFailoverEntity(); + if (strategyFailoverEntity == null) { + strategyFailoverEntity = new StrategyFailoverEntity(); + ruleEntity.setStrategyFailoverEntity(strategyFailoverEntity); + } + + setFailover(failoverType, strategyFailoverEntity, failoverValue); + } + + private void clearFailover(FailoverType failoverType, RuleEntity ruleEntity) { + StrategyFailoverEntity strategyFailoverEntity = ruleEntity.getStrategyFailoverEntity(); + if (strategyFailoverEntity != null) { + setFailover(failoverType, strategyFailoverEntity, null); + } + } + + private void setFailover(FailoverType failoverType, StrategyFailoverEntity strategyFailoverEntity, String failoverValue) { + switch (failoverType) { + case VERSION_PREFER: + strategyFailoverEntity.setVersionPreferValue(failoverValue); + break; + case VERSION_FAILOVER: + strategyFailoverEntity.setVersionFailoverValue(failoverValue); + break; + case REGION_TRANSFER: + strategyFailoverEntity.setRegionTransferValue(failoverValue); + break; + case REGION_FAILOVER: + strategyFailoverEntity.setRegionFailoverValue(failoverValue); + break; + case ENVIRONMENT_FAILOVER: + strategyFailoverEntity.setEnvironmentFailoverValue(failoverValue); + break; + case ZONE_FAILOVER: + strategyFailoverEntity.setZoneFailoverValue(failoverValue); + break; + case ADDRESS_FAILOVER: + strategyFailoverEntity.setAddressFailoverValue(failoverValue); + break; + } + } +} \ No newline at end of file diff --git a/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/resource/InspectorResource.java b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/resource/InspectorResource.java new file mode 100644 index 0000000000..c7f158542f --- /dev/null +++ b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/resource/InspectorResource.java @@ -0,0 +1,19 @@ +package com.nepxion.discovery.console.resource; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.List; +import java.util.Map; + +public interface InspectorResource { + String inspect(String protocol, String portal, String path, List service, Map header, List filter); + + List> inspectToList(String protocol, String portal, String path, List service, Map header, List filter); +} \ No newline at end of file diff --git a/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/resource/InspectorResourceImpl.java b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/resource/InspectorResourceImpl.java new file mode 100644 index 0000000000..abc756eb40 --- /dev/null +++ b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/resource/InspectorResourceImpl.java @@ -0,0 +1,63 @@ +package com.nepxion.discovery.console.resource; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.commons.collections4.MapUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.web.client.RestTemplate; + +import com.nepxion.discovery.common.constant.DiscoveryConstant; +import com.nepxion.discovery.common.entity.InspectorEntity; +import com.nepxion.discovery.common.util.PluginInfoUtil; +import com.nepxion.discovery.common.util.UrlUtil; + +public class InspectorResourceImpl implements InspectorResource { + @Autowired + private RestTemplate loadBalancedRestTemplate; + + @Override + public String inspect(String protocol, String portal, String path, List service, Map header, List filter) { + String url = protocol + "://" + portal + UrlUtil.formatContextPath(path) + DiscoveryConstant.INSPECTOR_ENDPOINT_URL; + + InspectorEntity inspectorEntity = new InspectorEntity(); + inspectorEntity.setServiceIdList(service); + + if (MapUtils.isNotEmpty(header)) { + HttpHeaders headers = new HttpHeaders(); + for (Map.Entry entry : header.entrySet()) { + headers.add(entry.getKey(), entry.getValue()); + } + + HttpEntity requestEntity = new HttpEntity(inspectorEntity, headers); + + String result = loadBalancedRestTemplate.exchange(url, HttpMethod.POST, requestEntity, InspectorEntity.class, new HashMap()).getBody().getResult(); + + return PluginInfoUtil.extractAll(result, filter); + } + + String result = loadBalancedRestTemplate.postForEntity(url, inspectorEntity, InspectorEntity.class).getBody().getResult(); + + return PluginInfoUtil.extractAll(result, filter); + } + + @Override + public List> inspectToList(String protocol, String portal, String path, List service, Map header, List filter) { + String result = inspect(protocol, portal, path, service, header, filter); + + return PluginInfoUtil.assembleAll(result, filter); + } +} \ No newline at end of file diff --git a/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/resource/RouteResource.java b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/resource/RouteResource.java new file mode 100644 index 0000000000..9015afaebb --- /dev/null +++ b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/resource/RouteResource.java @@ -0,0 +1,33 @@ +package com.nepxion.discovery.console.resource; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.List; + +import com.nepxion.discovery.common.entity.GatewayType; +import com.nepxion.discovery.common.entity.ResultEntity; + +public interface RouteResource { + boolean updateRemoteRoute(GatewayType gatewayType, String group, String serviceId, String route); + + boolean clearRemoteRoute(GatewayType gatewayType, String group, String serviceId); + + String getRemoteRoute(GatewayType gatewayType, String group, String serviceId); + + List addRoute(GatewayType gatewayType, String serviceId, String route); + + List modifyRoute(GatewayType gatewayType, String serviceId, String route); + + List deleteRoute(GatewayType gatewayType, String serviceId, String routeId); + + List updateAllRoute(GatewayType gatewayType, String serviceId, String route); + + List viewAllRoute(GatewayType gatewayType, String serviceId); +} \ No newline at end of file diff --git a/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/resource/RouteResourceImpl.java b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/resource/RouteResourceImpl.java new file mode 100644 index 0000000000..cdf5ef065a --- /dev/null +++ b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/resource/RouteResourceImpl.java @@ -0,0 +1,99 @@ +package com.nepxion.discovery.console.resource; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.client.RestTemplate; + +import com.nepxion.discovery.common.constant.DiscoveryConstant; +import com.nepxion.discovery.common.entity.FormatType; +import com.nepxion.discovery.common.entity.GatewayType; +import com.nepxion.discovery.common.entity.ResultEntity; +import com.nepxion.discovery.common.exception.DiscoveryException; +import com.nepxion.discovery.console.rest.RouteAddRestInvoker; +import com.nepxion.discovery.console.rest.RouteDeleteRestInvoker; +import com.nepxion.discovery.console.rest.RouteModifyRestInvoker; +import com.nepxion.discovery.console.rest.RouteUpdateAllRestInvoker; +import com.nepxion.discovery.console.rest.RouteViewAllRestInvoker; + +public class RouteResourceImpl implements RouteResource { + @Autowired + private ServiceResource serviceResource; + + @Autowired + private ConfigResource configResource; + + @Autowired + private RestTemplate consoleRestTemplate; + + @Override + public boolean updateRemoteRoute(GatewayType gatewayType, String group, String serviceId, String route) { + try { + return configResource.updateRemoteConfig(group, serviceId + "-" + DiscoveryConstant.DYNAMIC_ROUTE_KEY, route, FormatType.JSON_FORMAT); + } catch (Exception e) { + throw new DiscoveryException("Update remote " + gatewayType.getName() + " dynamic route failed, group={}, serviceId={}", e); + } + } + + @Override + public boolean clearRemoteRoute(GatewayType gatewayType, String group, String serviceId) { + try { + return configResource.updateRemoteConfig(group, serviceId + "-" + DiscoveryConstant.DYNAMIC_ROUTE_KEY, DiscoveryConstant.EMPTY_JSON_RULE_MULTIPLE, FormatType.JSON_FORMAT); + } catch (Exception e) { + throw new DiscoveryException("Clear remote " + gatewayType.getName() + " dynamic route failed, group={}, serviceId={}", e); + } + } + + @Override + public String getRemoteRoute(GatewayType gatewayType, String group, String serviceId) { + try { + return configResource.getRemoteConfig(group, serviceId + "-" + DiscoveryConstant.DYNAMIC_ROUTE_KEY); + } catch (Exception e) { + throw new DiscoveryException("Get remote " + gatewayType.getName() + " dynamic route failed, group={}, serviceId={}", e); + } + } + + @Override + public List addRoute(GatewayType gatewayType, String serviceId, String route) { + RouteAddRestInvoker routeAddRestInvoker = new RouteAddRestInvoker(serviceResource, serviceId, consoleRestTemplate, gatewayType, route); + + return routeAddRestInvoker.invoke(); + } + + @Override + public List modifyRoute(GatewayType gatewayType, String serviceId, String route) { + RouteModifyRestInvoker routeModifyRestInvoker = new RouteModifyRestInvoker(serviceResource, serviceId, consoleRestTemplate, gatewayType, route); + + return routeModifyRestInvoker.invoke(); + } + + @Override + public List deleteRoute(GatewayType gatewayType, String serviceId, String routeId) { + RouteDeleteRestInvoker routeDeleteRestInvoker = new RouteDeleteRestInvoker(serviceResource, serviceId, consoleRestTemplate, gatewayType, routeId); + + return routeDeleteRestInvoker.invoke(); + } + + @Override + public List updateAllRoute(GatewayType gatewayType, String serviceId, String route) { + RouteUpdateAllRestInvoker routeUpdateAllRestInvoker = new RouteUpdateAllRestInvoker(serviceResource, serviceId, consoleRestTemplate, gatewayType, route); + + return routeUpdateAllRestInvoker.invoke(); + } + + @Override + public List viewAllRoute(GatewayType gatewayType, String serviceId) { + RouteViewAllRestInvoker routeViewAllRestInvoker = new RouteViewAllRestInvoker(serviceResource, serviceId, consoleRestTemplate, gatewayType); + + return routeViewAllRestInvoker.invoke(); + } +} \ No newline at end of file diff --git a/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/resource/SentinelResource.java b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/resource/SentinelResource.java new file mode 100644 index 0000000000..be4099e66e --- /dev/null +++ b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/resource/SentinelResource.java @@ -0,0 +1,29 @@ +package com.nepxion.discovery.console.resource; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.List; + +import com.nepxion.discovery.common.entity.ResultEntity; +import com.nepxion.discovery.common.entity.SentinelRuleType; + +public interface SentinelResource { + boolean updateRemoteSentinel(SentinelRuleType ruleType, String group, String serviceId, String rule); + + boolean clearRemoteSentinel(SentinelRuleType ruleType, String group, String serviceId); + + String getRemoteSentinel(SentinelRuleType ruleType, String group, String serviceId); + + List updateSentinel(SentinelRuleType ruleType, String serviceId, String rule); + + List clearSentinel(SentinelRuleType ruleType, String serviceId); + + List viewSentinel(SentinelRuleType ruleType, String serviceId); +} \ No newline at end of file diff --git a/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/resource/SentinelResourceImpl.java b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/resource/SentinelResourceImpl.java new file mode 100644 index 0000000000..5eca664885 --- /dev/null +++ b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/resource/SentinelResourceImpl.java @@ -0,0 +1,83 @@ +package com.nepxion.discovery.console.resource; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.client.RestTemplate; + +import com.nepxion.discovery.common.constant.DiscoveryConstant; +import com.nepxion.discovery.common.entity.FormatType; +import com.nepxion.discovery.common.entity.ResultEntity; +import com.nepxion.discovery.common.entity.SentinelRuleType; +import com.nepxion.discovery.common.exception.DiscoveryException; +import com.nepxion.discovery.console.rest.SentinelClearRestInvoker; +import com.nepxion.discovery.console.rest.SentinelUpdateRestInvoker; +import com.nepxion.discovery.console.rest.SentinelViewRestInvoker; + +public class SentinelResourceImpl implements SentinelResource { + @Autowired + private ServiceResource serviceResource; + + @Autowired + private ConfigResource configResource; + + @Autowired + private RestTemplate consoleRestTemplate; + + @Override + public boolean updateRemoteSentinel(SentinelRuleType ruleType, String group, String serviceId, String rule) { + try { + return configResource.updateRemoteConfig(group, serviceId + "-" + ruleType.getKey(), rule, FormatType.JSON_FORMAT); + } catch (Exception e) { + throw new DiscoveryException("Update remote " + ruleType.getDescription() + " failed, group={}, serviceId={}", e); + } + } + + @Override + public boolean clearRemoteSentinel(SentinelRuleType ruleType, String group, String serviceId) { + try { + return configResource.updateRemoteConfig(group, serviceId + "-" + ruleType.getKey(), DiscoveryConstant.EMPTY_JSON_RULE_MULTIPLE, FormatType.JSON_FORMAT); + } catch (Exception e) { + throw new DiscoveryException("Clear remote " + ruleType.getDescription() + " failed, group={}, serviceId={}", e); + } + } + + @Override + public String getRemoteSentinel(SentinelRuleType ruleType, String group, String serviceId) { + try { + return configResource.getRemoteConfig(group, serviceId + "-" + ruleType.getKey()); + } catch (Exception e) { + throw new DiscoveryException("Get remote " + ruleType.getDescription() + " failed, group={}, serviceId={}", e); + } + } + + @Override + public List updateSentinel(SentinelRuleType ruleType, String serviceId, String rule) { + SentinelUpdateRestInvoker sentinelUpdateRestInvoker = new SentinelUpdateRestInvoker(serviceResource, serviceId, consoleRestTemplate, ruleType, rule); + + return sentinelUpdateRestInvoker.invoke(); + } + + @Override + public List clearSentinel(SentinelRuleType ruleType, String serviceId) { + SentinelClearRestInvoker sentinelClearRestInvoker = new SentinelClearRestInvoker(serviceResource, serviceId, consoleRestTemplate, ruleType); + + return sentinelClearRestInvoker.invoke(); + } + + @Override + public List viewSentinel(SentinelRuleType ruleType, String serviceId) { + SentinelViewRestInvoker sentinelViewRestInvoker = new SentinelViewRestInvoker(serviceResource, serviceId, consoleRestTemplate, ruleType); + + return sentinelViewRestInvoker.invoke(); + } +} \ No newline at end of file diff --git a/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/resource/ServiceResource.java b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/resource/ServiceResource.java new file mode 100644 index 0000000000..c6e63a2e61 --- /dev/null +++ b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/resource/ServiceResource.java @@ -0,0 +1,49 @@ +package com.nepxion.discovery.console.resource; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.List; +import java.util.Map; + +import org.springframework.cloud.client.ServiceInstance; + +import com.nepxion.discovery.common.entity.DiscoveryType; +import com.nepxion.discovery.common.entity.GatewayType; +import com.nepxion.discovery.common.entity.InstanceEntity; +import com.nepxion.discovery.common.entity.MetadataParameter; +import com.nepxion.discovery.common.entity.ServiceType; + +public interface ServiceResource { + DiscoveryType getDiscoveryType(); + + List getGroups(); + + String getGroup(String serviceId); + + List getServices(); + + List getServiceList(List serviceTypes); + + List getServiceList(String group, List serviceTypes); + + List getGateways(); + + List getGatewayList(List gatewayTypes); + + List getInstances(String serviceId); + + List getInstanceList(String serviceId); + + Map> getInstanceMap(List groups); + + Map> getMetadataMap(String metadataKey, List serviceIds); + + Map> getMetadataMap(MetadataParameter metadataParameter); +} \ No newline at end of file diff --git a/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/resource/ServiceResourceImpl.java b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/resource/ServiceResourceImpl.java new file mode 100644 index 0000000000..99b941592b --- /dev/null +++ b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/resource/ServiceResourceImpl.java @@ -0,0 +1,373 @@ +package com.nepxion.discovery.console.resource; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import org.apache.commons.collections4.CollectionUtils; +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cloud.client.ServiceInstance; +import org.springframework.cloud.client.discovery.DiscoveryClient; +import org.springframework.cloud.client.discovery.composite.CompositeDiscoveryClient; + +import com.nepxion.discovery.common.constant.DiscoveryConstant; +import com.nepxion.discovery.common.delegate.DiscoveryClientDelegate; +import com.nepxion.discovery.common.entity.DiscoveryType; +import com.nepxion.discovery.common.entity.GatewayType; +import com.nepxion.discovery.common.entity.InstanceEntity; +import com.nepxion.discovery.common.entity.InstanceEntityWrapper; +import com.nepxion.discovery.common.entity.MetadataParameter; +import com.nepxion.discovery.common.entity.ServiceType; + +public class ServiceResourceImpl implements ServiceResource { + @Autowired + private DiscoveryClient discoveryClient; + + @SuppressWarnings("unchecked") + @Override + public DiscoveryType getDiscoveryType() { + DiscoveryClient delegatedDiscoveryClient = null; + if (discoveryClient instanceof DiscoveryClientDelegate) { + delegatedDiscoveryClient = ((DiscoveryClientDelegate) discoveryClient).getDelegate(); + } else { + delegatedDiscoveryClient = discoveryClient; + } + + if (delegatedDiscoveryClient instanceof CompositeDiscoveryClient) { + CompositeDiscoveryClient compositeDiscoveryClient = (CompositeDiscoveryClient) delegatedDiscoveryClient; + List discoveryClients = compositeDiscoveryClient.getDiscoveryClients(); + for (DiscoveryClient client : discoveryClients) { + String discoveryDescription = client.description(); + DiscoveryType[] discoveryTypes = DiscoveryType.values(); + for (int i = 0; i < discoveryTypes.length; i++) { + DiscoveryType discoveryType = discoveryTypes[i]; + if (discoveryDescription.toLowerCase().contains(discoveryType.toString().toLowerCase())) { + return discoveryType; + } + } + } + } else { + String discoveryDescription = delegatedDiscoveryClient.description(); + DiscoveryType[] discoveryTypes = DiscoveryType.values(); + for (int i = 0; i < discoveryTypes.length; i++) { + DiscoveryType discoveryType = discoveryTypes[i]; + if (discoveryDescription.toLowerCase().contains(discoveryType.toString().toLowerCase())) { + return discoveryType; + } + } + } + + return null; + } + + @Override + public List getGroups() { + List groupList = new ArrayList(); + + List services = getServices(); + for (String service : services) { + List instanceEntityList = getInstanceList(service); + for (InstanceEntity instance : instanceEntityList) { + String group = instance.getGroup(); + if (!groupList.contains(group)) { + groupList.add(group); + } + } + } + + groupList.sort(String::compareTo); + + return groupList; + } + + @Override + public String getGroup(String serviceId) { + List instanceEntityList = getInstanceList(serviceId); + for (InstanceEntity instance : instanceEntityList) { + String group = instance.getGroup(); + if (StringUtils.isNotEmpty(group)) { + return group; + } + } + + return null; + } + + @Override + public List getServices() { + List serviceList = discoveryClient.getServices(); + + serviceList.sort(String::compareTo); + + return serviceList; + } + + @Override + public List getServiceList(List types) { + List serviceList = new ArrayList(); + List services = getServices(); + for (String service : services) { + List instances = getInstances(service); + for (ServiceInstance instance : instances) { + Map metadata = instance.getMetadata(); + String serviceId = instance.getServiceId().toLowerCase(); + String serviceType = InstanceEntityWrapper.getServiceType(metadata); + for (ServiceType type : types) { + if (StringUtils.equals(serviceType, type.toString())) { + if (!serviceList.contains(serviceId)) { + serviceList.add(serviceId); + } + } + } + } + } + + return serviceList; + } + + @Override + public List getServiceList(String group, List types) { + List serviceList = new ArrayList(); + List services = getServices(); + for (String service : services) { + List instances = getInstances(service); + for (ServiceInstance instance : instances) { + Map metadata = instance.getMetadata(); + String serviceGroup = InstanceEntityWrapper.getGroup(metadata); + if (StringUtils.equals(serviceGroup, group)) { + String serviceId = instance.getServiceId().toLowerCase(); + String serviceType = InstanceEntityWrapper.getServiceType(metadata); + for (ServiceType type : types) { + if (StringUtils.equals(serviceType, type.toString())) { + if (!serviceList.contains(serviceId)) { + serviceList.add(serviceId); + } + } + } + } + } + } + + return serviceList; + } + + @Override + public List getGateways() { + List gatewayList = new ArrayList(); + List services = getServices(); + for (String service : services) { + List instances = getInstances(service); + for (ServiceInstance instance : instances) { + Map metadata = instance.getMetadata(); + String serviceId = instance.getServiceId().toLowerCase(); + String serviceType = InstanceEntityWrapper.getServiceType(metadata); + if (StringUtils.equals(serviceType, ServiceType.GATEWAY.toString())) { + if (!gatewayList.contains(serviceId)) { + gatewayList.add(serviceId); + } + } + } + } + + return gatewayList; + } + + @Override + public List getGatewayList(List types) { + List gatewayList = new ArrayList(); + List services = getServices(); + for (String service : services) { + List instances = getInstances(service); + for (ServiceInstance instance : instances) { + Map metadata = instance.getMetadata(); + String serviceId = instance.getServiceId().toLowerCase(); + String serviceType = InstanceEntityWrapper.getServiceType(metadata); + String gatewayType = InstanceEntityWrapper.getGatewayType(metadata); + if (StringUtils.equals(serviceType, ServiceType.GATEWAY.toString())) { + for (GatewayType type : types) { + if (StringUtils.equals(gatewayType, type.toString())) { + if (!gatewayList.contains(serviceId)) { + gatewayList.add(serviceId); + } + } + } + } + } + } + + return gatewayList; + } + + @Override + public List getInstances(String serviceId) { + List instanceList = discoveryClient.getInstances(serviceId); + + // instanceList.sort(Comparator.comparing(ServiceInstance::getHost).thenComparing(ServiceInstance::getPort)); + instanceList.sort(Comparator.nullsLast(Comparator.comparing(ServiceInstance::getHost, Comparator.nullsLast(String::compareTo))).thenComparing(ServiceInstance::getPort)); + + return instanceList; + } + + @Override + public List getInstanceList(String service) { + List instances = getInstances(service); + List instanceEntityList = new ArrayList(instances.size()); + for (ServiceInstance instance : instances) { + Map metadata = instance.getMetadata(); + String plugin = InstanceEntityWrapper.getPlugin(metadata); + String group = InstanceEntityWrapper.getGroup(metadata); + String serviceType = InstanceEntityWrapper.getServiceType(metadata); + String serviceId = instance.getServiceId().toLowerCase(); + String serviceAppId = InstanceEntityWrapper.getServiceAppId(metadata); + String serviceUUId = InstanceEntityWrapper.getServiceUUId(metadata); + String version = InstanceEntityWrapper.getVersion(metadata); + String region = InstanceEntityWrapper.getRegion(metadata); + String environment = InstanceEntityWrapper.getEnvironment(metadata); + String zone = InstanceEntityWrapper.getZone(metadata); + boolean active = InstanceEntityWrapper.isActive(metadata); + String protocol = InstanceEntityWrapper.getProtocol(metadata); + String contextPath = InstanceEntityWrapper.getContextPath(metadata); + String formatContextPath = InstanceEntityWrapper.getFormatContextPath(metadata); + String host = instance.getHost(); + int port = instance.getPort(); + + InstanceEntity instanceEntity = new InstanceEntity(); + instanceEntity.setPlugin(plugin); + instanceEntity.setGroup(group); + instanceEntity.setServiceType(serviceType); + instanceEntity.setServiceId(serviceId); + instanceEntity.setServiceAppId(serviceAppId); + instanceEntity.setServiceUUId(serviceUUId); + instanceEntity.setVersion(version); + instanceEntity.setRegion(region); + instanceEntity.setEnvironment(environment); + instanceEntity.setZone(zone); + instanceEntity.setActive(active); + instanceEntity.setProtocol(protocol); + instanceEntity.setContextPath(contextPath); + instanceEntity.setFormatContextPath(formatContextPath); + instanceEntity.setHost(host); + instanceEntity.setPort(port); + instanceEntity.setMetadata(metadata); + + instanceEntityList.add(instanceEntity); + } + + return instanceEntityList; + } + + @Override + public Map> getInstanceMap(List groups) { + List services = getServices(); + Map> instanceMap = new LinkedHashMap>(services.size()); + for (String service : services) { + List instanceEntityList = getInstanceList(service); + if (CollectionUtils.isNotEmpty(groups)) { + for (InstanceEntity instance : instanceEntityList) { + String group = instance.getGroup(); + if (groups.contains(group)) { + List instanceList = instanceMap.get(service); + if (instanceList == null) { + instanceList = new ArrayList(); + instanceMap.put(service, instanceList); + } + instanceList.add(instance); + } + } + } else { + instanceMap.put(service, instanceEntityList); + } + } + + return instanceMap; + } + + @Override + public Map> getMetadataMap(String metadataKey, List serviceIds) { + Map> metadataMap = new LinkedHashMap>(serviceIds.size()); + for (String serviceId : serviceIds) { + List instanceEntityList = getInstanceList(serviceId); + for (InstanceEntity instance : instanceEntityList) { + List metadataList = metadataMap.get(serviceId); + if (metadataList == null) { + metadataList = new ArrayList(); + metadataMap.put(serviceId, metadataList); + } + String metadataValue = null; + if (StringUtils.equals(metadataKey, DiscoveryConstant.HOST + ":" + DiscoveryConstant.PORT)) { + metadataValue = instance.getHost() + ":" + instance.getPort(); + } else if (StringUtils.equals(metadataKey, DiscoveryConstant.HOST)) { + metadataValue = instance.getHost(); + } else if (StringUtils.equals(metadataKey, DiscoveryConstant.PORT)) { + metadataValue = String.valueOf(instance.getPort()); + } else { + metadataValue = instance.getMetadata().get(metadataKey); + } + if (!metadataList.contains(metadataValue)) { + if (StringUtils.isNotEmpty(metadataValue)) { + metadataList.add(metadataValue); + } + } + } + } + + return metadataMap; + } + + @Override + public Map> getMetadataMap(MetadataParameter metadataParameter) { + List metadataKeys = metadataParameter.getMetadataKeys(); + List serviceIds = metadataParameter.getServiceIds(); + String separate = metadataParameter.getSeparate(); + Map> metadataMap = new LinkedHashMap>(serviceIds.size()); + for (String serviceId : serviceIds) { + List instanceEntityList = getInstanceList(serviceId); + for (InstanceEntity instance : instanceEntityList) { + List metadataList = metadataMap.get(serviceId); + if (metadataList == null) { + metadataList = new ArrayList(); + metadataMap.put(serviceId, metadataList); + } + StringBuilder stringBuilder = new StringBuilder(); + int index = 0; + for (String metadataKey : metadataKeys) { + if (StringUtils.equals(metadataKey, DiscoveryConstant.HOST + ":" + DiscoveryConstant.PORT)) { + stringBuilder.append(instance.getHost() + ":" + instance.getPort()); + } else if (StringUtils.equals(metadataKey, DiscoveryConstant.HOST)) { + stringBuilder.append(instance.getHost()); + } else if (StringUtils.equals(metadataKey, DiscoveryConstant.PORT)) { + stringBuilder.append(instance.getPort()); + } else { + stringBuilder.append(instance.getMetadata().get(metadataKey)); + } + if (index < metadataKeys.size() - 1) { + stringBuilder.append(separate); + } + + index++; + } + + String metadataValues = stringBuilder.toString(); + if (!metadataList.contains(metadataValues)) { + if (StringUtils.isNotEmpty(metadataValues)) { + metadataList.add(metadataValues); + } + } + } + } + + return metadataMap; + } +} \ No newline at end of file diff --git a/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/resource/StrategyResource.java b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/resource/StrategyResource.java new file mode 100644 index 0000000000..fbc0c3dd21 --- /dev/null +++ b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/resource/StrategyResource.java @@ -0,0 +1,72 @@ +package com.nepxion.discovery.console.resource; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import com.nepxion.discovery.common.entity.ConditionRouteStrategy; +import com.nepxion.discovery.common.entity.ConditionStrategy; + +public interface StrategyResource { + // 全局订阅方式,获取Json格式的蓝绿灰度发布 + ConditionStrategy getVersionRelease(String group); + + // 全局订阅方式,根据Yaml格式,创建版本蓝绿灰度发布 + String createVersionRelease(String group, String conditionStrategyYaml); + + // 全局订阅方式,根据Json格式,创建版本蓝绿灰度发布 + String createVersionRelease(String group, ConditionStrategy conditionStrategy); + + // 全局订阅方式,根据Yaml格式,重新创建版本蓝绿灰度发布(创建链路智能编排,不创建条件表达式) + String recreateVersionRelease(String group, String conditionRouteStrategyYaml); + + // 全局订阅方式,根据Json格式,重新创建版本蓝绿灰度发布(创建链路智能编排,不创建条件表达式) + String recreateVersionRelease(String group, ConditionRouteStrategy conditionRouteStrategy); + + // 全局订阅方式,重置蓝绿灰度发布(清除链路智能编排,不清除条件表达式) + String resetRelease(String group); + + // 全局订阅方式,清除蓝绿灰度发布 + String clearRelease(String group); + + // 局部订阅方式,获取Json格式的蓝绿灰度发布 + ConditionStrategy getVersionRelease(String group, String serviceId); + + // 局部订阅方式,根据Yaml格式,创建版本蓝绿灰度发布 + String createVersionRelease(String group, String serviceId, String conditionStrategyYaml); + + // 局部订阅方式,根据Json格式,创建版本蓝绿灰度发布 + String createVersionRelease(String group, String serviceId, ConditionStrategy conditionStrategy); + + // 局部订阅方式,根据Yaml格式,重新创建版本蓝绿灰度发布(创建链路智能编排,不创建条件表达式) + String recreateVersionRelease(String group, String serviceId, String conditionRouteStrategyYaml); + + // 局部订阅方式,根据Json格式,重新创建版本蓝绿灰度发布(创建链路智能编排,不创建条件表达式) + String recreateVersionRelease(String group, String serviceId, ConditionRouteStrategy conditionRouteStrategy); + + // 局部订阅方式,重置蓝绿灰度发布(清除链路智能编排,不清除条件表达式) + String resetRelease(String group, String serviceId); + + // 局部订阅方式,清除蓝绿灰度发布 + String clearRelease(String group, String serviceId); + + // 根据Yaml格式,解析版本蓝绿灰度发布策略为Xml格式 + String parseVersionRelease(String conditionStrategyYaml); + + // 根据Json格式,解析版本蓝绿灰度发布策略为Xml格式 + String parseVersionRelease(ConditionStrategy conditionStrategy); + + // 根据Xml格式,反解析版本蓝绿灰度发布策略为Json格式 + ConditionStrategy deparseVersionReleaseXml(String ruleXml); + + // 根据Yaml格式,反解析版本蓝绿灰度发布策略为Json格式 + ConditionStrategy deparseVersionReleaseYaml(String conditionStrategyYaml); + + // 校验策略的条件表达式 + boolean validateExpression(String expression, String validation); +} \ No newline at end of file diff --git a/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/resource/StrategyResourceImpl.java b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/resource/StrategyResourceImpl.java new file mode 100644 index 0000000000..d8ad8af375 --- /dev/null +++ b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/resource/StrategyResourceImpl.java @@ -0,0 +1,465 @@ +package com.nepxion.discovery.console.resource; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import org.apache.commons.collections4.CollectionUtils; +import org.apache.commons.collections4.MapUtils; +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.expression.TypeComparator; + +import com.nepxion.discovery.common.constant.DiscoveryConstant; +import com.nepxion.discovery.common.entity.ConditionBlueGreenEntity; +import com.nepxion.discovery.common.entity.ConditionBlueGreenRoute; +import com.nepxion.discovery.common.entity.ConditionGrayEntity; +import com.nepxion.discovery.common.entity.ConditionRouteStrategy; +import com.nepxion.discovery.common.entity.ConditionStrategy; +import com.nepxion.discovery.common.entity.InstanceEntity; +import com.nepxion.discovery.common.entity.RuleEntity; +import com.nepxion.discovery.common.entity.StrategyConditionBlueGreenEntity; +import com.nepxion.discovery.common.entity.StrategyConditionGrayEntity; +import com.nepxion.discovery.common.entity.StrategyEntity; +import com.nepxion.discovery.common.entity.StrategyHeaderEntity; +import com.nepxion.discovery.common.entity.StrategyReleaseEntity; +import com.nepxion.discovery.common.entity.StrategyRouteEntity; +import com.nepxion.discovery.common.entity.StrategyRouteType; +import com.nepxion.discovery.common.entity.VersionSortType; +import com.nepxion.discovery.common.entity.VersionWeightEntity; +import com.nepxion.discovery.common.exception.DiscoveryException; +import com.nepxion.discovery.common.expression.DiscoveryExpressionResolver; +import com.nepxion.discovery.common.expression.DiscoveryTypeComparator; +import com.nepxion.discovery.common.util.JsonUtil; +import com.nepxion.discovery.common.util.StringUtil; +import com.nepxion.discovery.common.util.VersionSortUtil; +import com.nepxion.discovery.common.util.YamlUtil; +import com.nepxion.discovery.common.yaml.YamlSafeConstructor; +import com.nepxion.discovery.console.constant.ConsoleConstant; +import com.nepxion.discovery.console.delegate.ConsoleResourceDelegateImpl; + +public class StrategyResourceImpl extends ConsoleResourceDelegateImpl implements StrategyResource { + public static final String CONDITION = "condition"; + public static final String ROUTE = "route"; + + private TypeComparator typeComparator = new DiscoveryTypeComparator(); + + private YamlSafeConstructor conditionStrategyYamlSafeConstructor = new YamlSafeConstructor(new LinkedHashSet>(Arrays.asList(ConditionStrategy.class))); + + private YamlSafeConstructor conditionRouteStrategyYamlSafeConstructor = new YamlSafeConstructor(new LinkedHashSet>(Arrays.asList(ConditionRouteStrategy.class))); + + @Autowired + private ServiceResource serviceResource; + + @Autowired + private ConfigResource configResource; + + @Value("${" + ConsoleConstant.SPRING_APPLICATION_CONSOLE_STRATEGY_ENDPOINT_VALIDATE_EXPRESSION_ENABLED + ":true}") + private Boolean validateExpressionEnabled; + + @Override + public ConditionStrategy getVersionRelease(String group) { + return getVersionRelease(group, null); + } + + @Override + public String createVersionRelease(String group, String conditionStrategyYaml) { + ConditionStrategy conditionStrategy = deparseVersionReleaseYaml(conditionStrategyYaml); + + return createVersionRelease(group, conditionStrategy); + } + + @Override + public String createVersionRelease(String group, ConditionStrategy conditionStrategy) { + return createVersionRelease(group, null, conditionStrategy); + } + + @Override + public String recreateVersionRelease(String group, String conditionRouteStrategyYaml) { + return recreateVersionRelease(group, null, conditionRouteStrategyYaml); + } + + @Override + public String recreateVersionRelease(String group, ConditionRouteStrategy conditionRouteStrategy) { + return recreateVersionRelease(group, null, conditionRouteStrategy); + } + + @Override + public String resetRelease(String group) { + return resetRelease(group, null); + } + + @Override + public String clearRelease(String group) { + return clearRelease(group, null); + } + + @Override + public ConditionStrategy getVersionRelease(String group, String serviceId) { + RuleEntity ruleEntity = getRemoteRuleEntity(group, serviceId); + + return deparseVersionStrategyRelease(ruleEntity); + } + + @Override + public String createVersionRelease(String group, String serviceId, String conditionStrategyYaml) { + ConditionStrategy conditionStrategy = deparseVersionReleaseYaml(conditionStrategyYaml); + + return createVersionRelease(group, serviceId, conditionStrategy); + } + + @Override + public String createVersionRelease(String group, String serviceId, ConditionStrategy conditionStrategy) { + RuleEntity ruleEntity = getRemoteRuleEntity(group, serviceId); + + createVersionStrategyRelease(ruleEntity, conditionStrategy); + + updateRemoteRuleEntity(group, serviceId, ruleEntity); + + return configResource.fromRuleEntity(ruleEntity); + } + + @Override + public String recreateVersionRelease(String group, String serviceId, String conditionRouteStrategyYaml) { + ConditionRouteStrategy conditionRouteStrategy = YamlUtil.fromYaml(conditionRouteStrategyYamlSafeConstructor, conditionRouteStrategyYaml, ConditionRouteStrategy.class); + + return recreateVersionRelease(group, serviceId, conditionRouteStrategy); + } + + @Override + public String recreateVersionRelease(String group, String serviceId, ConditionRouteStrategy conditionRouteStrategy) { + RuleEntity ruleEntity = getRemoteRuleEntity(group, serviceId); + + List service = conditionRouteStrategy.getService(); + boolean condition = conditionRouteStrategy.isCondition(); // 是否创建条件路由 + String sort = conditionRouteStrategy.getSort(); + + ConditionStrategy conditionStrategy = deparseVersionStrategyRelease(ruleEntity); + conditionStrategy.setService(service); + conditionStrategy.setSort(sort); + + createVersionStrategyRelease(ruleEntity, conditionStrategy, condition); + + updateRemoteRuleEntity(group, serviceId, ruleEntity); + + return configResource.fromRuleEntity(ruleEntity); + } + + @Override + public String resetRelease(String group, String serviceId) { + RuleEntity ruleEntity = getRemoteRuleEntity(group, serviceId); + + resetStrategyRelease(ruleEntity); + + updateRemoteRuleEntity(group, serviceId, ruleEntity); + + return configResource.fromRuleEntity(ruleEntity); + } + + @Override + public String clearRelease(String group, String serviceId) { + RuleEntity ruleEntity = getRemoteRuleEntity(group, serviceId); + + clearStrategyRelease(ruleEntity); + + updateRemoteRuleEntity(group, serviceId, ruleEntity); + + return configResource.fromRuleEntity(ruleEntity); + } + + @Override + public String parseVersionRelease(String conditionStrategyYaml) { + ConditionStrategy conditionStrategy = deparseVersionReleaseYaml(conditionStrategyYaml); + + return parseVersionRelease(conditionStrategy); + } + + @Override + public String parseVersionRelease(ConditionStrategy conditionStrategy) { + RuleEntity ruleEntity = new RuleEntity(); + + createVersionStrategyRelease(ruleEntity, conditionStrategy); + + return configResource.fromRuleEntity(ruleEntity); + } + + @Override + public ConditionStrategy deparseVersionReleaseXml(String ruleXml) { + RuleEntity ruleEntity = configResource.toRuleEntity(ruleXml); + + return deparseVersionStrategyRelease(ruleEntity); + } + + @Override + public ConditionStrategy deparseVersionReleaseYaml(String conditionStrategyYaml) { + return YamlUtil.fromYaml(conditionStrategyYamlSafeConstructor, conditionStrategyYaml, ConditionStrategy.class); + } + + @Override + public boolean validateExpression(String expression, String validation) { + if (!validateExpressionEnabled) { + throw new DiscoveryException("Strategy endpoint for validate-expression is disabled"); + } + + Map map = null; + try { + map = StringUtil.splitToMap(validation); + } catch (Exception e) { + throw new DiscoveryException("Invalid format for validation input"); + } + + return DiscoveryExpressionResolver.eval(expression, DiscoveryConstant.EXPRESSION_PREFIX, map, typeComparator); + } + + private void createVersionStrategyRelease(RuleEntity ruleEntity, ConditionStrategy conditionStrategy) { + createVersionStrategyRelease(ruleEntity, conditionStrategy, true); + } + + private void createVersionStrategyRelease(RuleEntity ruleEntity, ConditionStrategy conditionStrategy, boolean createConditionRoute) { + List serviceList = conditionStrategy.getService(); + // 输入的服务列表为空,不允许执行蓝绿灰度发布,抛出异常 + if (CollectionUtils.isEmpty(serviceList)) { + throw new DiscoveryException("Services are empty"); + } + + String sort = conditionStrategy.getSort(); + VersionSortType versionSortType = VersionSortType.fromString(sort); + Map stableVersionMap = new LinkedHashMap(); + Map unstableVersionMap = new LinkedHashMap(); + for (String service : serviceList) { + List versionList = assembleVersionList(service, versionSortType); + // 如果线上版本为0个,不允许执行蓝绿灰度发布,抛出异常 + if (CollectionUtils.isEmpty(versionList)) { + throw new DiscoveryException("Service[" + service + "] has no versions"); + } + + // 旧版本,取值第1个 + String stableVersion = versionList.get(0); + stableVersionMap.put(service, stableVersion); + + String unstableVersion = null; + // 如果线上版本只有1个(属于用户误把非蓝绿灰度发布的服务添加入名单),新/旧版本相同,取值第1个 + if (versionList.size() == 1) { + unstableVersion = versionList.get(0); + // 如果线上版本只有2个(标准蓝绿灰度发布),取值第2个 + } else if (versionList.size() == 2) { + unstableVersion = versionList.get(1); + // 如果线上版本多于2个,取值第2个到最后1个,用分号分隔 + // 例如,3个版本为1.0, 2.0, 3.0,新版本为“2.0;3.0” + } else { + versionList.remove(0); + + unstableVersion = StringUtil.convertToString(versionList); + } + unstableVersionMap.put(service, unstableVersion); + } + + List blueGreenList = conditionStrategy.getBlueGreen(); + List grayList = conditionStrategy.getGray(); + + StrategyEntity strategyEntity = new StrategyEntity(); + strategyEntity.setVersionValue(JsonUtil.toJson(stableVersionMap)); + ruleEntity.setStrategyEntity(strategyEntity); + + List strategyConditionBlueGreenEntityList = null; + if (CollectionUtils.isNotEmpty(blueGreenList)) { + if (blueGreenList.size() != 2) { + throw new DiscoveryException("BlueGreens must have two expressions"); + } + + ConditionBlueGreenEntity conditionBlueGreenEntity0 = blueGreenList.get(0); + String blueGreenExpression0 = conditionBlueGreenEntity0.getExpression(); + if (StringUtils.isEmpty(blueGreenExpression0)) { + throw new DiscoveryException("BlueGreens must not have empty expressions"); + } + String blueGreenRoute0 = conditionBlueGreenEntity0.getRoute(); + + ConditionBlueGreenEntity conditionBlueGreenEntity1 = blueGreenList.get(1); + String blueGreenExpression1 = conditionBlueGreenEntity1.getExpression(); + if (StringUtils.isEmpty(blueGreenExpression1)) { + throw new DiscoveryException("BlueGreens must not have empty expressions"); + } + String blueGreenRoute1 = conditionBlueGreenEntity1.getRoute(); + + if (ConditionBlueGreenRoute.fromString(blueGreenRoute0) == ConditionBlueGreenRoute.fromString(blueGreenRoute1)) { + throw new DiscoveryException("BlueGreens must have one expression with green, another expression with blue"); + } + + StrategyConditionBlueGreenEntity strategyConditionBlueGreenEntity0 = new StrategyConditionBlueGreenEntity(); + strategyConditionBlueGreenEntity0.setId(CONDITION + "-" + (ConditionBlueGreenRoute.fromString(blueGreenRoute0) == ConditionBlueGreenRoute.GREEN ? "0" : "1")); + strategyConditionBlueGreenEntity0.setVersionId(ROUTE + "-" + (ConditionBlueGreenRoute.fromString(blueGreenRoute0) == ConditionBlueGreenRoute.GREEN ? "0" : "1")); + strategyConditionBlueGreenEntity0.setExpression(blueGreenExpression0); + + StrategyConditionBlueGreenEntity strategyConditionBlueGreenEntity1 = new StrategyConditionBlueGreenEntity(); + strategyConditionBlueGreenEntity1.setId(CONDITION + "-" + (ConditionBlueGreenRoute.fromString(blueGreenRoute1) == ConditionBlueGreenRoute.BLUE ? "1" : "0")); + strategyConditionBlueGreenEntity1.setVersionId(ROUTE + "-" + (ConditionBlueGreenRoute.fromString(blueGreenRoute1) == ConditionBlueGreenRoute.BLUE ? "1" : "0")); + strategyConditionBlueGreenEntity1.setExpression(blueGreenExpression1); + + strategyConditionBlueGreenEntityList = new ArrayList(); + strategyConditionBlueGreenEntityList.add(strategyConditionBlueGreenEntity0); + strategyConditionBlueGreenEntityList.add(strategyConditionBlueGreenEntity1); + } + + List strategyConditionGrayEntityList = null; + if (CollectionUtils.isNotEmpty(grayList)) { + strategyConditionGrayEntityList = new ArrayList(); + + int index = 0; + for (ConditionGrayEntity gray : grayList) { + String grayExpression = gray.getExpression(); + List grayWeightList = gray.getWeight(); + if (grayWeightList.size() != 2) { + throw new DiscoveryException("Grays weights must have 2 values"); + } + + Map weightMap = new LinkedHashMap(); + weightMap.put(ROUTE + "-0", grayWeightList.get(0)); + weightMap.put(ROUTE + "-1", grayWeightList.get(1)); + + VersionWeightEntity versionWeightEntity = new VersionWeightEntity(); + versionWeightEntity.setWeightMap(weightMap); + + StrategyConditionGrayEntity strategyConditionGrayEntity = new StrategyConditionGrayEntity(); + strategyConditionGrayEntity.setId(CONDITION + "-" + index); + strategyConditionGrayEntity.setExpression(grayExpression); + strategyConditionGrayEntity.setVersionWeightEntity(versionWeightEntity); + strategyConditionGrayEntityList.add(strategyConditionGrayEntity); + + index++; + } + } + + if (strategyConditionBlueGreenEntityList != null || strategyConditionGrayEntityList != null) { + StrategyReleaseEntity strategyReleaseEntity = new StrategyReleaseEntity(); + ruleEntity.setStrategyReleaseEntity(strategyReleaseEntity); + + if (strategyConditionBlueGreenEntityList != null) { + strategyReleaseEntity.setStrategyConditionBlueGreenEntityList(strategyConditionBlueGreenEntityList); + } + + if (strategyConditionGrayEntityList != null) { + strategyReleaseEntity.setStrategyConditionGrayEntityList(strategyConditionGrayEntityList); + } + + if (createConditionRoute) { + StrategyRouteEntity strategyRouteEntity0 = new StrategyRouteEntity(); + strategyRouteEntity0.setId(ROUTE + "-0"); + strategyRouteEntity0.setType(StrategyRouteType.VERSION); + strategyRouteEntity0.setValue(JsonUtil.toJson(stableVersionMap)); + + StrategyRouteEntity strategyRouteEntity1 = new StrategyRouteEntity(); + strategyRouteEntity1.setId(ROUTE + "-1"); + strategyRouteEntity1.setType(StrategyRouteType.VERSION); + strategyRouteEntity1.setValue(JsonUtil.toJson(unstableVersionMap)); + + List strategyRouteEntityList = new ArrayList(); + strategyRouteEntityList.add(strategyRouteEntity0); + strategyRouteEntityList.add(strategyRouteEntity1); + strategyReleaseEntity.setStrategyRouteEntityList(strategyRouteEntityList); + } + + Map headerMap = conditionStrategy.getHeader(); + StrategyHeaderEntity strategyHeaderEntity = new StrategyHeaderEntity(); + strategyHeaderEntity.setHeaderMap(headerMap); + strategyReleaseEntity.setStrategyHeaderEntity(strategyHeaderEntity); + } + } + + @SuppressWarnings("unchecked") + private ConditionStrategy deparseVersionStrategyRelease(RuleEntity ruleEntity) { + ConditionStrategy conditionStrategy = new ConditionStrategy(); + + StrategyEntity strategyEntity = ruleEntity.getStrategyEntity(); + if (strategyEntity != null) { + String versionValue = strategyEntity.getVersionValue(); + if (StringUtils.isNotEmpty(versionValue)) { + Map serviceMap = JsonUtil.fromJson(versionValue, Map.class); + conditionStrategy.setService(serviceMap.entrySet().stream().map(entry -> entry.getKey()).collect(Collectors.toList())); + } + } + + StrategyReleaseEntity strategyReleaseEntity = ruleEntity.getStrategyReleaseEntity(); + if (strategyReleaseEntity != null) { + List strategyConditionBlueGreenEntityList = strategyReleaseEntity.getStrategyConditionBlueGreenEntityList(); + if (CollectionUtils.isNotEmpty(strategyConditionBlueGreenEntityList)) { + List blueGreen = new ArrayList(); + for (StrategyConditionBlueGreenEntity strategyConditionBlueGreenEntity : strategyConditionBlueGreenEntityList) { + String id = strategyConditionBlueGreenEntity.getId(); + String expression = strategyConditionBlueGreenEntity.getExpression(); + + ConditionBlueGreenEntity conditionBlueGreenEntity = new ConditionBlueGreenEntity(); + conditionBlueGreenEntity.setExpression(expression); + if (StringUtils.equals(id, CONDITION + "-0")) { + conditionBlueGreenEntity.setRoute(ConditionBlueGreenRoute.GREEN.toString()); + } else if (StringUtils.equals(id, CONDITION + "-1")) { + conditionBlueGreenEntity.setRoute(ConditionBlueGreenRoute.BLUE.toString()); + } + blueGreen.add(conditionBlueGreenEntity); + } + conditionStrategy.setBlueGreen(blueGreen); + } + + List strategyConditionGrayEntityList = strategyReleaseEntity.getStrategyConditionGrayEntityList(); + if (CollectionUtils.isNotEmpty(strategyConditionGrayEntityList)) { + List gray = new ArrayList(); + for (StrategyConditionGrayEntity strategyConditionGrayEntity : strategyConditionGrayEntityList) { + String expression = strategyConditionGrayEntity.getExpression(); + + ConditionGrayEntity conditionGrayEntity = new ConditionGrayEntity(); + conditionGrayEntity.setExpression(expression); + VersionWeightEntity versionWeightEntity = strategyConditionGrayEntity.getVersionWeightEntity(); + if (versionWeightEntity != null) { + Map weightMap = versionWeightEntity.getWeightMap(); + if (MapUtils.isNotEmpty(weightMap)) { + int weight0 = weightMap.get(ROUTE + "-0"); + int weight1 = weightMap.get(ROUTE + "-1"); + conditionGrayEntity.setWeight(Arrays.asList(weight0, weight1)); + } + } + gray.add(conditionGrayEntity); + } + conditionStrategy.setGray(gray); + } + + StrategyHeaderEntity strategyHeaderEntity = strategyReleaseEntity.getStrategyHeaderEntity(); + if (strategyHeaderEntity != null) { + conditionStrategy.setHeader(strategyHeaderEntity.getHeaderMap()); + } + } + + return conditionStrategy; + } + + private void clearStrategyRelease(RuleEntity ruleEntity) { + ruleEntity.setStrategyEntity(null); + ruleEntity.setStrategyReleaseEntity(null); + } + + private void resetStrategyRelease(RuleEntity ruleEntity) { + ruleEntity.setStrategyEntity(null); + StrategyReleaseEntity strategyReleaseEntity = ruleEntity.getStrategyReleaseEntity(); + if (strategyReleaseEntity != null) { + strategyReleaseEntity.setStrategyRouteEntityList(null); + } + } + + private List assembleVersionList(String serviceId, VersionSortType versionSortType) { + List instanceEntityList = serviceResource.getInstanceList(serviceId); + + return VersionSortUtil.assembleVersionList(instanceEntityList, versionSortType); + } +} \ No newline at end of file diff --git a/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/resource/VersionResource.java b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/resource/VersionResource.java new file mode 100644 index 0000000000..21b74c6f41 --- /dev/null +++ b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/resource/VersionResource.java @@ -0,0 +1,22 @@ +package com.nepxion.discovery.console.resource; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.List; + +import com.nepxion.discovery.common.entity.ResultEntity; + +public interface VersionResource { + List updateVersion(String serviceId, String version, boolean async); + + List clearVersion(String serviceId, String version, boolean async); + + List viewVersion(String serviceId); +} \ No newline at end of file diff --git a/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/resource/VersionResourceImpl.java b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/resource/VersionResourceImpl.java new file mode 100644 index 0000000000..b58e262cc4 --- /dev/null +++ b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/resource/VersionResourceImpl.java @@ -0,0 +1,49 @@ +package com.nepxion.discovery.console.resource; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.client.RestTemplate; + +import com.nepxion.discovery.common.entity.ResultEntity; +import com.nepxion.discovery.console.rest.VersionClearRestInvoker; +import com.nepxion.discovery.console.rest.VersionUpdateRestInvoker; +import com.nepxion.discovery.console.rest.VersionViewRestInvoker; + +public class VersionResourceImpl implements VersionResource { + @Autowired + private ServiceResource serviceResource; + + @Autowired + private RestTemplate consoleRestTemplate; + + @Override + public List updateVersion(String serviceId, String version, boolean async) { + VersionUpdateRestInvoker versionUpdateRestInvoker = new VersionUpdateRestInvoker(serviceResource, serviceId, consoleRestTemplate, async, version); + + return versionUpdateRestInvoker.invoke(); + } + + @Override + public List clearVersion(String serviceId, String version, boolean async) { + VersionClearRestInvoker versionClearRestInvoker = new VersionClearRestInvoker(serviceResource, serviceId, consoleRestTemplate, async, version); + + return versionClearRestInvoker.invoke(); + } + + @Override + public List viewVersion(String serviceId) { + VersionViewRestInvoker versionViewRestInvoker = new VersionViewRestInvoker(serviceResource, serviceId, consoleRestTemplate); + + return versionViewRestInvoker.invoke(); + } +} \ No newline at end of file diff --git a/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/rest/AbstractRestInvoker.java b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/rest/AbstractRestInvoker.java new file mode 100644 index 0000000000..ff25786bc0 --- /dev/null +++ b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/rest/AbstractRestInvoker.java @@ -0,0 +1,122 @@ +package com.nepxion.discovery.console.rest; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import org.apache.commons.collections4.CollectionUtils; +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.cloud.client.ServiceInstance; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; +import org.springframework.web.client.RestTemplate; + +import com.nepxion.discovery.common.constant.DiscoveryConstant; +import com.nepxion.discovery.common.entity.InstanceEntityWrapper; +import com.nepxion.discovery.common.entity.ResultEntity; +import com.nepxion.discovery.common.exception.DiscoveryException; +import com.nepxion.discovery.common.util.ResponseUtil; +import com.nepxion.discovery.common.util.RestUtil; +import com.nepxion.discovery.console.resource.ServiceResource; + +public abstract class AbstractRestInvoker { + private static final Logger LOG = LoggerFactory.getLogger(AbstractRestInvoker.class); + + protected ServiceResource serviceResource; + protected String serviceId; + protected RestTemplate restTemplate; + protected boolean async; + + public AbstractRestInvoker(ServiceResource serviceResource, String serviceId, RestTemplate restTemplate) { + this(serviceResource, serviceId, restTemplate, false); + } + + public AbstractRestInvoker(ServiceResource serviceResource, String serviceId, RestTemplate restTemplate, boolean async) { + this.serviceResource = serviceResource; + this.serviceId = serviceId; + this.restTemplate = restTemplate; + this.async = async; + } + + public List invoke() { + List instances = serviceResource.getInstances(serviceId); + if (CollectionUtils.isEmpty(instances)) { + LOG.warn("No service instances found"); + + throw new DiscoveryException("No service instances found"); + } + + List resultEntityList = new ArrayList(); + for (ServiceInstance instance : instances) { + Map metadata = instance.getMetadata(); + String host = instance.getHost(); + int port = instance.getPort(); + + String protocol = InstanceEntityWrapper.getProtocol(metadata); + String contextPath = InstanceEntityWrapper.getFormatContextPath(metadata); + + String url = protocol + "://" + host + ":" + port + contextPath + getSuffixPath(); + + String result = null; + try { + result = doRest(url); + String error = RestUtil.getError(restTemplate); + if (StringUtils.isNotEmpty(error)) { + result = error; + } + } catch (Exception e) { + result = ResponseUtil.getFailureMessage(e); + } + + ResultEntity resultEntity = new ResultEntity(); + resultEntity.setServiceId(serviceId); + resultEntity.setHost(host); + resultEntity.setPort(port); + resultEntity.setUrl(url); + resultEntity.setResult(result); + + resultEntityList.add(resultEntity); + } + + String description = getDescription(); + + LOG.info(description + " results=\n{}", resultEntityList); + + return resultEntityList; + } + + protected String getInvokeType() { + return async ? DiscoveryConstant.ASYNC : DiscoveryConstant.SYNC; + } + + protected HttpHeaders getInvokeHeaders() { + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON_UTF8); + + return headers; + } + + protected HttpEntity getInvokeEntity(String content) { + HttpHeaders headers = getInvokeHeaders(); + + return new HttpEntity(content, headers); + } + + protected abstract String getDescription(); + + protected abstract String getSuffixPath(); + + protected abstract String doRest(String url); +} \ No newline at end of file diff --git a/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/rest/ConfigClearRestInvoker.java b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/rest/ConfigClearRestInvoker.java new file mode 100644 index 0000000000..6cc089fa6e --- /dev/null +++ b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/rest/ConfigClearRestInvoker.java @@ -0,0 +1,35 @@ +package com.nepxion.discovery.console.rest; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.springframework.web.client.RestTemplate; + +import com.nepxion.discovery.console.resource.ServiceResource; + +public class ConfigClearRestInvoker extends AbstractRestInvoker { + public ConfigClearRestInvoker(ServiceResource serviceResource, String serviceId, RestTemplate restTemplate, boolean async) { + super(serviceResource, serviceId, restTemplate, async); + } + + @Override + protected String getDescription() { + return "Config cleared"; + } + + @Override + protected String getSuffixPath() { + return "config/clear-" + getInvokeType(); + } + + @Override + protected String doRest(String url) { + return restTemplate.postForEntity(url, null, String.class).getBody(); + } +} \ No newline at end of file diff --git a/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/rest/ConfigUpdateRestInvoker.java b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/rest/ConfigUpdateRestInvoker.java new file mode 100644 index 0000000000..9797dc6d35 --- /dev/null +++ b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/rest/ConfigUpdateRestInvoker.java @@ -0,0 +1,39 @@ +package com.nepxion.discovery.console.rest; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.springframework.web.client.RestTemplate; + +import com.nepxion.discovery.console.resource.ServiceResource; + +public class ConfigUpdateRestInvoker extends AbstractRestInvoker { + private String config; + + public ConfigUpdateRestInvoker(ServiceResource serviceResource, String serviceId, RestTemplate restTemplate, boolean async, String config) { + super(serviceResource, serviceId, restTemplate, async); + + this.config = config; + } + + @Override + protected String getDescription() { + return "Config updated"; + } + + @Override + protected String getSuffixPath() { + return "config/update-" + getInvokeType(); + } + + @Override + protected String doRest(String url) { + return restTemplate.postForEntity(url, getInvokeEntity(config), String.class).getBody(); + } +} \ No newline at end of file diff --git a/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/rest/ConfigViewRestInvoker.java b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/rest/ConfigViewRestInvoker.java new file mode 100644 index 0000000000..651f2276a8 --- /dev/null +++ b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/rest/ConfigViewRestInvoker.java @@ -0,0 +1,35 @@ +package com.nepxion.discovery.console.rest; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.springframework.web.client.RestTemplate; + +import com.nepxion.discovery.console.resource.ServiceResource; + +public class ConfigViewRestInvoker extends AbstractRestInvoker { + public ConfigViewRestInvoker(ServiceResource serviceResource, String serviceId, RestTemplate restTemplate) { + super(serviceResource, serviceId, restTemplate); + } + + @Override + protected String getDescription() { + return "Config viewed"; + } + + @Override + protected String getSuffixPath() { + return "config/view"; + } + + @Override + protected String doRest(String url) { + return restTemplate.getForEntity(url, String.class).getBody(); + } +} \ No newline at end of file diff --git a/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/rest/RouteAddRestInvoker.java b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/rest/RouteAddRestInvoker.java new file mode 100644 index 0000000000..f04e9109af --- /dev/null +++ b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/rest/RouteAddRestInvoker.java @@ -0,0 +1,42 @@ +package com.nepxion.discovery.console.rest; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.springframework.web.client.RestTemplate; + +import com.nepxion.discovery.common.entity.GatewayType; +import com.nepxion.discovery.console.resource.ServiceResource; + +public class RouteAddRestInvoker extends AbstractRestInvoker { + private GatewayType gatewayType; + private String route; + + public RouteAddRestInvoker(ServiceResource serviceResource, String serviceId, RestTemplate restTemplate, GatewayType gatewayType, String route) { + super(serviceResource, serviceId, restTemplate); + + this.gatewayType = gatewayType; + this.route = route; + } + + @Override + protected String getDescription() { + return "Route added"; + } + + @Override + protected String getSuffixPath() { + return gatewayType + "-route/add"; + } + + @Override + protected String doRest(String url) { + return restTemplate.postForEntity(url, getInvokeEntity(route), String.class).getBody(); + } +} \ No newline at end of file diff --git a/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/rest/RouteDeleteRestInvoker.java b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/rest/RouteDeleteRestInvoker.java new file mode 100644 index 0000000000..044fa44cf1 --- /dev/null +++ b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/rest/RouteDeleteRestInvoker.java @@ -0,0 +1,44 @@ +package com.nepxion.discovery.console.rest; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.springframework.web.client.RestTemplate; + +import com.nepxion.discovery.common.entity.GatewayType; +import com.nepxion.discovery.console.resource.ServiceResource; + +public class RouteDeleteRestInvoker extends AbstractRestInvoker { + private GatewayType gatewayType; + private String routeId; + + public RouteDeleteRestInvoker(ServiceResource serviceResource, String serviceId, RestTemplate restTemplate, GatewayType gatewayType, String routeId) { + super(serviceResource, serviceId, restTemplate); + + this.gatewayType = gatewayType; + this.routeId = routeId; + } + + @Override + protected String getDescription() { + return "Route deleted"; + } + + @Override + protected String getSuffixPath() { + return gatewayType + "-route/delete/" + routeId; + } + + @Override + protected String doRest(String url) { + restTemplate.delete(url); + + return Boolean.TRUE.toString(); + } +} \ No newline at end of file diff --git a/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/rest/RouteModifyRestInvoker.java b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/rest/RouteModifyRestInvoker.java new file mode 100644 index 0000000000..e4e5f791f5 --- /dev/null +++ b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/rest/RouteModifyRestInvoker.java @@ -0,0 +1,42 @@ +package com.nepxion.discovery.console.rest; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.springframework.web.client.RestTemplate; + +import com.nepxion.discovery.common.entity.GatewayType; +import com.nepxion.discovery.console.resource.ServiceResource; + +public class RouteModifyRestInvoker extends AbstractRestInvoker { + private GatewayType gatewayType; + private String route; + + public RouteModifyRestInvoker(ServiceResource serviceResource, String serviceId, RestTemplate restTemplate, GatewayType gatewayType, String route) { + super(serviceResource, serviceId, restTemplate); + + this.gatewayType = gatewayType; + this.route = route; + } + + @Override + protected String getDescription() { + return "Route modified"; + } + + @Override + protected String getSuffixPath() { + return gatewayType + "-route/modify"; + } + + @Override + protected String doRest(String url) { + return restTemplate.postForEntity(url, getInvokeEntity(route), String.class).getBody(); + } +} \ No newline at end of file diff --git a/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/rest/RouteUpdateAllRestInvoker.java b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/rest/RouteUpdateAllRestInvoker.java new file mode 100644 index 0000000000..dfd5b35903 --- /dev/null +++ b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/rest/RouteUpdateAllRestInvoker.java @@ -0,0 +1,42 @@ +package com.nepxion.discovery.console.rest; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.springframework.web.client.RestTemplate; + +import com.nepxion.discovery.common.entity.GatewayType; +import com.nepxion.discovery.console.resource.ServiceResource; + +public class RouteUpdateAllRestInvoker extends AbstractRestInvoker { + private GatewayType gatewayType; + private String route; + + public RouteUpdateAllRestInvoker(ServiceResource serviceResource, String serviceId, RestTemplate restTemplate, GatewayType gatewayType, String route) { + super(serviceResource, serviceId, restTemplate); + + this.gatewayType = gatewayType; + this.route = route; + } + + @Override + protected String getDescription() { + return "Route updated all"; + } + + @Override + protected String getSuffixPath() { + return gatewayType + "-route/update-all"; + } + + @Override + protected String doRest(String url) { + return restTemplate.postForEntity(url, getInvokeEntity(route), String.class).getBody(); + } +} \ No newline at end of file diff --git a/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/rest/RouteViewAllRestInvoker.java b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/rest/RouteViewAllRestInvoker.java new file mode 100644 index 0000000000..a32f44c2f8 --- /dev/null +++ b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/rest/RouteViewAllRestInvoker.java @@ -0,0 +1,40 @@ +package com.nepxion.discovery.console.rest; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.springframework.web.client.RestTemplate; + +import com.nepxion.discovery.common.entity.GatewayType; +import com.nepxion.discovery.console.resource.ServiceResource; + +public class RouteViewAllRestInvoker extends AbstractRestInvoker { + private GatewayType gatewayType; + + public RouteViewAllRestInvoker(ServiceResource serviceResource, String serviceId, RestTemplate restTemplate, GatewayType gatewayType) { + super(serviceResource, serviceId, restTemplate); + + this.gatewayType = gatewayType; + } + + @Override + protected String getDescription() { + return "Route viewed"; + } + + @Override + protected String getSuffixPath() { + return gatewayType + "-route/view-all"; + } + + @Override + protected String doRest(String url) { + return restTemplate.getForEntity(url, String.class).getBody(); + } +} \ No newline at end of file diff --git a/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/rest/SentinelClearRestInvoker.java b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/rest/SentinelClearRestInvoker.java new file mode 100644 index 0000000000..612916455e --- /dev/null +++ b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/rest/SentinelClearRestInvoker.java @@ -0,0 +1,43 @@ +package com.nepxion.discovery.console.rest; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.apache.commons.lang3.StringUtils; +import org.springframework.web.client.RestTemplate; + +import com.nepxion.discovery.common.entity.SentinelRuleType; +import com.nepxion.discovery.console.resource.ServiceResource; + +public class SentinelClearRestInvoker extends AbstractRestInvoker { + private SentinelRuleType ruleType; + + public SentinelClearRestInvoker(ServiceResource serviceResource, String serviceId, RestTemplate restTemplate, SentinelRuleType ruleType) { + super(serviceResource, serviceId, restTemplate); + + this.ruleType = ruleType; + } + + @Override + protected String getDescription() { + return "Sentinel rules cleared"; + } + + @Override + protected String getSuffixPath() { + String path = StringUtils.equals(ruleType.toString(), "param-flow") ? "sentinel-param" : "sentinel-core"; + + return path + "/clear-" + ruleType + "-rules"; + } + + @Override + protected String doRest(String url) { + return restTemplate.postForEntity(url, null, String.class).getBody(); + } +} \ No newline at end of file diff --git a/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/rest/SentinelUpdateRestInvoker.java b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/rest/SentinelUpdateRestInvoker.java new file mode 100644 index 0000000000..ca4c7e3575 --- /dev/null +++ b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/rest/SentinelUpdateRestInvoker.java @@ -0,0 +1,45 @@ +package com.nepxion.discovery.console.rest; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.apache.commons.lang3.StringUtils; +import org.springframework.web.client.RestTemplate; + +import com.nepxion.discovery.common.entity.SentinelRuleType; +import com.nepxion.discovery.console.resource.ServiceResource; + +public class SentinelUpdateRestInvoker extends AbstractRestInvoker { + private SentinelRuleType ruleType; + private String rule; + + public SentinelUpdateRestInvoker(ServiceResource serviceResource, String serviceId, RestTemplate restTemplate, SentinelRuleType ruleType, String rule) { + super(serviceResource, serviceId, restTemplate); + + this.ruleType = ruleType; + this.rule = rule; + } + + @Override + protected String getDescription() { + return "Sentinel rules updated"; + } + + @Override + protected String getSuffixPath() { + String path = StringUtils.equals(ruleType.toString(), "param-flow") ? "sentinel-param" : "sentinel-core"; + + return path + "/update-" + ruleType + "-rules"; + } + + @Override + protected String doRest(String url) { + return restTemplate.postForEntity(url, getInvokeEntity(rule), String.class).getBody(); + } +} \ No newline at end of file diff --git a/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/rest/SentinelViewRestInvoker.java b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/rest/SentinelViewRestInvoker.java new file mode 100644 index 0000000000..2de29c3e3b --- /dev/null +++ b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/rest/SentinelViewRestInvoker.java @@ -0,0 +1,43 @@ +package com.nepxion.discovery.console.rest; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.apache.commons.lang3.StringUtils; +import org.springframework.web.client.RestTemplate; + +import com.nepxion.discovery.common.entity.SentinelRuleType; +import com.nepxion.discovery.console.resource.ServiceResource; + +public class SentinelViewRestInvoker extends AbstractRestInvoker { + private SentinelRuleType ruleType; + + public SentinelViewRestInvoker(ServiceResource serviceResource, String serviceId, RestTemplate restTemplate, SentinelRuleType ruleType) { + super(serviceResource, serviceId, restTemplate); + + this.ruleType = ruleType; + } + + @Override + protected String getDescription() { + return "Sentinel rules viewed"; + } + + @Override + protected String getSuffixPath() { + String path = StringUtils.equals(ruleType.toString(), "param-flow") ? "sentinel-param" : "sentinel-core"; + + return path + "/view-" + ruleType + "-rules"; + } + + @Override + protected String doRest(String url) { + return restTemplate.getForEntity(url, String.class).getBody(); + } +} \ No newline at end of file diff --git a/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/rest/VersionClearRestInvoker.java b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/rest/VersionClearRestInvoker.java new file mode 100644 index 0000000000..4f069fce9b --- /dev/null +++ b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/rest/VersionClearRestInvoker.java @@ -0,0 +1,39 @@ +package com.nepxion.discovery.console.rest; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.springframework.web.client.RestTemplate; + +import com.nepxion.discovery.console.resource.ServiceResource; + +public class VersionClearRestInvoker extends AbstractRestInvoker { + private String version; + + public VersionClearRestInvoker(ServiceResource serviceResource, String serviceId, RestTemplate restTemplate, boolean async, String version) { + super(serviceResource, serviceId, restTemplate, async); + + this.version = version; + } + + @Override + protected String getDescription() { + return "Version cleared"; + } + + @Override + protected String getSuffixPath() { + return "version/clear-" + getInvokeType(); + } + + @Override + protected String doRest(String url) { + return restTemplate.postForEntity(url, version, String.class).getBody(); + } +} \ No newline at end of file diff --git a/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/rest/VersionUpdateRestInvoker.java b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/rest/VersionUpdateRestInvoker.java new file mode 100644 index 0000000000..0798544b18 --- /dev/null +++ b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/rest/VersionUpdateRestInvoker.java @@ -0,0 +1,39 @@ +package com.nepxion.discovery.console.rest; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.springframework.web.client.RestTemplate; + +import com.nepxion.discovery.console.resource.ServiceResource; + +public class VersionUpdateRestInvoker extends AbstractRestInvoker { + private String version; + + public VersionUpdateRestInvoker(ServiceResource serviceResource, String serviceId, RestTemplate restTemplate, boolean async, String version) { + super(serviceResource, serviceId, restTemplate, async); + + this.version = version; + } + + @Override + protected String getDescription() { + return "Version updated"; + } + + @Override + protected String getSuffixPath() { + return "version/update-" + getInvokeType(); + } + + @Override + protected String doRest(String url) { + return restTemplate.postForEntity(url, version, String.class).getBody(); + } +} \ No newline at end of file diff --git a/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/rest/VersionViewRestInvoker.java b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/rest/VersionViewRestInvoker.java new file mode 100644 index 0000000000..65bc822147 --- /dev/null +++ b/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/rest/VersionViewRestInvoker.java @@ -0,0 +1,35 @@ +package com.nepxion.discovery.console.rest; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.springframework.web.client.RestTemplate; + +import com.nepxion.discovery.console.resource.ServiceResource; + +public class VersionViewRestInvoker extends AbstractRestInvoker { + public VersionViewRestInvoker(ServiceResource serviceResource, String serviceId, RestTemplate restTemplate) { + super(serviceResource, serviceId, restTemplate); + } + + @Override + protected String getDescription() { + return "Version viewed"; + } + + @Override + protected String getSuffixPath() { + return "version/view"; + } + + @Override + protected String doRest(String url) { + return restTemplate.getForEntity(url, String.class).getBody(); + } +} \ No newline at end of file diff --git a/discovery-console/discovery-console-starter/src/main/resources/META-INF/additional-spring-configuration-metadata.json b/discovery-console/discovery-console-starter/src/main/resources/META-INF/additional-spring-configuration-metadata.json new file mode 100644 index 0000000000..4569696d2b --- /dev/null +++ b/discovery-console/discovery-console-starter/src/main/resources/META-INF/additional-spring-configuration-metadata.json @@ -0,0 +1,70 @@ +{ + "properties": [ + { + "name": "spring.application.console.service.endpoint.enabled", + "type": "java.lang.Boolean", + "defaultValue": true, + "description": "Whether console service endpoint is enabled." + }, + { + "name": "spring.application.console.config.endpoint.enabled", + "type": "java.lang.Boolean", + "defaultValue": true, + "description": "Whether console config endpoint is enabled." + }, + { + "name": "spring.application.console.version.endpoint.enabled", + "type": "java.lang.Boolean", + "defaultValue": true, + "description": "Whether console version endpoint is enabled." + }, + { + "name": "spring.application.console.inspector.endpoint.enabled", + "type": "java.lang.Boolean", + "defaultValue": true, + "description": "Whether console inspector endpoint is enabled." + }, + { + "name": "spring.application.console.route.endpoint.enabled", + "type": "java.lang.Boolean", + "defaultValue": true, + "description": "Whether console route endpoint is enabled." + }, + { + "name": "spring.application.console.strategy.endpoint.enabled", + "type": "java.lang.Boolean", + "defaultValue": true, + "description": "Whether console strategy endpoint is enabled." + }, + { + "name": "spring.application.console.sentinel.endpoint.enabled", + "type": "java.lang.Boolean", + "defaultValue": true, + "description": "Whether console sentinel endpoint is enabled." + }, + { + "name": "spring.application.console.blacklist.endpoint.enabled", + "type": "java.lang.Boolean", + "defaultValue": true, + "description": "Whether console blacklist endpoint is enabled." + }, + { + "name": "spring.application.console.failover.endpoint.enabled", + "type": "java.lang.Boolean", + "defaultValue": true, + "description": "Whether console failover endpoint is enabled." + }, + { + "name": "spring.application.console.authentication.endpoint.enabled", + "type": "java.lang.Boolean", + "defaultValue": true, + "description": "Whether console authentication endpoint is enabled." + }, + { + "name": "spring.application.console.strategy.endpoint.validate-expression.enabled", + "type": "java.lang.Boolean", + "defaultValue": true, + "description": "Whether console strategy endpoint for validate-expression is enabled." + } + ] +} \ No newline at end of file diff --git a/discovery-console/discovery-console-starter/src/main/resources/META-INF/spring.factories b/discovery-console/discovery-console-starter/src/main/resources/META-INF/spring.factories new file mode 100644 index 0000000000..1de49f28f5 --- /dev/null +++ b/discovery-console/discovery-console-starter/src/main/resources/META-INF/spring.factories @@ -0,0 +1,8 @@ +org.springframework.boot.env.EnvironmentPostProcessor=\ +com.nepxion.discovery.console.context.ConsoleEnvironmentPostProcessor + +org.springframework.context.ApplicationContextInitializer=\ +com.nepxion.discovery.console.context.ConsoleApplicationContextInitializer + +org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ +com.nepxion.discovery.console.configuration.ConsoleAutoConfiguration \ No newline at end of file diff --git a/discovery-console/pom.xml b/discovery-console/pom.xml index e45a6f9db4..a4bc7f419f 100644 --- a/discovery-console/pom.xml +++ b/discovery-console/pom.xml @@ -3,56 +3,24 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> discovery-console Nepxion Discovery Console - jar + pom 4.0.0 - Nepxion Discovery is an enhancement for Spring Cloud Discovery + Nepxion Discovery is a solution for Spring Cloud with blue green, gray, weight, limitation, circuit breaker, degrade, isolation, monitor, tracing, dye, failover, async agent http://www.nepxion.com com.nepxion discovery - 5.2.0-SNAPSHOT + 6.23.0 - - - ${project.groupId} - discovery-common - - - - ${project.groupId} - banner - - - - org.springframework.cloud - spring-cloud-starter - - - - org.springframework.cloud - spring-cloud-starter-netflix-ribbon - - - - org.springframework.boot - spring-boot-starter-web - - - - org.springframework.boot - spring-boot-starter-actuator - - - - io.springfox - springfox-swagger2 - - - - io.springfox - springfox-swagger-ui - - + + discovery-console-starter + discovery-console-starter-apollo + discovery-console-starter-nacos + discovery-console-starter-redis + discovery-console-starter-zookeeper + discovery-console-starter-consul + discovery-console-starter-etcd + \ No newline at end of file diff --git a/discovery-console/src/main/java/com/nepxion/discovery/console/adapter/ConfigAdapter.java b/discovery-console/src/main/java/com/nepxion/discovery/console/adapter/ConfigAdapter.java deleted file mode 100644 index 129ce89aa7..0000000000 --- a/discovery-console/src/main/java/com/nepxion/discovery/console/adapter/ConfigAdapter.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.nepxion.discovery.console.adapter; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -public interface ConfigAdapter { - boolean updateConfig(String group, String serviceId, String config) throws Exception; - - boolean clearConfig(String group, String serviceId) throws Exception; - - String getConfig(String group, String serviceId) throws Exception; - - String getConfigType(); -} \ No newline at end of file diff --git a/discovery-console/src/main/java/com/nepxion/discovery/console/authentication/AuthenticationResource.java b/discovery-console/src/main/java/com/nepxion/discovery/console/authentication/AuthenticationResource.java deleted file mode 100644 index b32f4ced3f..0000000000 --- a/discovery-console/src/main/java/com/nepxion/discovery/console/authentication/AuthenticationResource.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.nepxion.discovery.console.authentication; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import com.nepxion.discovery.common.entity.UserEntity; - -public interface AuthenticationResource { - boolean authenticate(UserEntity userEntity) throws Exception; -} \ No newline at end of file diff --git a/discovery-console/src/main/java/com/nepxion/discovery/console/authentication/AuthenticationResourceImpl.java b/discovery-console/src/main/java/com/nepxion/discovery/console/authentication/AuthenticationResourceImpl.java deleted file mode 100644 index 5ba7f97336..0000000000 --- a/discovery-console/src/main/java/com/nepxion/discovery/console/authentication/AuthenticationResourceImpl.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.nepxion.discovery.console.authentication; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import org.apache.commons.lang3.StringUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.core.env.Environment; - -import com.nepxion.discovery.common.entity.UserEntity; - -public class AuthenticationResourceImpl implements AuthenticationResource { - @Autowired - private Environment environment; - - @Override - public boolean authenticate(UserEntity userEntity) throws Exception { - String userId = userEntity.getUserId().trim(); - String password = userEntity.getPassword().trim(); - - String passwordValue = environment.getProperty(userId); - if (StringUtils.isNotEmpty(passwordValue)) { - return StringUtils.equals(password, passwordValue); - } else { - throw new IllegalArgumentException("Not exists for [" + userId + "]"); - } - } -} \ No newline at end of file diff --git a/discovery-console/src/main/java/com/nepxion/discovery/console/configuration/ConsoleAutoConfiguration.java b/discovery-console/src/main/java/com/nepxion/discovery/console/configuration/ConsoleAutoConfiguration.java deleted file mode 100644 index 36872b6047..0000000000 --- a/discovery-console/src/main/java/com/nepxion/discovery/console/configuration/ConsoleAutoConfiguration.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.nepxion.discovery.console.configuration; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import org.springframework.boot.actuate.endpoint.web.annotation.RestControllerEndpoint; -import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; -import org.springframework.web.client.RestTemplate; - -import com.nepxion.discovery.common.handler.RestErrorHandler; -import com.nepxion.discovery.console.authentication.AuthenticationResource; -import com.nepxion.discovery.console.authentication.AuthenticationResourceImpl; -import com.nepxion.discovery.console.endpoint.ConsoleEndpoint; - -@Configuration -@Import({ SwaggerConfiguration.class, CorsRegistryConfiguration.class }) -public class ConsoleAutoConfiguration { - @ConditionalOnClass(RestControllerEndpoint.class) - protected static class ConsoleEndpointConfiguration { - @Bean - public ConsoleEndpoint consoleEndpoint() { - return new ConsoleEndpoint(); - } - - @Bean - public RestTemplate consoleRestTemplate() { - RestTemplate restTemplate = new RestTemplate(); - restTemplate.setErrorHandler(new RestErrorHandler()); - - return restTemplate; - } - - @Bean - @ConditionalOnMissingBean - public AuthenticationResource authenticationResource() { - return new AuthenticationResourceImpl(); - } - } -} \ No newline at end of file diff --git a/discovery-console/src/main/java/com/nepxion/discovery/console/configuration/CorsRegistryConfiguration.java b/discovery-console/src/main/java/com/nepxion/discovery/console/configuration/CorsRegistryConfiguration.java deleted file mode 100644 index cfcdf5e8b6..0000000000 --- a/discovery-console/src/main/java/com/nepxion/discovery/console/configuration/CorsRegistryConfiguration.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.nepxion.discovery.console.configuration; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.context.annotation.Configuration; -import org.springframework.web.servlet.config.annotation.CorsRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; - -@Configuration -@ConditionalOnProperty(value = "cors.registry.enabled", matchIfMissing = true) -public class CorsRegistryConfiguration implements WebMvcConfigurer { - // 解决跨域问题 - @Override - public void addCorsMappings(CorsRegistry registry) { - registry.addMapping("/**") - .allowedHeaders("*") - .allowedMethods("*") - .allowedOrigins("*"); - } -} \ No newline at end of file diff --git a/discovery-console/src/main/java/com/nepxion/discovery/console/configuration/SwaggerConfiguration.java b/discovery-console/src/main/java/com/nepxion/discovery/console/configuration/SwaggerConfiguration.java deleted file mode 100644 index 535bf378ad..0000000000 --- a/discovery-console/src/main/java/com/nepxion/discovery/console/configuration/SwaggerConfiguration.java +++ /dev/null @@ -1,125 +0,0 @@ -package com.nepxion.discovery.console.configuration; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import springfox.documentation.RequestHandler; -import springfox.documentation.builders.ApiInfoBuilder; -import springfox.documentation.builders.PathSelectors; -import springfox.documentation.service.ApiInfo; -import springfox.documentation.service.Contact; -import springfox.documentation.service.Parameter; -import springfox.documentation.spi.DocumentationType; -import springfox.documentation.spring.web.plugins.Docket; -import springfox.documentation.swagger2.annotations.EnableSwagger2; - -import java.util.List; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -import com.google.common.base.Function; -import com.google.common.base.Optional; -import com.google.common.base.Predicate; -import com.nepxion.discovery.common.constant.DiscoveryConstant; - -@Configuration -@EnableSwagger2 -@ConditionalOnProperty(value = "swagger.service.enabled", matchIfMissing = true) -public class SwaggerConfiguration { - public static final String BASE_PACKAGE = "com.nepxion.discovery.console.endpoint"; - - @Value("${spring.application.name}") - private String serviceName; - - @Value("${swagger.service.description:Console Restful APIs}") - private String description; - - @Value("${swagger.service.version:1.0.0}") - private String version; - - @Value("${swagger.service.license.name:Apache License 2.0}") - private String license; - - @Value("${swagger.service.license.url:http://www.apache.org/licenses/LICENSE-2.0}") - private String licenseUrl; - - @Value("${swagger.service.contact.name:Haojun Ren}") - private String contactName; - - @Value("${swagger.service.contact.url:https://github.com/Nepxion/Discovery}") - private String contactUrl; - - @Value("${swagger.service.contact.email:1394997@qq.com}") - private String contactEmail; - - @Value("${swagger.service.termsOfServiceUrl:http://www.nepxion.com}") - private String termsOfServiceUrl; - - @Autowired(required = false) - private List swaggerHeaderParameters; - - @Bean("discoveryDocket") - public Docket createRestApi() { - return new Docket(DocumentationType.SWAGGER_2) - .groupName("discovery") - .apiInfo(apiInfo()) - .select() - .apis(SwaggerConfiguration.basePackage(BASE_PACKAGE)) // 扫描该包下的所有需要在Swagger中展示的API,@ApiIgnore注解标注的除外 - .paths(PathSelectors.any()) - .build() - .globalOperationParameters(swaggerHeaderParameters); - } - - private ApiInfo apiInfo() { - return new ApiInfoBuilder() - .title(serviceName) - .description(description) - .version(version) - .license(license) - .licenseUrl(licenseUrl) - .contact(new Contact(contactName, contactUrl, contactEmail)) - .termsOfServiceUrl(termsOfServiceUrl) - .build(); - } - - public static Predicate basePackage(String basePackage) { - return new Predicate() { - @Override - public boolean apply(RequestHandler input) { - return declaringClass(input).transform(handlerPackage(basePackage)).or(true); - } - }; - } - - private static Function, Boolean> handlerPackage(String basePackage) { - return new Function, Boolean>() { - @Override - public Boolean apply(Class input) { - String[] subPackages = basePackage.split(DiscoveryConstant.SEPARATE); - for (String subPackage : subPackages) { - boolean matched = input.getPackage().getName().startsWith(subPackage.trim()); - if (matched) { - return true; - } - } - - return false; - } - }; - } - - @SuppressWarnings("deprecation") - private static Optional> declaringClass(RequestHandler input) { - return Optional.fromNullable(input.declaringClass()); - } -} \ No newline at end of file diff --git a/discovery-console/src/main/java/com/nepxion/discovery/console/context/ConsoleApplicationContextInitializer.java b/discovery-console/src/main/java/com/nepxion/discovery/console/context/ConsoleApplicationContextInitializer.java deleted file mode 100644 index 17c1699e9f..0000000000 --- a/discovery-console/src/main/java/com/nepxion/discovery/console/context/ConsoleApplicationContextInitializer.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.nepxion.discovery.console.context; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import org.springframework.context.ApplicationContextInitializer; -import org.springframework.context.ConfigurableApplicationContext; - -import com.nepxion.banner.BannerConstant; -import com.nepxion.banner.Description; -import com.nepxion.banner.LogoBanner; -import com.nepxion.banner.NepxionBanner; -import com.nepxion.discovery.common.constant.DiscoveryConstant; -import com.taobao.text.Color; - -public class ConsoleApplicationContextInitializer implements ApplicationContextInitializer { - @Override - public void initialize(ConfigurableApplicationContext applicationContext) { - String applicationContextClassName = applicationContext.getClass().getName(); - if (applicationContextClassName.endsWith(DiscoveryConstant.ANNOTATION_CONFIG_SERVLET_WEB_SERVER_APPLICATION_CONTEXT) || applicationContextClassName.endsWith(DiscoveryConstant.ANNOTATION_CONFIG_REACTIVE_WEB_SERVER_APPLICATION_CONTEXT)) { - /*String bannerShown = System.getProperty(BannerConstant.BANNER_SHOWN, "true"); - if (Boolean.valueOf(bannerShown)) { - System.out.println(""); - System.out.println("╔═══╗"); - System.out.println("╚╗╔╗║"); - System.out.println(" ║║║╠╦══╦══╦══╦╗╔╦══╦═╦╗ ╔╗"); - System.out.println(" ║║║╠╣══╣╔═╣╔╗║╚╝║║═╣╔╣║ ║║"); - System.out.println("╔╝╚╝║╠══║╚═╣╚╝╠╗╔╣║═╣║║╚═╝║"); - System.out.println("╚═══╩╩══╩══╩══╝╚╝╚══╩╝╚═╗╔╝"); - System.out.println(" ╔═╝║"); - System.out.println(" ╚══╝"); - System.out.println("Nepxion Discovery - Console v" + DiscoveryConstant.DISCOVERY_VERSION); - System.out.println(""); - }*/ - - LogoBanner logoBanner = new LogoBanner(ConsoleApplicationContextInitializer.class, "/com/nepxion/discovery/resource/logo.txt", "Welcome to Nepxion", 9, 5, new Color[] { Color.red, Color.green, Color.cyan, Color.blue, Color.yellow, Color.magenta, Color.red, Color.green, Color.cyan }, true); - - NepxionBanner.show(logoBanner, new Description(BannerConstant.VERSION + ":", DiscoveryConstant.DISCOVERY_VERSION, 0, 1), new Description(BannerConstant.PLUGIN + ":", "Console", 0, 1), new Description(BannerConstant.GITHUB + ":", BannerConstant.NEPXION_GITHUB + "/Discovery", 0, 1)); - } - - if (applicationContextClassName.endsWith(DiscoveryConstant.ANNOTATION_CONFIG_SERVLET_WEB_SERVER_APPLICATION_CONTEXT)) { - System.setProperty(DiscoveryConstant.SPRING_APPLICATION_SERVLET_WEB_SERVER_ENABLED, Boolean.toString(true)); - } - if (applicationContextClassName.endsWith(DiscoveryConstant.ANNOTATION_CONFIG_REACTIVE_WEB_SERVER_APPLICATION_CONTEXT)) { - System.setProperty(DiscoveryConstant.SPRING_APPLICATION_REACTIVE_WEB_SERVER_ENABLED, Boolean.toString(true)); - } - } -} \ No newline at end of file diff --git a/discovery-console/src/main/java/com/nepxion/discovery/console/endpoint/ConsoleEndpoint.java b/discovery-console/src/main/java/com/nepxion/discovery/console/endpoint/ConsoleEndpoint.java deleted file mode 100644 index 41339947eb..0000000000 --- a/discovery-console/src/main/java/com/nepxion/discovery/console/endpoint/ConsoleEndpoint.java +++ /dev/null @@ -1,431 +0,0 @@ -package com.nepxion.discovery.console.endpoint; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; - -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -import org.apache.commons.collections4.CollectionUtils; -import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.actuate.endpoint.web.annotation.RestControllerEndpoint; -import org.springframework.cloud.client.ServiceInstance; -import org.springframework.cloud.client.discovery.DiscoveryClient; -import org.springframework.cloud.client.discovery.composite.CompositeDiscoveryClient; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.jmx.export.annotation.ManagedOperation; -import org.springframework.jmx.export.annotation.ManagedResource; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.ResponseBody; -import org.springframework.web.bind.annotation.RestController; -import org.springframework.web.client.RestTemplate; - -import com.nepxion.discovery.common.constant.DiscoveryConstant; -import com.nepxion.discovery.common.entity.InstanceEntity; -import com.nepxion.discovery.common.entity.InstanceEntityWrapper; -import com.nepxion.discovery.common.entity.UserEntity; -import com.nepxion.discovery.console.adapter.ConfigAdapter; -import com.nepxion.discovery.console.authentication.AuthenticationResource; -import com.nepxion.discovery.console.rest.ConfigClearRestInvoker; -import com.nepxion.discovery.console.rest.ConfigUpdateRestInvoker; -import com.nepxion.discovery.console.rest.VersionClearRestInvoker; -import com.nepxion.discovery.console.rest.VersionUpdateRestInvoker; - -@RestController -@RequestMapping(path = "/console") -@Api(tags = { "控制台接口" }) -@RestControllerEndpoint(id = "console") -@ManagedResource(description = "Console Endpoint") -public class ConsoleEndpoint { - private static final Logger LOG = LoggerFactory.getLogger(ConsoleEndpoint.class); - - private static final String[] DISCOVERY_TYPES = { "Eureka", "Consul", "Zookeeper", "Nacos" }; - - @Autowired - private DiscoveryClient discoveryClient; - - @Autowired(required = false) - private ConfigAdapter configAdapter; - - @Autowired - private RestTemplate consoleRestTemplate; - - @Autowired - private AuthenticationResource authenticationResource; - - @RequestMapping(path = "/authenticate", method = RequestMethod.POST) - @ApiOperation(value = "登录认证", notes = "", response = ResponseEntity.class, httpMethod = "POST") - @ResponseBody - @ManagedOperation - public ResponseEntity authenticate(@RequestBody @ApiParam(value = "UserEntity实例", required = true) UserEntity userEntity) { - return executeAuthenticate(userEntity); - } - - @RequestMapping(path = "/discovery-type", method = RequestMethod.GET) - @ApiOperation(value = "获取注册发现中心类型", notes = "", response = ResponseEntity.class, httpMethod = "GET") - @ResponseBody - @ManagedOperation - public ResponseEntity discoveryType() { - return getDiscoveryType(); - } - - @RequestMapping(path = "/config-type", method = RequestMethod.GET) - @ApiOperation(value = "获取配置中心类型", notes = "", response = ResponseEntity.class, httpMethod = "GET") - @ResponseBody - @ManagedOperation - public ResponseEntity configType() { - return getConfigType(); - } - - @RequestMapping(path = "/groups", method = RequestMethod.GET) - @ApiOperation(value = "获取服务注册中心的服务组名列表", notes = "", response = List.class, httpMethod = "GET") - @ResponseBody - @ManagedOperation - public List groups() { - return getGroups(); - } - - @RequestMapping(path = "/services", method = RequestMethod.GET) - @ApiOperation(value = "获取服务注册中心的服务名列表", notes = "", response = List.class, httpMethod = "GET") - @ResponseBody - @ManagedOperation - public List services() { - return getServices(); - } - - @RequestMapping(path = "/instances/{serviceId}", method = RequestMethod.GET) - @ApiOperation(value = "获取服务注册中心的服务实例列表", notes = "", response = List.class, httpMethod = "GET") - @ResponseBody - @ManagedOperation - public List instances(@PathVariable(value = "serviceId") @ApiParam(value = "服务名", required = true) String serviceId) { - return getInstances(serviceId); - } - - @RequestMapping(path = "/instance-list/{serviceId}", method = RequestMethod.GET) - @ApiOperation(value = "获取服务注册中心的服务实例列表(精简数据)", notes = "", response = List.class, httpMethod = "GET") - @ResponseBody - @ManagedOperation - public List instanceList(@PathVariable(value = "serviceId") @ApiParam(value = "服务名", required = true) String serviceId) { - return getInstanceList(serviceId); - } - - @RequestMapping(path = "/instance-map", method = RequestMethod.POST) - @ApiOperation(value = "获取服务注册中心的服务实例的Map(精简数据)", notes = "服务组名列表", response = Map.class, httpMethod = "POST") - @ResponseBody - @ManagedOperation - public Map> instanceMap(@RequestBody @ApiParam(value = "服务组名列表,传入空列则可以获取全部服务实例数据", required = true) List groups) { - return getInstanceMap(groups); - } - - @RequestMapping(path = "/remote-config/update/{group}/{serviceId}", method = RequestMethod.POST) - @ApiOperation(value = "推送更新规则配置信息到远程配置中心", notes = "", response = ResponseEntity.class, httpMethod = "POST") - @ResponseBody - @ManagedOperation - public ResponseEntity remoteConfigUpdate(@PathVariable(value = "group") @ApiParam(value = "组名", required = true) String group, @PathVariable(value = "serviceId") @ApiParam(value = "服务名。当全局推送模式下,服务名必须由组名来代替", required = true) String serviceId, @RequestBody @ApiParam(value = "规则配置内容,XML格式", required = true) String config) { - return executeRemoteConfigUpdate(group, serviceId, config); - } - - @RequestMapping(path = "/remote-config/clear/{group}/{serviceId}", method = RequestMethod.POST) - @ApiOperation(value = "清除规则配置信息到远程配置中心", notes = "", response = ResponseEntity.class, httpMethod = "POST") - @ResponseBody - @ManagedOperation - public ResponseEntity remoteConfigClear(@PathVariable(value = "group") @ApiParam(value = "组名", required = true) String group, @PathVariable(value = "serviceId") @ApiParam(value = "服务名。当全局推送模式下,服务名必须由组名来代替", required = true) String serviceId) { - return executeRemoteConfigClear(group, serviceId); - } - - @RequestMapping(path = "/remote-config/view/{group}/{serviceId}", method = RequestMethod.GET) - @ApiOperation(value = "查看远程配置中心的规则配置信息", notes = "", response = ResponseEntity.class, httpMethod = "GET") - @ResponseBody - @ManagedOperation - public ResponseEntity remoteConfigView(@PathVariable(value = "group") @ApiParam(value = "组名", required = true) String group, @PathVariable(value = "serviceId") @ApiParam(value = "服务名。当全局推送模式下,服务名必须由组名来代替", required = true) String serviceId) { - return executeRemoteConfigView(group, serviceId); - } - - @RequestMapping(path = "/config/update-async/{serviceId}", method = RequestMethod.POST) - @ApiOperation(value = "批量异步推送更新规则配置信息", notes = "", response = ResponseEntity.class, httpMethod = "POST") - @ResponseBody - @ManagedOperation - public ResponseEntity configUpdateAsync(@PathVariable(value = "serviceId") @ApiParam(value = "服务名", required = true) String serviceId, @RequestBody @ApiParam(value = "规则配置内容,XML格式", required = true) String config) { - return executeConfigUpdate(serviceId, config, true); - } - - @RequestMapping(path = "/config/update-sync/{serviceId}", method = RequestMethod.POST) - @ApiOperation(value = "批量同步推送更新规则配置信息", notes = "", response = ResponseEntity.class, httpMethod = "POST") - @ResponseBody - @ManagedOperation - public ResponseEntity configUpdateSync(@PathVariable(value = "serviceId") @ApiParam(value = "服务名", required = true) String serviceId, @RequestBody @ApiParam(value = "规则配置内容,XML格式", required = true) String config) { - return executeConfigUpdate(serviceId, config, false); - } - - @RequestMapping(path = "/config/clear-async/{serviceId}", method = RequestMethod.POST) - @ApiOperation(value = "批量异步清除更新的规则配置信息", notes = "", response = ResponseEntity.class, httpMethod = "POST") - @ResponseBody - @ManagedOperation - public ResponseEntity configClearAsync(@PathVariable(value = "serviceId") @ApiParam(value = "服务名", required = true) String serviceId) { - return executeConfigClear(serviceId, true); - } - - @RequestMapping(path = "/config/clear-sync/{serviceId}", method = RequestMethod.POST) - @ApiOperation(value = "批量同步清除更新的规则配置信息", notes = "", response = ResponseEntity.class, httpMethod = "POST") - @ResponseBody - @ManagedOperation - public ResponseEntity configClearSync(@PathVariable(value = "serviceId") @ApiParam(value = "服务名", required = true) String serviceId) { - return executeConfigClear(serviceId, false); - } - - @RequestMapping(path = "/version/update-async/{serviceId}", method = RequestMethod.POST) - @ApiOperation(value = "批量异步更新服务的动态版本", notes = "根据指定的localVersion更新服务的dynamicVersion。如果输入的localVersion不匹配服务的localVersion,则忽略;如果如果输入的localVersion为空,则直接更新服务的dynamicVersion", response = ResponseEntity.class, httpMethod = "POST") - @ResponseBody - @ManagedOperation - public ResponseEntity versionUpdateAsync(@PathVariable(value = "serviceId") @ApiParam(value = "服务名", required = true) String serviceId, @RequestBody @ApiParam(value = "版本号,格式为[dynamicVersion]或者[dynamicVersion];[localVersion]", required = true) String version) { - return executeVersionUpdate(serviceId, version, true); - } - - @RequestMapping(path = "/version/update-sync/{serviceId}", method = RequestMethod.POST) - @ApiOperation(value = "批量同步更新服务的动态版本", notes = "根据指定的localVersion更新服务的dynamicVersion。如果输入的localVersion不匹配服务的localVersion,则忽略;如果如果输入的localVersion为空,则直接更新服务的dynamicVersion", response = ResponseEntity.class, httpMethod = "POST") - @ResponseBody - @ManagedOperation - public ResponseEntity versionUpdateSync(@PathVariable(value = "serviceId") @ApiParam(value = "服务名", required = true) String serviceId, @RequestBody @ApiParam(value = "版本号,格式为[dynamicVersion]或者[dynamicVersion];[localVersion]", required = true) String version) { - return executeVersionUpdate(serviceId, version, false); - } - - @RequestMapping(path = "/version/clear-async/{serviceId}", method = RequestMethod.POST) - @ApiOperation(value = "批量异步清除服务的动态版本", notes = "根据指定的localVersion清除服务的dynamicVersion。如果输入的localVersion不匹配服务的localVersion,则忽略;如果如果输入的localVersion为空,则直接清除服务的dynamicVersion", response = ResponseEntity.class, httpMethod = "POST") - @ResponseBody - @ManagedOperation - public ResponseEntity versionClearAsync(@PathVariable(value = "serviceId") @ApiParam(value = "服务名", required = true) String serviceId, @RequestBody(required = false) @ApiParam(value = "版本号,指localVersion,可以为空") String version) { - return executeVersionClear(serviceId, version, true); - } - - @RequestMapping(path = "/version/clear-sync/{serviceId}", method = RequestMethod.POST) - @ApiOperation(value = "批量同步清除服务的动态版本", notes = "根据指定的localVersion清除服务的dynamicVersion。如果输入的localVersion不匹配服务的localVersion,则忽略;如果如果输入的localVersion为空,则直接清除服务的dynamicVersion", response = ResponseEntity.class, httpMethod = "POST") - @ResponseBody - @ManagedOperation - public ResponseEntity versionClearSync(@PathVariable(value = "serviceId") @ApiParam(value = "服务名", required = true) String serviceId, @RequestBody(required = false) @ApiParam(value = "版本号,指localVersion,可以为空") String version) { - return executeVersionClear(serviceId, version, false); - } - - private ResponseEntity executeAuthenticate(UserEntity userEntity) { - try { - boolean result = authenticationResource.authenticate(userEntity); - - return ResponseEntity.ok().body(result); - } catch (Exception e) { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage()); - } - } - - private ResponseEntity getDiscoveryType() { - if (discoveryClient instanceof CompositeDiscoveryClient) { - CompositeDiscoveryClient compositeDiscoveryClient = (CompositeDiscoveryClient) discoveryClient; - List discoveryClients = compositeDiscoveryClient.getDiscoveryClients(); - for (DiscoveryClient client : discoveryClients) { - String discoveryDescription = client.description(); - for (int i = 0; i < DISCOVERY_TYPES.length; i++) { - String discoveryType = DISCOVERY_TYPES[i]; - if (discoveryDescription.toLowerCase().contains(discoveryType.toLowerCase())) { - return ResponseEntity.ok().body(discoveryType); - } - } - } - } else { - String discoveryDescription = discoveryClient.description(); - for (int i = 0; i < DISCOVERY_TYPES.length; i++) { - String discoveryType = DISCOVERY_TYPES[i]; - if (discoveryDescription.toLowerCase().contains(discoveryType.toLowerCase())) { - return ResponseEntity.ok().body(discoveryType); - } - } - } - - return ResponseEntity.ok().body(DiscoveryConstant.UNKNOWN); - } - - private ResponseEntity getConfigType() { - if (configAdapter != null) { - String configType = configAdapter.getConfigType(); - - return ResponseEntity.ok().body(configType); - } - - return ResponseEntity.ok().body(DiscoveryConstant.UNKNOWN); - } - - public List getGroups() { - List groups = new ArrayList(); - - List services = getServices(); - for (String service : services) { - List instanceEntityList = getInstanceList(service); - for (InstanceEntity instance : instanceEntityList) { - String plugin = InstanceEntityWrapper.getPlugin(instance); - String group = InstanceEntityWrapper.getGroup(instance); - if (StringUtils.isNotEmpty(plugin) && !groups.contains(group)) { - groups.add(group); - } - } - } - - return groups; - } - - public List getServices() { - return discoveryClient.getServices(); - } - - public List getInstances(String serviceId) { - return discoveryClient.getInstances(serviceId); - } - - public List getInstanceList(String service) { - List serviceInstances = getInstances(service); - List instanceEntityList = new ArrayList(serviceInstances.size()); - for (ServiceInstance serviceInstance : serviceInstances) { - Map metadata = serviceInstance.getMetadata(); - String serviceId = serviceInstance.getServiceId().toLowerCase(); - String serviceType = metadata.get(DiscoveryConstant.SPRING_APPLICATION_TYPE); - String version = metadata.get(DiscoveryConstant.VERSION); - String region = metadata.get(DiscoveryConstant.REGION); - String host = serviceInstance.getHost(); - int port = serviceInstance.getPort(); - - InstanceEntity instanceEntity = new InstanceEntity(); - instanceEntity.setServiceType(serviceType); - instanceEntity.setServiceId(serviceId); - instanceEntity.setVersion(version); - instanceEntity.setRegion(region); - instanceEntity.setHost(host); - instanceEntity.setPort(port); - instanceEntity.setMetadata(metadata); - - instanceEntityList.add(instanceEntity); - } - - return instanceEntityList; - } - - public Map> getInstanceMap(List groups) { - List services = getServices(); - Map> instanceMap = new LinkedHashMap>(services.size()); - for (String service : services) { - List instanceEntityList = getInstanceList(service); - if (CollectionUtils.isNotEmpty(groups)) { - for (InstanceEntity instance : instanceEntityList) { - String plugin = InstanceEntityWrapper.getPlugin(instance); - String group = InstanceEntityWrapper.getGroup(instance); - if (StringUtils.isNotEmpty(plugin) && groups.contains(group)) { - List instanceList = instanceMap.get(service); - if (instanceList == null) { - instanceList = new ArrayList(); - instanceMap.put(service, instanceList); - } - instanceList.add(instance); - } - } - } else { - instanceMap.put(service, instanceEntityList); - } - } - - return instanceMap; - } - - private ResponseEntity executeRemoteConfigUpdate(String group, String serviceId, String config) { - if (configAdapter == null) { - LOG.error("Remote config adapter isn't provided"); - - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Remote config adapter isn't provided"); - } - - try { - boolean result = configAdapter.updateConfig(group, serviceId, config); - - return ResponseEntity.ok().body(result ? DiscoveryConstant.OK : DiscoveryConstant.NO); - } catch (Exception e) { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage()); - } - } - - private ResponseEntity executeRemoteConfigClear(String group, String serviceId) { - if (configAdapter == null) { - LOG.error("Remote config adapter isn't provided"); - - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Remote config adapter isn't provided"); - } - - try { - boolean result = configAdapter.clearConfig(group, serviceId); - - return ResponseEntity.ok().body(result ? DiscoveryConstant.OK : DiscoveryConstant.NO); - } catch (Exception e) { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage()); - } - } - - private ResponseEntity executeRemoteConfigView(String group, String serviceId) { - if (configAdapter == null) { - LOG.error("Remote config adapter isn't provided"); - - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Remote config adapter isn't provided"); - } - - try { - String config = configAdapter.getConfig(group, serviceId); - - return ResponseEntity.ok().body(config); - } catch (Exception e) { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage()); - } - } - - private ResponseEntity executeConfigUpdate(String serviceId, String config, boolean async) { - List serviceInstances = getInstances(serviceId); - - ConfigUpdateRestInvoker configUpdateRestInvoker = new ConfigUpdateRestInvoker(serviceInstances, consoleRestTemplate, config, async); - - return configUpdateRestInvoker.invoke(); - } - - private ResponseEntity executeConfigClear(String serviceId, boolean async) { - List serviceInstances = getInstances(serviceId); - - ConfigClearRestInvoker configClearRestInvoker = new ConfigClearRestInvoker(serviceInstances, consoleRestTemplate, async); - - return configClearRestInvoker.invoke(); - } - - private ResponseEntity executeVersionUpdate(String serviceId, String version, boolean async) { - List serviceInstances = getInstances(serviceId); - - VersionUpdateRestInvoker versionUpdateRestInvoker = new VersionUpdateRestInvoker(serviceInstances, consoleRestTemplate, version, async); - - return versionUpdateRestInvoker.invoke(); - } - - private ResponseEntity executeVersionClear(String serviceId, String version, boolean async) { - List serviceInstances = getInstances(serviceId); - - VersionClearRestInvoker versionClearRestInvoker = new VersionClearRestInvoker(serviceInstances, consoleRestTemplate, version, async); - - return versionClearRestInvoker.invoke(); - } -} \ No newline at end of file diff --git a/discovery-console/src/main/java/com/nepxion/discovery/console/rest/AbstractRestInvoker.java b/discovery-console/src/main/java/com/nepxion/discovery/console/rest/AbstractRestInvoker.java deleted file mode 100644 index f040251720..0000000000 --- a/discovery-console/src/main/java/com/nepxion/discovery/console/rest/AbstractRestInvoker.java +++ /dev/null @@ -1,120 +0,0 @@ -package com.nepxion.discovery.console.rest; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import org.apache.commons.collections4.CollectionUtils; -import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.cloud.client.ServiceInstance; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.client.RestTemplate; - -import com.nepxion.discovery.common.constant.DiscoveryConstant; -import com.nepxion.discovery.common.entity.ResultEntity; -import com.nepxion.discovery.common.util.RestUtil; -import com.nepxion.discovery.common.util.UrlUtil; - -public abstract class AbstractRestInvoker { - private static final Logger LOG = LoggerFactory.getLogger(AbstractRestInvoker.class); - - protected List serviceInstances; - protected RestTemplate restTemplate; - protected boolean async; - - public AbstractRestInvoker(List serviceInstances, RestTemplate restTemplate, boolean async) { - this.serviceInstances = serviceInstances; - this.restTemplate = restTemplate; - this.async = async; - } - - public ResponseEntity invoke() { - if (CollectionUtils.isEmpty(serviceInstances)) { - LOG.warn("No service instances found"); - - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("No service instances found"); - } - - List resultEntityList = new ArrayList(); - for (ServiceInstance serviceInstance : serviceInstances) { - Map metadata = serviceInstance.getMetadata(); - String host = serviceInstance.getHost(); - int port = serviceInstance.getPort(); - String contextPath = metadata.get(DiscoveryConstant.SPRING_APPLICATION_CONTEXT_PATH); - String url = "http://" + host + ":" + port + UrlUtil.formatContextPath(contextPath) + getSuffixPath(); - - String result = null; - try { - checkPermission(serviceInstance); - - result = doRest(url); - if (!StringUtils.equals(result, DiscoveryConstant.OK)) { - result = RestUtil.getCause(restTemplate); - } - } catch (Exception e) { - result = e.getMessage(); - } - - ResultEntity resultEntity = new ResultEntity(); - resultEntity.setUrl(url); - resultEntity.setResult(result); - - resultEntityList.add(resultEntity); - } - - String info = getInfo(); - LOG.info(info + " results=\n{}", resultEntityList); - - return ResponseEntity.ok().body(resultEntityList); - } - - protected String getInvokeType() { - return async ? DiscoveryConstant.ASYNC : DiscoveryConstant.SYNC; - } - - protected void checkDiscoveryControlPermission(ServiceInstance serviceInstance) { - Map metadata = serviceInstance.getMetadata(); - - String discoveryControlEnabled = metadata.get(DiscoveryConstant.SPRING_APPLICATION_DISCOVERY_CONTROL_ENABLED); - if (StringUtils.isEmpty(discoveryControlEnabled)) { - throw new IllegalArgumentException("No metadata for key=" + DiscoveryConstant.SPRING_APPLICATION_DISCOVERY_CONTROL_ENABLED); - } - - if (!Boolean.valueOf(discoveryControlEnabled)) { - throw new IllegalArgumentException("Discovery control is disabled"); - } - } - - protected void checkConfigRestControlPermission(ServiceInstance serviceInstance) { - Map metadata = serviceInstance.getMetadata(); - - String configRestControlEnabled = metadata.get(DiscoveryConstant.SPRING_APPLICATION_CONFIG_REST_CONTROL_ENABLED); - if (StringUtils.isEmpty(configRestControlEnabled)) { - throw new IllegalArgumentException("No metadata for key=" + DiscoveryConstant.SPRING_APPLICATION_CONFIG_REST_CONTROL_ENABLED); - } - - if (!Boolean.valueOf(configRestControlEnabled)) { - throw new IllegalArgumentException("Config rest control is disabled"); - } - } - - protected abstract String getInfo(); - - protected abstract String getSuffixPath(); - - protected abstract String doRest(String url); - - protected abstract void checkPermission(ServiceInstance serviceInstance) throws Exception; -} \ No newline at end of file diff --git a/discovery-console/src/main/java/com/nepxion/discovery/console/rest/ConfigClearRestInvoker.java b/discovery-console/src/main/java/com/nepxion/discovery/console/rest/ConfigClearRestInvoker.java deleted file mode 100644 index a6d699c5a6..0000000000 --- a/discovery-console/src/main/java/com/nepxion/discovery/console/rest/ConfigClearRestInvoker.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.nepxion.discovery.console.rest; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import java.util.List; - -import org.springframework.cloud.client.ServiceInstance; -import org.springframework.web.client.RestTemplate; - -public class ConfigClearRestInvoker extends AbstractRestInvoker { - public ConfigClearRestInvoker(List serviceInstances, RestTemplate restTemplate, boolean async) { - super(serviceInstances, restTemplate, async); - } - - @Override - protected String getInfo() { - return "Config cleared"; - } - - @Override - protected String getSuffixPath() { - return "config/clear-" + getInvokeType(); - } - - @Override - protected String doRest(String url) { - return restTemplate.postForEntity(url, null, String.class).getBody(); - } - - @Override - protected void checkPermission(ServiceInstance serviceInstance) throws Exception { - checkDiscoveryControlPermission(serviceInstance); - checkConfigRestControlPermission(serviceInstance); - } -} \ No newline at end of file diff --git a/discovery-console/src/main/java/com/nepxion/discovery/console/rest/ConfigUpdateRestInvoker.java b/discovery-console/src/main/java/com/nepxion/discovery/console/rest/ConfigUpdateRestInvoker.java deleted file mode 100644 index 27ac220a5d..0000000000 --- a/discovery-console/src/main/java/com/nepxion/discovery/console/rest/ConfigUpdateRestInvoker.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.nepxion.discovery.console.rest; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import java.util.List; - -import org.springframework.cloud.client.ServiceInstance; -import org.springframework.http.HttpEntity; -import org.springframework.http.HttpHeaders; -import org.springframework.http.MediaType; -import org.springframework.web.client.RestTemplate; - -public class ConfigUpdateRestInvoker extends AbstractRestInvoker { - private String config; - - public ConfigUpdateRestInvoker(List serviceInstances, RestTemplate restTemplate, String config, boolean async) { - super(serviceInstances, restTemplate, async); - - this.config = config; - } - - @Override - protected String getInfo() { - return "Config updated"; - } - - @Override - protected String getSuffixPath() { - return "config/update-" + getInvokeType(); - } - - @Override - protected String doRest(String url) { - HttpHeaders headers = new HttpHeaders(); - headers.setContentType(MediaType.APPLICATION_JSON_UTF8); - - HttpEntity entity = new HttpEntity(config, headers); - - return restTemplate.postForEntity(url, entity, String.class).getBody(); - } - - @Override - protected void checkPermission(ServiceInstance serviceInstance) throws Exception { - checkDiscoveryControlPermission(serviceInstance); - checkConfigRestControlPermission(serviceInstance); - } -} \ No newline at end of file diff --git a/discovery-console/src/main/java/com/nepxion/discovery/console/rest/VersionClearRestInvoker.java b/discovery-console/src/main/java/com/nepxion/discovery/console/rest/VersionClearRestInvoker.java deleted file mode 100644 index bb4f01a218..0000000000 --- a/discovery-console/src/main/java/com/nepxion/discovery/console/rest/VersionClearRestInvoker.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.nepxion.discovery.console.rest; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import java.util.List; - -import org.springframework.cloud.client.ServiceInstance; -import org.springframework.web.client.RestTemplate; - -public class VersionClearRestInvoker extends AbstractRestInvoker { - private String version; - - public VersionClearRestInvoker(List serviceInstances, RestTemplate restTemplate, String version, boolean async) { - super(serviceInstances, restTemplate, async); - - this.version = version; - } - - @Override - protected String getInfo() { - return "Version cleared"; - } - - @Override - protected String getSuffixPath() { - return "version/clear-" + getInvokeType(); - } - - @Override - protected String doRest(String url) { - return restTemplate.postForEntity(url, version, String.class).getBody(); - } - - @Override - protected void checkPermission(ServiceInstance serviceInstance) throws Exception { - checkDiscoveryControlPermission(serviceInstance); - } -} \ No newline at end of file diff --git a/discovery-console/src/main/java/com/nepxion/discovery/console/rest/VersionUpdateRestInvoker.java b/discovery-console/src/main/java/com/nepxion/discovery/console/rest/VersionUpdateRestInvoker.java deleted file mode 100644 index 8c67ea4e0b..0000000000 --- a/discovery-console/src/main/java/com/nepxion/discovery/console/rest/VersionUpdateRestInvoker.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.nepxion.discovery.console.rest; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import java.util.List; - -import org.springframework.cloud.client.ServiceInstance; -import org.springframework.web.client.RestTemplate; - -public class VersionUpdateRestInvoker extends AbstractRestInvoker { - private String version; - - public VersionUpdateRestInvoker(List serviceInstances, RestTemplate restTemplate, String version, boolean async) { - super(serviceInstances, restTemplate, async); - - this.version = version; - } - - @Override - protected String getInfo() { - return "Version updated"; - } - - @Override - protected String getSuffixPath() { - return "version/update-" + getInvokeType(); - } - - @Override - protected String doRest(String url) { - return restTemplate.postForEntity(url, version, String.class).getBody(); - } - - @Override - protected void checkPermission(ServiceInstance serviceInstance) throws Exception { - checkDiscoveryControlPermission(serviceInstance); - } -} \ No newline at end of file diff --git a/discovery-console/src/main/resources/META-INF/spring.factories b/discovery-console/src/main/resources/META-INF/spring.factories deleted file mode 100644 index a377d4639b..0000000000 --- a/discovery-console/src/main/resources/META-INF/spring.factories +++ /dev/null @@ -1,5 +0,0 @@ -org.springframework.context.ApplicationContextInitializer=\ -com.nepxion.discovery.console.context.ConsoleApplicationContextInitializer - -org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ -com.nepxion.discovery.console.configuration.ConsoleAutoConfiguration \ No newline at end of file diff --git a/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/pom.xml b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/pom.xml new file mode 100644 index 0000000000..5ad3fd29b6 --- /dev/null +++ b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/pom.xml @@ -0,0 +1,62 @@ + + + discovery-plugin-admin-center-starter-swagger + Nepxion Discovery Plugin Admin Center Starter Swagger + jar + 4.0.0 + Nepxion Discovery is a solution for Spring Cloud with blue green, gray, weight, limitation, circuit breaker, degrade, isolation, monitor, tracing, dye, failover, async agent + http://www.nepxion.com + + + com.nepxion + discovery-plugin-admin-center + 6.23.0 + + + + + ${project.groupId} + discovery-plugin-strategy-starter-gateway + provided + + + + ${project.groupId} + discovery-plugin-strategy-starter-zuul + provided + + + + io.swagger + swagger-annotations + + + + io.swagger + swagger-models + + + + io.springfox + springfox-swagger2 + + + + io.springfox + springfox-swagger-ui + + + + com.alibaba.csp + sentinel-parameter-flow-control + provided + + + + com.alibaba.csp + sentinel-transport-simple-http + provided + + + \ No newline at end of file diff --git a/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/configuration/AdminAutoConfiguration.java b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/configuration/AdminAutoConfiguration.java new file mode 100644 index 0000000000..743676f6d4 --- /dev/null +++ b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/configuration/AdminAutoConfiguration.java @@ -0,0 +1,227 @@ +package com.nepxion.discovery.plugin.admincenter.configuration; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @author Ning Zhang + * @version 1.0 + */ + +import org.springframework.boot.autoconfigure.AutoConfigureOrder; +import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Import; +import org.springframework.core.Ordered; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +import com.alibaba.csp.sentinel.slots.block.flow.FlowRule; +import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowRule; +import com.nepxion.discovery.plugin.admincenter.constant.AdminConstant; +import com.nepxion.discovery.plugin.admincenter.endpoint.ConfigEndpoint; +import com.nepxion.discovery.plugin.admincenter.endpoint.GatewayStrategyRouteEndpoint; +import com.nepxion.discovery.plugin.admincenter.endpoint.GitEndpoint; +import com.nepxion.discovery.plugin.admincenter.endpoint.InspectorEndpoint; +import com.nepxion.discovery.plugin.admincenter.endpoint.RouterEndpoint; +import com.nepxion.discovery.plugin.admincenter.endpoint.SentinelCoreEndpoint; +import com.nepxion.discovery.plugin.admincenter.endpoint.SentinelParamEndpoint; +import com.nepxion.discovery.plugin.admincenter.endpoint.ServiceEndpoint; +import com.nepxion.discovery.plugin.admincenter.endpoint.StrategyEndpoint; +import com.nepxion.discovery.plugin.admincenter.endpoint.VersionEndpoint; +import com.nepxion.discovery.plugin.admincenter.endpoint.ZuulStrategyRouteEndpoint; +import com.nepxion.discovery.plugin.admincenter.resource.ConfigResource; +import com.nepxion.discovery.plugin.admincenter.resource.ConfigResourceImpl; +import com.nepxion.discovery.plugin.admincenter.resource.GatewayStrategyRouteResource; +import com.nepxion.discovery.plugin.admincenter.resource.GatewayStrategyRouteResourceImpl; +import com.nepxion.discovery.plugin.admincenter.resource.GitResource; +import com.nepxion.discovery.plugin.admincenter.resource.GitResourceImpl; +import com.nepxion.discovery.plugin.admincenter.resource.InspectorResource; +import com.nepxion.discovery.plugin.admincenter.resource.InspectorResourceImpl; +import com.nepxion.discovery.plugin.admincenter.resource.RouterResource; +import com.nepxion.discovery.plugin.admincenter.resource.RouterResourceImpl; +import com.nepxion.discovery.plugin.admincenter.resource.SentinelCoreResource; +import com.nepxion.discovery.plugin.admincenter.resource.SentinelCoreResourceImpl; +import com.nepxion.discovery.plugin.admincenter.resource.SentinelParamResource; +import com.nepxion.discovery.plugin.admincenter.resource.SentinelParamResourceImpl; +import com.nepxion.discovery.plugin.admincenter.resource.ServiceResource; +import com.nepxion.discovery.plugin.admincenter.resource.ServiceResourceImpl; +import com.nepxion.discovery.plugin.admincenter.resource.StrategyResource; +import com.nepxion.discovery.plugin.admincenter.resource.StrategyResourceImpl; +import com.nepxion.discovery.plugin.admincenter.resource.VersionResource; +import com.nepxion.discovery.plugin.admincenter.resource.VersionResourceImpl; +import com.nepxion.discovery.plugin.admincenter.resource.ZuulStrategyRouteResource; +import com.nepxion.discovery.plugin.admincenter.resource.ZuulStrategyRouteResourceImpl; +import com.nepxion.discovery.plugin.framework.generator.GitGenerator; +import com.nepxion.discovery.plugin.strategy.gateway.route.GatewayStrategyRoute; +import com.nepxion.discovery.plugin.strategy.wrapper.StrategyWrapper; +import com.nepxion.discovery.plugin.strategy.zuul.route.ZuulStrategyRoute; + +@Configuration +@Import(SwaggerConfiguration.class) +@AutoConfigureOrder(Ordered.LOWEST_PRECEDENCE) +public class AdminAutoConfiguration { + @ConditionalOnProperty(value = AdminConstant.SPRING_APPLICATION_ADMIN_SERVICE_ENDPOINT_ENABLED, matchIfMissing = true) + protected static class ServiceEndpointConfiguration { + @Bean + public ServiceResource serviceResource() { + return new ServiceResourceImpl(); + } + + @Bean + public ServiceEndpoint serviceEndpoint() { + return new ServiceEndpoint(); + } + } + + @ConditionalOnProperty(value = AdminConstant.SPRING_APPLICATION_ADMIN_CONFIG_ENDPOINT_ENABLED, matchIfMissing = true) + protected static class ConfigEndpointConfiguration { + @Bean + public ConfigResource configResource() { + return new ConfigResourceImpl(); + } + + @Bean + public ConfigEndpoint configEndpoint() { + return new ConfigEndpoint(); + } + } + + @ConditionalOnProperty(value = AdminConstant.SPRING_APPLICATION_ADMIN_VERSION_ENDPOINT_ENABLED, matchIfMissing = true) + protected static class VersionEndpointConfiguration { + @Bean + public VersionResource versionResource() { + return new VersionResourceImpl(); + } + + @Bean + public VersionEndpoint versionEndpoint() { + return new VersionEndpoint(); + } + } + + @ConditionalOnProperty(value = AdminConstant.SPRING_APPLICATION_ADMIN_INSPECTOR_ENDPOINT_ENABLED, matchIfMissing = true) + protected static class InspectorEndpointConfiguration { + @Bean + public InspectorResource inspectorResource() { + return new InspectorResourceImpl(); + } + + @Bean + public InspectorEndpoint inspectorEndpoint() { + return new InspectorEndpoint(); + } + } + + @ConditionalOnProperty(value = AdminConstant.SPRING_APPLICATION_ADMIN_ROUTER_ENDPOINT_ENABLED, matchIfMissing = true) + protected static class RouterEndpointConfiguration { + @Bean + public RouterResource routerResource() { + return new RouterResourceImpl(); + } + + @Bean + public RouterEndpoint routerEndpoint() { + return new RouterEndpoint(); + } + } + + @ConditionalOnClass(StrategyWrapper.class) + @ConditionalOnProperty(value = AdminConstant.SPRING_APPLICATION_ADMIN_STRATEGY_ENDPOINT_ENABLED, matchIfMissing = true) + protected static class StrategyEndpointConfiguration { + @Bean + public StrategyResource strategyResource() { + return new StrategyResourceImpl(); + } + + @Bean + public StrategyEndpoint strategyEndpoint() { + return new StrategyEndpoint(); + } + } + + @ConditionalOnClass(FlowRule.class) + @ConditionalOnProperty(value = AdminConstant.SPRING_APPLICATION_ADMIN_SENTINEL_ENDPOINT_ENABLED, matchIfMissing = true) + protected static class SentinelCoreEndpointConfiguration { + @Bean + public SentinelCoreResource sentinelCoreResource() { + return new SentinelCoreResourceImpl(); + } + + @Bean + public SentinelCoreEndpoint sentinelCoreEndpoint() { + return new SentinelCoreEndpoint(); + } + } + + @ConditionalOnClass(ParamFlowRule.class) + @ConditionalOnProperty(value = AdminConstant.SPRING_APPLICATION_ADMIN_SENTINEL_ENDPOINT_ENABLED, matchIfMissing = true) + protected static class SentinelParamEndpointConfiguration { + @Bean + public SentinelParamResource sentinelParamResource() { + return new SentinelParamResourceImpl(); + } + + @Bean + public SentinelParamEndpoint sentinelParamEndpoint() { + return new SentinelParamEndpoint(); + } + } + + @ConditionalOnBean(GitGenerator.class) + @ConditionalOnProperty(value = AdminConstant.SPRING_APPLICATION_ADMIN_GIT_ENDPOINT_ENABLED, matchIfMissing = true) + protected static class GitEndpointConfiguration { + @Bean + public GitResource gitResource() { + return new GitResourceImpl(); + } + + @Bean + public GitEndpoint gitEndpoint() { + return new GitEndpoint(); + } + } + + @ConditionalOnBean(GatewayStrategyRoute.class) + @ConditionalOnProperty(value = AdminConstant.SPRING_APPLICATION_ADMIN_GATEWAY_ENDPOINT_ENABLED, matchIfMissing = true) + protected static class GatewayStrategyRouteEndpointConfiguration { + @Bean + @ConditionalOnProperty(value = "spring.cloud.gateway.discovery.locator.enabled", havingValue = "false", matchIfMissing = true) + public GatewayStrategyRouteResource gatewayStrategyRouteResource() { + return new GatewayStrategyRouteResourceImpl(); + } + + @Bean + @ConditionalOnProperty(value = "spring.cloud.gateway.discovery.locator.enabled", havingValue = "false", matchIfMissing = true) + public GatewayStrategyRouteEndpoint gatewayStrategyRouteEndpoint() { + return new GatewayStrategyRouteEndpoint(); + } + } + + @ConditionalOnBean(ZuulStrategyRoute.class) + @ConditionalOnProperty(value = AdminConstant.SPRING_APPLICATION_ADMIN_ZUUL_ENDPOINT_ENABLED, matchIfMissing = true) + protected static class ZuulStrategyRouteEndpointConfiguration { + @Bean + public ZuulStrategyRouteResource zuulStrategyRouteResource() { + return new ZuulStrategyRouteResourceImpl(); + } + + @Bean + public ZuulStrategyRouteEndpoint zuulStrategyRouteEndpoint() { + return new ZuulStrategyRouteEndpoint(); + } + } + + @ConditionalOnClass(WebMvcConfigurer.class) + protected static class WebMvcActivationConfiguration { + @Bean + @ConditionalOnProperty(value = "cors.registry.enabled", matchIfMissing = false) + public CorsRegistryConfiguration corsRegistryConfiguration() { + return new CorsRegistryConfiguration(); + } + } +} \ No newline at end of file diff --git a/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/configuration/CorsRegistryConfiguration.java b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/configuration/CorsRegistryConfiguration.java new file mode 100644 index 0000000000..38812aa683 --- /dev/null +++ b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/configuration/CorsRegistryConfiguration.java @@ -0,0 +1,30 @@ +package com.nepxion.discovery.plugin.admincenter.configuration; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.CorsRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +@Configuration +@ConditionalOnClass(WebMvcConfigurer.class) +@ConditionalOnProperty(value = "cors.registry.enabled", matchIfMissing = false) +public class CorsRegistryConfiguration implements WebMvcConfigurer { + // 解决跨域问题 + @Override + public void addCorsMappings(CorsRegistry registry) { + registry.addMapping("/**") + .allowedHeaders("*") + .allowedMethods("*") + .allowedOrigins("*"); + } +} \ No newline at end of file diff --git a/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/configuration/SwaggerConfiguration.java b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/configuration/SwaggerConfiguration.java new file mode 100644 index 0000000000..377d94e283 --- /dev/null +++ b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/configuration/SwaggerConfiguration.java @@ -0,0 +1,191 @@ +package com.nepxion.discovery.plugin.admincenter.configuration; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import springfox.documentation.RequestHandler; +import springfox.documentation.builders.ApiInfoBuilder; +import springfox.documentation.builders.PathSelectors; +import springfox.documentation.service.ApiInfo; +import springfox.documentation.service.Contact; +import springfox.documentation.service.Parameter; +import springfox.documentation.service.SecurityScheme; +import springfox.documentation.spi.DocumentationType; +import springfox.documentation.spi.service.contexts.SecurityContext; +import springfox.documentation.spring.web.plugins.Docket; +import springfox.documentation.swagger2.annotations.EnableSwagger2; + +import java.util.Collections; +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.HandlerMapping; + +import com.google.common.base.Function; +import com.google.common.base.Optional; +import com.google.common.base.Predicate; +import com.nepxion.discovery.common.constant.DiscoveryConstant; +import com.nepxion.discovery.common.constant.DiscoverySwaggerConstant; + +@Configuration +@EnableSwagger2 +@ConditionalOnClass(HandlerMapping.class) +@ConditionalOnProperty(value = DiscoverySwaggerConstant.SWAGGER_ENABLED, matchIfMissing = true) +public class SwaggerConfiguration { + private String discoveryGroup = DiscoverySwaggerConstant.SWAGGER_DEFAULT_GROUP_VALUE; + private String discoveryPackages = "com.nepxion.discovery.plugin.admincenter.endpoint"; + private String discoveryDescription = "Admin Center Restful APIs"; + private String discoveryVersion = DiscoverySwaggerConstant.SWAGGER_DEFAULT_VERSION_VALUE; + private String discoveryLicenseName = DiscoverySwaggerConstant.SWAGGER_DEFAULT_LICENSE_NAME_VALUE; + private String discoveryLicenseUrl = DiscoverySwaggerConstant.SWAGGER_DEFAULT_LICENSE_URL_VALUE; + private String discoveryContactName = DiscoverySwaggerConstant.SWAGGER_DEFAULT_CONTACT_NAME_VALUE; + private String discoveryContactUrl = DiscoverySwaggerConstant.SWAGGER_DEFAULT_CONTACT_URL_VALUE; + private String discoveryContactEmail = DiscoverySwaggerConstant.SWAGGER_DEFAULT_CONTACT_EMAIL_VALUE; + private String discoveryTermsOfServiceUrl = DiscoverySwaggerConstant.SWAGGER_DEFAULT_TERMSOFSERVICE_URL_VALUE; + + @Value("${" + DiscoverySwaggerConstant.SWAGGER_SERVICE_GROUP + ":}") + private String serviceGroup; + + @Value("${" + DiscoverySwaggerConstant.SWAGGER_SERVICE_PACKAGES + ":}") + private String servicePackages; + + @Value("${" + DiscoverySwaggerConstant.SWAGGER_SERVICE_DESCRIPTION + ":}") + private String serviceDescription; + + @Value("${" + DiscoverySwaggerConstant.SWAGGER_SERVICE_VERSION + ":}") + private String serviceVersion; + + @Value("${" + DiscoverySwaggerConstant.SWAGGER_SERVICE_LICENSE_NAME + ":" + DiscoverySwaggerConstant.SWAGGER_DEFAULT_LICENSE_NAME_VALUE + "}") + private String serviceLicenseName; + + @Value("${" + DiscoverySwaggerConstant.SWAGGER_SERVICE_LICENSE_URL + ":" + DiscoverySwaggerConstant.SWAGGER_DEFAULT_LICENSE_URL_VALUE + "}") + private String serviceLicenseUrl; + + @Value("${" + DiscoverySwaggerConstant.SWAGGER_SERVICE_CONTACT_NAME + ":" + DiscoverySwaggerConstant.SWAGGER_DEFAULT_CONTACT_NAME_VALUE + "}") + private String serviceContactName; + + @Value("${" + DiscoverySwaggerConstant.SWAGGER_SERVICE_CONTACT_URL + ":" + DiscoverySwaggerConstant.SWAGGER_DEFAULT_CONTACT_URL_VALUE + "}") + private String serviceContactUrl; + + @Value("${" + DiscoverySwaggerConstant.SWAGGER_SERVICE_CONTACT_EMAIL + ":" + DiscoverySwaggerConstant.SWAGGER_DEFAULT_CONTACT_EMAIL_VALUE + "}") + private String serviceContactEmail; + + @Value("${" + DiscoverySwaggerConstant.SWAGGER_SERVICE_TERMSOFSERVICE_URL + ":" + DiscoverySwaggerConstant.SWAGGER_DEFAULT_TERMSOFSERVICE_URL_VALUE + "}") + private String serviceTermsOfServiceUrl; + + @Value("${" + DiscoveryConstant.SPRING_APPLICATION_NAME + "}") + private String serviceName; + + @Autowired(required = false) + private List swaggerHeaderParameters; + + @Autowired(required = false) + private List swaggerSecuritySchemes; + + @Autowired(required = false) + private List swaggerSecurityContexts; + + @Bean("discoveryDocket") + public Docket discoveryDocket() { + return new Docket(DocumentationType.SWAGGER_2) + .groupName(discoveryGroup) + .apiInfo(apiInfo(discoveryDescription, + discoveryVersion, + discoveryLicenseName, + discoveryLicenseUrl, + discoveryContactName, + discoveryContactUrl, + discoveryContactEmail, + discoveryTermsOfServiceUrl)) + .select() + .apis(SwaggerConfiguration.basePackage(discoveryPackages)) // 扫描该包下的所有需要在Swagger中展示的API,@ApiIgnore注解标注的除外 + .paths(PathSelectors.any()) + .build() + .globalOperationParameters(swaggerHeaderParameters) + .securitySchemes(swaggerSecuritySchemes) + .securityContexts(swaggerSecurityContexts != null ? swaggerSecurityContexts : Collections.emptyList()); + } + + @Bean("serviceDocket") + @ConditionalOnProperty(name = DiscoverySwaggerConstant.SWAGGER_SERVICE_GROUP) + public Docket serviceDocket() { + return new Docket(DocumentationType.SWAGGER_2) + .groupName(serviceGroup) + .apiInfo(apiInfo(serviceDescription, + serviceVersion, + serviceLicenseName, + serviceLicenseUrl, + serviceContactName, + serviceContactUrl, + serviceContactEmail, + serviceTermsOfServiceUrl)) + .select() + .apis(SwaggerConfiguration.basePackage(servicePackages)) // 扫描该包下的所有需要在Swagger中展示的API,@ApiIgnore注解标注的除外 + .paths(PathSelectors.any()) + .build() + .globalOperationParameters(swaggerHeaderParameters) + .securitySchemes(swaggerSecuritySchemes) + .securityContexts(swaggerSecurityContexts != null ? swaggerSecurityContexts : Collections.emptyList()); + } + + private ApiInfo apiInfo(String description, + String version, + String licenseName, + String licenseUrl, + String contactName, + String contactUrl, + String contactEmail, + String termsOfServiceUrl) { + return new ApiInfoBuilder() + .title(serviceName) + .description(description) + .version(version) + .license(licenseName) + .licenseUrl(licenseUrl) + .contact(new Contact(contactName, contactUrl, contactEmail)) + .termsOfServiceUrl(termsOfServiceUrl) + .build(); + } + + public static Predicate basePackage(String basePackage) { + return new Predicate() { + @Override + public boolean apply(RequestHandler input) { + return declaringClass(input).transform(handlerPackage(basePackage)).or(true); + } + }; + } + + private static Function, Boolean> handlerPackage(String basePackage) { + return new Function, Boolean>() { + @Override + public Boolean apply(Class input) { + String[] subPackages = basePackage.split(DiscoveryConstant.SEPARATE); + for (String subPackage : subPackages) { + boolean matched = input.getPackage().getName().startsWith(subPackage.trim()); + if (matched) { + return true; + } + } + + return false; + } + }; + } + + @SuppressWarnings("deprecation") + private static Optional> declaringClass(RequestHandler input) { + return Optional.fromNullable(input.declaringClass()); + } +} \ No newline at end of file diff --git a/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/constant/AdminConstant.java b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/constant/AdminConstant.java new file mode 100644 index 0000000000..4141c991c8 --- /dev/null +++ b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/constant/AdminConstant.java @@ -0,0 +1,25 @@ +package com.nepxion.discovery.plugin.admincenter.constant; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +public class AdminConstant { + public static final String SPRING_APPLICATION_ADMIN_SERVICE_ENDPOINT_ENABLED = "spring.application.admin.service.endpoint.enabled"; + public static final String SPRING_APPLICATION_ADMIN_CONFIG_ENDPOINT_ENABLED = "spring.application.admin.config.endpoint.enabled"; + public static final String SPRING_APPLICATION_ADMIN_VERSION_ENDPOINT_ENABLED = "spring.application.admin.version.endpoint.enabled"; + public static final String SPRING_APPLICATION_ADMIN_INSPECTOR_ENDPOINT_ENABLED = "spring.application.admin.inspector.endpoint.enabled"; + public static final String SPRING_APPLICATION_ADMIN_ROUTER_ENDPOINT_ENABLED = "spring.application.admin.router.endpoint.enabled"; + public static final String SPRING_APPLICATION_ADMIN_STRATEGY_ENDPOINT_ENABLED = "spring.application.admin.strategy.endpoint.enabled"; + public static final String SPRING_APPLICATION_ADMIN_SENTINEL_ENDPOINT_ENABLED = "spring.application.admin.sentinel.endpoint.enabled"; + public static final String SPRING_APPLICATION_ADMIN_GIT_ENDPOINT_ENABLED = "spring.application.admin.git.endpoint.enabled"; + public static final String SPRING_APPLICATION_ADMIN_GATEWAY_ENDPOINT_ENABLED = "spring.application.admin.gateway.endpoint.enabled"; + public static final String SPRING_APPLICATION_ADMIN_ZUUL_ENDPOINT_ENABLED = "spring.application.admin.zuul.endpoint.enabled"; + + public static final String SPRING_APPLICATION_ADMIN_STRATEGY_ENDPOINT_VALIDATE_EXPRESSION_ENABLED = "spring.application.admin.strategy.endpoint.validate-expression.enabled"; +} \ No newline at end of file diff --git a/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/endpoint/ConfigEndpoint.java b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/endpoint/ConfigEndpoint.java new file mode 100644 index 0000000000..25230cc8ed --- /dev/null +++ b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/endpoint/ConfigEndpoint.java @@ -0,0 +1,117 @@ +package com.nepxion.discovery.plugin.admincenter.endpoint; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; + +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.RestController; + +import com.nepxion.discovery.common.util.ResponseUtil; +import com.nepxion.discovery.plugin.admincenter.resource.ConfigResource; + +@RestController +@RequestMapping(path = "/config") +@Api(tags = { "配置接口" }) +public class ConfigEndpoint { + @Autowired + private ConfigResource configResource; + + @RequestMapping(path = "/config-type", method = RequestMethod.GET) + @ApiOperation(value = "获取配置中心类型", notes = "", response = ResponseEntity.class, httpMethod = "GET") + @ResponseBody + public ResponseEntity configType() { + return doConfigType(); + } + + @RequestMapping(path = "/update-async", method = RequestMethod.POST) + @ApiOperation(value = "异步更新规则配置", notes = "", response = ResponseEntity.class, httpMethod = "POST") + @ResponseBody + public ResponseEntity updateAsync(@RequestBody @ApiParam(value = "规则配置内容", required = true) String config) { + return doUpdate(config, true); + } + + @RequestMapping(path = "/update-sync", method = RequestMethod.POST) + @ApiOperation(value = "同步更新规则配置", notes = "", response = ResponseEntity.class, httpMethod = "POST") + @ResponseBody + public ResponseEntity updateSync(@RequestBody @ApiParam(value = "规则配置内容", required = true) String config) { + return doUpdate(config, false); + } + + @RequestMapping(path = "/clear-async", method = RequestMethod.POST) + @ApiOperation(value = "异步清除规则配置", notes = "", response = ResponseEntity.class, httpMethod = "POST") + @ResponseBody + public ResponseEntity clearAsync() { + return doClear(true); + } + + @RequestMapping(path = "/clear-sync", method = RequestMethod.POST) + @ApiOperation(value = "同步清除规则配置", notes = "", response = ResponseEntity.class, httpMethod = "POST") + @ResponseBody + public ResponseEntity clearSync() { + return doClear(false); + } + + @RequestMapping(path = "/view", method = RequestMethod.GET) + @ApiOperation(value = "查看本地和更新的规则配置", notes = "", response = ResponseEntity.class, httpMethod = "GET") + @ResponseBody + public ResponseEntity view() { + return doView(); + } + + private ResponseEntity doConfigType() { + try { + String configType = configResource.getConfigType().toString(); + + return ResponseUtil.getSuccessResponse(configType); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doUpdate(String config, boolean async) { + try { + configResource.update(config, async); + + return ResponseUtil.getSuccessResponse(true); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doClear(boolean async) { + try { + configResource.clear(async); + + return ResponseUtil.getSuccessResponse(true); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doView() { + try { + List ruleList = configResource.view(); + + return ResponseUtil.getSuccessResponse(ruleList); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } +} \ No newline at end of file diff --git a/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/endpoint/GatewayStrategyRouteEndpoint.java b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/endpoint/GatewayStrategyRouteEndpoint.java new file mode 100644 index 0000000000..9e71d81663 --- /dev/null +++ b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/endpoint/GatewayStrategyRouteEndpoint.java @@ -0,0 +1,140 @@ +package com.nepxion.discovery.plugin.admincenter.endpoint; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Ning Zhang + * @author Haojun Ren + * @version 1.0 + */ + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; + +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.RestController; + +import com.nepxion.discovery.common.entity.GatewayStrategyRouteEntity; +import com.nepxion.discovery.common.util.ResponseUtil; +import com.nepxion.discovery.plugin.admincenter.resource.GatewayStrategyRouteResource; + +@RestController +@RequestMapping(path = "/spring-cloud-gateway-route") +@Api(tags = { "网关动态路由接口" }) +public class GatewayStrategyRouteEndpoint { + @Autowired + private GatewayStrategyRouteResource gatewayStrategyRouteResource; + + @RequestMapping(path = "/add", method = RequestMethod.POST) + @ApiOperation(value = "增加网关路由", notes = "", response = ResponseEntity.class, httpMethod = "POST") + @ResponseBody + public ResponseEntity add(@RequestBody @ApiParam(value = "网关路由对象", required = true) GatewayStrategyRouteEntity gatewayStrategyRouteEntity) { + return doAdd(gatewayStrategyRouteEntity); + } + + @RequestMapping(path = "/modify", method = RequestMethod.POST) + @ApiOperation(value = "修改网关路由", notes = "", response = ResponseEntity.class, httpMethod = "POST") + @ResponseBody + public ResponseEntity modify(@RequestBody @ApiParam(value = "网关路由对象", required = true) GatewayStrategyRouteEntity gatewayStrategyRouteEntity) { + return doModify(gatewayStrategyRouteEntity); + } + + @RequestMapping(path = "/delete/{routeId}", method = RequestMethod.DELETE) + @ApiOperation(value = "删除网关路由", notes = "", response = ResponseEntity.class, httpMethod = "DELETE") + @ResponseBody + public ResponseEntity delete(@PathVariable(value = "routeId") @ApiParam(value = "路由Id", required = true) String routeId) { + return doDelete(routeId); + } + + @RequestMapping(path = "/update-all", method = RequestMethod.POST) + @ApiOperation(value = "更新全部网关路由", notes = "", response = ResponseEntity.class, httpMethod = "POST") + @ResponseBody + public ResponseEntity updateAll(@RequestBody @ApiParam(value = "网关路由对象列表", required = true) List gatewayStrategyRouteEntityList) { + return doUpdateAll(gatewayStrategyRouteEntityList); + } + + @RequestMapping(path = "/view/{routeId}", method = RequestMethod.GET) + @ApiOperation(value = "根据路由Id查看网关路由", notes = "", response = ResponseEntity.class, httpMethod = "GET") + @ResponseBody + public ResponseEntity view(@PathVariable(value = "routeId") @ApiParam(value = "路由Id", required = true) String routeId) { + return doView(routeId); + } + + @RequestMapping(path = "/view-all", method = RequestMethod.GET) + @ApiOperation(value = "查看全部网关路由", notes = "", response = ResponseEntity.class, httpMethod = "GET") + @ResponseBody + public ResponseEntity viewAll() { + return doViewAll(); + } + + private ResponseEntity doAdd(GatewayStrategyRouteEntity gatewayStrategyRouteEntity) { + try { + gatewayStrategyRouteResource.add(gatewayStrategyRouteEntity); + + return ResponseUtil.getSuccessResponse(true); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doModify(GatewayStrategyRouteEntity gatewayStrategyRouteEntity) { + try { + gatewayStrategyRouteResource.modify(gatewayStrategyRouteEntity); + + return ResponseUtil.getSuccessResponse(true); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doDelete(String routeId) { + try { + gatewayStrategyRouteResource.delete(routeId); + + return ResponseUtil.getSuccessResponse(true); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doUpdateAll(List gatewayStrategyRouteEntityList) { + try { + gatewayStrategyRouteResource.updateAll(gatewayStrategyRouteEntityList); + + return ResponseUtil.getSuccessResponse(true); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doView(String routeId) { + try { + GatewayStrategyRouteEntity gatewayStrategyRouteEntity = gatewayStrategyRouteResource.view(routeId); + + return ResponseUtil.getSuccessResponse(gatewayStrategyRouteEntity); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doViewAll() { + try { + List gatewayStrategyRouteEntityList = gatewayStrategyRouteResource.viewAll(); + + return ResponseUtil.getSuccessResponse(gatewayStrategyRouteEntityList); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } +} \ No newline at end of file diff --git a/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/endpoint/GitEndpoint.java b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/endpoint/GitEndpoint.java new file mode 100644 index 0000000000..b18aa53046 --- /dev/null +++ b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/endpoint/GitEndpoint.java @@ -0,0 +1,67 @@ +package com.nepxion.discovery.plugin.admincenter.endpoint; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; + +import java.util.Map; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.RestController; + +import com.nepxion.discovery.common.util.ResponseUtil; +import com.nepxion.discovery.plugin.admincenter.resource.GitResource; + +@RestController +@RequestMapping(path = "/git") +@Api(tags = { "Git信息接口" }) +public class GitEndpoint { + @Autowired + private GitResource gitResource; + + @RequestMapping(path = "/map", method = RequestMethod.GET) + @ApiOperation(value = "获取Git信息的Map格式", notes = "", response = ResponseEntity.class, httpMethod = "GET") + @ResponseBody + public ResponseEntity map() { + return doMap(); + } + + @RequestMapping(path = "/text", method = RequestMethod.GET) + @ApiOperation(value = "获取Git信息的文本格式", notes = "", response = ResponseEntity.class, httpMethod = "GET") + @ResponseBody + public ResponseEntity text() { + return doText(); + } + + private ResponseEntity doMap() { + try { + Map map = gitResource.map(); + + return ResponseUtil.getSuccessResponse(map); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doText() { + try { + String text = gitResource.text(); + + return ResponseUtil.getSuccessResponse(text); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } +} \ No newline at end of file diff --git a/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/endpoint/InspectorEndpoint.java b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/endpoint/InspectorEndpoint.java new file mode 100644 index 0000000000..ae7662c04d --- /dev/null +++ b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/endpoint/InspectorEndpoint.java @@ -0,0 +1,70 @@ +package com.nepxion.discovery.plugin.admincenter.endpoint; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; + +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.RestController; + +import com.nepxion.discovery.common.entity.InspectorEntity; +import com.nepxion.discovery.common.util.ResponseUtil; +import com.nepxion.discovery.plugin.admincenter.resource.InspectorResource; + +@RestController +@RequestMapping(path = "/inspector") +@Api(tags = { "侦测接口" }) +public class InspectorEndpoint { + @Autowired + private InspectorResource inspectorResource; + + @RequestMapping(path = "/inspect", method = RequestMethod.POST) + @ApiOperation(value = "侦测全链路路由", notes = "", response = ResponseEntity.class, httpMethod = "POST") + @ResponseBody + public ResponseEntity inspect(@RequestBody @ApiParam(value = "侦测对象", required = true) InspectorEntity inspectorEntity) { + return doInspect(inspectorEntity); + } + + @RequestMapping(path = "/inspect-service", method = RequestMethod.POST) + @ApiOperation(value = "侦测全链路路由", notes = "", response = ResponseEntity.class, httpMethod = "POST") + @ResponseBody + public ResponseEntity inspect(@RequestBody @ApiParam(value = "侦测服务列表", required = true) List service) { + return doInspect(service); + } + + private ResponseEntity doInspect(InspectorEntity inspectorEntity) { + try { + InspectorEntity result = inspectorResource.inspect(inspectorEntity); + + return ResponseUtil.getSuccessResponse(result); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doInspect(List service) { + try { + String result = inspectorResource.inspect(service); + + return ResponseUtil.getSuccessResponse(result); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } +} \ No newline at end of file diff --git a/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/endpoint/RouterEndpoint.java b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/endpoint/RouterEndpoint.java new file mode 100644 index 0000000000..cd6e915d4e --- /dev/null +++ b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/endpoint/RouterEndpoint.java @@ -0,0 +1,105 @@ +package com.nepxion.discovery.plugin.admincenter.endpoint; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; + +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.RestController; + +import com.nepxion.discovery.common.entity.RouterEntity; +import com.nepxion.discovery.common.util.ResponseUtil; +import com.nepxion.discovery.plugin.admincenter.resource.RouterResource; + +@RestController +@RequestMapping(path = "/router") +@Api(tags = { "路由接口" }) +public class RouterEndpoint { + @Autowired + private RouterResource routerResource; + + @RequestMapping(path = "/info", method = RequestMethod.GET) + @ApiOperation(value = "获取本地节点信息", notes = "获取当前节点的简单信息", response = ResponseEntity.class, httpMethod = "GET") + @ResponseBody + public ResponseEntity info() { + return doInfo(); + } + + @RequestMapping(path = "/route/{routeServiceId}", method = RequestMethod.GET) + @ApiOperation(value = "获取本地节点可访问其他节点的路由信息列表", notes = "", response = ResponseEntity.class, httpMethod = "GET") + @ResponseBody + public ResponseEntity route(@PathVariable(value = "routeServiceId") @ApiParam(value = "目标服务名", required = true) String routeServiceId) { + return doNativeRoute(routeServiceId); + } + + @RequestMapping(path = "/route/{routeServiceId}/{routeProtocol}/{routeHost}/{routePort}/{routeContextPath}", method = RequestMethod.GET) + @ApiOperation(value = "获取指定节点可访问其他节点的路由信息列表", notes = "", response = ResponseEntity.class, httpMethod = "GET") + @ResponseBody + public ResponseEntity route(@PathVariable(value = "routeServiceId") @ApiParam(value = "目标服务名", required = true) String routeServiceId, @PathVariable(value = "routeProtocol") @ApiParam(value = "目标服务采用的协议。取值: http | https", defaultValue = "http", required = true) String routeProtocol, @PathVariable(value = "routeHost") @ApiParam(value = "目标服务所在机器的IP地址", required = true) String routeHost, @PathVariable(value = "routePort") @ApiParam(value = "目标服务所在机器的端口号", required = true) int routePort, @PathVariable(value = "routeContextPath") @ApiParam(value = "目标服务的调用路径前缀", defaultValue = "/", required = true) String routeContextPath) { + return doRemoteRoute(routeServiceId, routeProtocol, routeHost, routePort, routeContextPath); + } + + @RequestMapping(path = "/routes", method = RequestMethod.POST) + @ApiOperation(value = "获取全路径的路由信息树", notes = "参数按调用服务名的前后次序排列,起始节点的服务名不能加上去。如果多个用“;”分隔,不允许出现空格", response = ResponseEntity.class, httpMethod = "POST") + @ResponseBody + public ResponseEntity routes(@RequestBody @ApiParam(value = "格式示例:service-a;service-b", required = true) String routeServiceIds) { + return doRoutes(routeServiceIds); + } + + private ResponseEntity doInfo() { + try { + RouterEntity routerEntity = routerResource.getRouterEntity(); + + return ResponseUtil.getSuccessResponse(routerEntity); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doNativeRoute(String routeServiceId) { + try { + List routerEntityList = routerResource.getRouterEntityList(routeServiceId); + + return ResponseUtil.getSuccessResponse(routerEntityList); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doRemoteRoute(String routeServiceId, String routeProtocol, String routeHost, int routePort, String routeContextPath) { + try { + List routerEntityList = routerResource.getRouterEntityList(routeServiceId, routeProtocol, routeHost, routePort, routeContextPath); + + return ResponseUtil.getSuccessResponse(routerEntityList); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doRoutes(String routeServiceIds) { + try { + RouterEntity routerEntity = routerResource.routeTree(routeServiceIds); + + return ResponseUtil.getSuccessResponse(routerEntity); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } +} \ No newline at end of file diff --git a/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/endpoint/SentinelCoreEndpoint.java b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/endpoint/SentinelCoreEndpoint.java new file mode 100644 index 0000000000..b7a84bdf8c --- /dev/null +++ b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/endpoint/SentinelCoreEndpoint.java @@ -0,0 +1,243 @@ +package com.nepxion.discovery.plugin.admincenter.endpoint; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; + +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.RestController; + +import com.alibaba.csp.sentinel.slots.block.authority.AuthorityRule; +import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule; +import com.alibaba.csp.sentinel.slots.block.flow.FlowRule; +import com.alibaba.csp.sentinel.slots.system.SystemRule; +import com.nepxion.discovery.common.util.ResponseUtil; +import com.nepxion.discovery.plugin.admincenter.resource.SentinelCoreResource; + +@RestController +@RequestMapping(path = "/sentinel-core") +@Api(tags = { "哨兵核心接口" }) +public class SentinelCoreEndpoint { + @Autowired + private SentinelCoreResource sentinelCoreResource; + + @RequestMapping(path = "/update-flow-rules", method = RequestMethod.POST) + @ApiOperation(value = "更新流控规则列表", notes = "", response = ResponseEntity.class, httpMethod = "POST") + @ResponseBody + public ResponseEntity updateFlowRules(@RequestBody @ApiParam(value = "流控规则内容,Json格式", required = true) String rule) { + return doUpdateFlowRules(rule); + } + + @RequestMapping(path = "/clear-flow-rules", method = RequestMethod.POST) + @ApiOperation(value = "清除流控规则列表", notes = "", response = ResponseEntity.class, httpMethod = "POST") + @ResponseBody + public ResponseEntity clearFlowRules() { + return doClearFlowRules(); + } + + @RequestMapping(path = "/view-flow-rules", method = RequestMethod.GET) + @ApiOperation(value = "查看流控规则列表", notes = "", response = ResponseEntity.class, httpMethod = "GET") + @ResponseBody + public ResponseEntity viewFlowRules() { + return doViewFlowRules(); + } + + @RequestMapping(path = "/update-degrade-rules", method = RequestMethod.POST) + @ApiOperation(value = "更新降级规则列表", notes = "", response = ResponseEntity.class, httpMethod = "POST") + @ResponseBody + public ResponseEntity updateDegradeRules(@RequestBody @ApiParam(value = "降级规则内容,Json格式", required = true) String rule) { + return doUpdateDegradeRules(rule); + } + + @RequestMapping(path = "/clear-degrade-rules", method = RequestMethod.POST) + @ApiOperation(value = "清除降级规则列表", notes = "", response = ResponseEntity.class, httpMethod = "POST") + @ResponseBody + public ResponseEntity clearDegradeRules() { + return doClearDegradeRules(); + } + + @RequestMapping(path = "/view-degrade-rules", method = RequestMethod.GET) + @ApiOperation(value = "查看降级规则列表", notes = "", response = ResponseEntity.class, httpMethod = "GET") + @ResponseBody + public ResponseEntity viewDegradeRules() { + return doViewDegradeRules(); + } + + @RequestMapping(path = "/update-authority-rules", method = RequestMethod.POST) + @ApiOperation(value = "更新授权规则列表", notes = "", response = ResponseEntity.class, httpMethod = "POST") + @ResponseBody + public ResponseEntity updateAuthorityRules(@RequestBody @ApiParam(value = "授权规则内容,Json格式", required = true) String rule) { + return doUpdateAuthorityRules(rule); + } + + @RequestMapping(path = "/clear-authority-rules", method = RequestMethod.POST) + @ApiOperation(value = "清除授权规则列表", notes = "", response = ResponseEntity.class, httpMethod = "POST") + @ResponseBody + public ResponseEntity clearAuthorityRules() { + return doClearAuthorityRules(); + } + + @RequestMapping(path = "/view-authority-rules", method = RequestMethod.GET) + @ApiOperation(value = "查看授权规则列表", notes = "", response = ResponseEntity.class, httpMethod = "GET") + @ResponseBody + public ResponseEntity viewAuthorityRules() { + return doViewAuthorityRules(); + } + + @RequestMapping(path = "/update-system-rules", method = RequestMethod.POST) + @ApiOperation(value = "更新系统规则列表", notes = "", response = ResponseEntity.class, httpMethod = "POST") + @ResponseBody + public ResponseEntity updateSystemRules(@RequestBody @ApiParam(value = "系统规则内容,Json格式", required = true) String rule) { + return doUpdateSystemRules(rule); + } + + @RequestMapping(path = "/clear-system-rules", method = RequestMethod.POST) + @ApiOperation(value = "清除系统规则列表", notes = "", response = ResponseEntity.class, httpMethod = "POST") + @ResponseBody + public ResponseEntity clearSystemRules() { + return doClearSystemRules(); + } + + @RequestMapping(path = "/view-system-rules", method = RequestMethod.GET) + @ApiOperation(value = "查看系统规则列表", notes = "", response = ResponseEntity.class, httpMethod = "GET") + @ResponseBody + public ResponseEntity viewSystemRules() { + return doViewSystemRules(); + } + + private ResponseEntity doUpdateFlowRules(String rule) { + try { + sentinelCoreResource.updateFlowRules(rule); + + return ResponseUtil.getSuccessResponse(true); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doClearFlowRules() { + try { + sentinelCoreResource.clearFlowRules(); + + return ResponseUtil.getSuccessResponse(true); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doViewFlowRules() { + try { + List flowRules = sentinelCoreResource.viewFlowRules(); + + return ResponseUtil.getSuccessResponse(flowRules); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doUpdateDegradeRules(String rule) { + try { + sentinelCoreResource.updateDegradeRules(rule); + + return ResponseUtil.getSuccessResponse(true); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doClearDegradeRules() { + try { + sentinelCoreResource.clearDegradeRules(); + + return ResponseUtil.getSuccessResponse(true); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doViewDegradeRules() { + try { + List degradeRules = sentinelCoreResource.viewDegradeRules(); + + return ResponseUtil.getSuccessResponse(degradeRules); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doUpdateAuthorityRules(String rule) { + try { + sentinelCoreResource.updateAuthorityRules(rule); + + return ResponseUtil.getSuccessResponse(true); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doClearAuthorityRules() { + try { + sentinelCoreResource.clearAuthorityRules(); + + return ResponseUtil.getSuccessResponse(true); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doViewAuthorityRules() { + try { + List authorityRules = sentinelCoreResource.viewAuthorityRules(); + + return ResponseUtil.getSuccessResponse(authorityRules); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doUpdateSystemRules(String rule) { + try { + sentinelCoreResource.updateSystemRules(rule); + + return ResponseUtil.getSuccessResponse(true); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doClearSystemRules() { + try { + sentinelCoreResource.clearSystemRules(); + + return ResponseUtil.getSuccessResponse(true); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doViewSystemRules() { + try { + List systemRules = sentinelCoreResource.viewSystemRules(); + + return ResponseUtil.getSuccessResponse(systemRules); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } +} \ No newline at end of file diff --git a/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/endpoint/SentinelParamEndpoint.java b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/endpoint/SentinelParamEndpoint.java new file mode 100644 index 0000000000..bd6872ed67 --- /dev/null +++ b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/endpoint/SentinelParamEndpoint.java @@ -0,0 +1,87 @@ +package com.nepxion.discovery.plugin.admincenter.endpoint; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; + +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.RestController; + +import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowRule; +import com.nepxion.discovery.common.util.ResponseUtil; +import com.nepxion.discovery.plugin.admincenter.resource.SentinelParamResource; + +@RestController +@RequestMapping(path = "/sentinel-param") +@Api(tags = { "哨兵参数接口" }) +public class SentinelParamEndpoint { + @Autowired + private SentinelParamResource sentinelParamResource; + + @RequestMapping(path = "/update-param-flow-rules", method = RequestMethod.POST) + @ApiOperation(value = "更新热点参数流控规则列表", notes = "", response = ResponseEntity.class, httpMethod = "POST") + @ResponseBody + public ResponseEntity updateParamFlowRules(@RequestBody @ApiParam(value = "热点参数流控规则内容,Json格式", required = true) String rule) { + return doUpdateParamFlowRules(rule); + } + + @RequestMapping(path = "/clear-param-flow-rules", method = RequestMethod.POST) + @ApiOperation(value = "清除热点参数流控规则列表", notes = "", response = ResponseEntity.class, httpMethod = "POST") + @ResponseBody + public ResponseEntity clearParamFlowRules() { + return doClearParamFlowRules(); + } + + @RequestMapping(path = "/view-param-flow-rules", method = RequestMethod.GET) + @ApiOperation(value = "查看热点参数流控规则列表", notes = "", response = ResponseEntity.class, httpMethod = "GET") + @ResponseBody + public ResponseEntity viewParamFlowRules() { + return doViewParamFlowRules(); + } + + private ResponseEntity doUpdateParamFlowRules(String rule) { + try { + sentinelParamResource.updateParamFlowRules(rule); + + return ResponseUtil.getSuccessResponse(true); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doClearParamFlowRules() { + try { + sentinelParamResource.clearParamFlowRules(); + + return ResponseUtil.getSuccessResponse(true); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doViewParamFlowRules() { + try { + List paramFlowRules = sentinelParamResource.viewParamFlowRules(); + + return ResponseUtil.getSuccessResponse(paramFlowRules); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } +} \ No newline at end of file diff --git a/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/endpoint/ServiceEndpoint.java b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/endpoint/ServiceEndpoint.java new file mode 100644 index 0000000000..e6ffac6095 --- /dev/null +++ b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/endpoint/ServiceEndpoint.java @@ -0,0 +1,279 @@ +package com.nepxion.discovery.plugin.admincenter.endpoint; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cloud.client.ServiceInstance; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.RestController; + +import com.nepxion.discovery.common.entity.GatewayType; +import com.nepxion.discovery.common.entity.InstanceEntity; +import com.nepxion.discovery.common.entity.MetadataParameter; +import com.nepxion.discovery.common.entity.ServiceType; +import com.nepxion.discovery.common.util.ResponseUtil; +import com.nepxion.discovery.plugin.admincenter.resource.ServiceResource; + +@RestController +@RequestMapping(path = "/service") +@Api(tags = { "服务接口" }) +public class ServiceEndpoint { + @Autowired + private ServiceResource serviceResource; + + @RequestMapping(path = "/discovery-type", method = RequestMethod.GET) + @ApiOperation(value = "获取注册发现中心类型", notes = "", response = ResponseEntity.class, httpMethod = "GET") + @ResponseBody + public ResponseEntity discoveryType() { + return doDiscoveryType(); + } + + @RequestMapping(path = "/groups", method = RequestMethod.GET) + @ApiOperation(value = "获取注册中心的服务组名列表", notes = "", response = ResponseEntity.class, httpMethod = "GET") + @ResponseBody + public ResponseEntity groups() { + return doGroups(); + } + + @RequestMapping(path = "/group/{serviceId}", method = RequestMethod.GET) + @ApiOperation(value = "获取注册中心的服务组名", notes = "", response = ResponseEntity.class, httpMethod = "GET") + @ResponseBody + public ResponseEntity group(@PathVariable(value = "serviceId") @ApiParam(value = "服务名", required = true) String serviceId) { + return doGroup(serviceId); + } + + @RequestMapping(path = "/services", method = RequestMethod.GET) + @ApiOperation(value = "获取注册中心的服务名列表", notes = "", response = ResponseEntity.class, httpMethod = "GET") + @ResponseBody + public ResponseEntity services() { + return doServices(); + } + + @RequestMapping(path = "/service-list", method = RequestMethod.POST) + @ApiOperation(value = "获取注册中心的服务名列表", notes = "", response = ResponseEntity.class, httpMethod = "POST") + @ResponseBody + public ResponseEntity serviceList(@RequestBody @ApiParam(value = "服务类型列表。取值: service | gateway", required = true) List serviceTypes) { + return doServiceList(serviceTypes); + } + + @RequestMapping(path = "/service-list/{group}", method = RequestMethod.POST) + @ApiOperation(value = "获取注册中心的组下服务名列表", notes = "", response = ResponseEntity.class, httpMethod = "POST") + @ResponseBody + public ResponseEntity serviceList(@PathVariable(value = "group") @ApiParam(value = "组名", required = true) String group, @RequestBody @ApiParam(value = "服务类型列表。取值: service | gateway", required = true) List serviceTypes) { + return doServiceList(group, serviceTypes); + } + + @RequestMapping(path = "/gateways", method = RequestMethod.GET) + @ApiOperation(value = "获取注册中心的网关名列表", notes = "", response = ResponseEntity.class, httpMethod = "GET") + @ResponseBody + public ResponseEntity gateways() { + return doGateways(); + } + + @RequestMapping(path = "/gateway-list", method = RequestMethod.POST) + @ApiOperation(value = "获取注册中心的网关名列表", notes = "", response = ResponseEntity.class, httpMethod = "POST") + @ResponseBody + public ResponseEntity gatewayList(@RequestBody @ApiParam(value = "网关类型列表。取值: spring-cloud-gateway | zuul。spring-cloud-gateway指Spring Cloud Gateway, zuul指Netflix Zuul", required = true) List gatewayTypes) { + return doGatewayList(gatewayTypes); + } + + @RequestMapping(path = "/instances/{serviceId}", method = RequestMethod.GET) + @ApiOperation(value = "获取注册中心的服务实例列表", notes = "", response = ResponseEntity.class, httpMethod = "GET") + @ResponseBody + public ResponseEntity instances(@PathVariable(value = "serviceId") @ApiParam(value = "服务名", required = true) String serviceId) { + return doInstances(serviceId); + } + + @RequestMapping(path = "/instance-list/{serviceId}", method = RequestMethod.GET) + @ApiOperation(value = "获取注册中心的服务实例列表(精简数据)", notes = "", response = ResponseEntity.class, httpMethod = "GET") + @ResponseBody + public ResponseEntity instanceList(@PathVariable(value = "serviceId") @ApiParam(value = "服务名", required = true) String serviceId) { + return doInstanceList(serviceId); + } + + @RequestMapping(path = "/instance-map", method = RequestMethod.POST) + @ApiOperation(value = "获取注册中心的服务实例的Map(精简数据)", notes = "", response = ResponseEntity.class, httpMethod = "POST") + @ResponseBody + public ResponseEntity instanceMap(@RequestBody @ApiParam(value = "服务组名列表,传入空列则可以获取全部服务实例数据", required = true) List groups) { + return doInstanceMap(groups); + } + + @RequestMapping(path = "/metadata-map/{metadataKey}", method = RequestMethod.POST) + @ApiOperation(value = "获取注册中心的服务实例元数据值列表的Map(值包含单个元数据)", notes = "", response = ResponseEntity.class, httpMethod = "POST") + @ResponseBody + public ResponseEntity metadataMap(@PathVariable(value = "metadataKey") @ApiParam(value = "元数据键名", required = true) String metadataKey, @RequestBody @ApiParam(value = "服务名列表", required = true) List serviceIds) { + return doMetadataMap(metadataKey, serviceIds); + } + + @RequestMapping(path = "/metadata-map", method = RequestMethod.POST) + @ApiOperation(value = "获取注册中心的服务实例元数据值列表的Map(值包含多个元数据,通过分隔符分隔)", notes = "", response = ResponseEntity.class, httpMethod = "POST") + @ResponseBody + public ResponseEntity metadataMap(@RequestBody @ApiParam(value = "元数据查询参数对象", required = true) MetadataParameter metadataParameter) { + return doMetadataMap(metadataParameter); + } + + private ResponseEntity doDiscoveryType() { + try { + String discoveryType = serviceResource.getDiscoveryType().toString(); + + return ResponseUtil.getSuccessResponse(discoveryType); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doGroups() { + try { + List groups = serviceResource.getGroups(); + + return ResponseUtil.getSuccessResponse(groups); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doGroup(String serviceId) { + try { + String group = serviceResource.getGroup(serviceId); + + return ResponseUtil.getSuccessResponse(group); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doServices() { + try { + List services = serviceResource.getServices(); + + return ResponseUtil.getSuccessResponse(services); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doServiceList(List serviceTypes) { + try { + List types = new ArrayList(); + for (String serviceType : serviceTypes) { + types.add(ServiceType.fromString(serviceType)); + } + + List services = serviceResource.getServiceList(types); + + return ResponseUtil.getSuccessResponse(services); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doServiceList(String group, List serviceTypes) { + try { + List types = new ArrayList(); + for (String serviceType : serviceTypes) { + types.add(ServiceType.fromString(serviceType)); + } + + List services = serviceResource.getServiceList(group, types); + + return ResponseUtil.getSuccessResponse(services); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doGateways() { + try { + List gateways = serviceResource.getGateways(); + + return ResponseUtil.getSuccessResponse(gateways); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doGatewayList(List gatewayTypes) { + try { + List types = new ArrayList(); + for (String gatewayType : gatewayTypes) { + types.add(GatewayType.fromString(gatewayType)); + } + + List gatewayList = serviceResource.getGatewayList(types); + + return ResponseUtil.getSuccessResponse(gatewayList); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doInstances(String serviceId) { + try { + List instances = serviceResource.getInstances(serviceId); + + return ResponseUtil.getSuccessResponse(instances); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doInstanceList(String serviceId) { + try { + List instanceList = serviceResource.getInstanceList(serviceId); + + return ResponseUtil.getSuccessResponse(instanceList); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doInstanceMap(List groups) { + try { + Map> instanceMaps = serviceResource.getInstanceMap(groups); + + return ResponseUtil.getSuccessResponse(instanceMaps); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doMetadataMap(String metadataKey, List serviceIds) { + try { + Map> metadataMap = serviceResource.getMetadataMap(metadataKey, serviceIds); + + return ResponseUtil.getSuccessResponse(metadataMap); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doMetadataMap(MetadataParameter metadataParameter) { + try { + Map> metadataMap = serviceResource.getMetadataMap(metadataParameter); + + return ResponseUtil.getSuccessResponse(metadataMap); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } +} \ No newline at end of file diff --git a/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/endpoint/StrategyEndpoint.java b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/endpoint/StrategyEndpoint.java new file mode 100644 index 0000000000..ad01292f0e --- /dev/null +++ b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/endpoint/StrategyEndpoint.java @@ -0,0 +1,67 @@ +package com.nepxion.discovery.plugin.admincenter.endpoint; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.RestController; + +import com.nepxion.discovery.common.util.ResponseUtil; +import com.nepxion.discovery.plugin.admincenter.resource.StrategyResource; + +@RestController +@RequestMapping(path = "/strategy") +@Api(tags = { "策略接口" }) +public class StrategyEndpoint { + @Autowired + private StrategyResource strategyResource; + + @RequestMapping(path = "/validate-expression", method = RequestMethod.GET) + @ApiOperation(value = "校验策略的条件表达式", notes = "", response = ResponseEntity.class, httpMethod = "GET") + @ResponseBody + public ResponseEntity validateExpression(@RequestParam @ApiParam(value = "条件表达式,格式示例:#H['a'] == '1' && #H['b'] != '2'。注意,引号是否为中文格式", defaultValue = "#H['a'] == '1' && #H['b'] != '2'", required = true) String expression, @RequestParam(defaultValue = "", required = false) @ApiParam(value = "校验参数,格式示例:a=1;b=1。如果多个用“;”分隔,不允许出现空格。允许为空", defaultValue = "a=1;b=1") String validation) { + return doValidateExpression(expression, validation); + } + + @RequestMapping(path = "/validate-route", method = RequestMethod.GET) + @ApiOperation(value = "校验策略的全链路路由", notes = "", response = ResponseEntity.class, httpMethod = "GET") + @ResponseBody + public ResponseEntity validateRoute(@RequestParam @ApiParam(value = "路由策略类型。取值:version | region | address | version-weight | region-weight | id-blacklist | address-blacklist", defaultValue = "version", required = true) String routeType, @RequestParam(defaultValue = "", required = false) @ApiParam(value = "校验参数,格式示例:a=1;b=1。如果多个用“;”分隔,不允许出现空格,允许为空。如果选择最后两项策略类型,则不需要校验参数", defaultValue = "a=1;b=1") String validation) { + return doValidateRoute(routeType, validation); + } + + private ResponseEntity doValidateExpression(String expression, String validation) { + try { + boolean result = strategyResource.validateExpression(expression, validation); + + return ResponseUtil.getSuccessResponse(result); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doValidateRoute(String routeType, String validation) { + try { + String route = strategyResource.validateRoute(routeType, validation); + + return ResponseUtil.getSuccessResponse(route); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } +} \ No newline at end of file diff --git a/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/endpoint/VersionEndpoint.java b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/endpoint/VersionEndpoint.java new file mode 100644 index 0000000000..6129de44d4 --- /dev/null +++ b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/endpoint/VersionEndpoint.java @@ -0,0 +1,100 @@ +package com.nepxion.discovery.plugin.admincenter.endpoint; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; + +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.RestController; + +import com.nepxion.discovery.common.util.ResponseUtil; +import com.nepxion.discovery.plugin.admincenter.resource.VersionResource; + +@RestController +@RequestMapping(path = "/version") +@Api(tags = { "版本接口" }) +public class VersionEndpoint { + @Autowired + private VersionResource versionResource; + + @RequestMapping(path = "/update-async", method = RequestMethod.POST) + @ApiOperation(value = "异步更新动态版本", notes = "根据指定的localVersion更新服务的dynamicVersion。如果输入的localVersion不匹配服务的localVersion,则忽略;如果如果输入的localVersion为空,则直接更新服务的dynamicVersion", response = ResponseEntity.class, httpMethod = "POST") + @ResponseBody + public ResponseEntity updateAsync(@RequestBody @ApiParam(value = "版本号,格式为${dynamicVersion}或者${dynamicVersion};${localVersion}", required = true) String version) { + return doUpdate(version, true); + } + + @RequestMapping(path = "/update-sync", method = RequestMethod.POST) + @ApiOperation(value = "同步更新动态版本", notes = "根据指定的localVersion更新服务的dynamicVersion。如果输入的localVersion不匹配服务的localVersion,则忽略;如果如果输入的localVersion为空,则直接更新服务的dynamicVersion", response = ResponseEntity.class, httpMethod = "POST") + @ResponseBody + public ResponseEntity updateSync(@RequestBody @ApiParam(value = "版本号,格式为${dynamicVersion}或者${dynamicVersion};${localVersion}", required = true) String version) { + return doUpdate(version, false); + } + + @RequestMapping(path = "/clear-async", method = RequestMethod.POST) + @ApiOperation(value = "异步清除动态版本", notes = "根据指定的localVersion清除服务的dynamicVersion。如果输入的localVersion不匹配服务的localVersion,则忽略;如果如果输入的localVersion为空,则直接清除服务的dynamicVersion", response = ResponseEntity.class, httpMethod = "POST") + @ResponseBody + public ResponseEntity clearAsync(@RequestBody(required = false) @ApiParam(value = "版本号,指localVersion,可以为空") String version) { + return doClear(version, true); + } + + @RequestMapping(path = "/clear-sync", method = RequestMethod.POST) + @ApiOperation(value = "同步清除动态版本", notes = "根据指定的localVersion清除服务的dynamicVersion。如果输入的localVersion不匹配服务的localVersion,则忽略;如果如果输入的localVersion为空,则直接清除服务的dynamicVersion", response = ResponseEntity.class, httpMethod = "POST") + @ResponseBody + public ResponseEntity clearSync(@RequestBody(required = false) @ApiParam(value = "版本号,指localVersion,可以为空") String version) { + return doClear(version, false); + } + + @RequestMapping(path = "/view", method = RequestMethod.GET) + @ApiOperation(value = "查看本地版本和动态版本", notes = "", response = ResponseEntity.class, httpMethod = "GET") + @ResponseBody + public ResponseEntity view() { + return doView(); + } + + private ResponseEntity doUpdate(String version, boolean async) { + try { + versionResource.update(version, async); + + return ResponseUtil.getSuccessResponse(true); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doClear(String version, boolean async) { + try { + versionResource.clear(version, async); + + return ResponseUtil.getSuccessResponse(true); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doView() { + try { + List versionList = versionResource.view(); + + return ResponseUtil.getSuccessResponse(versionList); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } +} \ No newline at end of file diff --git a/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/endpoint/ZuulStrategyRouteEndpoint.java b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/endpoint/ZuulStrategyRouteEndpoint.java new file mode 100644 index 0000000000..a942c36864 --- /dev/null +++ b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/endpoint/ZuulStrategyRouteEndpoint.java @@ -0,0 +1,140 @@ +package com.nepxion.discovery.plugin.admincenter.endpoint; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Ning Zhang + * @author Haojun Ren + * @version 1.0 + */ + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; + +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.RestController; + +import com.nepxion.discovery.common.entity.ZuulStrategyRouteEntity; +import com.nepxion.discovery.common.util.ResponseUtil; +import com.nepxion.discovery.plugin.admincenter.resource.ZuulStrategyRouteResource; + +@RestController +@RequestMapping(path = "/zuul-route") +@Api(tags = { "网关动态路由接口" }) +public class ZuulStrategyRouteEndpoint { + @Autowired + private ZuulStrategyRouteResource zuulStrategyRouteResource; + + @RequestMapping(path = "/add", method = RequestMethod.POST) + @ApiOperation(value = "增加网关路由", notes = "", response = ResponseEntity.class, httpMethod = "POST") + @ResponseBody + public ResponseEntity add(@RequestBody @ApiParam(value = "网关路由对象", required = true) ZuulStrategyRouteEntity zuulStrategyRouteEntity) { + return doAdd(zuulStrategyRouteEntity); + } + + @RequestMapping(path = "/modify", method = RequestMethod.POST) + @ApiOperation(value = "修改网关路由", notes = "", response = ResponseEntity.class, httpMethod = "POST") + @ResponseBody + public ResponseEntity modify(@RequestBody @ApiParam(value = "网关路由对象", required = true) ZuulStrategyRouteEntity zuulStrategyRouteEntity) { + return doModify(zuulStrategyRouteEntity); + } + + @RequestMapping(path = "/delete/{routeId}", method = RequestMethod.DELETE) + @ApiOperation(value = "删除网关路由", notes = "", response = ResponseEntity.class, httpMethod = "DELETE") + @ResponseBody + public ResponseEntity delete(@PathVariable(value = "routeId") @ApiParam(value = "路由Id", required = true) String routeId) { + return doDelete(routeId); + } + + @RequestMapping(path = "/update-all", method = RequestMethod.POST) + @ApiOperation(value = "更新全部网关路由", notes = "", response = ResponseEntity.class, httpMethod = "POST") + @ResponseBody + public ResponseEntity updateAll(@RequestBody @ApiParam(value = "网关路由对象列表", required = true) List zuulStrategyRouteEntityList) { + return doUpdateAll(zuulStrategyRouteEntityList); + } + + @RequestMapping(path = "/view/{routeId}", method = RequestMethod.GET) + @ApiOperation(value = "根据路由Id查看网关路由", notes = "", response = ResponseEntity.class, httpMethod = "GET") + @ResponseBody + public ResponseEntity view(@PathVariable(value = "routeId") @ApiParam(value = "路由Id", required = true) String routeId) { + return doView(routeId); + } + + @RequestMapping(path = "/view-all", method = RequestMethod.GET) + @ApiOperation(value = "查看全部网关路由", notes = "", response = ResponseEntity.class, httpMethod = "GET") + @ResponseBody + public ResponseEntity viewAll() { + return doViewAll(); + } + + private ResponseEntity doAdd(ZuulStrategyRouteEntity zuulStrategyRouteEntity) { + try { + zuulStrategyRouteResource.add(zuulStrategyRouteEntity); + + return ResponseUtil.getSuccessResponse(true); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doModify(ZuulStrategyRouteEntity zuulStrategyRouteEntity) { + try { + zuulStrategyRouteResource.modify(zuulStrategyRouteEntity); + + return ResponseUtil.getSuccessResponse(true); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doDelete(String routeId) { + try { + zuulStrategyRouteResource.delete(routeId); + + return ResponseUtil.getSuccessResponse(true); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doUpdateAll(List zuulStrategyRouteEntityList) { + try { + zuulStrategyRouteResource.updateAll(zuulStrategyRouteEntityList); + + return ResponseUtil.getSuccessResponse(true); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doView(String routeId) { + try { + ZuulStrategyRouteEntity zuulStrategyRouteEntity = zuulStrategyRouteResource.view(routeId); + + return ResponseUtil.getSuccessResponse(zuulStrategyRouteEntity); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doViewAll() { + try { + List zuulStrategyRouteEntityList = zuulStrategyRouteResource.viewAll(); + + return ResponseUtil.getSuccessResponse(zuulStrategyRouteEntityList); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } +} \ No newline at end of file diff --git a/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/ConfigResource.java b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/ConfigResource.java new file mode 100644 index 0000000000..ae6a574a03 --- /dev/null +++ b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/ConfigResource.java @@ -0,0 +1,24 @@ +package com.nepxion.discovery.plugin.admincenter.resource; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.List; + +import com.nepxion.discovery.common.entity.ConfigType; + +public interface ConfigResource { + ConfigType getConfigType(); + + void update(String config, boolean async); + + void clear(boolean async); + + List view(); +} \ No newline at end of file diff --git a/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/ConfigResourceImpl.java b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/ConfigResourceImpl.java new file mode 100644 index 0000000000..4d47ed6bca --- /dev/null +++ b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/ConfigResourceImpl.java @@ -0,0 +1,91 @@ +package com.nepxion.discovery.plugin.admincenter.resource; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.ArrayList; +import java.util.List; + +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; + +import com.nepxion.discovery.common.entity.ConfigType; +import com.nepxion.discovery.common.entity.RuleEntity; +import com.nepxion.discovery.common.entity.SubscriptionType; +import com.nepxion.discovery.common.exception.DiscoveryException; +import com.nepxion.discovery.plugin.framework.adapter.PluginAdapter; +import com.nepxion.discovery.plugin.framework.adapter.PluginConfigAdapter; +import com.nepxion.discovery.plugin.framework.event.PluginEventWapper; +import com.nepxion.discovery.plugin.framework.event.RuleClearedEvent; +import com.nepxion.discovery.plugin.framework.event.RuleUpdatedEvent; + +public class ConfigResourceImpl implements ConfigResource { + private static final Logger LOG = LoggerFactory.getLogger(ConfigResourceImpl.class); + + @Autowired + private PluginAdapter pluginAdapter; + + @Autowired(required = false) + private PluginConfigAdapter pluginConfigAdapter; + + @Autowired + private PluginEventWapper pluginEventWapper; + + @Override + public ConfigType getConfigType() { + if (pluginConfigAdapter == null) { + LOG.error("Remote config adapter isn't provided"); + + throw new DiscoveryException("Remote config adapter isn't provided"); + } + + return pluginConfigAdapter.getConfigType(); + } + + @Override + public void update(String config, boolean async) { + pluginEventWapper.fireRuleUpdated(new RuleUpdatedEvent(SubscriptionType.PARTIAL, config), async); + } + + @Override + public void clear(boolean async) { + pluginEventWapper.fireRuleCleared(new RuleClearedEvent(SubscriptionType.PARTIAL), async); + } + + @Override + public List view() { + List ruleList = new ArrayList(3); + + String localRuleContent = StringUtils.EMPTY; + RuleEntity localRuleEntity = pluginAdapter.getLocalRule(); + if (localRuleEntity != null && StringUtils.isNotEmpty(localRuleEntity.getContent())) { + localRuleContent = localRuleEntity.getContent(); + } + + String dynamicGlobalRuleContent = StringUtils.EMPTY; + RuleEntity dynamicGlobalRuleEntity = pluginAdapter.getDynamicGlobalRule(); + if (dynamicGlobalRuleEntity != null && StringUtils.isNotEmpty(dynamicGlobalRuleEntity.getContent())) { + dynamicGlobalRuleContent = dynamicGlobalRuleEntity.getContent(); + } + + String dynamicPartialRuleContent = StringUtils.EMPTY; + RuleEntity dynamicPartialRuleEntity = pluginAdapter.getDynamicPartialRule(); + if (dynamicPartialRuleEntity != null && StringUtils.isNotEmpty(dynamicPartialRuleEntity.getContent())) { + dynamicPartialRuleContent = dynamicPartialRuleEntity.getContent(); + } + + ruleList.add(localRuleContent); + ruleList.add(dynamicGlobalRuleContent); + ruleList.add(dynamicPartialRuleContent); + + return ruleList; + } +} \ No newline at end of file diff --git a/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/GatewayStrategyRouteResource.java b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/GatewayStrategyRouteResource.java new file mode 100644 index 0000000000..7da3e4ef66 --- /dev/null +++ b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/GatewayStrategyRouteResource.java @@ -0,0 +1,30 @@ +package com.nepxion.discovery.plugin.admincenter.resource; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.List; + +import com.nepxion.discovery.common.entity.GatewayStrategyRouteEntity; + +public interface GatewayStrategyRouteResource { + void add(GatewayStrategyRouteEntity gatewayStrategyRouteEntity); + + void modify(GatewayStrategyRouteEntity gatewayStrategyRouteEntity); + + void delete(String routeId); + + void updateAll(List gatewayStrategyRouteEntityList); + + void updateAll(String gatewayStrategyRouteConfig); + + GatewayStrategyRouteEntity view(String routeId); + + List viewAll(); +} \ No newline at end of file diff --git a/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/GatewayStrategyRouteResourceImpl.java b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/GatewayStrategyRouteResourceImpl.java new file mode 100644 index 0000000000..77de5e4f7e --- /dev/null +++ b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/GatewayStrategyRouteResourceImpl.java @@ -0,0 +1,57 @@ +package com.nepxion.discovery.plugin.admincenter.resource; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; + +import com.nepxion.discovery.common.entity.GatewayStrategyRouteEntity; +import com.nepxion.discovery.plugin.strategy.gateway.route.GatewayStrategyRoute; + +public class GatewayStrategyRouteResourceImpl implements GatewayStrategyRouteResource { + @Autowired + private GatewayStrategyRoute gatewayStrategyRoute; + + @Override + public void add(GatewayStrategyRouteEntity gatewayStrategyRouteEntity) { + gatewayStrategyRoute.add(gatewayStrategyRouteEntity); + } + + @Override + public void modify(GatewayStrategyRouteEntity gatewayStrategyRouteEntity) { + gatewayStrategyRoute.modify(gatewayStrategyRouteEntity); + } + + @Override + public void delete(String routeId) { + gatewayStrategyRoute.delete(routeId); + } + + @Override + public void updateAll(List gatewayStrategyRouteEntityList) { + gatewayStrategyRoute.updateAll(gatewayStrategyRouteEntityList); + } + + @Override + public void updateAll(String gatewayStrategyRouteConfig) { + gatewayStrategyRoute.updateAll(gatewayStrategyRouteConfig); + } + + @Override + public GatewayStrategyRouteEntity view(String routeId) { + return gatewayStrategyRoute.view(routeId); + } + + @Override + public List viewAll() { + return gatewayStrategyRoute.viewAll(); + } +} \ No newline at end of file diff --git a/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/GitResource.java b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/GitResource.java new file mode 100644 index 0000000000..40a4efb508 --- /dev/null +++ b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/GitResource.java @@ -0,0 +1,18 @@ +package com.nepxion.discovery.plugin.admincenter.resource; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.Map; + +public interface GitResource { + Map map(); + + String text(); +} \ No newline at end of file diff --git a/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/GitResourceImpl.java b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/GitResourceImpl.java new file mode 100644 index 0000000000..815afda590 --- /dev/null +++ b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/GitResourceImpl.java @@ -0,0 +1,31 @@ +package com.nepxion.discovery.plugin.admincenter.resource; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.Map; + +import org.springframework.beans.factory.annotation.Autowired; + +import com.nepxion.discovery.plugin.framework.generator.GitGenerator; + +public class GitResourceImpl implements GitResource { + @Autowired + private GitGenerator gitGenerator; + + @Override + public Map map() { + return gitGenerator.getMap(); + } + + @Override + public String text() { + return gitGenerator.getText(); + } +} \ No newline at end of file diff --git a/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/InspectorResource.java b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/InspectorResource.java new file mode 100644 index 0000000000..07e911efb6 --- /dev/null +++ b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/InspectorResource.java @@ -0,0 +1,20 @@ +package com.nepxion.discovery.plugin.admincenter.resource; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.List; + +import com.nepxion.discovery.common.entity.InspectorEntity; + +public interface InspectorResource { + InspectorEntity inspect(InspectorEntity inspectorEntity); + + String inspect(List service); +} \ No newline at end of file diff --git a/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/InspectorResourceImpl.java b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/InspectorResourceImpl.java new file mode 100644 index 0000000000..7104ca8ad3 --- /dev/null +++ b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/InspectorResourceImpl.java @@ -0,0 +1,110 @@ +package com.nepxion.discovery.plugin.admincenter.resource; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.List; + +import org.apache.commons.collections4.CollectionUtils; +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cloud.client.ServiceInstance; +import org.springframework.cloud.client.discovery.DiscoveryClient; +import org.springframework.web.client.RestTemplate; + +import com.nepxion.discovery.common.constant.DiscoveryConstant; +import com.nepxion.discovery.common.entity.InspectorEntity; +import com.nepxion.discovery.common.exception.DiscoveryException; +import com.nepxion.discovery.plugin.framework.adapter.PluginAdapter; +import com.nepxion.discovery.plugin.framework.context.PluginContextHolder; + +public class InspectorResourceImpl implements InspectorResource { + private static final Logger LOG = LoggerFactory.getLogger(InspectorResourceImpl.class); + + @Autowired + private RestTemplate pluginRestTemplate; + + @Autowired + private PluginAdapter pluginAdapter; + + @Autowired + private DiscoveryClient discoveryClient; + + @Autowired(required = false) + private PluginContextHolder pluginContextHolder; + + @Override + public InspectorEntity inspect(InspectorEntity inspectorEntity) { + List serviceIdList = inspectorEntity.getServiceIdList(); + String result = inspectorEntity.getResult(); + + // 第一个侦测节点,不会产生侦测信息,需要通过Header方式埋入 + if (StringUtils.isEmpty(result) && pluginContextHolder != null) { + result = pluginContextHolder.getContext(DiscoveryConstant.INSPECTOR_ENDPOINT_HEADER); + } + + String pluginInfo = pluginAdapter.getPluginInfo(result); + inspectorEntity.setResult(pluginInfo); + + if (CollectionUtils.isNotEmpty(serviceIdList)) { + // 获取侦测列表中的第一个服务,作为下一个侦测中继节点 + String nextServiceId = serviceIdList.get(0); + + // 删除侦测列表中的第一个服务 + serviceIdList.remove(0); + + String url = null; + try { + ServiceInstance nextInstance = getInstance(nextServiceId); + + String protocol = pluginAdapter.getInstanceProtocol(nextInstance); + String contextPath = pluginAdapter.getInstanceFormatContextPath(nextInstance); + + url = protocol + "://" + nextServiceId + contextPath + DiscoveryConstant.INSPECTOR_ENDPOINT_URL; + + // 直调方式需要走负载均衡模式下的RestTemplate + return pluginRestTemplate.postForEntity(url, inspectorEntity, InspectorEntity.class).getBody(); + } catch (Exception e) { + String exceptionMessage = "Failed to inspect, current serviceId=" + pluginAdapter.getServiceId() + ", next serviceId=" + nextServiceId + ", url=" + url; + + LOG.error(exceptionMessage, e); + + throw new DiscoveryException(exceptionMessage, e); + } + } else { + return inspectorEntity; + } + } + + @Override + public String inspect(List service) { + InspectorEntity inspectorEntity = new InspectorEntity(); + inspectorEntity.setServiceIdList(service); + + return inspect(inspectorEntity).getResult(); + } + + private ServiceInstance getInstance(String serviceId) { + List instances = null; + + try { + instances = discoveryClient.getInstances(serviceId); + } catch (Exception e) { + throw new DiscoveryException("Failed to get instance list, serviceId=" + serviceId, e); + } + + if (CollectionUtils.isEmpty(instances)) { + throw new DiscoveryException("Instance list is empty, serviceId=" + serviceId); + } + + return instances.get(0); + } +} \ No newline at end of file diff --git a/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/RouterResource.java b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/RouterResource.java new file mode 100644 index 0000000000..3773483c1d --- /dev/null +++ b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/RouterResource.java @@ -0,0 +1,24 @@ +package com.nepxion.discovery.plugin.admincenter.resource; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.List; + +import com.nepxion.discovery.common.entity.RouterEntity; + +public interface RouterResource { + RouterEntity getRouterEntity(); + + List getRouterEntityList(String routeServiceId); + + List getRouterEntityList(String routeServiceId, String routeProtocol, String routeHost, int routePort, String routeContextPath); + + RouterEntity routeTree(String routeServiceIds); +} \ No newline at end of file diff --git a/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/RouterResourceImpl.java b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/RouterResourceImpl.java new file mode 100644 index 0000000000..031c9a527c --- /dev/null +++ b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/RouterResourceImpl.java @@ -0,0 +1,233 @@ +package com.nepxion.discovery.plugin.admincenter.resource; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +import org.apache.commons.collections4.CollectionUtils; +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cloud.client.ServiceInstance; +import org.springframework.web.client.RestClientException; +import org.springframework.web.client.RestTemplate; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.nepxion.discovery.common.constant.DiscoveryConstant; +import com.nepxion.discovery.common.entity.DiscoveryEntity; +import com.nepxion.discovery.common.entity.RouterEntity; +import com.nepxion.discovery.common.entity.RuleEntity; +import com.nepxion.discovery.common.entity.WeightEntityWrapper; +import com.nepxion.discovery.common.entity.WeightFilterEntity; +import com.nepxion.discovery.common.exception.DiscoveryException; +import com.nepxion.discovery.common.util.JsonUtil; +import com.nepxion.discovery.plugin.framework.adapter.PluginAdapter; + +public class RouterResourceImpl implements RouterResource { + @Autowired + private PluginAdapter pluginAdapter; + + @Autowired + private ServiceResource serviceResource; + + private RestTemplate routerRestTemplate; + + public RouterResourceImpl() { + routerRestTemplate = new RestTemplate(); + } + + @Override + public RouterEntity getRouterEntity() { + String serviceType = pluginAdapter.getServiceType(); + String serviceId = pluginAdapter.getServiceId(); + String version = pluginAdapter.getVersion(); + String region = pluginAdapter.getRegion(); + String environment = pluginAdapter.getEnvironment(); + String zone = pluginAdapter.getZone(); + String host = pluginAdapter.getHost(); + int port = pluginAdapter.getPort(); + int weight = -1; + String protocol = pluginAdapter.getProtocol(); + String contextPath = pluginAdapter.getFormatContextPath(); + + RouterEntity routerEntity = new RouterEntity(); + routerEntity.setServiceType(serviceType); + routerEntity.setServiceId(serviceId); + routerEntity.setVersion(version); + routerEntity.setRegion(region); + routerEntity.setEnvironment(environment); + routerEntity.setZone(zone); + routerEntity.setHost(host); + routerEntity.setPort(port); + routerEntity.setWeight(weight); + routerEntity.setProtocol(protocol); + routerEntity.setContextPath(contextPath); + + return routerEntity; + } + + @Override + public List getRouterEntityList(String routeServiceId) { + List instanceList = null; + + try { + instanceList = serviceResource.getInstances(routeServiceId); + } catch (Exception e) { + throw new DiscoveryException("Get instance list for route serviceId=" + routeServiceId + " failed", e); + } + + if (CollectionUtils.isEmpty(instanceList)) { + return null; + } + + List routerEntityList = new ArrayList(); + for (ServiceInstance instance : instanceList) { + String serviceId = pluginAdapter.getInstanceServiceId(instance); + String serviceType = pluginAdapter.getInstanceServiceType(instance); + String version = pluginAdapter.getInstanceVersion(instance); + String region = pluginAdapter.getInstanceRegion(instance); + String environment = pluginAdapter.getInstanceEnvironment(instance); + String zone = pluginAdapter.getInstanceZone(instance); + String host = instance.getHost(); + int port = instance.getPort(); + int weight = getWeight(routeServiceId, version, region); + String protocol = pluginAdapter.getInstanceProtocol(instance); + String contextPath = pluginAdapter.getInstanceFormatContextPath(instance); + + RouterEntity routerEntity = new RouterEntity(); + routerEntity.setServiceType(serviceType); + routerEntity.setServiceId(serviceId); + routerEntity.setVersion(version); + routerEntity.setRegion(region); + routerEntity.setEnvironment(environment); + routerEntity.setZone(zone); + routerEntity.setHost(host); + routerEntity.setPort(port); + routerEntity.setWeight(weight); + routerEntity.setProtocol(protocol); + routerEntity.setContextPath(contextPath); + + routerEntityList.add(routerEntity); + } + + return routerEntityList; + } + + @Override + public List getRouterEntityList(String routeServiceId, String routeProtocol, String routeHost, int routePort, String routeContextPath) { + String url = routeProtocol + "://" + routeHost + ":" + routePort + routeContextPath + "router/route/" + routeServiceId; + + String result = null; + try { + result = routerRestTemplate.getForEntity(url, String.class).getBody(); + } catch (RestClientException e) { + throw new DiscoveryException("Failed to execute to route, serviceId=" + routeServiceId + ", url=" + url, e); + } + + if (StringUtils.isEmpty(result)) { + return null; + } + + List routerEntityList = JsonUtil.fromJson(result, new TypeReference>() { + }); + + return routerEntityList; + } + + @Override + public RouterEntity routeTree(String routeServiceIds) { + if (StringUtils.isEmpty(routeServiceIds)) { + throw new DiscoveryException("Route serviceIds is empty"); + } + + String[] serviceIdArray = null; + try { + serviceIdArray = StringUtils.split(routeServiceIds, DiscoveryConstant.SEPARATE); + } catch (Exception e) { + throw new DiscoveryException("Route serviceIds must be separated with '" + DiscoveryConstant.SEPARATE + "'", e); + } + + RouterEntity firstRouterEntity = getRouterEntity(); + + // 路由深度为Key + HashMap> routerEntityMap = new HashMap>(); + int routerDepth = 0; + for (String serviceId : serviceIdArray) { + serviceId = serviceId.toLowerCase().trim(); + if (routerDepth == 0) { + routeFirst(firstRouterEntity, serviceId); + + retrieveRouterEntityList(routerEntityMap, routerDepth).addAll(firstRouterEntity.getNexts()); + } else { + List routerEntityList = retrieveRouterEntityList(routerEntityMap, routerDepth - 1); + for (RouterEntity routerEntity : routerEntityList) { + String routeHost = routerEntity.getHost(); + int routePort = routerEntity.getPort(); + String routeProtocol = routerEntity.getProtocol(); + String routeContextPath = routerEntity.getContextPath(); + + route(routerEntity, serviceId, routeProtocol, routeHost, routePort, routeContextPath); + + retrieveRouterEntityList(routerEntityMap, routerDepth).addAll(routerEntity.getNexts()); + } + } + + routerDepth++; + } + + return firstRouterEntity; + } + + private void routeFirst(RouterEntity routerEntity, String routeServiceId) { + List routerEntityList = getRouterEntityList(routeServiceId); + if (CollectionUtils.isNotEmpty(routerEntityList)) { + routerEntity.getNexts().addAll(routerEntityList); + } + } + + private void route(RouterEntity routerEntity, String routeServiceId, String routeProtocol, String routeHost, int routePort, String routeContextPath) { + List routerEntityList = getRouterEntityList(routeServiceId, routeProtocol, routeHost, routePort, routeContextPath); + if (CollectionUtils.isNotEmpty(routerEntityList)) { + routerEntity.getNexts().addAll(routerEntityList); + } + } + + private List retrieveRouterEntityList(HashMap> routerEntityMap, int routerDepth) { + List routerEntityList = routerEntityMap.get(routerDepth); + if (routerEntityList == null) { + routerEntityList = new ArrayList(); + routerEntityMap.put(routerDepth, routerEntityList); + } + + return routerEntityList; + } + + private int getWeight(String providerServiceId, String providerVersion, String providerRegion) { + RuleEntity ruleEntity = pluginAdapter.getRule(); + if (ruleEntity == null) { + return -1; + } + + DiscoveryEntity discoveryEntity = ruleEntity.getDiscoveryEntity(); + if (discoveryEntity == null) { + return -1; + } + + WeightFilterEntity weightFilterEntity = discoveryEntity.getWeightFilterEntity(); + if (weightFilterEntity == null || !weightFilterEntity.hasWeight()) { + return -1; + } + + String serviceId = pluginAdapter.getServiceId(); + + return WeightEntityWrapper.getWeight(weightFilterEntity, providerServiceId, providerVersion, providerRegion, serviceId); + } +} \ No newline at end of file diff --git a/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/SentinelCoreResource.java b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/SentinelCoreResource.java new file mode 100644 index 0000000000..041925f13a --- /dev/null +++ b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/SentinelCoreResource.java @@ -0,0 +1,43 @@ +package com.nepxion.discovery.plugin.admincenter.resource; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.List; + +import com.alibaba.csp.sentinel.slots.block.authority.AuthorityRule; +import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule; +import com.alibaba.csp.sentinel.slots.block.flow.FlowRule; +import com.alibaba.csp.sentinel.slots.system.SystemRule; + +public interface SentinelCoreResource { + void updateFlowRules(String rule); + + void clearFlowRules(); + + public List viewFlowRules(); + + void updateDegradeRules(String rule); + + void clearDegradeRules(); + + List viewDegradeRules(); + + void updateAuthorityRules(String rule); + + void clearAuthorityRules(); + + List viewAuthorityRules(); + + void updateSystemRules(String rule); + + void clearSystemRules(); + + List viewSystemRules(); +} \ No newline at end of file diff --git a/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/SentinelCoreResourceImpl.java b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/SentinelCoreResourceImpl.java new file mode 100644 index 0000000000..60457b9492 --- /dev/null +++ b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/SentinelCoreResourceImpl.java @@ -0,0 +1,141 @@ +package com.nepxion.discovery.plugin.admincenter.resource; + +import java.util.ArrayList; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.List; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.alibaba.csp.sentinel.datasource.Converter; +import com.alibaba.csp.sentinel.slots.block.authority.AuthorityRule; +import com.alibaba.csp.sentinel.slots.block.authority.AuthorityRuleManager; +import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule; +import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager; +import com.alibaba.csp.sentinel.slots.block.flow.FlowRule; +import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager; +import com.alibaba.csp.sentinel.slots.system.SystemRule; +import com.alibaba.csp.sentinel.slots.system.SystemRuleManager; +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.TypeReference; + +public class SentinelCoreResourceImpl implements SentinelCoreResource { + private static final Logger LOG = LoggerFactory.getLogger(SentinelCoreResourceImpl.class); + + private static Converter> sentinelFlowRuleParser = new Converter>() { + @Override + public List convert(String source) { + return JSON.parseObject(source, new TypeReference>() { + }); + } + }; + + private static Converter> sentinelDegradeRuleParser = new Converter>() { + @Override + public List convert(String source) { + return JSON.parseObject(source, new TypeReference>() { + }); + } + }; + + private static Converter> sentinelAuthorityRuleParser = new Converter>() { + @Override + public List convert(String source) { + return JSON.parseObject(source, new TypeReference>() { + }); + } + }; + + private static Converter> sentinelSystemRuleParser = new Converter>() { + @Override + public List convert(String source) { + return JSON.parseObject(source, new TypeReference>() { + }); + } + }; + + @Override + public void updateFlowRules(String rule) { + FlowRuleManager.loadRules(sentinelFlowRuleParser.convert(rule)); + + LOG.info("{} flow rules loaded...", FlowRuleManager.getRules().size()); + } + + @Override + public void clearFlowRules() { + LOG.info("{} flow rules cleared...", FlowRuleManager.getRules().size()); + + FlowRuleManager.loadRules(new ArrayList()); + } + + @Override + public List viewFlowRules() { + return FlowRuleManager.getRules(); + } + + @Override + public void updateDegradeRules(String rule) { + DegradeRuleManager.loadRules(sentinelDegradeRuleParser.convert(rule)); + + LOG.info("{} degrade rules loaded...", DegradeRuleManager.getRules().size()); + } + + @Override + public void clearDegradeRules() { + LOG.info("{} degrade rules cleared...", DegradeRuleManager.getRules().size()); + + DegradeRuleManager.loadRules(new ArrayList()); + } + + @Override + public List viewDegradeRules() { + return DegradeRuleManager.getRules(); + } + + @Override + public void updateAuthorityRules(String rule) { + AuthorityRuleManager.loadRules(sentinelAuthorityRuleParser.convert(rule)); + + LOG.info("{} authority rules loaded...", AuthorityRuleManager.getRules().size()); + } + + @Override + public void clearAuthorityRules() { + LOG.info("{} authority rules cleared...", AuthorityRuleManager.getRules().size()); + + AuthorityRuleManager.loadRules(new ArrayList()); + } + + @Override + public List viewAuthorityRules() { + return AuthorityRuleManager.getRules(); + } + + @Override + public void updateSystemRules(String rule) { + SystemRuleManager.loadRules(sentinelSystemRuleParser.convert(rule)); + + LOG.info("{} system rules loaded...", SystemRuleManager.getRules().size()); + } + + @Override + public void clearSystemRules() { + LOG.info("{} system rules cleared...", SystemRuleManager.getRules().size()); + + SystemRuleManager.loadRules(new ArrayList()); + } + + @Override + public List viewSystemRules() { + return SystemRuleManager.getRules(); + } +} \ No newline at end of file diff --git a/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/SentinelParamResource.java b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/SentinelParamResource.java new file mode 100644 index 0000000000..150e507e4a --- /dev/null +++ b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/SentinelParamResource.java @@ -0,0 +1,22 @@ +package com.nepxion.discovery.plugin.admincenter.resource; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.List; + +import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowRule; + +public interface SentinelParamResource { + void updateParamFlowRules(String rule); + + void clearParamFlowRules(); + + List viewParamFlowRules(); +} \ No newline at end of file diff --git a/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/SentinelParamResourceImpl.java b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/SentinelParamResourceImpl.java new file mode 100644 index 0000000000..5514e7b790 --- /dev/null +++ b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/SentinelParamResourceImpl.java @@ -0,0 +1,54 @@ +package com.nepxion.discovery.plugin.admincenter.resource; + +import java.util.ArrayList; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.List; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.alibaba.csp.sentinel.datasource.Converter; +import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowRule; +import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowRuleManager; +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.TypeReference; + +public class SentinelParamResourceImpl implements SentinelParamResource { + private static final Logger LOG = LoggerFactory.getLogger(SentinelParamResourceImpl.class); + + private static Converter> sentinelParamFlowRuleParser = new Converter>() { + @Override + public List convert(String source) { + return JSON.parseObject(source, new TypeReference>() { + }); + } + }; + + @Override + public void updateParamFlowRules(String rule) { + ParamFlowRuleManager.loadRules(sentinelParamFlowRuleParser.convert(rule)); + + LOG.info("{} param flow rules loaded...", ParamFlowRuleManager.getRules().size()); + } + + @Override + public void clearParamFlowRules() { + LOG.info("{} param flow rules cleared...", ParamFlowRuleManager.getRules().size()); + + ParamFlowRuleManager.loadRules(new ArrayList()); + } + + @Override + public List viewParamFlowRules() { + return ParamFlowRuleManager.getRules(); + } +} \ No newline at end of file diff --git a/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/ServiceResource.java b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/ServiceResource.java new file mode 100644 index 0000000000..0f170c59ee --- /dev/null +++ b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/ServiceResource.java @@ -0,0 +1,49 @@ +package com.nepxion.discovery.plugin.admincenter.resource; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.List; +import java.util.Map; + +import org.springframework.cloud.client.ServiceInstance; + +import com.nepxion.discovery.common.entity.DiscoveryType; +import com.nepxion.discovery.common.entity.GatewayType; +import com.nepxion.discovery.common.entity.InstanceEntity; +import com.nepxion.discovery.common.entity.MetadataParameter; +import com.nepxion.discovery.common.entity.ServiceType; + +public interface ServiceResource { + DiscoveryType getDiscoveryType(); + + List getGroups(); + + String getGroup(String serviceId); + + List getServices(); + + List getServiceList(List serviceTypes); + + List getServiceList(String group, List serviceTypes); + + List getGateways(); + + List getGatewayList(List gatewayTypes); + + List getInstances(String serviceId); + + List getInstanceList(String serviceId); + + Map> getInstanceMap(List groups); + + Map> getMetadataMap(String metadataKey, List serviceIds); + + Map> getMetadataMap(MetadataParameter metadataParameter); +} \ No newline at end of file diff --git a/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/ServiceResourceImpl.java b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/ServiceResourceImpl.java new file mode 100644 index 0000000000..ab2e975356 --- /dev/null +++ b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/ServiceResourceImpl.java @@ -0,0 +1,373 @@ +package com.nepxion.discovery.plugin.admincenter.resource; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import org.apache.commons.collections4.CollectionUtils; +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cloud.client.ServiceInstance; +import org.springframework.cloud.client.discovery.DiscoveryClient; +import org.springframework.cloud.client.discovery.composite.CompositeDiscoveryClient; + +import com.nepxion.discovery.common.constant.DiscoveryConstant; +import com.nepxion.discovery.common.delegate.DiscoveryClientDelegate; +import com.nepxion.discovery.common.entity.DiscoveryType; +import com.nepxion.discovery.common.entity.GatewayType; +import com.nepxion.discovery.common.entity.InstanceEntity; +import com.nepxion.discovery.common.entity.InstanceEntityWrapper; +import com.nepxion.discovery.common.entity.MetadataParameter; +import com.nepxion.discovery.common.entity.ServiceType; + +public class ServiceResourceImpl implements ServiceResource { + @Autowired + private DiscoveryClient discoveryClient; + + @SuppressWarnings("unchecked") + @Override + public DiscoveryType getDiscoveryType() { + DiscoveryClient delegatedDiscoveryClient = null; + if (discoveryClient instanceof DiscoveryClientDelegate) { + delegatedDiscoveryClient = ((DiscoveryClientDelegate) discoveryClient).getDelegate(); + } else { + delegatedDiscoveryClient = discoveryClient; + } + + if (delegatedDiscoveryClient instanceof CompositeDiscoveryClient) { + CompositeDiscoveryClient compositeDiscoveryClient = (CompositeDiscoveryClient) delegatedDiscoveryClient; + List discoveryClients = compositeDiscoveryClient.getDiscoveryClients(); + for (DiscoveryClient client : discoveryClients) { + String discoveryDescription = client.description(); + DiscoveryType[] discoveryTypes = DiscoveryType.values(); + for (int i = 0; i < discoveryTypes.length; i++) { + DiscoveryType discoveryType = discoveryTypes[i]; + if (discoveryDescription.toLowerCase().contains(discoveryType.toString().toLowerCase())) { + return discoveryType; + } + } + } + } else { + String discoveryDescription = delegatedDiscoveryClient.description(); + DiscoveryType[] discoveryTypes = DiscoveryType.values(); + for (int i = 0; i < discoveryTypes.length; i++) { + DiscoveryType discoveryType = discoveryTypes[i]; + if (discoveryDescription.toLowerCase().contains(discoveryType.toString().toLowerCase())) { + return discoveryType; + } + } + } + + return null; + } + + @Override + public List getGroups() { + List groupList = new ArrayList(); + + List services = getServices(); + for (String service : services) { + List instanceEntityList = getInstanceList(service); + for (InstanceEntity instance : instanceEntityList) { + String group = instance.getGroup(); + if (!groupList.contains(group)) { + groupList.add(group); + } + } + } + + groupList.sort(String::compareTo); + + return groupList; + } + + @Override + public String getGroup(String serviceId) { + List instanceEntityList = getInstanceList(serviceId); + for (InstanceEntity instance : instanceEntityList) { + String group = instance.getGroup(); + if (StringUtils.isNotEmpty(group)) { + return group; + } + } + + return null; + } + + @Override + public List getServices() { + List serviceList = discoveryClient.getServices(); + + serviceList.sort(String::compareTo); + + return serviceList; + } + + @Override + public List getServiceList(List types) { + List serviceList = new ArrayList(); + List services = getServices(); + for (String service : services) { + List instances = getInstances(service); + for (ServiceInstance instance : instances) { + Map metadata = instance.getMetadata(); + String serviceId = instance.getServiceId().toLowerCase(); + String serviceType = InstanceEntityWrapper.getServiceType(metadata); + for (ServiceType type : types) { + if (StringUtils.equals(serviceType, type.toString())) { + if (!serviceList.contains(serviceId)) { + serviceList.add(serviceId); + } + } + } + } + } + + return serviceList; + } + + @Override + public List getServiceList(String group, List types) { + List serviceList = new ArrayList(); + List services = getServices(); + for (String service : services) { + List instances = getInstances(service); + for (ServiceInstance instance : instances) { + Map metadata = instance.getMetadata(); + String serviceGroup = InstanceEntityWrapper.getGroup(metadata); + if (StringUtils.equals(serviceGroup, group)) { + String serviceId = instance.getServiceId().toLowerCase(); + String serviceType = InstanceEntityWrapper.getServiceType(metadata); + for (ServiceType type : types) { + if (StringUtils.equals(serviceType, type.toString())) { + if (!serviceList.contains(serviceId)) { + serviceList.add(serviceId); + } + } + } + } + } + } + + return serviceList; + } + + @Override + public List getGateways() { + List gatewayList = new ArrayList(); + List services = getServices(); + for (String service : services) { + List instances = getInstances(service); + for (ServiceInstance instance : instances) { + Map metadata = instance.getMetadata(); + String serviceId = instance.getServiceId().toLowerCase(); + String serviceType = InstanceEntityWrapper.getServiceType(metadata); + if (StringUtils.equals(serviceType, ServiceType.GATEWAY.toString())) { + if (!gatewayList.contains(serviceId)) { + gatewayList.add(serviceId); + } + } + } + } + + return gatewayList; + } + + @Override + public List getGatewayList(List types) { + List gatewayList = new ArrayList(); + List services = getServices(); + for (String service : services) { + List instances = getInstances(service); + for (ServiceInstance instance : instances) { + Map metadata = instance.getMetadata(); + String serviceId = instance.getServiceId().toLowerCase(); + String serviceType = InstanceEntityWrapper.getServiceType(metadata); + String gatewayType = InstanceEntityWrapper.getGatewayType(metadata); + if (StringUtils.equals(serviceType, ServiceType.GATEWAY.toString())) { + for (GatewayType type : types) { + if (StringUtils.equals(gatewayType, type.toString())) { + if (!gatewayList.contains(serviceId)) { + gatewayList.add(serviceId); + } + } + } + } + } + } + + return gatewayList; + } + + @Override + public List getInstances(String serviceId) { + List instanceList = discoveryClient.getInstances(serviceId); + + // instanceList.sort(Comparator.comparing(ServiceInstance::getHost).thenComparing(ServiceInstance::getPort)); + instanceList.sort(Comparator.nullsLast(Comparator.comparing(ServiceInstance::getHost, Comparator.nullsLast(String::compareTo))).thenComparing(ServiceInstance::getPort)); + + return instanceList; + } + + @Override + public List getInstanceList(String service) { + List instances = getInstances(service); + List instanceEntityList = new ArrayList(instances.size()); + for (ServiceInstance instance : instances) { + Map metadata = instance.getMetadata(); + String plugin = InstanceEntityWrapper.getPlugin(metadata); + String group = InstanceEntityWrapper.getGroup(metadata); + String serviceType = InstanceEntityWrapper.getServiceType(metadata); + String serviceId = instance.getServiceId().toLowerCase(); + String serviceAppId = InstanceEntityWrapper.getServiceAppId(metadata); + String serviceUUId = InstanceEntityWrapper.getServiceUUId(metadata); + String version = InstanceEntityWrapper.getVersion(metadata); + String region = InstanceEntityWrapper.getRegion(metadata); + String environment = InstanceEntityWrapper.getEnvironment(metadata); + String zone = InstanceEntityWrapper.getZone(metadata); + boolean active = InstanceEntityWrapper.isActive(metadata); + String protocol = InstanceEntityWrapper.getProtocol(metadata); + String contextPath = InstanceEntityWrapper.getContextPath(metadata); + String formatContextPath = InstanceEntityWrapper.getFormatContextPath(metadata); + String host = instance.getHost(); + int port = instance.getPort(); + + InstanceEntity instanceEntity = new InstanceEntity(); + instanceEntity.setPlugin(plugin); + instanceEntity.setGroup(group); + instanceEntity.setServiceType(serviceType); + instanceEntity.setServiceId(serviceId); + instanceEntity.setServiceAppId(serviceAppId); + instanceEntity.setServiceUUId(serviceUUId); + instanceEntity.setVersion(version); + instanceEntity.setRegion(region); + instanceEntity.setEnvironment(environment); + instanceEntity.setZone(zone); + instanceEntity.setActive(active); + instanceEntity.setProtocol(protocol); + instanceEntity.setContextPath(contextPath); + instanceEntity.setFormatContextPath(formatContextPath); + instanceEntity.setHost(host); + instanceEntity.setPort(port); + instanceEntity.setMetadata(metadata); + + instanceEntityList.add(instanceEntity); + } + + return instanceEntityList; + } + + @Override + public Map> getInstanceMap(List groups) { + List services = getServices(); + Map> instanceMap = new LinkedHashMap>(services.size()); + for (String service : services) { + List instanceEntityList = getInstanceList(service); + if (CollectionUtils.isNotEmpty(groups)) { + for (InstanceEntity instance : instanceEntityList) { + String group = instance.getGroup(); + if (groups.contains(group)) { + List instanceList = instanceMap.get(service); + if (instanceList == null) { + instanceList = new ArrayList(); + instanceMap.put(service, instanceList); + } + instanceList.add(instance); + } + } + } else { + instanceMap.put(service, instanceEntityList); + } + } + + return instanceMap; + } + + @Override + public Map> getMetadataMap(String metadataKey, List serviceIds) { + Map> metadataMap = new LinkedHashMap>(serviceIds.size()); + for (String serviceId : serviceIds) { + List instanceEntityList = getInstanceList(serviceId); + for (InstanceEntity instance : instanceEntityList) { + List metadataList = metadataMap.get(serviceId); + if (metadataList == null) { + metadataList = new ArrayList(); + metadataMap.put(serviceId, metadataList); + } + String metadataValue = null; + if (StringUtils.equals(metadataKey, DiscoveryConstant.HOST + ":" + DiscoveryConstant.PORT)) { + metadataValue = instance.getHost() + ":" + instance.getPort(); + } else if (StringUtils.equals(metadataKey, DiscoveryConstant.HOST)) { + metadataValue = instance.getHost(); + } else if (StringUtils.equals(metadataKey, DiscoveryConstant.PORT)) { + metadataValue = String.valueOf(instance.getPort()); + } else { + metadataValue = instance.getMetadata().get(metadataKey); + } + if (!metadataList.contains(metadataValue)) { + if (StringUtils.isNotEmpty(metadataValue)) { + metadataList.add(metadataValue); + } + } + } + } + + return metadataMap; + } + + @Override + public Map> getMetadataMap(MetadataParameter metadataParameter) { + List metadataKeys = metadataParameter.getMetadataKeys(); + List serviceIds = metadataParameter.getServiceIds(); + String separate = metadataParameter.getSeparate(); + Map> metadataMap = new LinkedHashMap>(serviceIds.size()); + for (String serviceId : serviceIds) { + List instanceEntityList = getInstanceList(serviceId); + for (InstanceEntity instance : instanceEntityList) { + List metadataList = metadataMap.get(serviceId); + if (metadataList == null) { + metadataList = new ArrayList(); + metadataMap.put(serviceId, metadataList); + } + StringBuilder stringBuilder = new StringBuilder(); + int index = 0; + for (String metadataKey : metadataKeys) { + if (StringUtils.equals(metadataKey, DiscoveryConstant.HOST + ":" + DiscoveryConstant.PORT)) { + stringBuilder.append(instance.getHost() + ":" + instance.getPort()); + } else if (StringUtils.equals(metadataKey, DiscoveryConstant.HOST)) { + stringBuilder.append(instance.getHost()); + } else if (StringUtils.equals(metadataKey, DiscoveryConstant.PORT)) { + stringBuilder.append(instance.getPort()); + } else { + stringBuilder.append(instance.getMetadata().get(metadataKey)); + } + if (index < metadataKeys.size() - 1) { + stringBuilder.append(separate); + } + + index++; + } + + String metadataValues = stringBuilder.toString(); + if (!metadataList.contains(metadataValues)) { + if (StringUtils.isNotEmpty(metadataValues)) { + metadataList.add(metadataValues); + } + } + } + } + + return metadataMap; + } +} \ No newline at end of file diff --git a/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/StrategyResource.java b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/StrategyResource.java new file mode 100644 index 0000000000..9447d151fa --- /dev/null +++ b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/StrategyResource.java @@ -0,0 +1,16 @@ +package com.nepxion.discovery.plugin.admincenter.resource; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +public interface StrategyResource { + boolean validateExpression(String expression, String validation); + + String validateRoute(String routeType, String validation); +} \ No newline at end of file diff --git a/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/StrategyResourceImpl.java b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/StrategyResourceImpl.java new file mode 100644 index 0000000000..d8d9e32e6d --- /dev/null +++ b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/StrategyResourceImpl.java @@ -0,0 +1,97 @@ +package com.nepxion.discovery.plugin.admincenter.resource; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.Map; + +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; + +import com.nepxion.discovery.common.entity.StrategyConditionEntity; +import com.nepxion.discovery.common.entity.StrategyRouteType; +import com.nepxion.discovery.common.exception.DiscoveryException; +import com.nepxion.discovery.common.util.StringUtil; +import com.nepxion.discovery.plugin.admincenter.constant.AdminConstant; +import com.nepxion.discovery.plugin.strategy.condition.StrategyCondition; +import com.nepxion.discovery.plugin.strategy.wrapper.StrategyWrapper; + +public class StrategyResourceImpl implements StrategyResource { + @Autowired + private StrategyCondition strategyCondition; + + @Autowired + private StrategyWrapper strategyWrapper; + + @Value("${" + AdminConstant.SPRING_APPLICATION_ADMIN_STRATEGY_ENDPOINT_VALIDATE_EXPRESSION_ENABLED + ":true}") + private Boolean validateExpressionEnabled; + + @Override + public boolean validateExpression(String expression, String validation) { + if (!validateExpressionEnabled) { + throw new DiscoveryException("Strategy endpoint for validate-expression is disabled"); + } + + StrategyConditionEntity strategyConditionEntity = new StrategyConditionEntity(); + strategyConditionEntity.setExpression(expression); + + Map map = null; + try { + map = StringUtil.splitToMap(validation); + } catch (Exception e) { + throw new DiscoveryException("Invalid format for validation input"); + } + + return strategyCondition.isTriggered(strategyConditionEntity, map); + } + + @Override + public String validateRoute(String routeType, String validation) { + StrategyRouteType strategyRouteType = StrategyRouteType.fromString(routeType); + + Map map = null; + try { + map = StringUtil.splitToMap(validation); + } catch (Exception e) { + throw new DiscoveryException("Invalid format for validation input"); + } + + String route = null; + switch (strategyRouteType) { + case VERSION: + route = strategyWrapper.getRouteVersion(map); + break; + case REGION: + route = strategyWrapper.getRouteRegion(map); + break; + case ADDRESS: + route = strategyWrapper.getRouteAddress(map); + break; + case VERSION_WEIGHT: + route = strategyWrapper.getRouteVersionWeight(map); + break; + case REGION_WEIGHT: + route = strategyWrapper.getRouteRegionWeight(map); + break; + case ID_BLACKLIST: + route = strategyWrapper.getRouteIdBlacklist(); + break; + case ADDRESS_BLACKLIST: + route = strategyWrapper.getRouteAddressBlacklist(); + break; + } + + if (StringUtils.isEmpty(route)) { + throw new DiscoveryException("Not found any " + routeType + " routes"); + } + + return route; + } +} \ No newline at end of file diff --git a/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/VersionResource.java b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/VersionResource.java new file mode 100644 index 0000000000..ff30cf570e --- /dev/null +++ b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/VersionResource.java @@ -0,0 +1,20 @@ +package com.nepxion.discovery.plugin.admincenter.resource; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.List; + +public interface VersionResource { + void update(String version, boolean async); + + void clear(String version, boolean async); + + List view(); +} \ No newline at end of file diff --git a/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/VersionResourceImpl.java b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/VersionResourceImpl.java new file mode 100644 index 0000000000..6faa91db7e --- /dev/null +++ b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/VersionResourceImpl.java @@ -0,0 +1,75 @@ +package com.nepxion.discovery.plugin.admincenter.resource; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.ArrayList; +import java.util.List; + +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; + +import com.nepxion.discovery.common.constant.DiscoveryConstant; +import com.nepxion.discovery.common.exception.DiscoveryException; +import com.nepxion.discovery.plugin.framework.adapter.PluginAdapter; +import com.nepxion.discovery.plugin.framework.event.PluginEventWapper; +import com.nepxion.discovery.plugin.framework.event.VersionClearedEvent; +import com.nepxion.discovery.plugin.framework.event.VersionUpdatedEvent; + +public class VersionResourceImpl implements VersionResource { + @Autowired + private PluginAdapter pluginAdapter; + + @Autowired + private PluginEventWapper pluginEventWapper; + + @Override + public void update(String version, boolean async) { + if (StringUtils.isEmpty(version)) { + throw new DiscoveryException("Version can't be null or empty"); + } + + String dynamicVersion = null; + String localVersion = null; + String[] versionArray = StringUtils.split(version, DiscoveryConstant.SEPARATE); + if (versionArray.length == 2) { + dynamicVersion = versionArray[0]; + localVersion = versionArray[1]; + } else if (versionArray.length == 1) { + dynamicVersion = versionArray[0]; + } else { + throw new DiscoveryException("Invalid version format, it must be '${dynamicVersion}' or '${dynamicVersion};${localVersion}'"); + } + + pluginEventWapper.fireVersionUpdated(new VersionUpdatedEvent(dynamicVersion, localVersion), async); + } + + @Override + public void clear(String version, boolean async) { + // 修复Swagger的一个Bug,当在Swagger界面不输入版本号的时候,传到后端变成了“{}” + if (StringUtils.isNotEmpty(version) && StringUtils.equals(version.trim(), "{}")) { + version = null; + } + + pluginEventWapper.fireVersionCleared(new VersionClearedEvent(version), async); + } + + @Override + public List view() { + List versionList = new ArrayList(2); + + String localVersion = pluginAdapter.getLocalVersion(); + String dynamicVersion = pluginAdapter.getDynamicVersion(); + + versionList.add(StringUtils.isNotEmpty(localVersion) ? localVersion : StringUtils.EMPTY); + versionList.add(StringUtils.isNotEmpty(dynamicVersion) ? dynamicVersion : StringUtils.EMPTY); + + return versionList; + } +} \ No newline at end of file diff --git a/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/ZuulStrategyRouteResource.java b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/ZuulStrategyRouteResource.java new file mode 100644 index 0000000000..e8f6b689da --- /dev/null +++ b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/ZuulStrategyRouteResource.java @@ -0,0 +1,30 @@ +package com.nepxion.discovery.plugin.admincenter.resource; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.List; + +import com.nepxion.discovery.common.entity.ZuulStrategyRouteEntity; + +public interface ZuulStrategyRouteResource { + void add(ZuulStrategyRouteEntity zuulStrategyRouteEntity); + + void modify(ZuulStrategyRouteEntity zuulStrategyRouteEntity); + + void delete(String routeId); + + void updateAll(List zuulStrategyRouteEntityList); + + void updateAll(String zuulStrategyRouteConfig); + + ZuulStrategyRouteEntity view(String routeId); + + List viewAll(); +} \ No newline at end of file diff --git a/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/ZuulStrategyRouteResourceImpl.java b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/ZuulStrategyRouteResourceImpl.java new file mode 100644 index 0000000000..54b9aebc8c --- /dev/null +++ b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/ZuulStrategyRouteResourceImpl.java @@ -0,0 +1,57 @@ +package com.nepxion.discovery.plugin.admincenter.resource; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; + +import com.nepxion.discovery.common.entity.ZuulStrategyRouteEntity; +import com.nepxion.discovery.plugin.strategy.zuul.route.ZuulStrategyRoute; + +public class ZuulStrategyRouteResourceImpl implements ZuulStrategyRouteResource { + @Autowired + private ZuulStrategyRoute zuulStrategyRoute; + + @Override + public void add(ZuulStrategyRouteEntity zuulStrategyRouteEntity) { + zuulStrategyRoute.add(zuulStrategyRouteEntity); + } + + @Override + public void modify(ZuulStrategyRouteEntity zuulStrategyRouteEntity) { + zuulStrategyRoute.modify(zuulStrategyRouteEntity); + } + + @Override + public void delete(String routeId) { + zuulStrategyRoute.delete(routeId); + } + + @Override + public void updateAll(List zuulStrategyRouteEntityList) { + zuulStrategyRoute.updateAll(zuulStrategyRouteEntityList); + } + + @Override + public void updateAll(String zuulStrategyRouteConfig) { + zuulStrategyRoute.updateAll(zuulStrategyRouteConfig); + } + + @Override + public ZuulStrategyRouteEntity view(String routeId) { + return zuulStrategyRoute.view(routeId); + } + + @Override + public List viewAll() { + return zuulStrategyRoute.viewAll(); + } +} \ No newline at end of file diff --git a/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/resources/META-INF/additional-spring-configuration-metadata.json b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/resources/META-INF/additional-spring-configuration-metadata.json new file mode 100644 index 0000000000..e0188d9a44 --- /dev/null +++ b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/resources/META-INF/additional-spring-configuration-metadata.json @@ -0,0 +1,70 @@ +{ + "properties": [ + { + "name": "spring.application.admin.service.endpoint.enabled", + "type": "java.lang.Boolean", + "defaultValue": true, + "description": "Whether admin service endpoint is enabled." + }, + { + "name": "spring.application.admin.config.endpoint.enabled", + "type": "java.lang.Boolean", + "defaultValue": true, + "description": "Whether admin config endpoint is enabled." + }, + { + "name": "spring.application.admin.version.endpoint.enabled", + "type": "java.lang.Boolean", + "defaultValue": true, + "description": "Whether admin version endpoint is enabled." + }, + { + "name": "spring.application.admin.inspector.endpoint.enabled", + "type": "java.lang.Boolean", + "defaultValue": true, + "description": "Whether admin inspector endpoint is enabled." + }, + { + "name": "spring.application.admin.router.endpoint.enabled", + "type": "java.lang.Boolean", + "defaultValue": true, + "description": "Whether admin router endpoint is enabled." + }, + { + "name": "spring.application.admin.strategy.endpoint.enabled", + "type": "java.lang.Boolean", + "defaultValue": true, + "description": "Whether admin strategy endpoint is enabled." + }, + { + "name": "spring.application.admin.sentinel.endpoint.enabled", + "type": "java.lang.Boolean", + "defaultValue": true, + "description": "Whether admin sentinel endpoint is enabled." + }, + { + "name": "spring.application.admin.git.endpoint.enabled", + "type": "java.lang.Boolean", + "defaultValue": true, + "description": "Whether admin git endpoint is enabled." + }, + { + "name": "spring.application.admin.gateway.endpoint.enabled", + "type": "java.lang.Boolean", + "defaultValue": true, + "description": "Whether admin gateway endpoint is enabled." + }, + { + "name": "spring.application.admin.zuul.endpoint.enabled", + "type": "java.lang.Boolean", + "defaultValue": true, + "description": "Whether admin zuul endpoint is enabled." + }, + { + "name": "spring.application.admin.strategy.endpoint.validate-expression.enabled", + "type": "java.lang.Boolean", + "defaultValue": true, + "description": "Whether admin strategy endpoint for validate-expression is enabled." + } + ] +} \ No newline at end of file diff --git a/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/resources/META-INF/spring.factories b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/resources/META-INF/spring.factories new file mode 100644 index 0000000000..d60b8e3ee2 --- /dev/null +++ b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/resources/META-INF/spring.factories @@ -0,0 +1,2 @@ +org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ +com.nepxion.discovery.plugin.admincenter.configuration.AdminAutoConfiguration \ No newline at end of file diff --git a/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/pom.xml b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/pom.xml new file mode 100644 index 0000000000..4a9ff759a4 --- /dev/null +++ b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/pom.xml @@ -0,0 +1,42 @@ + + + discovery-plugin-admin-center-starter + Nepxion Discovery Plugin Admin Center Starter + jar + 4.0.0 + Nepxion Discovery is a solution for Spring Cloud with blue green, gray, weight, limitation, circuit breaker, degrade, isolation, monitor, tracing, dye, failover, async agent + http://www.nepxion.com + + + com.nepxion + discovery-plugin-admin-center + 6.23.0 + + + + + ${project.groupId} + discovery-plugin-strategy-starter-gateway + provided + + + + ${project.groupId} + discovery-plugin-strategy-starter-zuul + provided + + + + com.alibaba.csp + sentinel-parameter-flow-control + provided + + + + com.alibaba.csp + sentinel-transport-simple-http + provided + + + \ No newline at end of file diff --git a/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/configuration/AdminAutoConfiguration.java b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/configuration/AdminAutoConfiguration.java new file mode 100644 index 0000000000..63ed3d62b3 --- /dev/null +++ b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/configuration/AdminAutoConfiguration.java @@ -0,0 +1,225 @@ +package com.nepxion.discovery.plugin.admincenter.configuration; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @author Ning Zhang + * @version 1.0 + */ + +import org.springframework.boot.autoconfigure.AutoConfigureOrder; +import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.Ordered; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +import com.alibaba.csp.sentinel.slots.block.flow.FlowRule; +import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowRule; +import com.nepxion.discovery.plugin.admincenter.constant.AdminConstant; +import com.nepxion.discovery.plugin.admincenter.endpoint.ConfigEndpoint; +import com.nepxion.discovery.plugin.admincenter.endpoint.GatewayStrategyRouteEndpoint; +import com.nepxion.discovery.plugin.admincenter.endpoint.GitEndpoint; +import com.nepxion.discovery.plugin.admincenter.endpoint.InspectorEndpoint; +import com.nepxion.discovery.plugin.admincenter.endpoint.RouterEndpoint; +import com.nepxion.discovery.plugin.admincenter.endpoint.SentinelCoreEndpoint; +import com.nepxion.discovery.plugin.admincenter.endpoint.SentinelParamEndpoint; +import com.nepxion.discovery.plugin.admincenter.endpoint.ServiceEndpoint; +import com.nepxion.discovery.plugin.admincenter.endpoint.StrategyEndpoint; +import com.nepxion.discovery.plugin.admincenter.endpoint.VersionEndpoint; +import com.nepxion.discovery.plugin.admincenter.endpoint.ZuulStrategyRouteEndpoint; +import com.nepxion.discovery.plugin.admincenter.resource.ConfigResource; +import com.nepxion.discovery.plugin.admincenter.resource.ConfigResourceImpl; +import com.nepxion.discovery.plugin.admincenter.resource.GatewayStrategyRouteResource; +import com.nepxion.discovery.plugin.admincenter.resource.GatewayStrategyRouteResourceImpl; +import com.nepxion.discovery.plugin.admincenter.resource.GitResource; +import com.nepxion.discovery.plugin.admincenter.resource.GitResourceImpl; +import com.nepxion.discovery.plugin.admincenter.resource.InspectorResource; +import com.nepxion.discovery.plugin.admincenter.resource.InspectorResourceImpl; +import com.nepxion.discovery.plugin.admincenter.resource.RouterResource; +import com.nepxion.discovery.plugin.admincenter.resource.RouterResourceImpl; +import com.nepxion.discovery.plugin.admincenter.resource.SentinelCoreResource; +import com.nepxion.discovery.plugin.admincenter.resource.SentinelCoreResourceImpl; +import com.nepxion.discovery.plugin.admincenter.resource.SentinelParamResource; +import com.nepxion.discovery.plugin.admincenter.resource.SentinelParamResourceImpl; +import com.nepxion.discovery.plugin.admincenter.resource.ServiceResource; +import com.nepxion.discovery.plugin.admincenter.resource.ServiceResourceImpl; +import com.nepxion.discovery.plugin.admincenter.resource.StrategyResource; +import com.nepxion.discovery.plugin.admincenter.resource.StrategyResourceImpl; +import com.nepxion.discovery.plugin.admincenter.resource.VersionResource; +import com.nepxion.discovery.plugin.admincenter.resource.VersionResourceImpl; +import com.nepxion.discovery.plugin.admincenter.resource.ZuulStrategyRouteResource; +import com.nepxion.discovery.plugin.admincenter.resource.ZuulStrategyRouteResourceImpl; +import com.nepxion.discovery.plugin.framework.generator.GitGenerator; +import com.nepxion.discovery.plugin.strategy.gateway.route.GatewayStrategyRoute; +import com.nepxion.discovery.plugin.strategy.wrapper.StrategyWrapper; +import com.nepxion.discovery.plugin.strategy.zuul.route.ZuulStrategyRoute; + +@Configuration +@AutoConfigureOrder(Ordered.LOWEST_PRECEDENCE) +public class AdminAutoConfiguration { + @ConditionalOnProperty(value = AdminConstant.SPRING_APPLICATION_ADMIN_SERVICE_ENDPOINT_ENABLED, matchIfMissing = true) + protected static class ServiceEndpointConfiguration { + @Bean + public ServiceResource serviceResource() { + return new ServiceResourceImpl(); + } + + @Bean + public ServiceEndpoint serviceEndpoint() { + return new ServiceEndpoint(); + } + } + + @ConditionalOnProperty(value = AdminConstant.SPRING_APPLICATION_ADMIN_CONFIG_ENDPOINT_ENABLED, matchIfMissing = true) + protected static class ConfigEndpointConfiguration { + @Bean + public ConfigResource configResource() { + return new ConfigResourceImpl(); + } + + @Bean + public ConfigEndpoint configEndpoint() { + return new ConfigEndpoint(); + } + } + + @ConditionalOnProperty(value = AdminConstant.SPRING_APPLICATION_ADMIN_VERSION_ENDPOINT_ENABLED, matchIfMissing = true) + protected static class VersionEndpointConfiguration { + @Bean + public VersionResource versionResource() { + return new VersionResourceImpl(); + } + + @Bean + public VersionEndpoint versionEndpoint() { + return new VersionEndpoint(); + } + } + + @ConditionalOnProperty(value = AdminConstant.SPRING_APPLICATION_ADMIN_INSPECTOR_ENDPOINT_ENABLED, matchIfMissing = true) + protected static class InspectorEndpointConfiguration { + @Bean + public InspectorResource inspectorResource() { + return new InspectorResourceImpl(); + } + + @Bean + public InspectorEndpoint inspectorEndpoint() { + return new InspectorEndpoint(); + } + } + + @ConditionalOnProperty(value = AdminConstant.SPRING_APPLICATION_ADMIN_ROUTER_ENDPOINT_ENABLED, matchIfMissing = true) + protected static class RouterEndpointConfiguration { + @Bean + public RouterResource routerResource() { + return new RouterResourceImpl(); + } + + @Bean + public RouterEndpoint routerEndpoint() { + return new RouterEndpoint(); + } + } + + @ConditionalOnClass(StrategyWrapper.class) + @ConditionalOnProperty(value = AdminConstant.SPRING_APPLICATION_ADMIN_STRATEGY_ENDPOINT_ENABLED, matchIfMissing = true) + protected static class StrategyEndpointConfiguration { + @Bean + public StrategyResource strategyResource() { + return new StrategyResourceImpl(); + } + + @Bean + public StrategyEndpoint strategyEndpoint() { + return new StrategyEndpoint(); + } + } + + @ConditionalOnClass(FlowRule.class) + @ConditionalOnProperty(value = AdminConstant.SPRING_APPLICATION_ADMIN_SENTINEL_ENDPOINT_ENABLED, matchIfMissing = true) + protected static class SentinelCoreEndpointConfiguration { + @Bean + public SentinelCoreResource sentinelCoreResource() { + return new SentinelCoreResourceImpl(); + } + + @Bean + public SentinelCoreEndpoint sentinelCoreEndpoint() { + return new SentinelCoreEndpoint(); + } + } + + @ConditionalOnClass(ParamFlowRule.class) + @ConditionalOnProperty(value = AdminConstant.SPRING_APPLICATION_ADMIN_SENTINEL_ENDPOINT_ENABLED, matchIfMissing = true) + protected static class SentinelParamEndpointConfiguration { + @Bean + public SentinelParamResource sentinelParamResource() { + return new SentinelParamResourceImpl(); + } + + @Bean + public SentinelParamEndpoint sentinelParamEndpoint() { + return new SentinelParamEndpoint(); + } + } + + @ConditionalOnBean(GitGenerator.class) + @ConditionalOnProperty(value = AdminConstant.SPRING_APPLICATION_ADMIN_GIT_ENDPOINT_ENABLED, matchIfMissing = true) + protected static class GitEndpointConfiguration { + @Bean + public GitResource gitResource() { + return new GitResourceImpl(); + } + + @Bean + public GitEndpoint gitEndpoint() { + return new GitEndpoint(); + } + } + + @ConditionalOnBean(GatewayStrategyRoute.class) + @ConditionalOnProperty(value = AdminConstant.SPRING_APPLICATION_ADMIN_GATEWAY_ENDPOINT_ENABLED, matchIfMissing = true) + protected static class GatewayStrategyRouteEndpointConfiguration { + @Bean + @ConditionalOnProperty(value = "spring.cloud.gateway.discovery.locator.enabled", havingValue = "false", matchIfMissing = true) + public GatewayStrategyRouteResource gatewayStrategyRouteResource() { + return new GatewayStrategyRouteResourceImpl(); + } + + @Bean + @ConditionalOnProperty(value = "spring.cloud.gateway.discovery.locator.enabled", havingValue = "false", matchIfMissing = true) + public GatewayStrategyRouteEndpoint gatewayStrategyRouteEndpoint() { + return new GatewayStrategyRouteEndpoint(); + } + } + + @ConditionalOnBean(ZuulStrategyRoute.class) + @ConditionalOnProperty(value = AdminConstant.SPRING_APPLICATION_ADMIN_ZUUL_ENDPOINT_ENABLED, matchIfMissing = true) + protected static class ZuulStrategyRouteEndpointConfiguration { + @Bean + public ZuulStrategyRouteResource zuulStrategyRouteResource() { + return new ZuulStrategyRouteResourceImpl(); + } + + @Bean + public ZuulStrategyRouteEndpoint zuulStrategyRouteEndpoint() { + return new ZuulStrategyRouteEndpoint(); + } + } + + @ConditionalOnClass(WebMvcConfigurer.class) + protected static class WebMvcActivationConfiguration { + @Bean + @ConditionalOnProperty(value = "cors.registry.enabled", matchIfMissing = false) + public CorsRegistryConfiguration corsRegistryConfiguration() { + return new CorsRegistryConfiguration(); + } + } +} \ No newline at end of file diff --git a/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/configuration/CorsRegistryConfiguration.java b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/configuration/CorsRegistryConfiguration.java new file mode 100644 index 0000000000..38812aa683 --- /dev/null +++ b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/configuration/CorsRegistryConfiguration.java @@ -0,0 +1,30 @@ +package com.nepxion.discovery.plugin.admincenter.configuration; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.CorsRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +@Configuration +@ConditionalOnClass(WebMvcConfigurer.class) +@ConditionalOnProperty(value = "cors.registry.enabled", matchIfMissing = false) +public class CorsRegistryConfiguration implements WebMvcConfigurer { + // 解决跨域问题 + @Override + public void addCorsMappings(CorsRegistry registry) { + registry.addMapping("/**") + .allowedHeaders("*") + .allowedMethods("*") + .allowedOrigins("*"); + } +} \ No newline at end of file diff --git a/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/constant/AdminConstant.java b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/constant/AdminConstant.java new file mode 100644 index 0000000000..4141c991c8 --- /dev/null +++ b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/constant/AdminConstant.java @@ -0,0 +1,25 @@ +package com.nepxion.discovery.plugin.admincenter.constant; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +public class AdminConstant { + public static final String SPRING_APPLICATION_ADMIN_SERVICE_ENDPOINT_ENABLED = "spring.application.admin.service.endpoint.enabled"; + public static final String SPRING_APPLICATION_ADMIN_CONFIG_ENDPOINT_ENABLED = "spring.application.admin.config.endpoint.enabled"; + public static final String SPRING_APPLICATION_ADMIN_VERSION_ENDPOINT_ENABLED = "spring.application.admin.version.endpoint.enabled"; + public static final String SPRING_APPLICATION_ADMIN_INSPECTOR_ENDPOINT_ENABLED = "spring.application.admin.inspector.endpoint.enabled"; + public static final String SPRING_APPLICATION_ADMIN_ROUTER_ENDPOINT_ENABLED = "spring.application.admin.router.endpoint.enabled"; + public static final String SPRING_APPLICATION_ADMIN_STRATEGY_ENDPOINT_ENABLED = "spring.application.admin.strategy.endpoint.enabled"; + public static final String SPRING_APPLICATION_ADMIN_SENTINEL_ENDPOINT_ENABLED = "spring.application.admin.sentinel.endpoint.enabled"; + public static final String SPRING_APPLICATION_ADMIN_GIT_ENDPOINT_ENABLED = "spring.application.admin.git.endpoint.enabled"; + public static final String SPRING_APPLICATION_ADMIN_GATEWAY_ENDPOINT_ENABLED = "spring.application.admin.gateway.endpoint.enabled"; + public static final String SPRING_APPLICATION_ADMIN_ZUUL_ENDPOINT_ENABLED = "spring.application.admin.zuul.endpoint.enabled"; + + public static final String SPRING_APPLICATION_ADMIN_STRATEGY_ENDPOINT_VALIDATE_EXPRESSION_ENABLED = "spring.application.admin.strategy.endpoint.validate-expression.enabled"; +} \ No newline at end of file diff --git a/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/endpoint/ConfigEndpoint.java b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/endpoint/ConfigEndpoint.java new file mode 100644 index 0000000000..0c61005755 --- /dev/null +++ b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/endpoint/ConfigEndpoint.java @@ -0,0 +1,106 @@ +package com.nepxion.discovery.plugin.admincenter.endpoint; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.RestController; + +import com.nepxion.discovery.common.util.ResponseUtil; +import com.nepxion.discovery.plugin.admincenter.resource.ConfigResource; + +@RestController +@RequestMapping(path = "/config") +public class ConfigEndpoint { + @Autowired + private ConfigResource configResource; + + @RequestMapping(path = "/config-type", method = RequestMethod.GET) + @ResponseBody + public ResponseEntity configType() { + return doConfigType(); + } + + @RequestMapping(path = "/update-async", method = RequestMethod.POST) + @ResponseBody + public ResponseEntity updateAsync(@RequestBody String config) { + return doUpdate(config, true); + } + + @RequestMapping(path = "/update-sync", method = RequestMethod.POST) + @ResponseBody + public ResponseEntity updateSync(@RequestBody String config) { + return doUpdate(config, false); + } + + @RequestMapping(path = "/clear-async", method = RequestMethod.POST) + @ResponseBody + public ResponseEntity clearAsync() { + return doClear(true); + } + + @RequestMapping(path = "/clear-sync", method = RequestMethod.POST) + @ResponseBody + public ResponseEntity clearSync() { + return doClear(false); + } + + @RequestMapping(path = "/view", method = RequestMethod.GET) + @ResponseBody + public ResponseEntity view() { + return doView(); + } + + private ResponseEntity doConfigType() { + try { + String configType = configResource.getConfigType().toString(); + + return ResponseUtil.getSuccessResponse(configType); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doUpdate(String config, boolean async) { + try { + configResource.update(config, async); + + return ResponseUtil.getSuccessResponse(true); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doClear(boolean async) { + try { + configResource.clear(async); + + return ResponseUtil.getSuccessResponse(true); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doView() { + try { + List ruleList = configResource.view(); + + return ResponseUtil.getSuccessResponse(ruleList); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } +} \ No newline at end of file diff --git a/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/endpoint/GatewayStrategyRouteEndpoint.java b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/endpoint/GatewayStrategyRouteEndpoint.java new file mode 100644 index 0000000000..88a8299f31 --- /dev/null +++ b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/endpoint/GatewayStrategyRouteEndpoint.java @@ -0,0 +1,129 @@ +package com.nepxion.discovery.plugin.admincenter.endpoint; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Ning Zhang + * @author Haojun Ren + * @version 1.0 + */ + +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.RestController; + +import com.nepxion.discovery.common.entity.GatewayStrategyRouteEntity; +import com.nepxion.discovery.common.util.ResponseUtil; +import com.nepxion.discovery.plugin.admincenter.resource.GatewayStrategyRouteResource; + +@RestController +@RequestMapping(path = "/spring-cloud-gateway-route") +public class GatewayStrategyRouteEndpoint { + @Autowired + private GatewayStrategyRouteResource gatewayStrategyRouteResource; + + @RequestMapping(path = "/add", method = RequestMethod.POST) + @ResponseBody + public ResponseEntity add(@RequestBody GatewayStrategyRouteEntity gatewayStrategyRouteEntity) { + return doAdd(gatewayStrategyRouteEntity); + } + + @RequestMapping(path = "/modify", method = RequestMethod.POST) + @ResponseBody + public ResponseEntity modify(@RequestBody GatewayStrategyRouteEntity gatewayStrategyRouteEntity) { + return doModify(gatewayStrategyRouteEntity); + } + + @RequestMapping(path = "/delete/{routeId}", method = RequestMethod.DELETE) + @ResponseBody + public ResponseEntity delete(@PathVariable(value = "routeId") String routeId) { + return doDelete(routeId); + } + + @RequestMapping(path = "/update-all", method = RequestMethod.POST) + @ResponseBody + public ResponseEntity updateAll(@RequestBody List gatewayStrategyRouteEntityList) { + return doUpdateAll(gatewayStrategyRouteEntityList); + } + + @RequestMapping(path = "/view/{routeId}", method = RequestMethod.GET) + @ResponseBody + public ResponseEntity view(@PathVariable(value = "routeId") String routeId) { + return doView(routeId); + } + + @RequestMapping(path = "/view-all", method = RequestMethod.GET) + @ResponseBody + public ResponseEntity viewAll() { + return doViewAll(); + } + + private ResponseEntity doAdd(GatewayStrategyRouteEntity gatewayStrategyRouteEntity) { + try { + gatewayStrategyRouteResource.add(gatewayStrategyRouteEntity); + + return ResponseUtil.getSuccessResponse(true); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doModify(GatewayStrategyRouteEntity gatewayStrategyRouteEntity) { + try { + gatewayStrategyRouteResource.modify(gatewayStrategyRouteEntity); + + return ResponseUtil.getSuccessResponse(true); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doDelete(String routeId) { + try { + gatewayStrategyRouteResource.delete(routeId); + + return ResponseUtil.getSuccessResponse(true); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doUpdateAll(List gatewayStrategyRouteEntityList) { + try { + gatewayStrategyRouteResource.updateAll(gatewayStrategyRouteEntityList); + + return ResponseUtil.getSuccessResponse(true); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doView(String routeId) { + try { + GatewayStrategyRouteEntity gatewayStrategyRouteEntity = gatewayStrategyRouteResource.view(routeId); + + return ResponseUtil.getSuccessResponse(gatewayStrategyRouteEntity); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doViewAll() { + try { + List gatewayStrategyRouteEntityList = gatewayStrategyRouteResource.viewAll(); + + return ResponseUtil.getSuccessResponse(gatewayStrategyRouteEntityList); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } +} \ No newline at end of file diff --git a/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/endpoint/GitEndpoint.java b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/endpoint/GitEndpoint.java new file mode 100644 index 0000000000..129bb9bf5e --- /dev/null +++ b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/endpoint/GitEndpoint.java @@ -0,0 +1,61 @@ +package com.nepxion.discovery.plugin.admincenter.endpoint; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.Map; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.RestController; + +import com.nepxion.discovery.common.util.ResponseUtil; +import com.nepxion.discovery.plugin.admincenter.resource.GitResource; + +@RestController +@RequestMapping(path = "/git") +public class GitEndpoint { + @Autowired + private GitResource gitResource; + + @RequestMapping(path = "/map", method = RequestMethod.GET) + @ResponseBody + public ResponseEntity map() { + return doMap(); + } + + @RequestMapping(path = "/text", method = RequestMethod.GET) + @ResponseBody + public ResponseEntity text() { + return doText(); + } + + private ResponseEntity doMap() { + try { + Map map = gitResource.map(); + + return ResponseUtil.getSuccessResponse(map); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doText() { + try { + String text = gitResource.text(); + + return ResponseUtil.getSuccessResponse(text); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } +} \ No newline at end of file diff --git a/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/endpoint/InspectorEndpoint.java b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/endpoint/InspectorEndpoint.java new file mode 100644 index 0000000000..d1fc75a2db --- /dev/null +++ b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/endpoint/InspectorEndpoint.java @@ -0,0 +1,63 @@ +package com.nepxion.discovery.plugin.admincenter.endpoint; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.RestController; + +import com.nepxion.discovery.common.entity.InspectorEntity; +import com.nepxion.discovery.common.util.ResponseUtil; +import com.nepxion.discovery.plugin.admincenter.resource.InspectorResource; + +@RestController +@RequestMapping(path = "/inspector") +public class InspectorEndpoint { + @Autowired + private InspectorResource inspectorResource; + + @RequestMapping(path = "/inspect", method = RequestMethod.POST) + @ResponseBody + public ResponseEntity inspect(@RequestBody InspectorEntity inspectorEntity) { + return doInspect(inspectorEntity); + } + + @RequestMapping(path = "/inspect-service", method = RequestMethod.POST) + @ResponseBody + public ResponseEntity inspect(@RequestBody List service) { + return doInspect(service); + } + + private ResponseEntity doInspect(InspectorEntity inspectorEntity) { + try { + InspectorEntity result = inspectorResource.inspect(inspectorEntity); + + return ResponseUtil.getSuccessResponse(result); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doInspect(List service) { + try { + String result = inspectorResource.inspect(service); + + return ResponseUtil.getSuccessResponse(result); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } +} \ No newline at end of file diff --git a/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/endpoint/RouterEndpoint.java b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/endpoint/RouterEndpoint.java new file mode 100644 index 0000000000..4c9134e27d --- /dev/null +++ b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/endpoint/RouterEndpoint.java @@ -0,0 +1,96 @@ +package com.nepxion.discovery.plugin.admincenter.endpoint; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.RestController; + +import com.nepxion.discovery.common.entity.RouterEntity; +import com.nepxion.discovery.common.util.ResponseUtil; +import com.nepxion.discovery.plugin.admincenter.resource.RouterResource; + +@RestController +@RequestMapping(path = "/router") +public class RouterEndpoint { + @Autowired + private RouterResource routerResource; + + @RequestMapping(path = "/info", method = RequestMethod.GET) + @ResponseBody + public ResponseEntity info() { + return doInfo(); + } + + @RequestMapping(path = "/route/{routeServiceId}", method = RequestMethod.GET) + @ResponseBody + public ResponseEntity route(@PathVariable(value = "routeServiceId") String routeServiceId) { + return doNativeRoute(routeServiceId); + } + + @RequestMapping(path = "/route/{routeServiceId}/{routeProtocol}/{routeHost}/{routePort}/{routeContextPath}", method = RequestMethod.GET) + @ResponseBody + public ResponseEntity route(@PathVariable(value = "routeServiceId") String routeServiceId, @PathVariable(value = "routeProtocol") String routeProtocol, @PathVariable(value = "routeHost") String routeHost, @PathVariable(value = "routePort") int routePort, @PathVariable(value = "routeContextPath") String routeContextPath) { + return doRemoteRoute(routeServiceId, routeProtocol, routeHost, routePort, routeContextPath); + } + + @RequestMapping(path = "/routes", method = RequestMethod.POST) + @ResponseBody + public ResponseEntity routes(@RequestBody String routeServiceIds) { + return doRoutes(routeServiceIds); + } + + private ResponseEntity doInfo() { + try { + RouterEntity routerEntity = routerResource.getRouterEntity(); + + return ResponseUtil.getSuccessResponse(routerEntity); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doNativeRoute(String routeServiceId) { + try { + List routerEntityList = routerResource.getRouterEntityList(routeServiceId); + + return ResponseUtil.getSuccessResponse(routerEntityList); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doRemoteRoute(String routeServiceId, String routeProtocol, String routeHost, int routePort, String routeContextPath) { + try { + List routerEntityList = routerResource.getRouterEntityList(routeServiceId, routeProtocol, routeHost, routePort, routeContextPath); + + return ResponseUtil.getSuccessResponse(routerEntityList); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doRoutes(String routeServiceIds) { + try { + RouterEntity routerEntity = routerResource.routeTree(routeServiceIds); + + return ResponseUtil.getSuccessResponse(routerEntity); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } +} \ No newline at end of file diff --git a/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/endpoint/SentinelCoreEndpoint.java b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/endpoint/SentinelCoreEndpoint.java new file mode 100644 index 0000000000..50a271b7f9 --- /dev/null +++ b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/endpoint/SentinelCoreEndpoint.java @@ -0,0 +1,226 @@ +package com.nepxion.discovery.plugin.admincenter.endpoint; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.RestController; + +import com.alibaba.csp.sentinel.slots.block.authority.AuthorityRule; +import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule; +import com.alibaba.csp.sentinel.slots.block.flow.FlowRule; +import com.alibaba.csp.sentinel.slots.system.SystemRule; +import com.nepxion.discovery.common.util.ResponseUtil; +import com.nepxion.discovery.plugin.admincenter.resource.SentinelCoreResource; + +@RestController +@RequestMapping(path = "/sentinel-core") +public class SentinelCoreEndpoint { + @Autowired + private SentinelCoreResource sentinelCoreResource; + + @RequestMapping(path = "/update-flow-rules", method = RequestMethod.POST) + @ResponseBody + public ResponseEntity updateFlowRules(@RequestBody String rule) { + return doUpdateFlowRules(rule); + } + + @RequestMapping(path = "/clear-flow-rules", method = RequestMethod.POST) + @ResponseBody + public ResponseEntity clearFlowRules() { + return doClearFlowRules(); + } + + @RequestMapping(path = "/view-flow-rules", method = RequestMethod.GET) + @ResponseBody + public ResponseEntity viewFlowRules() { + return doViewFlowRules(); + } + + @RequestMapping(path = "/update-degrade-rules", method = RequestMethod.POST) + @ResponseBody + public ResponseEntity updateDegradeRules(@RequestBody String rule) { + return doUpdateDegradeRules(rule); + } + + @RequestMapping(path = "/clear-degrade-rules", method = RequestMethod.POST) + @ResponseBody + public ResponseEntity clearDegradeRules() { + return doClearDegradeRules(); + } + + @RequestMapping(path = "/view-degrade-rules", method = RequestMethod.GET) + @ResponseBody + public ResponseEntity viewDegradeRules() { + return doViewDegradeRules(); + } + + @RequestMapping(path = "/update-authority-rules", method = RequestMethod.POST) + @ResponseBody + public ResponseEntity updateAuthorityRules(@RequestBody String rule) { + return doUpdateAuthorityRules(rule); + } + + @RequestMapping(path = "/clear-authority-rules", method = RequestMethod.POST) + @ResponseBody + public ResponseEntity clearAuthorityRules() { + return doClearAuthorityRules(); + } + + @RequestMapping(path = "/view-authority-rules", method = RequestMethod.GET) + @ResponseBody + public ResponseEntity viewAuthorityRules() { + return doViewAuthorityRules(); + } + + @RequestMapping(path = "/update-system-rules", method = RequestMethod.POST) + @ResponseBody + public ResponseEntity updateSystemRules(@RequestBody String rule) { + return doUpdateSystemRules(rule); + } + + @RequestMapping(path = "/clear-system-rules", method = RequestMethod.POST) + @ResponseBody + public ResponseEntity clearSystemRules() { + return doClearSystemRules(); + } + + @RequestMapping(path = "/view-system-rules", method = RequestMethod.GET) + @ResponseBody + public ResponseEntity viewSystemRules() { + return doViewSystemRules(); + } + + private ResponseEntity doUpdateFlowRules(String rule) { + try { + sentinelCoreResource.updateFlowRules(rule); + + return ResponseUtil.getSuccessResponse(true); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doClearFlowRules() { + try { + sentinelCoreResource.clearFlowRules(); + + return ResponseUtil.getSuccessResponse(true); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doViewFlowRules() { + try { + List flowRules = sentinelCoreResource.viewFlowRules(); + + return ResponseUtil.getSuccessResponse(flowRules); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doUpdateDegradeRules(String rule) { + try { + sentinelCoreResource.updateDegradeRules(rule); + + return ResponseUtil.getSuccessResponse(true); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doClearDegradeRules() { + try { + sentinelCoreResource.clearDegradeRules(); + + return ResponseUtil.getSuccessResponse(true); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doViewDegradeRules() { + try { + List degradeRules = sentinelCoreResource.viewDegradeRules(); + + return ResponseUtil.getSuccessResponse(degradeRules); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doUpdateAuthorityRules(String rule) { + try { + sentinelCoreResource.updateAuthorityRules(rule); + + return ResponseUtil.getSuccessResponse(true); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doClearAuthorityRules() { + try { + sentinelCoreResource.clearAuthorityRules(); + + return ResponseUtil.getSuccessResponse(true); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doViewAuthorityRules() { + try { + List authorityRules = sentinelCoreResource.viewAuthorityRules(); + + return ResponseUtil.getSuccessResponse(authorityRules); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doUpdateSystemRules(String rule) { + try { + sentinelCoreResource.updateSystemRules(rule); + + return ResponseUtil.getSuccessResponse(true); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doClearSystemRules() { + try { + sentinelCoreResource.clearSystemRules(); + + return ResponseUtil.getSuccessResponse(true); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doViewSystemRules() { + try { + List systemRules = sentinelCoreResource.viewSystemRules(); + + return ResponseUtil.getSuccessResponse(systemRules); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } +} \ No newline at end of file diff --git a/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/endpoint/SentinelParamEndpoint.java b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/endpoint/SentinelParamEndpoint.java new file mode 100644 index 0000000000..c1d0236aab --- /dev/null +++ b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/endpoint/SentinelParamEndpoint.java @@ -0,0 +1,79 @@ +package com.nepxion.discovery.plugin.admincenter.endpoint; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.RestController; + +import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowRule; +import com.nepxion.discovery.common.util.ResponseUtil; +import com.nepxion.discovery.plugin.admincenter.resource.SentinelParamResource; + +@RestController +@RequestMapping(path = "/sentinel-param") +public class SentinelParamEndpoint { + @Autowired + private SentinelParamResource sentinelParamResource; + + @RequestMapping(path = "/update-param-flow-rules", method = RequestMethod.POST) + @ResponseBody + public ResponseEntity updateParamFlowRules(@RequestBody String rule) { + return doUpdateParamFlowRules(rule); + } + + @RequestMapping(path = "/clear-param-flow-rules", method = RequestMethod.POST) + @ResponseBody + public ResponseEntity clearParamFlowRules() { + return doClearParamFlowRules(); + } + + @RequestMapping(path = "/view-param-flow-rules", method = RequestMethod.GET) + @ResponseBody + public ResponseEntity viewParamFlowRules() { + return doViewParamFlowRules(); + } + + private ResponseEntity doUpdateParamFlowRules(String rule) { + try { + sentinelParamResource.updateParamFlowRules(rule); + + return ResponseUtil.getSuccessResponse(true); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doClearParamFlowRules() { + try { + sentinelParamResource.clearParamFlowRules(); + + return ResponseUtil.getSuccessResponse(true); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doViewParamFlowRules() { + try { + List paramFlowRules = sentinelParamResource.viewParamFlowRules(); + + return ResponseUtil.getSuccessResponse(paramFlowRules); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } +} \ No newline at end of file diff --git a/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/endpoint/ServiceEndpoint.java b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/endpoint/ServiceEndpoint.java new file mode 100644 index 0000000000..8b6fbbb2b4 --- /dev/null +++ b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/endpoint/ServiceEndpoint.java @@ -0,0 +1,261 @@ +package com.nepxion.discovery.plugin.admincenter.endpoint; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cloud.client.ServiceInstance; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.RestController; + +import com.nepxion.discovery.common.entity.GatewayType; +import com.nepxion.discovery.common.entity.InstanceEntity; +import com.nepxion.discovery.common.entity.MetadataParameter; +import com.nepxion.discovery.common.entity.ServiceType; +import com.nepxion.discovery.common.util.ResponseUtil; +import com.nepxion.discovery.plugin.admincenter.resource.ServiceResource; + +@RestController +@RequestMapping(path = "/service") +public class ServiceEndpoint { + @Autowired + private ServiceResource serviceResource; + + @RequestMapping(path = "/discovery-type", method = RequestMethod.GET) + @ResponseBody + public ResponseEntity discoveryType() { + return doDiscoveryType(); + } + + @RequestMapping(path = "/groups", method = RequestMethod.GET) + @ResponseBody + public ResponseEntity groups() { + return doGroups(); + } + + @RequestMapping(path = "/group/{serviceId}", method = RequestMethod.GET) + @ResponseBody + public ResponseEntity group(@PathVariable(value = "serviceId") String serviceId) { + return doGroup(serviceId); + } + + @RequestMapping(path = "/services", method = RequestMethod.GET) + @ResponseBody + public ResponseEntity services() { + return doServices(); + } + + @RequestMapping(path = "/service-list", method = RequestMethod.POST) + @ResponseBody + public ResponseEntity serviceList(@RequestBody List serviceTypes) { + return doServiceList(serviceTypes); + } + + @RequestMapping(path = "/service-list/{group}", method = RequestMethod.POST) + @ResponseBody + public ResponseEntity serviceList(@PathVariable(value = "group") String group, @RequestBody List serviceTypes) { + return doServiceList(group, serviceTypes); + } + + @RequestMapping(path = "/gateways", method = RequestMethod.GET) + @ResponseBody + public ResponseEntity gateways() { + return doGateways(); + } + + @RequestMapping(path = "/gateway-list", method = RequestMethod.POST) + @ResponseBody + public ResponseEntity gatewayList(@RequestBody List gatewayTypes) { + return doGatewayList(gatewayTypes); + } + + @RequestMapping(path = "/instances/{serviceId}", method = RequestMethod.GET) + @ResponseBody + public ResponseEntity instances(@PathVariable(value = "serviceId") String serviceId) { + return doInstances(serviceId); + } + + @RequestMapping(path = "/instance-list/{serviceId}", method = RequestMethod.GET) + @ResponseBody + public ResponseEntity instanceList(@PathVariable(value = "serviceId") String serviceId) { + return doInstanceList(serviceId); + } + + @RequestMapping(path = "/instance-map", method = RequestMethod.POST) + @ResponseBody + public ResponseEntity instanceMap(@RequestBody List groups) { + return doInstanceMap(groups); + } + + @RequestMapping(path = "/metadata-map/{metadataKey}", method = RequestMethod.POST) + @ResponseBody + public ResponseEntity metadataMap(@PathVariable(value = "metadataKey") String metadataKey, @RequestBody List serviceIds) { + return doMetadataMap(metadataKey, serviceIds); + } + + @RequestMapping(path = "/metadata-map", method = RequestMethod.POST) + @ResponseBody + public ResponseEntity metadataMap(@RequestBody MetadataParameter metadataParameter) { + return doMetadataMap(metadataParameter); + } + + private ResponseEntity doDiscoveryType() { + try { + String discoveryType = serviceResource.getDiscoveryType().toString(); + + return ResponseUtil.getSuccessResponse(discoveryType); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doGroups() { + try { + List groups = serviceResource.getGroups(); + + return ResponseUtil.getSuccessResponse(groups); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doGroup(String serviceId) { + try { + String group = serviceResource.getGroup(serviceId); + + return ResponseUtil.getSuccessResponse(group); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doServices() { + try { + List services = serviceResource.getServices(); + + return ResponseUtil.getSuccessResponse(services); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doServiceList(List serviceTypes) { + try { + List types = new ArrayList(); + for (String serviceType : serviceTypes) { + types.add(ServiceType.fromString(serviceType)); + } + + List services = serviceResource.getServiceList(types); + + return ResponseUtil.getSuccessResponse(services); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doServiceList(String group, List serviceTypes) { + try { + List types = new ArrayList(); + for (String serviceType : serviceTypes) { + types.add(ServiceType.fromString(serviceType)); + } + + List services = serviceResource.getServiceList(group, types); + + return ResponseUtil.getSuccessResponse(services); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doGateways() { + try { + List gateways = serviceResource.getGateways(); + + return ResponseUtil.getSuccessResponse(gateways); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doGatewayList(List gatewayTypes) { + try { + List types = new ArrayList(); + for (String gatewayType : gatewayTypes) { + types.add(GatewayType.fromString(gatewayType)); + } + + List gatewayList = serviceResource.getGatewayList(types); + + return ResponseUtil.getSuccessResponse(gatewayList); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doInstances(String serviceId) { + try { + List instances = serviceResource.getInstances(serviceId); + + return ResponseUtil.getSuccessResponse(instances); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doInstanceList(String serviceId) { + try { + List instanceList = serviceResource.getInstanceList(serviceId); + + return ResponseUtil.getSuccessResponse(instanceList); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doInstanceMap(List groups) { + try { + Map> instanceMaps = serviceResource.getInstanceMap(groups); + + return ResponseUtil.getSuccessResponse(instanceMaps); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doMetadataMap(String metadataKey, List serviceIds) { + try { + Map> metadataMap = serviceResource.getMetadataMap(metadataKey, serviceIds); + + return ResponseUtil.getSuccessResponse(metadataMap); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doMetadataMap(MetadataParameter metadataParameter) { + try { + Map> metadataMap = serviceResource.getMetadataMap(metadataParameter); + + return ResponseUtil.getSuccessResponse(metadataMap); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } +} \ No newline at end of file diff --git a/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/endpoint/StrategyEndpoint.java b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/endpoint/StrategyEndpoint.java new file mode 100644 index 0000000000..db2bccac19 --- /dev/null +++ b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/endpoint/StrategyEndpoint.java @@ -0,0 +1,60 @@ +package com.nepxion.discovery.plugin.admincenter.endpoint; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.RestController; + +import com.nepxion.discovery.common.util.ResponseUtil; +import com.nepxion.discovery.plugin.admincenter.resource.StrategyResource; + +@RestController +@RequestMapping(path = "/strategy") +public class StrategyEndpoint { + @Autowired + private StrategyResource strategyResource; + + @RequestMapping(path = "/validate-expression", method = RequestMethod.GET) + @ResponseBody + public ResponseEntity validateExpression(@RequestParam String expression, @RequestParam(defaultValue = "", required = false) String validation) { + return doValidateExpression(expression, validation); + } + + @RequestMapping(path = "/validate-route", method = RequestMethod.GET) + @ResponseBody + public ResponseEntity validateRoute(@RequestParam String routeType, @RequestParam(defaultValue = "", required = false) String validation) { + return doValidateRoute(routeType, validation); + } + + private ResponseEntity doValidateExpression(String expression, String validation) { + try { + boolean result = strategyResource.validateExpression(expression, validation); + + return ResponseUtil.getSuccessResponse(result); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doValidateRoute(String routeType, String validation) { + try { + String route = strategyResource.validateRoute(routeType, validation); + + return ResponseUtil.getSuccessResponse(route); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } +} \ No newline at end of file diff --git a/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/endpoint/VersionEndpoint.java b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/endpoint/VersionEndpoint.java new file mode 100644 index 0000000000..4b969aecff --- /dev/null +++ b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/endpoint/VersionEndpoint.java @@ -0,0 +1,90 @@ +package com.nepxion.discovery.plugin.admincenter.endpoint; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.RestController; + +import com.nepxion.discovery.common.util.ResponseUtil; +import com.nepxion.discovery.plugin.admincenter.resource.VersionResource; + +@RestController +@RequestMapping(path = "/version") +public class VersionEndpoint { + @Autowired + private VersionResource versionResource; + + @RequestMapping(path = "/update-async", method = RequestMethod.POST) + @ResponseBody + public ResponseEntity updateAsync(@RequestBody String version) { + return doUpdate(version, true); + } + + @RequestMapping(path = "/update-sync", method = RequestMethod.POST) + @ResponseBody + public ResponseEntity updateSync(@RequestBody String version) { + return doUpdate(version, false); + } + + @RequestMapping(path = "/clear-async", method = RequestMethod.POST) + @ResponseBody + public ResponseEntity clearAsync(@RequestBody(required = false) String version) { + return doClear(version, true); + } + + @RequestMapping(path = "/clear-sync", method = RequestMethod.POST) + @ResponseBody + public ResponseEntity clearSync(@RequestBody(required = false) String version) { + return doClear(version, false); + } + + @RequestMapping(path = "/view", method = RequestMethod.GET) + @ResponseBody + public ResponseEntity view() { + return doView(); + } + + private ResponseEntity doUpdate(String version, boolean async) { + try { + versionResource.update(version, async); + + return ResponseUtil.getSuccessResponse(true); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doClear(String version, boolean async) { + try { + versionResource.clear(version, async); + + return ResponseUtil.getSuccessResponse(true); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doView() { + try { + List versionList = versionResource.view(); + + return ResponseUtil.getSuccessResponse(versionList); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } +} \ No newline at end of file diff --git a/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/endpoint/ZuulStrategyRouteEndpoint.java b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/endpoint/ZuulStrategyRouteEndpoint.java new file mode 100644 index 0000000000..7e148b3383 --- /dev/null +++ b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/endpoint/ZuulStrategyRouteEndpoint.java @@ -0,0 +1,129 @@ +package com.nepxion.discovery.plugin.admincenter.endpoint; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Ning Zhang + * @author Haojun Ren + * @version 1.0 + */ + +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.RestController; + +import com.nepxion.discovery.common.entity.ZuulStrategyRouteEntity; +import com.nepxion.discovery.common.util.ResponseUtil; +import com.nepxion.discovery.plugin.admincenter.resource.ZuulStrategyRouteResource; + +@RestController +@RequestMapping(path = "/zuul-route") +public class ZuulStrategyRouteEndpoint { + @Autowired + private ZuulStrategyRouteResource zuulStrategyRouteResource; + + @RequestMapping(path = "/add", method = RequestMethod.POST) + @ResponseBody + public ResponseEntity add(@RequestBody ZuulStrategyRouteEntity zuulStrategyRouteEntity) { + return doAdd(zuulStrategyRouteEntity); + } + + @RequestMapping(path = "/modify", method = RequestMethod.POST) + @ResponseBody + public ResponseEntity modify(@RequestBody ZuulStrategyRouteEntity zuulStrategyRouteEntity) { + return doModify(zuulStrategyRouteEntity); + } + + @RequestMapping(path = "/delete/{routeId}", method = RequestMethod.DELETE) + @ResponseBody + public ResponseEntity delete(@PathVariable(value = "routeId") String routeId) { + return doDelete(routeId); + } + + @RequestMapping(path = "/update-all", method = RequestMethod.POST) + @ResponseBody + public ResponseEntity updateAll(@RequestBody List zuulStrategyRouteEntityList) { + return doUpdateAll(zuulStrategyRouteEntityList); + } + + @RequestMapping(path = "/view/{routeId}", method = RequestMethod.GET) + @ResponseBody + public ResponseEntity view(@PathVariable(value = "routeId") String routeId) { + return doView(routeId); + } + + @RequestMapping(path = "/view-all", method = RequestMethod.GET) + @ResponseBody + public ResponseEntity viewAll() { + return doViewAll(); + } + + private ResponseEntity doAdd(ZuulStrategyRouteEntity zuulStrategyRouteEntity) { + try { + zuulStrategyRouteResource.add(zuulStrategyRouteEntity); + + return ResponseUtil.getSuccessResponse(true); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doModify(ZuulStrategyRouteEntity zuulStrategyRouteEntity) { + try { + zuulStrategyRouteResource.modify(zuulStrategyRouteEntity); + + return ResponseUtil.getSuccessResponse(true); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doDelete(String routeId) { + try { + zuulStrategyRouteResource.delete(routeId); + + return ResponseUtil.getSuccessResponse(true); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doUpdateAll(List zuulStrategyRouteEntityList) { + try { + zuulStrategyRouteResource.updateAll(zuulStrategyRouteEntityList); + + return ResponseUtil.getSuccessResponse(true); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doView(String routeId) { + try { + ZuulStrategyRouteEntity zuulStrategyRouteEntity = zuulStrategyRouteResource.view(routeId); + + return ResponseUtil.getSuccessResponse(zuulStrategyRouteEntity); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } + + private ResponseEntity doViewAll() { + try { + List zuulStrategyRouteEntityList = zuulStrategyRouteResource.viewAll(); + + return ResponseUtil.getSuccessResponse(zuulStrategyRouteEntityList); + } catch (Exception e) { + return ResponseUtil.getFailureResponse(e); + } + } +} \ No newline at end of file diff --git a/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/ConfigResource.java b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/ConfigResource.java new file mode 100644 index 0000000000..ae6a574a03 --- /dev/null +++ b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/ConfigResource.java @@ -0,0 +1,24 @@ +package com.nepxion.discovery.plugin.admincenter.resource; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.List; + +import com.nepxion.discovery.common.entity.ConfigType; + +public interface ConfigResource { + ConfigType getConfigType(); + + void update(String config, boolean async); + + void clear(boolean async); + + List view(); +} \ No newline at end of file diff --git a/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/ConfigResourceImpl.java b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/ConfigResourceImpl.java new file mode 100644 index 0000000000..4d47ed6bca --- /dev/null +++ b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/ConfigResourceImpl.java @@ -0,0 +1,91 @@ +package com.nepxion.discovery.plugin.admincenter.resource; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.ArrayList; +import java.util.List; + +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; + +import com.nepxion.discovery.common.entity.ConfigType; +import com.nepxion.discovery.common.entity.RuleEntity; +import com.nepxion.discovery.common.entity.SubscriptionType; +import com.nepxion.discovery.common.exception.DiscoveryException; +import com.nepxion.discovery.plugin.framework.adapter.PluginAdapter; +import com.nepxion.discovery.plugin.framework.adapter.PluginConfigAdapter; +import com.nepxion.discovery.plugin.framework.event.PluginEventWapper; +import com.nepxion.discovery.plugin.framework.event.RuleClearedEvent; +import com.nepxion.discovery.plugin.framework.event.RuleUpdatedEvent; + +public class ConfigResourceImpl implements ConfigResource { + private static final Logger LOG = LoggerFactory.getLogger(ConfigResourceImpl.class); + + @Autowired + private PluginAdapter pluginAdapter; + + @Autowired(required = false) + private PluginConfigAdapter pluginConfigAdapter; + + @Autowired + private PluginEventWapper pluginEventWapper; + + @Override + public ConfigType getConfigType() { + if (pluginConfigAdapter == null) { + LOG.error("Remote config adapter isn't provided"); + + throw new DiscoveryException("Remote config adapter isn't provided"); + } + + return pluginConfigAdapter.getConfigType(); + } + + @Override + public void update(String config, boolean async) { + pluginEventWapper.fireRuleUpdated(new RuleUpdatedEvent(SubscriptionType.PARTIAL, config), async); + } + + @Override + public void clear(boolean async) { + pluginEventWapper.fireRuleCleared(new RuleClearedEvent(SubscriptionType.PARTIAL), async); + } + + @Override + public List view() { + List ruleList = new ArrayList(3); + + String localRuleContent = StringUtils.EMPTY; + RuleEntity localRuleEntity = pluginAdapter.getLocalRule(); + if (localRuleEntity != null && StringUtils.isNotEmpty(localRuleEntity.getContent())) { + localRuleContent = localRuleEntity.getContent(); + } + + String dynamicGlobalRuleContent = StringUtils.EMPTY; + RuleEntity dynamicGlobalRuleEntity = pluginAdapter.getDynamicGlobalRule(); + if (dynamicGlobalRuleEntity != null && StringUtils.isNotEmpty(dynamicGlobalRuleEntity.getContent())) { + dynamicGlobalRuleContent = dynamicGlobalRuleEntity.getContent(); + } + + String dynamicPartialRuleContent = StringUtils.EMPTY; + RuleEntity dynamicPartialRuleEntity = pluginAdapter.getDynamicPartialRule(); + if (dynamicPartialRuleEntity != null && StringUtils.isNotEmpty(dynamicPartialRuleEntity.getContent())) { + dynamicPartialRuleContent = dynamicPartialRuleEntity.getContent(); + } + + ruleList.add(localRuleContent); + ruleList.add(dynamicGlobalRuleContent); + ruleList.add(dynamicPartialRuleContent); + + return ruleList; + } +} \ No newline at end of file diff --git a/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/GatewayStrategyRouteResource.java b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/GatewayStrategyRouteResource.java new file mode 100644 index 0000000000..7da3e4ef66 --- /dev/null +++ b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/GatewayStrategyRouteResource.java @@ -0,0 +1,30 @@ +package com.nepxion.discovery.plugin.admincenter.resource; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.List; + +import com.nepxion.discovery.common.entity.GatewayStrategyRouteEntity; + +public interface GatewayStrategyRouteResource { + void add(GatewayStrategyRouteEntity gatewayStrategyRouteEntity); + + void modify(GatewayStrategyRouteEntity gatewayStrategyRouteEntity); + + void delete(String routeId); + + void updateAll(List gatewayStrategyRouteEntityList); + + void updateAll(String gatewayStrategyRouteConfig); + + GatewayStrategyRouteEntity view(String routeId); + + List viewAll(); +} \ No newline at end of file diff --git a/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/GatewayStrategyRouteResourceImpl.java b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/GatewayStrategyRouteResourceImpl.java new file mode 100644 index 0000000000..77de5e4f7e --- /dev/null +++ b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/GatewayStrategyRouteResourceImpl.java @@ -0,0 +1,57 @@ +package com.nepxion.discovery.plugin.admincenter.resource; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; + +import com.nepxion.discovery.common.entity.GatewayStrategyRouteEntity; +import com.nepxion.discovery.plugin.strategy.gateway.route.GatewayStrategyRoute; + +public class GatewayStrategyRouteResourceImpl implements GatewayStrategyRouteResource { + @Autowired + private GatewayStrategyRoute gatewayStrategyRoute; + + @Override + public void add(GatewayStrategyRouteEntity gatewayStrategyRouteEntity) { + gatewayStrategyRoute.add(gatewayStrategyRouteEntity); + } + + @Override + public void modify(GatewayStrategyRouteEntity gatewayStrategyRouteEntity) { + gatewayStrategyRoute.modify(gatewayStrategyRouteEntity); + } + + @Override + public void delete(String routeId) { + gatewayStrategyRoute.delete(routeId); + } + + @Override + public void updateAll(List gatewayStrategyRouteEntityList) { + gatewayStrategyRoute.updateAll(gatewayStrategyRouteEntityList); + } + + @Override + public void updateAll(String gatewayStrategyRouteConfig) { + gatewayStrategyRoute.updateAll(gatewayStrategyRouteConfig); + } + + @Override + public GatewayStrategyRouteEntity view(String routeId) { + return gatewayStrategyRoute.view(routeId); + } + + @Override + public List viewAll() { + return gatewayStrategyRoute.viewAll(); + } +} \ No newline at end of file diff --git a/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/GitResource.java b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/GitResource.java new file mode 100644 index 0000000000..40a4efb508 --- /dev/null +++ b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/GitResource.java @@ -0,0 +1,18 @@ +package com.nepxion.discovery.plugin.admincenter.resource; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.Map; + +public interface GitResource { + Map map(); + + String text(); +} \ No newline at end of file diff --git a/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/GitResourceImpl.java b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/GitResourceImpl.java new file mode 100644 index 0000000000..815afda590 --- /dev/null +++ b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/GitResourceImpl.java @@ -0,0 +1,31 @@ +package com.nepxion.discovery.plugin.admincenter.resource; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.Map; + +import org.springframework.beans.factory.annotation.Autowired; + +import com.nepxion.discovery.plugin.framework.generator.GitGenerator; + +public class GitResourceImpl implements GitResource { + @Autowired + private GitGenerator gitGenerator; + + @Override + public Map map() { + return gitGenerator.getMap(); + } + + @Override + public String text() { + return gitGenerator.getText(); + } +} \ No newline at end of file diff --git a/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/InspectorResource.java b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/InspectorResource.java new file mode 100644 index 0000000000..07e911efb6 --- /dev/null +++ b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/InspectorResource.java @@ -0,0 +1,20 @@ +package com.nepxion.discovery.plugin.admincenter.resource; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.List; + +import com.nepxion.discovery.common.entity.InspectorEntity; + +public interface InspectorResource { + InspectorEntity inspect(InspectorEntity inspectorEntity); + + String inspect(List service); +} \ No newline at end of file diff --git a/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/InspectorResourceImpl.java b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/InspectorResourceImpl.java new file mode 100644 index 0000000000..7104ca8ad3 --- /dev/null +++ b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/InspectorResourceImpl.java @@ -0,0 +1,110 @@ +package com.nepxion.discovery.plugin.admincenter.resource; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.List; + +import org.apache.commons.collections4.CollectionUtils; +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cloud.client.ServiceInstance; +import org.springframework.cloud.client.discovery.DiscoveryClient; +import org.springframework.web.client.RestTemplate; + +import com.nepxion.discovery.common.constant.DiscoveryConstant; +import com.nepxion.discovery.common.entity.InspectorEntity; +import com.nepxion.discovery.common.exception.DiscoveryException; +import com.nepxion.discovery.plugin.framework.adapter.PluginAdapter; +import com.nepxion.discovery.plugin.framework.context.PluginContextHolder; + +public class InspectorResourceImpl implements InspectorResource { + private static final Logger LOG = LoggerFactory.getLogger(InspectorResourceImpl.class); + + @Autowired + private RestTemplate pluginRestTemplate; + + @Autowired + private PluginAdapter pluginAdapter; + + @Autowired + private DiscoveryClient discoveryClient; + + @Autowired(required = false) + private PluginContextHolder pluginContextHolder; + + @Override + public InspectorEntity inspect(InspectorEntity inspectorEntity) { + List serviceIdList = inspectorEntity.getServiceIdList(); + String result = inspectorEntity.getResult(); + + // 第一个侦测节点,不会产生侦测信息,需要通过Header方式埋入 + if (StringUtils.isEmpty(result) && pluginContextHolder != null) { + result = pluginContextHolder.getContext(DiscoveryConstant.INSPECTOR_ENDPOINT_HEADER); + } + + String pluginInfo = pluginAdapter.getPluginInfo(result); + inspectorEntity.setResult(pluginInfo); + + if (CollectionUtils.isNotEmpty(serviceIdList)) { + // 获取侦测列表中的第一个服务,作为下一个侦测中继节点 + String nextServiceId = serviceIdList.get(0); + + // 删除侦测列表中的第一个服务 + serviceIdList.remove(0); + + String url = null; + try { + ServiceInstance nextInstance = getInstance(nextServiceId); + + String protocol = pluginAdapter.getInstanceProtocol(nextInstance); + String contextPath = pluginAdapter.getInstanceFormatContextPath(nextInstance); + + url = protocol + "://" + nextServiceId + contextPath + DiscoveryConstant.INSPECTOR_ENDPOINT_URL; + + // 直调方式需要走负载均衡模式下的RestTemplate + return pluginRestTemplate.postForEntity(url, inspectorEntity, InspectorEntity.class).getBody(); + } catch (Exception e) { + String exceptionMessage = "Failed to inspect, current serviceId=" + pluginAdapter.getServiceId() + ", next serviceId=" + nextServiceId + ", url=" + url; + + LOG.error(exceptionMessage, e); + + throw new DiscoveryException(exceptionMessage, e); + } + } else { + return inspectorEntity; + } + } + + @Override + public String inspect(List service) { + InspectorEntity inspectorEntity = new InspectorEntity(); + inspectorEntity.setServiceIdList(service); + + return inspect(inspectorEntity).getResult(); + } + + private ServiceInstance getInstance(String serviceId) { + List instances = null; + + try { + instances = discoveryClient.getInstances(serviceId); + } catch (Exception e) { + throw new DiscoveryException("Failed to get instance list, serviceId=" + serviceId, e); + } + + if (CollectionUtils.isEmpty(instances)) { + throw new DiscoveryException("Instance list is empty, serviceId=" + serviceId); + } + + return instances.get(0); + } +} \ No newline at end of file diff --git a/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/RouterResource.java b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/RouterResource.java new file mode 100644 index 0000000000..3773483c1d --- /dev/null +++ b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/RouterResource.java @@ -0,0 +1,24 @@ +package com.nepxion.discovery.plugin.admincenter.resource; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.List; + +import com.nepxion.discovery.common.entity.RouterEntity; + +public interface RouterResource { + RouterEntity getRouterEntity(); + + List getRouterEntityList(String routeServiceId); + + List getRouterEntityList(String routeServiceId, String routeProtocol, String routeHost, int routePort, String routeContextPath); + + RouterEntity routeTree(String routeServiceIds); +} \ No newline at end of file diff --git a/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/RouterResourceImpl.java b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/RouterResourceImpl.java new file mode 100644 index 0000000000..031c9a527c --- /dev/null +++ b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/RouterResourceImpl.java @@ -0,0 +1,233 @@ +package com.nepxion.discovery.plugin.admincenter.resource; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +import org.apache.commons.collections4.CollectionUtils; +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cloud.client.ServiceInstance; +import org.springframework.web.client.RestClientException; +import org.springframework.web.client.RestTemplate; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.nepxion.discovery.common.constant.DiscoveryConstant; +import com.nepxion.discovery.common.entity.DiscoveryEntity; +import com.nepxion.discovery.common.entity.RouterEntity; +import com.nepxion.discovery.common.entity.RuleEntity; +import com.nepxion.discovery.common.entity.WeightEntityWrapper; +import com.nepxion.discovery.common.entity.WeightFilterEntity; +import com.nepxion.discovery.common.exception.DiscoveryException; +import com.nepxion.discovery.common.util.JsonUtil; +import com.nepxion.discovery.plugin.framework.adapter.PluginAdapter; + +public class RouterResourceImpl implements RouterResource { + @Autowired + private PluginAdapter pluginAdapter; + + @Autowired + private ServiceResource serviceResource; + + private RestTemplate routerRestTemplate; + + public RouterResourceImpl() { + routerRestTemplate = new RestTemplate(); + } + + @Override + public RouterEntity getRouterEntity() { + String serviceType = pluginAdapter.getServiceType(); + String serviceId = pluginAdapter.getServiceId(); + String version = pluginAdapter.getVersion(); + String region = pluginAdapter.getRegion(); + String environment = pluginAdapter.getEnvironment(); + String zone = pluginAdapter.getZone(); + String host = pluginAdapter.getHost(); + int port = pluginAdapter.getPort(); + int weight = -1; + String protocol = pluginAdapter.getProtocol(); + String contextPath = pluginAdapter.getFormatContextPath(); + + RouterEntity routerEntity = new RouterEntity(); + routerEntity.setServiceType(serviceType); + routerEntity.setServiceId(serviceId); + routerEntity.setVersion(version); + routerEntity.setRegion(region); + routerEntity.setEnvironment(environment); + routerEntity.setZone(zone); + routerEntity.setHost(host); + routerEntity.setPort(port); + routerEntity.setWeight(weight); + routerEntity.setProtocol(protocol); + routerEntity.setContextPath(contextPath); + + return routerEntity; + } + + @Override + public List getRouterEntityList(String routeServiceId) { + List instanceList = null; + + try { + instanceList = serviceResource.getInstances(routeServiceId); + } catch (Exception e) { + throw new DiscoveryException("Get instance list for route serviceId=" + routeServiceId + " failed", e); + } + + if (CollectionUtils.isEmpty(instanceList)) { + return null; + } + + List routerEntityList = new ArrayList(); + for (ServiceInstance instance : instanceList) { + String serviceId = pluginAdapter.getInstanceServiceId(instance); + String serviceType = pluginAdapter.getInstanceServiceType(instance); + String version = pluginAdapter.getInstanceVersion(instance); + String region = pluginAdapter.getInstanceRegion(instance); + String environment = pluginAdapter.getInstanceEnvironment(instance); + String zone = pluginAdapter.getInstanceZone(instance); + String host = instance.getHost(); + int port = instance.getPort(); + int weight = getWeight(routeServiceId, version, region); + String protocol = pluginAdapter.getInstanceProtocol(instance); + String contextPath = pluginAdapter.getInstanceFormatContextPath(instance); + + RouterEntity routerEntity = new RouterEntity(); + routerEntity.setServiceType(serviceType); + routerEntity.setServiceId(serviceId); + routerEntity.setVersion(version); + routerEntity.setRegion(region); + routerEntity.setEnvironment(environment); + routerEntity.setZone(zone); + routerEntity.setHost(host); + routerEntity.setPort(port); + routerEntity.setWeight(weight); + routerEntity.setProtocol(protocol); + routerEntity.setContextPath(contextPath); + + routerEntityList.add(routerEntity); + } + + return routerEntityList; + } + + @Override + public List getRouterEntityList(String routeServiceId, String routeProtocol, String routeHost, int routePort, String routeContextPath) { + String url = routeProtocol + "://" + routeHost + ":" + routePort + routeContextPath + "router/route/" + routeServiceId; + + String result = null; + try { + result = routerRestTemplate.getForEntity(url, String.class).getBody(); + } catch (RestClientException e) { + throw new DiscoveryException("Failed to execute to route, serviceId=" + routeServiceId + ", url=" + url, e); + } + + if (StringUtils.isEmpty(result)) { + return null; + } + + List routerEntityList = JsonUtil.fromJson(result, new TypeReference>() { + }); + + return routerEntityList; + } + + @Override + public RouterEntity routeTree(String routeServiceIds) { + if (StringUtils.isEmpty(routeServiceIds)) { + throw new DiscoveryException("Route serviceIds is empty"); + } + + String[] serviceIdArray = null; + try { + serviceIdArray = StringUtils.split(routeServiceIds, DiscoveryConstant.SEPARATE); + } catch (Exception e) { + throw new DiscoveryException("Route serviceIds must be separated with '" + DiscoveryConstant.SEPARATE + "'", e); + } + + RouterEntity firstRouterEntity = getRouterEntity(); + + // 路由深度为Key + HashMap> routerEntityMap = new HashMap>(); + int routerDepth = 0; + for (String serviceId : serviceIdArray) { + serviceId = serviceId.toLowerCase().trim(); + if (routerDepth == 0) { + routeFirst(firstRouterEntity, serviceId); + + retrieveRouterEntityList(routerEntityMap, routerDepth).addAll(firstRouterEntity.getNexts()); + } else { + List routerEntityList = retrieveRouterEntityList(routerEntityMap, routerDepth - 1); + for (RouterEntity routerEntity : routerEntityList) { + String routeHost = routerEntity.getHost(); + int routePort = routerEntity.getPort(); + String routeProtocol = routerEntity.getProtocol(); + String routeContextPath = routerEntity.getContextPath(); + + route(routerEntity, serviceId, routeProtocol, routeHost, routePort, routeContextPath); + + retrieveRouterEntityList(routerEntityMap, routerDepth).addAll(routerEntity.getNexts()); + } + } + + routerDepth++; + } + + return firstRouterEntity; + } + + private void routeFirst(RouterEntity routerEntity, String routeServiceId) { + List routerEntityList = getRouterEntityList(routeServiceId); + if (CollectionUtils.isNotEmpty(routerEntityList)) { + routerEntity.getNexts().addAll(routerEntityList); + } + } + + private void route(RouterEntity routerEntity, String routeServiceId, String routeProtocol, String routeHost, int routePort, String routeContextPath) { + List routerEntityList = getRouterEntityList(routeServiceId, routeProtocol, routeHost, routePort, routeContextPath); + if (CollectionUtils.isNotEmpty(routerEntityList)) { + routerEntity.getNexts().addAll(routerEntityList); + } + } + + private List retrieveRouterEntityList(HashMap> routerEntityMap, int routerDepth) { + List routerEntityList = routerEntityMap.get(routerDepth); + if (routerEntityList == null) { + routerEntityList = new ArrayList(); + routerEntityMap.put(routerDepth, routerEntityList); + } + + return routerEntityList; + } + + private int getWeight(String providerServiceId, String providerVersion, String providerRegion) { + RuleEntity ruleEntity = pluginAdapter.getRule(); + if (ruleEntity == null) { + return -1; + } + + DiscoveryEntity discoveryEntity = ruleEntity.getDiscoveryEntity(); + if (discoveryEntity == null) { + return -1; + } + + WeightFilterEntity weightFilterEntity = discoveryEntity.getWeightFilterEntity(); + if (weightFilterEntity == null || !weightFilterEntity.hasWeight()) { + return -1; + } + + String serviceId = pluginAdapter.getServiceId(); + + return WeightEntityWrapper.getWeight(weightFilterEntity, providerServiceId, providerVersion, providerRegion, serviceId); + } +} \ No newline at end of file diff --git a/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/SentinelCoreResource.java b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/SentinelCoreResource.java new file mode 100644 index 0000000000..041925f13a --- /dev/null +++ b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/SentinelCoreResource.java @@ -0,0 +1,43 @@ +package com.nepxion.discovery.plugin.admincenter.resource; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.List; + +import com.alibaba.csp.sentinel.slots.block.authority.AuthorityRule; +import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule; +import com.alibaba.csp.sentinel.slots.block.flow.FlowRule; +import com.alibaba.csp.sentinel.slots.system.SystemRule; + +public interface SentinelCoreResource { + void updateFlowRules(String rule); + + void clearFlowRules(); + + public List viewFlowRules(); + + void updateDegradeRules(String rule); + + void clearDegradeRules(); + + List viewDegradeRules(); + + void updateAuthorityRules(String rule); + + void clearAuthorityRules(); + + List viewAuthorityRules(); + + void updateSystemRules(String rule); + + void clearSystemRules(); + + List viewSystemRules(); +} \ No newline at end of file diff --git a/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/SentinelCoreResourceImpl.java b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/SentinelCoreResourceImpl.java new file mode 100644 index 0000000000..60457b9492 --- /dev/null +++ b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/SentinelCoreResourceImpl.java @@ -0,0 +1,141 @@ +package com.nepxion.discovery.plugin.admincenter.resource; + +import java.util.ArrayList; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.List; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.alibaba.csp.sentinel.datasource.Converter; +import com.alibaba.csp.sentinel.slots.block.authority.AuthorityRule; +import com.alibaba.csp.sentinel.slots.block.authority.AuthorityRuleManager; +import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule; +import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager; +import com.alibaba.csp.sentinel.slots.block.flow.FlowRule; +import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager; +import com.alibaba.csp.sentinel.slots.system.SystemRule; +import com.alibaba.csp.sentinel.slots.system.SystemRuleManager; +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.TypeReference; + +public class SentinelCoreResourceImpl implements SentinelCoreResource { + private static final Logger LOG = LoggerFactory.getLogger(SentinelCoreResourceImpl.class); + + private static Converter> sentinelFlowRuleParser = new Converter>() { + @Override + public List convert(String source) { + return JSON.parseObject(source, new TypeReference>() { + }); + } + }; + + private static Converter> sentinelDegradeRuleParser = new Converter>() { + @Override + public List convert(String source) { + return JSON.parseObject(source, new TypeReference>() { + }); + } + }; + + private static Converter> sentinelAuthorityRuleParser = new Converter>() { + @Override + public List convert(String source) { + return JSON.parseObject(source, new TypeReference>() { + }); + } + }; + + private static Converter> sentinelSystemRuleParser = new Converter>() { + @Override + public List convert(String source) { + return JSON.parseObject(source, new TypeReference>() { + }); + } + }; + + @Override + public void updateFlowRules(String rule) { + FlowRuleManager.loadRules(sentinelFlowRuleParser.convert(rule)); + + LOG.info("{} flow rules loaded...", FlowRuleManager.getRules().size()); + } + + @Override + public void clearFlowRules() { + LOG.info("{} flow rules cleared...", FlowRuleManager.getRules().size()); + + FlowRuleManager.loadRules(new ArrayList()); + } + + @Override + public List viewFlowRules() { + return FlowRuleManager.getRules(); + } + + @Override + public void updateDegradeRules(String rule) { + DegradeRuleManager.loadRules(sentinelDegradeRuleParser.convert(rule)); + + LOG.info("{} degrade rules loaded...", DegradeRuleManager.getRules().size()); + } + + @Override + public void clearDegradeRules() { + LOG.info("{} degrade rules cleared...", DegradeRuleManager.getRules().size()); + + DegradeRuleManager.loadRules(new ArrayList()); + } + + @Override + public List viewDegradeRules() { + return DegradeRuleManager.getRules(); + } + + @Override + public void updateAuthorityRules(String rule) { + AuthorityRuleManager.loadRules(sentinelAuthorityRuleParser.convert(rule)); + + LOG.info("{} authority rules loaded...", AuthorityRuleManager.getRules().size()); + } + + @Override + public void clearAuthorityRules() { + LOG.info("{} authority rules cleared...", AuthorityRuleManager.getRules().size()); + + AuthorityRuleManager.loadRules(new ArrayList()); + } + + @Override + public List viewAuthorityRules() { + return AuthorityRuleManager.getRules(); + } + + @Override + public void updateSystemRules(String rule) { + SystemRuleManager.loadRules(sentinelSystemRuleParser.convert(rule)); + + LOG.info("{} system rules loaded...", SystemRuleManager.getRules().size()); + } + + @Override + public void clearSystemRules() { + LOG.info("{} system rules cleared...", SystemRuleManager.getRules().size()); + + SystemRuleManager.loadRules(new ArrayList()); + } + + @Override + public List viewSystemRules() { + return SystemRuleManager.getRules(); + } +} \ No newline at end of file diff --git a/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/SentinelParamResource.java b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/SentinelParamResource.java new file mode 100644 index 0000000000..150e507e4a --- /dev/null +++ b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/SentinelParamResource.java @@ -0,0 +1,22 @@ +package com.nepxion.discovery.plugin.admincenter.resource; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.List; + +import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowRule; + +public interface SentinelParamResource { + void updateParamFlowRules(String rule); + + void clearParamFlowRules(); + + List viewParamFlowRules(); +} \ No newline at end of file diff --git a/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/SentinelParamResourceImpl.java b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/SentinelParamResourceImpl.java new file mode 100644 index 0000000000..5514e7b790 --- /dev/null +++ b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/SentinelParamResourceImpl.java @@ -0,0 +1,54 @@ +package com.nepxion.discovery.plugin.admincenter.resource; + +import java.util.ArrayList; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.List; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.alibaba.csp.sentinel.datasource.Converter; +import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowRule; +import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowRuleManager; +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.TypeReference; + +public class SentinelParamResourceImpl implements SentinelParamResource { + private static final Logger LOG = LoggerFactory.getLogger(SentinelParamResourceImpl.class); + + private static Converter> sentinelParamFlowRuleParser = new Converter>() { + @Override + public List convert(String source) { + return JSON.parseObject(source, new TypeReference>() { + }); + } + }; + + @Override + public void updateParamFlowRules(String rule) { + ParamFlowRuleManager.loadRules(sentinelParamFlowRuleParser.convert(rule)); + + LOG.info("{} param flow rules loaded...", ParamFlowRuleManager.getRules().size()); + } + + @Override + public void clearParamFlowRules() { + LOG.info("{} param flow rules cleared...", ParamFlowRuleManager.getRules().size()); + + ParamFlowRuleManager.loadRules(new ArrayList()); + } + + @Override + public List viewParamFlowRules() { + return ParamFlowRuleManager.getRules(); + } +} \ No newline at end of file diff --git a/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/ServiceResource.java b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/ServiceResource.java new file mode 100644 index 0000000000..0f170c59ee --- /dev/null +++ b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/ServiceResource.java @@ -0,0 +1,49 @@ +package com.nepxion.discovery.plugin.admincenter.resource; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.List; +import java.util.Map; + +import org.springframework.cloud.client.ServiceInstance; + +import com.nepxion.discovery.common.entity.DiscoveryType; +import com.nepxion.discovery.common.entity.GatewayType; +import com.nepxion.discovery.common.entity.InstanceEntity; +import com.nepxion.discovery.common.entity.MetadataParameter; +import com.nepxion.discovery.common.entity.ServiceType; + +public interface ServiceResource { + DiscoveryType getDiscoveryType(); + + List getGroups(); + + String getGroup(String serviceId); + + List getServices(); + + List getServiceList(List serviceTypes); + + List getServiceList(String group, List serviceTypes); + + List getGateways(); + + List getGatewayList(List gatewayTypes); + + List getInstances(String serviceId); + + List getInstanceList(String serviceId); + + Map> getInstanceMap(List groups); + + Map> getMetadataMap(String metadataKey, List serviceIds); + + Map> getMetadataMap(MetadataParameter metadataParameter); +} \ No newline at end of file diff --git a/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/ServiceResourceImpl.java b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/ServiceResourceImpl.java new file mode 100644 index 0000000000..ab2e975356 --- /dev/null +++ b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/ServiceResourceImpl.java @@ -0,0 +1,373 @@ +package com.nepxion.discovery.plugin.admincenter.resource; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import org.apache.commons.collections4.CollectionUtils; +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cloud.client.ServiceInstance; +import org.springframework.cloud.client.discovery.DiscoveryClient; +import org.springframework.cloud.client.discovery.composite.CompositeDiscoveryClient; + +import com.nepxion.discovery.common.constant.DiscoveryConstant; +import com.nepxion.discovery.common.delegate.DiscoveryClientDelegate; +import com.nepxion.discovery.common.entity.DiscoveryType; +import com.nepxion.discovery.common.entity.GatewayType; +import com.nepxion.discovery.common.entity.InstanceEntity; +import com.nepxion.discovery.common.entity.InstanceEntityWrapper; +import com.nepxion.discovery.common.entity.MetadataParameter; +import com.nepxion.discovery.common.entity.ServiceType; + +public class ServiceResourceImpl implements ServiceResource { + @Autowired + private DiscoveryClient discoveryClient; + + @SuppressWarnings("unchecked") + @Override + public DiscoveryType getDiscoveryType() { + DiscoveryClient delegatedDiscoveryClient = null; + if (discoveryClient instanceof DiscoveryClientDelegate) { + delegatedDiscoveryClient = ((DiscoveryClientDelegate) discoveryClient).getDelegate(); + } else { + delegatedDiscoveryClient = discoveryClient; + } + + if (delegatedDiscoveryClient instanceof CompositeDiscoveryClient) { + CompositeDiscoveryClient compositeDiscoveryClient = (CompositeDiscoveryClient) delegatedDiscoveryClient; + List discoveryClients = compositeDiscoveryClient.getDiscoveryClients(); + for (DiscoveryClient client : discoveryClients) { + String discoveryDescription = client.description(); + DiscoveryType[] discoveryTypes = DiscoveryType.values(); + for (int i = 0; i < discoveryTypes.length; i++) { + DiscoveryType discoveryType = discoveryTypes[i]; + if (discoveryDescription.toLowerCase().contains(discoveryType.toString().toLowerCase())) { + return discoveryType; + } + } + } + } else { + String discoveryDescription = delegatedDiscoveryClient.description(); + DiscoveryType[] discoveryTypes = DiscoveryType.values(); + for (int i = 0; i < discoveryTypes.length; i++) { + DiscoveryType discoveryType = discoveryTypes[i]; + if (discoveryDescription.toLowerCase().contains(discoveryType.toString().toLowerCase())) { + return discoveryType; + } + } + } + + return null; + } + + @Override + public List getGroups() { + List groupList = new ArrayList(); + + List services = getServices(); + for (String service : services) { + List instanceEntityList = getInstanceList(service); + for (InstanceEntity instance : instanceEntityList) { + String group = instance.getGroup(); + if (!groupList.contains(group)) { + groupList.add(group); + } + } + } + + groupList.sort(String::compareTo); + + return groupList; + } + + @Override + public String getGroup(String serviceId) { + List instanceEntityList = getInstanceList(serviceId); + for (InstanceEntity instance : instanceEntityList) { + String group = instance.getGroup(); + if (StringUtils.isNotEmpty(group)) { + return group; + } + } + + return null; + } + + @Override + public List getServices() { + List serviceList = discoveryClient.getServices(); + + serviceList.sort(String::compareTo); + + return serviceList; + } + + @Override + public List getServiceList(List types) { + List serviceList = new ArrayList(); + List services = getServices(); + for (String service : services) { + List instances = getInstances(service); + for (ServiceInstance instance : instances) { + Map metadata = instance.getMetadata(); + String serviceId = instance.getServiceId().toLowerCase(); + String serviceType = InstanceEntityWrapper.getServiceType(metadata); + for (ServiceType type : types) { + if (StringUtils.equals(serviceType, type.toString())) { + if (!serviceList.contains(serviceId)) { + serviceList.add(serviceId); + } + } + } + } + } + + return serviceList; + } + + @Override + public List getServiceList(String group, List types) { + List serviceList = new ArrayList(); + List services = getServices(); + for (String service : services) { + List instances = getInstances(service); + for (ServiceInstance instance : instances) { + Map metadata = instance.getMetadata(); + String serviceGroup = InstanceEntityWrapper.getGroup(metadata); + if (StringUtils.equals(serviceGroup, group)) { + String serviceId = instance.getServiceId().toLowerCase(); + String serviceType = InstanceEntityWrapper.getServiceType(metadata); + for (ServiceType type : types) { + if (StringUtils.equals(serviceType, type.toString())) { + if (!serviceList.contains(serviceId)) { + serviceList.add(serviceId); + } + } + } + } + } + } + + return serviceList; + } + + @Override + public List getGateways() { + List gatewayList = new ArrayList(); + List services = getServices(); + for (String service : services) { + List instances = getInstances(service); + for (ServiceInstance instance : instances) { + Map metadata = instance.getMetadata(); + String serviceId = instance.getServiceId().toLowerCase(); + String serviceType = InstanceEntityWrapper.getServiceType(metadata); + if (StringUtils.equals(serviceType, ServiceType.GATEWAY.toString())) { + if (!gatewayList.contains(serviceId)) { + gatewayList.add(serviceId); + } + } + } + } + + return gatewayList; + } + + @Override + public List getGatewayList(List types) { + List gatewayList = new ArrayList(); + List services = getServices(); + for (String service : services) { + List instances = getInstances(service); + for (ServiceInstance instance : instances) { + Map metadata = instance.getMetadata(); + String serviceId = instance.getServiceId().toLowerCase(); + String serviceType = InstanceEntityWrapper.getServiceType(metadata); + String gatewayType = InstanceEntityWrapper.getGatewayType(metadata); + if (StringUtils.equals(serviceType, ServiceType.GATEWAY.toString())) { + for (GatewayType type : types) { + if (StringUtils.equals(gatewayType, type.toString())) { + if (!gatewayList.contains(serviceId)) { + gatewayList.add(serviceId); + } + } + } + } + } + } + + return gatewayList; + } + + @Override + public List getInstances(String serviceId) { + List instanceList = discoveryClient.getInstances(serviceId); + + // instanceList.sort(Comparator.comparing(ServiceInstance::getHost).thenComparing(ServiceInstance::getPort)); + instanceList.sort(Comparator.nullsLast(Comparator.comparing(ServiceInstance::getHost, Comparator.nullsLast(String::compareTo))).thenComparing(ServiceInstance::getPort)); + + return instanceList; + } + + @Override + public List getInstanceList(String service) { + List instances = getInstances(service); + List instanceEntityList = new ArrayList(instances.size()); + for (ServiceInstance instance : instances) { + Map metadata = instance.getMetadata(); + String plugin = InstanceEntityWrapper.getPlugin(metadata); + String group = InstanceEntityWrapper.getGroup(metadata); + String serviceType = InstanceEntityWrapper.getServiceType(metadata); + String serviceId = instance.getServiceId().toLowerCase(); + String serviceAppId = InstanceEntityWrapper.getServiceAppId(metadata); + String serviceUUId = InstanceEntityWrapper.getServiceUUId(metadata); + String version = InstanceEntityWrapper.getVersion(metadata); + String region = InstanceEntityWrapper.getRegion(metadata); + String environment = InstanceEntityWrapper.getEnvironment(metadata); + String zone = InstanceEntityWrapper.getZone(metadata); + boolean active = InstanceEntityWrapper.isActive(metadata); + String protocol = InstanceEntityWrapper.getProtocol(metadata); + String contextPath = InstanceEntityWrapper.getContextPath(metadata); + String formatContextPath = InstanceEntityWrapper.getFormatContextPath(metadata); + String host = instance.getHost(); + int port = instance.getPort(); + + InstanceEntity instanceEntity = new InstanceEntity(); + instanceEntity.setPlugin(plugin); + instanceEntity.setGroup(group); + instanceEntity.setServiceType(serviceType); + instanceEntity.setServiceId(serviceId); + instanceEntity.setServiceAppId(serviceAppId); + instanceEntity.setServiceUUId(serviceUUId); + instanceEntity.setVersion(version); + instanceEntity.setRegion(region); + instanceEntity.setEnvironment(environment); + instanceEntity.setZone(zone); + instanceEntity.setActive(active); + instanceEntity.setProtocol(protocol); + instanceEntity.setContextPath(contextPath); + instanceEntity.setFormatContextPath(formatContextPath); + instanceEntity.setHost(host); + instanceEntity.setPort(port); + instanceEntity.setMetadata(metadata); + + instanceEntityList.add(instanceEntity); + } + + return instanceEntityList; + } + + @Override + public Map> getInstanceMap(List groups) { + List services = getServices(); + Map> instanceMap = new LinkedHashMap>(services.size()); + for (String service : services) { + List instanceEntityList = getInstanceList(service); + if (CollectionUtils.isNotEmpty(groups)) { + for (InstanceEntity instance : instanceEntityList) { + String group = instance.getGroup(); + if (groups.contains(group)) { + List instanceList = instanceMap.get(service); + if (instanceList == null) { + instanceList = new ArrayList(); + instanceMap.put(service, instanceList); + } + instanceList.add(instance); + } + } + } else { + instanceMap.put(service, instanceEntityList); + } + } + + return instanceMap; + } + + @Override + public Map> getMetadataMap(String metadataKey, List serviceIds) { + Map> metadataMap = new LinkedHashMap>(serviceIds.size()); + for (String serviceId : serviceIds) { + List instanceEntityList = getInstanceList(serviceId); + for (InstanceEntity instance : instanceEntityList) { + List metadataList = metadataMap.get(serviceId); + if (metadataList == null) { + metadataList = new ArrayList(); + metadataMap.put(serviceId, metadataList); + } + String metadataValue = null; + if (StringUtils.equals(metadataKey, DiscoveryConstant.HOST + ":" + DiscoveryConstant.PORT)) { + metadataValue = instance.getHost() + ":" + instance.getPort(); + } else if (StringUtils.equals(metadataKey, DiscoveryConstant.HOST)) { + metadataValue = instance.getHost(); + } else if (StringUtils.equals(metadataKey, DiscoveryConstant.PORT)) { + metadataValue = String.valueOf(instance.getPort()); + } else { + metadataValue = instance.getMetadata().get(metadataKey); + } + if (!metadataList.contains(metadataValue)) { + if (StringUtils.isNotEmpty(metadataValue)) { + metadataList.add(metadataValue); + } + } + } + } + + return metadataMap; + } + + @Override + public Map> getMetadataMap(MetadataParameter metadataParameter) { + List metadataKeys = metadataParameter.getMetadataKeys(); + List serviceIds = metadataParameter.getServiceIds(); + String separate = metadataParameter.getSeparate(); + Map> metadataMap = new LinkedHashMap>(serviceIds.size()); + for (String serviceId : serviceIds) { + List instanceEntityList = getInstanceList(serviceId); + for (InstanceEntity instance : instanceEntityList) { + List metadataList = metadataMap.get(serviceId); + if (metadataList == null) { + metadataList = new ArrayList(); + metadataMap.put(serviceId, metadataList); + } + StringBuilder stringBuilder = new StringBuilder(); + int index = 0; + for (String metadataKey : metadataKeys) { + if (StringUtils.equals(metadataKey, DiscoveryConstant.HOST + ":" + DiscoveryConstant.PORT)) { + stringBuilder.append(instance.getHost() + ":" + instance.getPort()); + } else if (StringUtils.equals(metadataKey, DiscoveryConstant.HOST)) { + stringBuilder.append(instance.getHost()); + } else if (StringUtils.equals(metadataKey, DiscoveryConstant.PORT)) { + stringBuilder.append(instance.getPort()); + } else { + stringBuilder.append(instance.getMetadata().get(metadataKey)); + } + if (index < metadataKeys.size() - 1) { + stringBuilder.append(separate); + } + + index++; + } + + String metadataValues = stringBuilder.toString(); + if (!metadataList.contains(metadataValues)) { + if (StringUtils.isNotEmpty(metadataValues)) { + metadataList.add(metadataValues); + } + } + } + } + + return metadataMap; + } +} \ No newline at end of file diff --git a/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/StrategyResource.java b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/StrategyResource.java new file mode 100644 index 0000000000..9447d151fa --- /dev/null +++ b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/StrategyResource.java @@ -0,0 +1,16 @@ +package com.nepxion.discovery.plugin.admincenter.resource; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +public interface StrategyResource { + boolean validateExpression(String expression, String validation); + + String validateRoute(String routeType, String validation); +} \ No newline at end of file diff --git a/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/StrategyResourceImpl.java b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/StrategyResourceImpl.java new file mode 100644 index 0000000000..d8d9e32e6d --- /dev/null +++ b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/StrategyResourceImpl.java @@ -0,0 +1,97 @@ +package com.nepxion.discovery.plugin.admincenter.resource; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.Map; + +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; + +import com.nepxion.discovery.common.entity.StrategyConditionEntity; +import com.nepxion.discovery.common.entity.StrategyRouteType; +import com.nepxion.discovery.common.exception.DiscoveryException; +import com.nepxion.discovery.common.util.StringUtil; +import com.nepxion.discovery.plugin.admincenter.constant.AdminConstant; +import com.nepxion.discovery.plugin.strategy.condition.StrategyCondition; +import com.nepxion.discovery.plugin.strategy.wrapper.StrategyWrapper; + +public class StrategyResourceImpl implements StrategyResource { + @Autowired + private StrategyCondition strategyCondition; + + @Autowired + private StrategyWrapper strategyWrapper; + + @Value("${" + AdminConstant.SPRING_APPLICATION_ADMIN_STRATEGY_ENDPOINT_VALIDATE_EXPRESSION_ENABLED + ":true}") + private Boolean validateExpressionEnabled; + + @Override + public boolean validateExpression(String expression, String validation) { + if (!validateExpressionEnabled) { + throw new DiscoveryException("Strategy endpoint for validate-expression is disabled"); + } + + StrategyConditionEntity strategyConditionEntity = new StrategyConditionEntity(); + strategyConditionEntity.setExpression(expression); + + Map map = null; + try { + map = StringUtil.splitToMap(validation); + } catch (Exception e) { + throw new DiscoveryException("Invalid format for validation input"); + } + + return strategyCondition.isTriggered(strategyConditionEntity, map); + } + + @Override + public String validateRoute(String routeType, String validation) { + StrategyRouteType strategyRouteType = StrategyRouteType.fromString(routeType); + + Map map = null; + try { + map = StringUtil.splitToMap(validation); + } catch (Exception e) { + throw new DiscoveryException("Invalid format for validation input"); + } + + String route = null; + switch (strategyRouteType) { + case VERSION: + route = strategyWrapper.getRouteVersion(map); + break; + case REGION: + route = strategyWrapper.getRouteRegion(map); + break; + case ADDRESS: + route = strategyWrapper.getRouteAddress(map); + break; + case VERSION_WEIGHT: + route = strategyWrapper.getRouteVersionWeight(map); + break; + case REGION_WEIGHT: + route = strategyWrapper.getRouteRegionWeight(map); + break; + case ID_BLACKLIST: + route = strategyWrapper.getRouteIdBlacklist(); + break; + case ADDRESS_BLACKLIST: + route = strategyWrapper.getRouteAddressBlacklist(); + break; + } + + if (StringUtils.isEmpty(route)) { + throw new DiscoveryException("Not found any " + routeType + " routes"); + } + + return route; + } +} \ No newline at end of file diff --git a/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/VersionResource.java b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/VersionResource.java new file mode 100644 index 0000000000..ff30cf570e --- /dev/null +++ b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/VersionResource.java @@ -0,0 +1,20 @@ +package com.nepxion.discovery.plugin.admincenter.resource; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.List; + +public interface VersionResource { + void update(String version, boolean async); + + void clear(String version, boolean async); + + List view(); +} \ No newline at end of file diff --git a/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/VersionResourceImpl.java b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/VersionResourceImpl.java new file mode 100644 index 0000000000..6faa91db7e --- /dev/null +++ b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/VersionResourceImpl.java @@ -0,0 +1,75 @@ +package com.nepxion.discovery.plugin.admincenter.resource; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.ArrayList; +import java.util.List; + +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; + +import com.nepxion.discovery.common.constant.DiscoveryConstant; +import com.nepxion.discovery.common.exception.DiscoveryException; +import com.nepxion.discovery.plugin.framework.adapter.PluginAdapter; +import com.nepxion.discovery.plugin.framework.event.PluginEventWapper; +import com.nepxion.discovery.plugin.framework.event.VersionClearedEvent; +import com.nepxion.discovery.plugin.framework.event.VersionUpdatedEvent; + +public class VersionResourceImpl implements VersionResource { + @Autowired + private PluginAdapter pluginAdapter; + + @Autowired + private PluginEventWapper pluginEventWapper; + + @Override + public void update(String version, boolean async) { + if (StringUtils.isEmpty(version)) { + throw new DiscoveryException("Version can't be null or empty"); + } + + String dynamicVersion = null; + String localVersion = null; + String[] versionArray = StringUtils.split(version, DiscoveryConstant.SEPARATE); + if (versionArray.length == 2) { + dynamicVersion = versionArray[0]; + localVersion = versionArray[1]; + } else if (versionArray.length == 1) { + dynamicVersion = versionArray[0]; + } else { + throw new DiscoveryException("Invalid version format, it must be '${dynamicVersion}' or '${dynamicVersion};${localVersion}'"); + } + + pluginEventWapper.fireVersionUpdated(new VersionUpdatedEvent(dynamicVersion, localVersion), async); + } + + @Override + public void clear(String version, boolean async) { + // 修复Swagger的一个Bug,当在Swagger界面不输入版本号的时候,传到后端变成了“{}” + if (StringUtils.isNotEmpty(version) && StringUtils.equals(version.trim(), "{}")) { + version = null; + } + + pluginEventWapper.fireVersionCleared(new VersionClearedEvent(version), async); + } + + @Override + public List view() { + List versionList = new ArrayList(2); + + String localVersion = pluginAdapter.getLocalVersion(); + String dynamicVersion = pluginAdapter.getDynamicVersion(); + + versionList.add(StringUtils.isNotEmpty(localVersion) ? localVersion : StringUtils.EMPTY); + versionList.add(StringUtils.isNotEmpty(dynamicVersion) ? dynamicVersion : StringUtils.EMPTY); + + return versionList; + } +} \ No newline at end of file diff --git a/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/ZuulStrategyRouteResource.java b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/ZuulStrategyRouteResource.java new file mode 100644 index 0000000000..e8f6b689da --- /dev/null +++ b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/ZuulStrategyRouteResource.java @@ -0,0 +1,30 @@ +package com.nepxion.discovery.plugin.admincenter.resource; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.List; + +import com.nepxion.discovery.common.entity.ZuulStrategyRouteEntity; + +public interface ZuulStrategyRouteResource { + void add(ZuulStrategyRouteEntity zuulStrategyRouteEntity); + + void modify(ZuulStrategyRouteEntity zuulStrategyRouteEntity); + + void delete(String routeId); + + void updateAll(List zuulStrategyRouteEntityList); + + void updateAll(String zuulStrategyRouteConfig); + + ZuulStrategyRouteEntity view(String routeId); + + List viewAll(); +} \ No newline at end of file diff --git a/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/ZuulStrategyRouteResourceImpl.java b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/ZuulStrategyRouteResourceImpl.java new file mode 100644 index 0000000000..54b9aebc8c --- /dev/null +++ b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/ZuulStrategyRouteResourceImpl.java @@ -0,0 +1,57 @@ +package com.nepxion.discovery.plugin.admincenter.resource; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; + +import com.nepxion.discovery.common.entity.ZuulStrategyRouteEntity; +import com.nepxion.discovery.plugin.strategy.zuul.route.ZuulStrategyRoute; + +public class ZuulStrategyRouteResourceImpl implements ZuulStrategyRouteResource { + @Autowired + private ZuulStrategyRoute zuulStrategyRoute; + + @Override + public void add(ZuulStrategyRouteEntity zuulStrategyRouteEntity) { + zuulStrategyRoute.add(zuulStrategyRouteEntity); + } + + @Override + public void modify(ZuulStrategyRouteEntity zuulStrategyRouteEntity) { + zuulStrategyRoute.modify(zuulStrategyRouteEntity); + } + + @Override + public void delete(String routeId) { + zuulStrategyRoute.delete(routeId); + } + + @Override + public void updateAll(List zuulStrategyRouteEntityList) { + zuulStrategyRoute.updateAll(zuulStrategyRouteEntityList); + } + + @Override + public void updateAll(String zuulStrategyRouteConfig) { + zuulStrategyRoute.updateAll(zuulStrategyRouteConfig); + } + + @Override + public ZuulStrategyRouteEntity view(String routeId) { + return zuulStrategyRoute.view(routeId); + } + + @Override + public List viewAll() { + return zuulStrategyRoute.viewAll(); + } +} \ No newline at end of file diff --git a/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/resources/META-INF/additional-spring-configuration-metadata.json b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/resources/META-INF/additional-spring-configuration-metadata.json new file mode 100644 index 0000000000..e0188d9a44 --- /dev/null +++ b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/resources/META-INF/additional-spring-configuration-metadata.json @@ -0,0 +1,70 @@ +{ + "properties": [ + { + "name": "spring.application.admin.service.endpoint.enabled", + "type": "java.lang.Boolean", + "defaultValue": true, + "description": "Whether admin service endpoint is enabled." + }, + { + "name": "spring.application.admin.config.endpoint.enabled", + "type": "java.lang.Boolean", + "defaultValue": true, + "description": "Whether admin config endpoint is enabled." + }, + { + "name": "spring.application.admin.version.endpoint.enabled", + "type": "java.lang.Boolean", + "defaultValue": true, + "description": "Whether admin version endpoint is enabled." + }, + { + "name": "spring.application.admin.inspector.endpoint.enabled", + "type": "java.lang.Boolean", + "defaultValue": true, + "description": "Whether admin inspector endpoint is enabled." + }, + { + "name": "spring.application.admin.router.endpoint.enabled", + "type": "java.lang.Boolean", + "defaultValue": true, + "description": "Whether admin router endpoint is enabled." + }, + { + "name": "spring.application.admin.strategy.endpoint.enabled", + "type": "java.lang.Boolean", + "defaultValue": true, + "description": "Whether admin strategy endpoint is enabled." + }, + { + "name": "spring.application.admin.sentinel.endpoint.enabled", + "type": "java.lang.Boolean", + "defaultValue": true, + "description": "Whether admin sentinel endpoint is enabled." + }, + { + "name": "spring.application.admin.git.endpoint.enabled", + "type": "java.lang.Boolean", + "defaultValue": true, + "description": "Whether admin git endpoint is enabled." + }, + { + "name": "spring.application.admin.gateway.endpoint.enabled", + "type": "java.lang.Boolean", + "defaultValue": true, + "description": "Whether admin gateway endpoint is enabled." + }, + { + "name": "spring.application.admin.zuul.endpoint.enabled", + "type": "java.lang.Boolean", + "defaultValue": true, + "description": "Whether admin zuul endpoint is enabled." + }, + { + "name": "spring.application.admin.strategy.endpoint.validate-expression.enabled", + "type": "java.lang.Boolean", + "defaultValue": true, + "description": "Whether admin strategy endpoint for validate-expression is enabled." + } + ] +} \ No newline at end of file diff --git a/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/resources/META-INF/spring.factories b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/resources/META-INF/spring.factories new file mode 100644 index 0000000000..d60b8e3ee2 --- /dev/null +++ b/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/resources/META-INF/spring.factories @@ -0,0 +1,2 @@ +org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ +com.nepxion.discovery.plugin.admincenter.configuration.AdminAutoConfiguration \ No newline at end of file diff --git a/discovery-plugin-admin-center/pom.xml b/discovery-plugin-admin-center/pom.xml index 4410294873..377c69b250 100644 --- a/discovery-plugin-admin-center/pom.xml +++ b/discovery-plugin-admin-center/pom.xml @@ -3,42 +3,19 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> discovery-plugin-admin-center Nepxion Discovery Plugin Admin Center - jar + pom 4.0.0 - Nepxion Discovery is an enhancement for Spring Cloud Discovery + Nepxion Discovery is a solution for Spring Cloud with blue green, gray, weight, limitation, circuit breaker, degrade, isolation, monitor, tracing, dye, failover, async agent http://www.nepxion.com com.nepxion discovery - 5.2.0-SNAPSHOT + 6.23.0 - - - ${project.groupId} - discovery-plugin-framework - - - - org.springframework - spring-webmvc - provided - - - - org.springframework.boot - spring-boot-starter-actuator - - - - io.springfox - springfox-swagger2 - - - - io.springfox - springfox-swagger-ui - - + + discovery-plugin-admin-center-starter + discovery-plugin-admin-center-starter-swagger + \ No newline at end of file diff --git a/discovery-plugin-admin-center/src/main/java/com/nepxion/discovery/plugin/admincenter/configuration/AdminAutoConfiguration.java b/discovery-plugin-admin-center/src/main/java/com/nepxion/discovery/plugin/admincenter/configuration/AdminAutoConfiguration.java deleted file mode 100644 index c1d1d1450f..0000000000 --- a/discovery-plugin-admin-center/src/main/java/com/nepxion/discovery/plugin/admincenter/configuration/AdminAutoConfiguration.java +++ /dev/null @@ -1,59 +0,0 @@ -package com.nepxion.discovery.plugin.admincenter.configuration; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import org.springframework.boot.actuate.endpoint.web.annotation.RestControllerEndpoint; -import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; -import org.springframework.web.client.RestTemplate; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; - -import com.nepxion.discovery.plugin.admincenter.endpoint.ConfigEndpoint; -import com.nepxion.discovery.plugin.admincenter.endpoint.RouterEndpoint; -import com.nepxion.discovery.plugin.admincenter.endpoint.VersionEndpoint; - -@Configuration -@Import(SwaggerConfiguration.class) -public class AdminAutoConfiguration { - @ConditionalOnClass(RestControllerEndpoint.class) - protected static class AdminEndpointConfiguration { - @Bean - public ConfigEndpoint configEndpoint() { - return new ConfigEndpoint(); - } - - @Bean - public VersionEndpoint versionEndpoint() { - return new VersionEndpoint(); - } - - @Bean - public RouterEndpoint routerEndpoint() { - return new RouterEndpoint(); - } - - @Bean - public RestTemplate routerRestTemplate() { - return new RestTemplate(); - } - } - - @ConditionalOnClass(WebMvcConfigurer.class) - protected static class WebMvcActivationConfiguration { - @Bean - @ConditionalOnProperty(value = "cors.registry.enabled", matchIfMissing = true) - public CorsRegistryConfiguration corsRegistryConfiguration() { - return new CorsRegistryConfiguration(); - } - } -} \ No newline at end of file diff --git a/discovery-plugin-admin-center/src/main/java/com/nepxion/discovery/plugin/admincenter/configuration/CorsRegistryConfiguration.java b/discovery-plugin-admin-center/src/main/java/com/nepxion/discovery/plugin/admincenter/configuration/CorsRegistryConfiguration.java deleted file mode 100644 index d14f755534..0000000000 --- a/discovery-plugin-admin-center/src/main/java/com/nepxion/discovery/plugin/admincenter/configuration/CorsRegistryConfiguration.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.nepxion.discovery.plugin.admincenter.configuration; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.context.annotation.Configuration; -import org.springframework.web.servlet.config.annotation.CorsRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; - -@Configuration -@ConditionalOnClass(WebMvcConfigurer.class) -@ConditionalOnProperty(value = "cors.registry.enabled", matchIfMissing = true) -public class CorsRegistryConfiguration implements WebMvcConfigurer { - // 解决跨域问题 - @Override - public void addCorsMappings(CorsRegistry registry) { - registry.addMapping("/**") - .allowedHeaders("*") - .allowedMethods("*") - .allowedOrigins("*"); - } -} \ No newline at end of file diff --git a/discovery-plugin-admin-center/src/main/java/com/nepxion/discovery/plugin/admincenter/configuration/SwaggerConfiguration.java b/discovery-plugin-admin-center/src/main/java/com/nepxion/discovery/plugin/admincenter/configuration/SwaggerConfiguration.java deleted file mode 100644 index 307b4ea83f..0000000000 --- a/discovery-plugin-admin-center/src/main/java/com/nepxion/discovery/plugin/admincenter/configuration/SwaggerConfiguration.java +++ /dev/null @@ -1,128 +0,0 @@ -package com.nepxion.discovery.plugin.admincenter.configuration; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import springfox.documentation.RequestHandler; -import springfox.documentation.builders.ApiInfoBuilder; -import springfox.documentation.builders.PathSelectors; -import springfox.documentation.service.ApiInfo; -import springfox.documentation.service.Contact; -import springfox.documentation.service.Parameter; -import springfox.documentation.spi.DocumentationType; -import springfox.documentation.spring.web.plugins.Docket; -import springfox.documentation.swagger2.annotations.EnableSwagger2; - -import java.util.List; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.web.servlet.HandlerMapping; - -import com.google.common.base.Function; -import com.google.common.base.Optional; -import com.google.common.base.Predicate; -import com.nepxion.discovery.common.constant.DiscoveryConstant; - -@Configuration -@EnableSwagger2 -@ConditionalOnClass(HandlerMapping.class) -@ConditionalOnProperty(value = "swagger.service.enabled", matchIfMissing = true) -public class SwaggerConfiguration { - public static final String BASE_PACKAGE = "com.nepxion.discovery.plugin.admincenter.endpoint"; - - @Value("${spring.application.name}") - private String serviceName; - - @Value("${swagger.service.description:Admin Center Restful APIs}") - private String description; - - @Value("${swagger.service.version:1.0.0}") - private String version; - - @Value("${swagger.service.license.name:Apache License 2.0}") - private String license; - - @Value("${swagger.service.license.url:http://www.apache.org/licenses/LICENSE-2.0}") - private String licenseUrl; - - @Value("${swagger.service.contact.name:Haojun Ren}") - private String contactName; - - @Value("${swagger.service.contact.url:https://github.com/Nepxion/Discovery}") - private String contactUrl; - - @Value("${swagger.service.contact.email:1394997@qq.com}") - private String contactEmail; - - @Value("${swagger.service.termsOfServiceUrl:http://www.nepxion.com}") - private String termsOfServiceUrl; - - @Autowired(required = false) - private List swaggerHeaderParameters; - - @Bean("discoveryDocket") - public Docket createRestApi() { - return new Docket(DocumentationType.SWAGGER_2) - .groupName("discovery") - .apiInfo(apiInfo()) - .select() - .apis(SwaggerConfiguration.basePackage(BASE_PACKAGE)) // 扫描该包下的所有需要在Swagger中展示的API,@ApiIgnore注解标注的除外 - .paths(PathSelectors.any()) - .build() - .globalOperationParameters(swaggerHeaderParameters); - } - - private ApiInfo apiInfo() { - return new ApiInfoBuilder() - .title(serviceName) - .description(description) - .version(version) - .license(license) - .licenseUrl(licenseUrl) - .contact(new Contact(contactName, contactUrl, contactEmail)) - .termsOfServiceUrl(termsOfServiceUrl) - .build(); - } - - public static Predicate basePackage(String basePackage) { - return new Predicate() { - @Override - public boolean apply(RequestHandler input) { - return declaringClass(input).transform(handlerPackage(basePackage)).or(true); - } - }; - } - - private static Function, Boolean> handlerPackage(String basePackage) { - return new Function, Boolean>() { - @Override - public Boolean apply(Class input) { - String[] subPackages = basePackage.split(DiscoveryConstant.SEPARATE); - for (String subPackage : subPackages) { - boolean matched = input.getPackage().getName().startsWith(subPackage.trim()); - if (matched) { - return true; - } - } - - return false; - } - }; - } - - @SuppressWarnings("deprecation") - private static Optional> declaringClass(RequestHandler input) { - return Optional.fromNullable(input.declaringClass()); - } -} \ No newline at end of file diff --git a/discovery-plugin-admin-center/src/main/java/com/nepxion/discovery/plugin/admincenter/endpoint/ConfigEndpoint.java b/discovery-plugin-admin-center/src/main/java/com/nepxion/discovery/plugin/admincenter/endpoint/ConfigEndpoint.java deleted file mode 100644 index eb8cda4231..0000000000 --- a/discovery-plugin-admin-center/src/main/java/com/nepxion/discovery/plugin/admincenter/endpoint/ConfigEndpoint.java +++ /dev/null @@ -1,165 +0,0 @@ -package com.nepxion.discovery.plugin.admincenter.endpoint; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; - -import java.util.ArrayList; -import java.util.List; - -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.lang3.exception.ExceptionUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.actuate.endpoint.web.annotation.RestControllerEndpoint; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.jmx.export.annotation.ManagedOperation; -import org.springframework.jmx.export.annotation.ManagedResource; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.ResponseBody; -import org.springframework.web.bind.annotation.RestController; - -import com.nepxion.discovery.common.constant.DiscoveryConstant; -import com.nepxion.discovery.common.entity.RuleEntity; -import com.nepxion.discovery.plugin.framework.adapter.PluginAdapter; -import com.nepxion.discovery.plugin.framework.context.PluginContextAware; -import com.nepxion.discovery.plugin.framework.event.PluginEventWapper; -import com.nepxion.discovery.plugin.framework.event.RuleClearedEvent; -import com.nepxion.discovery.plugin.framework.event.RuleUpdatedEvent; - -@RestController -@RequestMapping(path = "/config") -@Api(tags = { "配置接口" }) -@RestControllerEndpoint(id = "config") -@ManagedResource(description = "Config Endpoint") -public class ConfigEndpoint { - @Autowired - private PluginContextAware pluginContextAware; - - @Autowired - private PluginAdapter pluginAdapter; - - @Autowired - private PluginEventWapper pluginEventWapper; - - @RequestMapping(path = "/update-async", method = RequestMethod.POST) - @ApiOperation(value = "异步推送更新规则配置信息", notes = "", response = ResponseEntity.class, httpMethod = "POST") - @ResponseBody - @ManagedOperation - public ResponseEntity updateAsync(@RequestBody @ApiParam(value = "规则配置内容,XML格式", required = true) String config) { - return update(config, true); - } - - @RequestMapping(path = "/update-sync", method = RequestMethod.POST) - @ApiOperation(value = "同步推送更新规则配置信息", notes = "", response = ResponseEntity.class, httpMethod = "POST") - @ResponseBody - @ManagedOperation - public ResponseEntity updateSync(@RequestBody @ApiParam(value = "规则配置内容,XML格式", required = true) String config) { - return update(config, false); - } - - @RequestMapping(path = "/clear-async", method = RequestMethod.POST) - @ApiOperation(value = "异步清除更新的规则配置信息", notes = "", response = ResponseEntity.class, httpMethod = "POST") - @ResponseBody - @ManagedOperation - public ResponseEntity clearAsync() { - return clear(true); - } - - @RequestMapping(path = "/clear-sync", method = RequestMethod.POST) - @ApiOperation(value = "同步清除更新的规则配置信息", notes = "", response = ResponseEntity.class, httpMethod = "POST") - @ResponseBody - @ManagedOperation - public ResponseEntity clearSync() { - return clear(false); - } - - @RequestMapping(path = "/view", method = RequestMethod.GET) - @ApiOperation(value = "查看本地和更新的规则配置信息", notes = "", response = ResponseEntity.class, httpMethod = "GET") - @ResponseBody - @ManagedOperation - public ResponseEntity> view() { - return view(false); - } - - private ResponseEntity update(String config, boolean async) { - Boolean discoveryControlEnabled = pluginContextAware.isDiscoveryControlEnabled(); - if (!discoveryControlEnabled) { - // return new ResponseEntity<>(Collections.singletonMap("Message", "Discovery control is disabled"), HttpStatus.NOT_FOUND); - - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Discovery control is disabled"); - } - - Boolean isConfigRestControlEnabled = pluginContextAware.isConfigRestControlEnabled(); - if (!isConfigRestControlEnabled) { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Config rest control is disabled"); - } - - pluginEventWapper.fireRuleUpdated(new RuleUpdatedEvent(config), async); - - // return ResponseEntity.ok().build(); - - return ResponseEntity.ok().body(DiscoveryConstant.OK); - } - - private ResponseEntity clear(boolean async) { - Boolean discoveryControlEnabled = pluginContextAware.isDiscoveryControlEnabled(); - if (!discoveryControlEnabled) { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Discovery control is disabled"); - } - - Boolean isConfigRestControlEnabled = pluginContextAware.isConfigRestControlEnabled(); - if (!isConfigRestControlEnabled) { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Config rest control is disabled"); - } - - pluginEventWapper.fireRuleCleared(new RuleClearedEvent(), async); - - return ResponseEntity.ok().body(DiscoveryConstant.OK); - } - - private ResponseEntity> view(boolean async) { - List ruleList = new ArrayList(2); - - String localRuleContent = StringUtils.EMPTY; - RuleEntity localRuleEntity = pluginAdapter.getLocalRule(); - if (localRuleEntity != null && StringUtils.isNotEmpty(localRuleEntity.getContent())) { - localRuleContent = localRuleEntity.getContent(); - } - - String dynamicRuleContent = StringUtils.EMPTY; - RuleEntity dynamicRuleEntity = pluginAdapter.getDynamicRule(); - if (dynamicRuleEntity != null && StringUtils.isNotEmpty(dynamicRuleEntity.getContent())) { - dynamicRuleContent = dynamicRuleEntity.getContent(); - } - - ruleList.add(localRuleContent); - ruleList.add(dynamicRuleContent); - - return ResponseEntity.ok().body(ruleList); - } - - protected ResponseEntity toExceptionResponseEntity(Exception e, boolean showDetail) { - String message = null; - if (showDetail) { - message = ExceptionUtils.getStackTrace(e); - } else { - message = e.getMessage(); - } - - message = "An internal error occurred while processing your request\n" + message; - - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(message); - } -} \ No newline at end of file diff --git a/discovery-plugin-admin-center/src/main/java/com/nepxion/discovery/plugin/admincenter/endpoint/RouterEndpoint.java b/discovery-plugin-admin-center/src/main/java/com/nepxion/discovery/plugin/admincenter/endpoint/RouterEndpoint.java deleted file mode 100644 index 4515d61c4d..0000000000 --- a/discovery-plugin-admin-center/src/main/java/com/nepxion/discovery/plugin/admincenter/endpoint/RouterEndpoint.java +++ /dev/null @@ -1,319 +0,0 @@ -package com.nepxion.discovery.plugin.admincenter.endpoint; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.apache.commons.collections4.CollectionUtils; -import org.apache.commons.lang3.StringUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.actuate.endpoint.web.annotation.RestControllerEndpoint; -import org.springframework.cloud.client.ServiceInstance; -import org.springframework.cloud.client.discovery.DiscoveryClient; -import org.springframework.jmx.export.annotation.ManagedOperation; -import org.springframework.jmx.export.annotation.ManagedResource; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.ResponseBody; -import org.springframework.web.bind.annotation.RestController; -import org.springframework.web.client.RestClientException; -import org.springframework.web.client.RestTemplate; - -import com.fasterxml.jackson.core.type.TypeReference; -import com.nepxion.discovery.common.constant.DiscoveryConstant; -import com.nepxion.discovery.common.entity.DiscoveryEntity; -import com.nepxion.discovery.common.entity.RegionWeightEntity; -import com.nepxion.discovery.common.entity.RouterEntity; -import com.nepxion.discovery.common.entity.RuleEntity; -import com.nepxion.discovery.common.entity.VersionWeightEntity; -import com.nepxion.discovery.common.entity.WeightEntity; -import com.nepxion.discovery.common.entity.WeightEntityWrapper; -import com.nepxion.discovery.common.entity.WeightFilterEntity; -import com.nepxion.discovery.common.exception.DiscoveryException; -import com.nepxion.discovery.common.util.JsonUtil; -import com.nepxion.discovery.common.util.UrlUtil; -import com.nepxion.discovery.plugin.framework.adapter.PluginAdapter; - -@RestController -@RequestMapping(path = "/router") -@Api(tags = { "路由接口" }) -@RestControllerEndpoint(id = "router") -@ManagedResource(description = "Router Endpoint") -public class RouterEndpoint { - @Autowired - private PluginAdapter pluginAdapter; - - @Autowired - private RestTemplate routerRestTemplate; - - @Autowired - private DiscoveryClient discoveryClient; - - @RequestMapping(path = "/services", method = RequestMethod.GET) - @ApiOperation(value = "获取服务注册中心的服务列表", notes = "", response = List.class, httpMethod = "GET") - @ResponseBody - @ManagedOperation - public List services() { - return getServices(); - } - - @RequestMapping(path = "/instances/{serviceId}", method = RequestMethod.GET) - @ApiOperation(value = "获取本地节点可访问其他节点(根据服务名)的实例列表", notes = "", response = List.class, httpMethod = "GET") - @ResponseBody - @ManagedOperation - public List instances(@PathVariable(value = "serviceId") @ApiParam(value = "目标服务名", required = true) String serviceId) { - return getInstanceList(serviceId); - } - - @RequestMapping(path = "/info", method = RequestMethod.GET) - @ApiOperation(value = "获取本地节点信息", notes = "获取当前节点的简单信息", response = RouterEntity.class, httpMethod = "GET") - @ResponseBody - @ManagedOperation - public RouterEntity info() { - return getRouterEntity(); - } - - @RequestMapping(path = "/route/{routeServiceId}", method = RequestMethod.GET) - @ApiOperation(value = "获取本地节点可访问其他节点(根据服务名)的路由信息列表", notes = "", response = List.class, httpMethod = "GET") - @ResponseBody - @ManagedOperation - public List route(@PathVariable(value = "routeServiceId") @ApiParam(value = "目标服务名", required = true) String routeServiceId) { - return getRouterEntityList(routeServiceId); - } - - @RequestMapping(path = "/route/{routeServiceId}/{routeHost}/{routePort}/{routeContextPath}", method = RequestMethod.GET) - @ApiOperation(value = "获取指定节点(根据IP和端口)可访问其他节点(根据服务名)的路由信息列表", notes = "", response = List.class, httpMethod = "GET") - @ResponseBody - @ManagedOperation - public List route(@PathVariable(value = "routeServiceId") @ApiParam(value = "目标服务名", required = true) String routeServiceId, @PathVariable(value = "routeHost") @ApiParam(value = "目标服务所在机器的IP地址", required = true) String routeHost, @PathVariable(value = "routePort") @ApiParam(value = "目标服务所在机器的端口号", required = true) int routePort, @PathVariable(value = "routeContextPath") @ApiParam(value = "目标服务的调用路径前缀", required = true, defaultValue = "/") String routeContextPath) { - return getRouterEntityList(routeServiceId, routeHost, routePort, routeContextPath); - } - - @RequestMapping(path = "/routes", method = RequestMethod.POST) - @ApiOperation(value = "获取全路径的路由信息树", notes = "参数按调用服务名的前后次序排列,起始节点的服务名不能加上去。如果多个用“;”分隔,不允许出现空格", response = RouterEntity.class, httpMethod = "POST") - @ResponseBody - @ManagedOperation - public RouterEntity routes(@RequestBody @ApiParam(value = "例如:service-a;service-b", required = true) String routeServiceIds) { - return routeTree(routeServiceIds); - } - - public List getServices() { - return discoveryClient.getServices(); - } - - public List getInstanceList(String serviceId) { - return discoveryClient.getInstances(serviceId); - } - - public RouterEntity getRouterEntity() { - String serviceType = pluginAdapter.getServiceType(); - String serviceId = pluginAdapter.getServiceId(); - String version = pluginAdapter.getVersion(); - String region = pluginAdapter.getRegion(); - String host = pluginAdapter.getHost(); - int port = pluginAdapter.getPort(); - int weight = getWeight(serviceId, version, region); - String contextPath = pluginAdapter.getContextPath(); - - RouterEntity routerEntity = new RouterEntity(); - routerEntity.setServiceType(serviceType); - routerEntity.setServiceId(serviceId); - routerEntity.setVersion(version); - routerEntity.setRegion(region); - routerEntity.setHost(host); - routerEntity.setPort(port); - routerEntity.setWeight(weight); - routerEntity.setContextPath(contextPath); - - return routerEntity; - } - - public List getRouterEntityList(String routeServiceId) { - List instanceList = null; - - try { - instanceList = getInstanceList(routeServiceId); - } catch (Exception e) { - throw new DiscoveryException("Get instance list for route serviceId=" + routeServiceId + " failed", e); - } - - if (CollectionUtils.isEmpty(instanceList)) { - return null; - } - - List routerEntityList = new ArrayList(); - for (ServiceInstance instance : instanceList) { - Map metadata = instance.getMetadata(); - String serviceId = instance.getServiceId().toLowerCase(); - String serviceType = metadata.get(DiscoveryConstant.SPRING_APPLICATION_TYPE); - String version = metadata.get(DiscoveryConstant.VERSION); - String region = metadata.get(DiscoveryConstant.REGION); - String host = instance.getHost(); - int port = instance.getPort(); - int weight = getWeight(routeServiceId, version, region); - String contextPath = metadata.get(DiscoveryConstant.SPRING_APPLICATION_CONTEXT_PATH); - - RouterEntity routerEntity = new RouterEntity(); - routerEntity.setServiceType(serviceType); - routerEntity.setServiceId(serviceId); - routerEntity.setVersion(version); - routerEntity.setRegion(region); - routerEntity.setHost(host); - routerEntity.setPort(port); - routerEntity.setWeight(weight); - routerEntity.setContextPath(contextPath); - - routerEntityList.add(routerEntity); - } - - return routerEntityList; - } - - public List getRouterEntityList(String routeServiceId, String routeHost, int routePort, String routeContextPath) { - String url = "http://" + routeHost + ":" + routePort + UrlUtil.formatContextPath(routeContextPath) + "router/route/" + routeServiceId; - - String result = null; - try { - result = routerRestTemplate.getForEntity(url, String.class).getBody(); - } catch (RestClientException e) { - throw new DiscoveryException("Get instance list for route serviceId=" + routeServiceId + " with url=" + url + " failed", e); - } - - if (StringUtils.isEmpty(result)) { - return null; - } - - List routerEntityList = JsonUtil.fromJson(result, new TypeReference>() { - }); - - return routerEntityList; - } - - public RouterEntity routeTree(String routeServiceIds) { - if (StringUtils.isEmpty(routeServiceIds)) { - throw new DiscoveryException("Route serviceIds is empty"); - } - - String[] serviceIdArray = null; - try { - serviceIdArray = StringUtils.split(routeServiceIds, DiscoveryConstant.SEPARATE); - } catch (Exception e) { - throw new DiscoveryException("Route serviceIds must be separated with '" + DiscoveryConstant.SEPARATE + "'", e); - } - - RouterEntity firstRouterEntity = getRouterEntity(); - - // 路由深度为Key - HashMap> routerEntityMap = new HashMap>(); - int routerDepth = 0; - for (String serviceId : serviceIdArray) { - serviceId = serviceId.toLowerCase().trim(); - if (routerDepth == 0) { - routeFirst(firstRouterEntity, serviceId); - - retrieveRouterEntityList(routerEntityMap, routerDepth).addAll(firstRouterEntity.getNexts()); - } else { - List routerEntityList = retrieveRouterEntityList(routerEntityMap, routerDepth - 1); - for (RouterEntity routerEntity : routerEntityList) { - String routeHost = routerEntity.getHost(); - int routePort = routerEntity.getPort(); - String routeContextPath = routerEntity.getContextPath(); - - route(routerEntity, serviceId, routeHost, routePort, routeContextPath); - - retrieveRouterEntityList(routerEntityMap, routerDepth).addAll(routerEntity.getNexts()); - } - } - - routerDepth++; - } - - return firstRouterEntity; - } - - private void routeFirst(RouterEntity routerEntity, String routeServiceId) { - List routerEntityList = getRouterEntityList(routeServiceId); - if (CollectionUtils.isNotEmpty(routerEntityList)) { - routerEntity.getNexts().addAll(routerEntityList); - } - } - - private void route(RouterEntity routerEntity, String routeServiceId, String routeHost, int routePort, String routeContextPath) { - List routerEntityList = getRouterEntityList(routeServiceId, routeHost, routePort, routeContextPath); - if (CollectionUtils.isNotEmpty(routerEntityList)) { - routerEntity.getNexts().addAll(routerEntityList); - } - } - - private List retrieveRouterEntityList(HashMap> routerEntityMap, int routerDepth) { - List routerEntityList = routerEntityMap.get(routerDepth); - if (routerEntityList == null) { - routerEntityList = new ArrayList(); - routerEntityMap.put(routerDepth, routerEntityList); - } - - return routerEntityList; - } - - private int getWeight(String providerServiceId, String providerVersion, String providerRegion) { - RuleEntity ruleEntity = pluginAdapter.getRule(); - if (ruleEntity == null) { - return -1; - } - - DiscoveryEntity discoveryEntity = ruleEntity.getDiscoveryEntity(); - if (discoveryEntity == null) { - return -1; - } - - WeightFilterEntity weightFilterEntity = discoveryEntity.getWeightFilterEntity(); - if (weightFilterEntity == null || !weightFilterEntity.hasWeight()) { - return -1; - } - - Map> versionWeightEntityMap = weightFilterEntity.getVersionWeightEntityMap(); - List versionWeightEntityList = weightFilterEntity.getVersionWeightEntityList(); - VersionWeightEntity versionWeightEntity = weightFilterEntity.getVersionWeightEntity(); - - Map> regionWeightEntityMap = weightFilterEntity.getRegionWeightEntityMap(); - List regionWeightEntityList = weightFilterEntity.getRegionWeightEntityList(); - RegionWeightEntity regionWeightEntity = weightFilterEntity.getRegionWeightEntity(); - - String serviceId = pluginAdapter.getServiceId(); - int weight = WeightEntityWrapper.getWeight(serviceId, providerServiceId, providerVersion, versionWeightEntityMap); - if (weight < 0) { - weight = WeightEntityWrapper.getWeight(providerServiceId, providerVersion, versionWeightEntityList); - } - if (weight < 0) { - weight = WeightEntityWrapper.getWeight(providerVersion, versionWeightEntity); - } - - if (weight < 0) { - weight = WeightEntityWrapper.getWeight(serviceId, providerServiceId, providerRegion, regionWeightEntityMap); - } - if (weight < 0) { - weight = WeightEntityWrapper.getWeight(providerServiceId, providerRegion, regionWeightEntityList); - } - if (weight < 0) { - weight = WeightEntityWrapper.getWeight(providerRegion, regionWeightEntity); - } - - return weight; - } -} \ No newline at end of file diff --git a/discovery-plugin-admin-center/src/main/java/com/nepxion/discovery/plugin/admincenter/endpoint/VersionEndpoint.java b/discovery-plugin-admin-center/src/main/java/com/nepxion/discovery/plugin/admincenter/endpoint/VersionEndpoint.java deleted file mode 100644 index 4a083f765e..0000000000 --- a/discovery-plugin-admin-center/src/main/java/com/nepxion/discovery/plugin/admincenter/endpoint/VersionEndpoint.java +++ /dev/null @@ -1,148 +0,0 @@ -package com.nepxion.discovery.plugin.admincenter.endpoint; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; - -import java.util.ArrayList; -import java.util.List; - -import org.apache.commons.lang3.StringUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.actuate.endpoint.web.annotation.RestControllerEndpoint; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.jmx.export.annotation.ManagedOperation; -import org.springframework.jmx.export.annotation.ManagedResource; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.ResponseBody; -import org.springframework.web.bind.annotation.RestController; - -import com.nepxion.discovery.common.constant.DiscoveryConstant; -import com.nepxion.discovery.plugin.framework.adapter.PluginAdapter; -import com.nepxion.discovery.plugin.framework.context.PluginContextAware; -import com.nepxion.discovery.plugin.framework.event.PluginEventWapper; -import com.nepxion.discovery.plugin.framework.event.VersionClearedEvent; -import com.nepxion.discovery.plugin.framework.event.VersionUpdatedEvent; - -@RestController -@RequestMapping(path = "/version") -@Api(tags = { "版本接口" }) -@RestControllerEndpoint(id = "version") -@ManagedResource(description = "Version Endpoint") -public class VersionEndpoint { - @Autowired - private PluginContextAware pluginContextAware; - - @Autowired - private PluginAdapter pluginAdapter; - - @Autowired - private PluginEventWapper pluginEventWapper; - - @RequestMapping(path = "/update-async", method = RequestMethod.POST) - @ApiOperation(value = "异步更新服务的动态版本", notes = "根据指定的localVersion更新服务的dynamicVersion。如果输入的localVersion不匹配服务的localVersion,则忽略;如果如果输入的localVersion为空,则直接更新服务的dynamicVersion", response = ResponseEntity.class, httpMethod = "POST") - @ResponseBody - @ManagedOperation - public ResponseEntity updateAsync(@RequestBody @ApiParam(value = "版本号,格式为[dynamicVersion]或者[dynamicVersion];[localVersion]", required = true) String version) { - return update(version, true); - } - - @RequestMapping(path = "/update-sync", method = RequestMethod.POST) - @ApiOperation(value = "同步更新服务的动态版本", notes = "根据指定的localVersion更新服务的dynamicVersion。如果输入的localVersion不匹配服务的localVersion,则忽略;如果如果输入的localVersion为空,则直接更新服务的dynamicVersion", response = ResponseEntity.class, httpMethod = "POST") - @ResponseBody - @ManagedOperation - public ResponseEntity updateSync(@RequestBody @ApiParam(value = "版本号,格式为[dynamicVersion]或者[dynamicVersion];[localVersion]", required = true) String version) { - return update(version, false); - } - - @RequestMapping(path = "/clear-async", method = RequestMethod.POST) - @ApiOperation(value = "异步清除服务的动态版本", notes = "根据指定的localVersion清除服务的dynamicVersion。如果输入的localVersion不匹配服务的localVersion,则忽略;如果如果输入的localVersion为空,则直接清除服务的dynamicVersion", response = ResponseEntity.class, httpMethod = "POST") - @ResponseBody - @ManagedOperation - public ResponseEntity clearAsync(@RequestBody(required = false) @ApiParam(value = "版本号,指localVersion,可以为空") String version) { - return clear(version, true); - } - - @RequestMapping(path = "/clear-sync", method = RequestMethod.POST) - @ApiOperation(value = "同步清除服务的动态版本", notes = "根据指定的localVersion清除服务的dynamicVersion。如果输入的localVersion不匹配服务的localVersion,则忽略;如果如果输入的localVersion为空,则直接清除服务的dynamicVersion", response = ResponseEntity.class, httpMethod = "POST") - @ResponseBody - @ManagedOperation - public ResponseEntity clearSync(@RequestBody(required = false) @ApiParam(value = "版本号,指localVersion,可以为空") String version) { - return clear(version, false); - } - - @RequestMapping(path = "/view", method = RequestMethod.GET) - @ApiOperation(value = "查看服务的本地版本和动态版本", notes = "", response = ResponseEntity.class, httpMethod = "GET") - @ResponseBody - @ManagedOperation - public ResponseEntity> view() { - return view(false); - } - - private ResponseEntity update(String version, boolean async) { - Boolean discoveryControlEnabled = pluginContextAware.isDiscoveryControlEnabled(); - if (!discoveryControlEnabled) { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Discovery control is disabled"); - } - - if (StringUtils.isEmpty(version)) { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Version can't be null or empty"); - } - - String dynamicVersion = null; - String localVersion = null; - String[] versionArray = StringUtils.split(version, DiscoveryConstant.SEPARATE); - if (versionArray.length == 2) { - dynamicVersion = versionArray[0]; - localVersion = versionArray[1]; - } else if (versionArray.length == 1) { - dynamicVersion = versionArray[0]; - } else { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Invalid version format, it must be '[dynamicVersion]' or '[dynamicVersion];[localVersion]'"); - } - - pluginEventWapper.fireVersionUpdated(new VersionUpdatedEvent(dynamicVersion, localVersion), async); - - return ResponseEntity.ok().body(DiscoveryConstant.OK); - } - - private ResponseEntity clear(String version, boolean async) { - Boolean discoveryControlEnabled = pluginContextAware.isDiscoveryControlEnabled(); - if (!discoveryControlEnabled) { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Discovery control is disabled"); - } - - // 修复Swagger的一个Bug,当在Swagger界面不输入版本号的时候,传到后端变成了“{}” - if (StringUtils.isNotEmpty(version) && StringUtils.equals(version.trim(), "{}")) { - version = null; - } - - pluginEventWapper.fireVersionCleared(new VersionClearedEvent(version), async); - - return ResponseEntity.ok().body(DiscoveryConstant.OK); - } - - private ResponseEntity> view(boolean async) { - List versionList = new ArrayList(2); - - String localVersion = pluginAdapter.getLocalVersion(); - String dynamicVersion = pluginAdapter.getDynamicVersion(); - - versionList.add(StringUtils.isNotEmpty(localVersion) ? localVersion : StringUtils.EMPTY); - versionList.add(StringUtils.isNotEmpty(dynamicVersion) ? dynamicVersion : StringUtils.EMPTY); - - return ResponseEntity.ok().body(versionList); - } -} \ No newline at end of file diff --git a/discovery-plugin-config-center-starter-apollo/pom.xml b/discovery-plugin-config-center-starter-apollo/pom.xml deleted file mode 100644 index 5ee7ad5d86..0000000000 --- a/discovery-plugin-config-center-starter-apollo/pom.xml +++ /dev/null @@ -1,28 +0,0 @@ - - - discovery-plugin-config-center-starter-apollo - Nepxion Discovery Plugin Config Center Starter Apollo - jar - 4.0.0 - Nepxion Discovery is an enhancement for Spring Cloud Discovery - http://www.nepxion.com - - - com.nepxion - discovery - 5.2.0-SNAPSHOT - - - - - ${project.groupId} - discovery-plugin-config-center - - - - ${project.groupId} - discovery-common-apollo - - - \ No newline at end of file diff --git a/discovery-plugin-config-center-starter-apollo/src/main/java/com/nepxion/discovery/plugin/configcenter/apollo/adapter/ApolloConfigAdapter.java b/discovery-plugin-config-center-starter-apollo/src/main/java/com/nepxion/discovery/plugin/configcenter/apollo/adapter/ApolloConfigAdapter.java deleted file mode 100644 index 243fc1b857..0000000000 --- a/discovery-plugin-config-center-starter-apollo/src/main/java/com/nepxion/discovery/plugin/configcenter/apollo/adapter/ApolloConfigAdapter.java +++ /dev/null @@ -1,143 +0,0 @@ -package com.nepxion.discovery.plugin.configcenter.apollo.adapter; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import javax.annotation.PostConstruct; - -import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; - -import com.ctrip.framework.apollo.ConfigChangeListener; -import com.nepxion.discovery.common.apollo.constant.ApolloConstant; -import com.nepxion.discovery.common.apollo.operation.ApolloOperation; -import com.nepxion.discovery.common.apollo.operation.ApolloSubscribeCallback; -import com.nepxion.discovery.common.constant.DiscoveryConstant; -import com.nepxion.discovery.common.entity.RuleEntity; -import com.nepxion.discovery.plugin.configcenter.adapter.ConfigAdapter; -import com.nepxion.discovery.plugin.framework.adapter.PluginAdapter; -import com.nepxion.discovery.plugin.framework.event.RuleClearedEvent; -import com.nepxion.discovery.plugin.framework.event.RuleUpdatedEvent; - -public class ApolloConfigAdapter extends ConfigAdapter { - private static final Logger LOG = LoggerFactory.getLogger(ApolloConfigAdapter.class); - - @Autowired - private PluginAdapter pluginAdapter; - - @Autowired - private ApolloOperation apolloOperation; - - private ConfigChangeListener partialListener; - private ConfigChangeListener globalListener; - - @Override - public String getConfig() throws Exception { - String config = getConfig(false); - if (StringUtils.isNotEmpty(config)) { - return config; - } else { - LOG.info("No {} config is retrieved from {} server", getConfigScope(false), getConfigType()); - } - - config = getConfig(true); - if (StringUtils.isNotEmpty(config)) { - return config; - } else { - LOG.info("No {} config is retrieved from {} server", getConfigScope(true), getConfigType()); - } - - return null; - } - - private String getConfig(boolean globalConfig) throws Exception { - String groupKey = pluginAdapter.getGroupKey(); - String group = pluginAdapter.getGroup(); - String serviceId = pluginAdapter.getServiceId(); - - LOG.info("Get {} config from {} server, {}={}, serviceId={}", getConfigScope(globalConfig), getConfigType(), groupKey, group, serviceId); - - return apolloOperation.getConfig(group, globalConfig ? group : serviceId); - } - - @PostConstruct - public void subscribeConfig() { - partialListener = subscribeConfig(false); - globalListener = subscribeConfig(true); - } - - private ConfigChangeListener subscribeConfig(boolean globalConfig) { - String groupKey = pluginAdapter.getGroupKey(); - String group = pluginAdapter.getGroup(); - String serviceId = pluginAdapter.getServiceId(); - - LOG.info("Subscribe {} config from {} server, {}={}, serviceId={}", getConfigScope(globalConfig), getConfigType(), groupKey, group, serviceId); - - try { - return apolloOperation.subscribeConfig(group, globalConfig ? group : serviceId, new ApolloSubscribeCallback() { - @Override - public void callback(String config) { - if (StringUtils.isNotEmpty(config)) { - LOG.info("Get {} config updated event from {} server, {}={}, serviceId={}", getConfigScope(globalConfig), getConfigType(), groupKey, group, serviceId); - - RuleEntity ruleEntity = pluginAdapter.getRule(); - String rule = null; - if (ruleEntity != null) { - rule = ruleEntity.getContent(); - } - if (!StringUtils.equals(rule, config)) { - fireRuleUpdated(new RuleUpdatedEvent(config), true); - } else { - LOG.info("Retrieved {} config from {} server is same as current config, ignore to update, {}={}, serviceId={}", getConfigScope(globalConfig), getConfigType(), groupKey, group, serviceId); - } - } else { - LOG.info("Get {} config cleared event from {} server, {}={}, serviceId={}", getConfigScope(globalConfig), getConfigType(), groupKey, group, serviceId); - - fireRuleCleared(new RuleClearedEvent(), true); - } - } - }); - } catch (Exception e) { - LOG.error("Subscribe {} config from {} server failed, {}={}, serviceId={}", getConfigScope(globalConfig), getConfigType(), groupKey, group, serviceId, e); - } - - return null; - } - - @Override - public void close() { - unsubscribeConfig(partialListener, false); - unsubscribeConfig(globalListener, true); - } - - private void unsubscribeConfig(ConfigChangeListener configListener, boolean globalConfig) { - if (configListener == null) { - return; - } - - String groupKey = pluginAdapter.getGroupKey(); - String group = pluginAdapter.getGroup(); - String serviceId = pluginAdapter.getServiceId(); - - LOG.info("Unsubscribe {} config from {} server, {}={}, serviceId={}", getConfigScope(globalConfig), getConfigType(), groupKey, group, serviceId); - - apolloOperation.unsubscribeConfig(group, globalConfig ? group : serviceId, configListener); - } - - public String getConfigScope(boolean globalConfig) { - return globalConfig ? DiscoveryConstant.GLOBAL : DiscoveryConstant.PARTIAL; - } - - @Override - public String getConfigType() { - return ApolloConstant.TYPE; - } -} \ No newline at end of file diff --git a/discovery-plugin-config-center-starter-apollo/src/main/java/com/nepxion/discovery/plugin/configcenter/apollo/configuration/ApolloConfigAutoConfiguration.java b/discovery-plugin-config-center-starter-apollo/src/main/java/com/nepxion/discovery/plugin/configcenter/apollo/configuration/ApolloConfigAutoConfiguration.java deleted file mode 100644 index 7aa9629916..0000000000 --- a/discovery-plugin-config-center-starter-apollo/src/main/java/com/nepxion/discovery/plugin/configcenter/apollo/configuration/ApolloConfigAutoConfiguration.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.nepxion.discovery.plugin.configcenter.apollo.configuration; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -import com.nepxion.banner.BannerConstant; -import com.nepxion.banner.Description; -import com.nepxion.banner.LogoBanner; -import com.nepxion.banner.NepxionBanner; -import com.nepxion.discovery.common.apollo.constant.ApolloConstant; -import com.nepxion.discovery.plugin.configcenter.adapter.ConfigAdapter; -import com.nepxion.discovery.plugin.configcenter.apollo.adapter.ApolloConfigAdapter; -import com.taobao.text.Color; - -@Configuration -public class ApolloConfigAutoConfiguration { - static { - /*String bannerShown = System.getProperty(BannerConstant.BANNER_SHOWN, "true"); - if (Boolean.valueOf(bannerShown)) { - System.out.println(""); - System.out.println("╔═══╗ ╔╗╔╗"); - System.out.println("║╔═╗║ ║║║║"); - System.out.println("║║ ║╠══╦══╣║║║╔══╗"); - System.out.println("║╚═╝║╔╗║╔╗║║║║║╔╗║"); - System.out.println("║╔═╗║╚╝║╚╝║╚╣╚╣╚╝║"); - System.out.println("╚╝ ╚╣╔═╩══╩═╩═╩══╝"); - System.out.println(" ║║"); - System.out.println(" ╚╝"); - System.out.println(ApolloConstant.TYPE + " Config"); - System.out.println(""); - }*/ - - LogoBanner logoBanner = new LogoBanner(ApolloConfigAutoConfiguration.class, "/com/nepxion/apollo/resource/logo.txt", "Welcome to Nepxion", 6, 5, new Color[] { Color.red, Color.green, Color.cyan, Color.blue, Color.yellow, Color.magenta }, true); - - NepxionBanner.show(logoBanner, new Description("Config:", ApolloConstant.TYPE, 0, 1), new Description(BannerConstant.GITHUB + ":", BannerConstant.NEPXION_GITHUB + "/Discovery", 0, 1)); - } - - @Bean - public ConfigAdapter configAdapter() { - return new ApolloConfigAdapter(); - } -} \ No newline at end of file diff --git a/discovery-plugin-config-center-starter-apollo/src/main/resources/META-INF/spring.factories b/discovery-plugin-config-center-starter-apollo/src/main/resources/META-INF/spring.factories deleted file mode 100644 index fcc3a18213..0000000000 --- a/discovery-plugin-config-center-starter-apollo/src/main/resources/META-INF/spring.factories +++ /dev/null @@ -1,3 +0,0 @@ -org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ -com.nepxion.discovery.common.apollo.configuration.ApolloAutoConfiguration,\ -com.nepxion.discovery.plugin.configcenter.apollo.configuration.ApolloConfigAutoConfiguration \ No newline at end of file diff --git a/discovery-plugin-config-center-starter-nacos/pom.xml b/discovery-plugin-config-center-starter-nacos/pom.xml deleted file mode 100644 index 6041097909..0000000000 --- a/discovery-plugin-config-center-starter-nacos/pom.xml +++ /dev/null @@ -1,28 +0,0 @@ - - - discovery-plugin-config-center-starter-nacos - Nepxion Discovery Plugin Config Center Starter Nacos - jar - 4.0.0 - Nepxion Discovery is an enhancement for Spring Cloud Discovery - http://www.nepxion.com - - - com.nepxion - discovery - 5.2.0-SNAPSHOT - - - - - ${project.groupId} - discovery-plugin-config-center - - - - ${project.groupId} - discovery-common-nacos - - - \ No newline at end of file diff --git a/discovery-plugin-config-center-starter-nacos/src/main/java/com/nepxion/discovery/plugin/configcenter/nacos/adapter/NacosConfigAdapter.java b/discovery-plugin-config-center-starter-nacos/src/main/java/com/nepxion/discovery/plugin/configcenter/nacos/adapter/NacosConfigAdapter.java deleted file mode 100644 index 3ba0c57a16..0000000000 --- a/discovery-plugin-config-center-starter-nacos/src/main/java/com/nepxion/discovery/plugin/configcenter/nacos/adapter/NacosConfigAdapter.java +++ /dev/null @@ -1,153 +0,0 @@ -package com.nepxion.discovery.plugin.configcenter.nacos.adapter; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import java.util.concurrent.ArrayBlockingQueue; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.TimeUnit; - -import javax.annotation.PostConstruct; - -import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; - -import com.alibaba.nacos.api.config.listener.Listener; -import com.nepxion.discovery.common.constant.DiscoveryConstant; -import com.nepxion.discovery.common.entity.RuleEntity; -import com.nepxion.discovery.common.nacos.constant.NacosConstant; -import com.nepxion.discovery.common.nacos.operation.NacosOperation; -import com.nepxion.discovery.common.nacos.operation.NacosSubscribeCallback; -import com.nepxion.discovery.common.thread.NamedThreadFactory; -import com.nepxion.discovery.plugin.configcenter.adapter.ConfigAdapter; -import com.nepxion.discovery.plugin.framework.adapter.PluginAdapter; -import com.nepxion.discovery.plugin.framework.event.RuleClearedEvent; -import com.nepxion.discovery.plugin.framework.event.RuleUpdatedEvent; - -public class NacosConfigAdapter extends ConfigAdapter { - private static final Logger LOG = LoggerFactory.getLogger(NacosConfigAdapter.class); - - private ExecutorService executorService = new ThreadPoolExecutor(2, 4, 0, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(1), new NamedThreadFactory("nacos-config"), new ThreadPoolExecutor.DiscardOldestPolicy()); - - @Autowired - private PluginAdapter pluginAdapter; - - @Autowired - private NacosOperation nacosOperation; - - private Listener partialListener; - private Listener globalListener; - - @Override - public String getConfig() throws Exception { - String config = getConfig(false); - if (StringUtils.isNotEmpty(config)) { - return config; - } else { - LOG.info("No {} config is retrieved from {} server", getConfigScope(false), getConfigType()); - } - - config = getConfig(true); - if (StringUtils.isNotEmpty(config)) { - return config; - } else { - LOG.info("No {} config is retrieved from {} server", getConfigScope(true), getConfigType()); - } - - return null; - } - - private String getConfig(boolean globalConfig) throws Exception { - String groupKey = pluginAdapter.getGroupKey(); - String group = pluginAdapter.getGroup(); - String serviceId = pluginAdapter.getServiceId(); - - LOG.info("Get {} config from {} server, {}={}, serviceId={}", getConfigScope(globalConfig), getConfigType(), groupKey, group, serviceId); - - return nacosOperation.getConfig(group, globalConfig ? group : serviceId); - } - - @PostConstruct - public void subscribeConfig() { - partialListener = subscribeConfig(false); - globalListener = subscribeConfig(true); - } - - private Listener subscribeConfig(boolean globalConfig) { - String groupKey = pluginAdapter.getGroupKey(); - String group = pluginAdapter.getGroup(); - String serviceId = pluginAdapter.getServiceId(); - - LOG.info("Subscribe {} config from {} server, {}={}, serviceId={}", getConfigScope(globalConfig), getConfigType(), groupKey, group, serviceId); - - try { - return nacosOperation.subscribeConfig(group, globalConfig ? group : serviceId, executorService, new NacosSubscribeCallback() { - @Override - public void callback(String config) { - if (StringUtils.isNotEmpty(config)) { - LOG.info("Get {} config updated event from {} server, {}={}, serviceId={}", getConfigScope(globalConfig), getConfigType(), groupKey, group, serviceId); - - RuleEntity ruleEntity = pluginAdapter.getRule(); - String rule = null; - if (ruleEntity != null) { - rule = ruleEntity.getContent(); - } - if (!StringUtils.equals(rule, config)) { - fireRuleUpdated(new RuleUpdatedEvent(config), true); - } else { - LOG.info("Retrieved {} config from {} server is same as current config, ignore to update, {}={}, serviceId={}", getConfigScope(globalConfig), getConfigType(), groupKey, group, serviceId); - } - } else { - LOG.info("Get {} config cleared event from {} server, {}={}, serviceId={}", getConfigScope(globalConfig), getConfigType(), groupKey, group, serviceId); - - fireRuleCleared(new RuleClearedEvent(), true); - } - } - }); - } catch (Exception e) { - LOG.error("Subscribe {} config from {} server failed, {}={}, serviceId={}", getConfigScope(globalConfig), getConfigType(), groupKey, group, serviceId, e); - } - - return null; - } - - @Override - public void close() { - unsubscribeConfig(partialListener, false); - unsubscribeConfig(globalListener, true); - - executorService.shutdownNow(); - } - - private void unsubscribeConfig(Listener configListener, boolean globalConfig) { - if (configListener == null) { - return; - } - - String groupKey = pluginAdapter.getGroupKey(); - String group = pluginAdapter.getGroup(); - String serviceId = pluginAdapter.getServiceId(); - - LOG.info("Unsubscribe {} config from {} server, {}={}, serviceId={}", getConfigScope(globalConfig), getConfigType(), groupKey, group, serviceId); - - nacosOperation.unsubscribeConfig(group, globalConfig ? group : serviceId, configListener); - } - - public String getConfigScope(boolean globalConfig) { - return globalConfig ? DiscoveryConstant.GLOBAL : DiscoveryConstant.PARTIAL; - } - - @Override - public String getConfigType() { - return NacosConstant.TYPE; - } -} \ No newline at end of file diff --git a/discovery-plugin-config-center-starter-nacos/src/main/java/com/nepxion/discovery/plugin/configcenter/nacos/configuration/NacosConfigAutoConfiguration.java b/discovery-plugin-config-center-starter-nacos/src/main/java/com/nepxion/discovery/plugin/configcenter/nacos/configuration/NacosConfigAutoConfiguration.java deleted file mode 100644 index 605d1ebafe..0000000000 --- a/discovery-plugin-config-center-starter-nacos/src/main/java/com/nepxion/discovery/plugin/configcenter/nacos/configuration/NacosConfigAutoConfiguration.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.nepxion.discovery.plugin.configcenter.nacos.configuration; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -import com.nepxion.banner.BannerConstant; -import com.nepxion.banner.Description; -import com.nepxion.banner.LogoBanner; -import com.nepxion.banner.NepxionBanner; -import com.nepxion.discovery.common.nacos.constant.NacosConstant; -import com.nepxion.discovery.plugin.configcenter.adapter.ConfigAdapter; -import com.nepxion.discovery.plugin.configcenter.nacos.adapter.NacosConfigAdapter; -import com.taobao.text.Color; - -@Configuration -public class NacosConfigAutoConfiguration { - static { - /*String bannerShown = System.getProperty(BannerConstant.BANNER_SHOWN, "true"); - if (Boolean.valueOf(bannerShown)) { - System.out.println(""); - System.out.println("╔═╗ ╔╗"); - System.out.println("║║╚╗║║"); - System.out.println("║╔╗╚╝╠══╦══╦══╦══╗"); - System.out.println("║║╚╗║║╔╗║╔═╣╔╗║══╣"); - System.out.println("║║ ║║║╔╗║╚═╣╚╝╠══║"); - System.out.println("╚╝ ╚═╩╝╚╩══╩══╩══╝"); - System.out.println(NacosConstant.TYPE + " Config"); - System.out.println(""); - }*/ - - LogoBanner logoBanner = new LogoBanner(NacosConfigAutoConfiguration.class, "/com/nepxion/nacos/resource/logo.txt", "Welcome to Nepxion", 5, 5, new Color[] { Color.red, Color.green, Color.cyan, Color.blue, Color.yellow }, true); - - NepxionBanner.show(logoBanner, new Description("Config:", NacosConstant.TYPE, 0, 1), new Description(BannerConstant.GITHUB + ":", BannerConstant.NEPXION_GITHUB + "/Discovery", 0, 1)); - } - - @Bean - public ConfigAdapter configAdapter() { - return new NacosConfigAdapter(); - } -} \ No newline at end of file diff --git a/discovery-plugin-config-center-starter-nacos/src/main/resources/META-INF/spring.factories b/discovery-plugin-config-center-starter-nacos/src/main/resources/META-INF/spring.factories deleted file mode 100644 index 0f6036852f..0000000000 --- a/discovery-plugin-config-center-starter-nacos/src/main/resources/META-INF/spring.factories +++ /dev/null @@ -1,3 +0,0 @@ -org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ -com.nepxion.discovery.common.nacos.configuration.NacosAutoConfiguration,\ -com.nepxion.discovery.plugin.configcenter.nacos.configuration.NacosConfigAutoConfiguration \ No newline at end of file diff --git a/discovery-plugin-config-center-starter-redis/pom.xml b/discovery-plugin-config-center-starter-redis/pom.xml deleted file mode 100644 index 28243aa091..0000000000 --- a/discovery-plugin-config-center-starter-redis/pom.xml +++ /dev/null @@ -1,28 +0,0 @@ - - - discovery-plugin-config-center-starter-redis - Nepxion Discovery Plugin Config Center Starter Redis - jar - 4.0.0 - Nepxion Discovery is an enhancement for Spring Cloud Discovery - http://www.nepxion.com - - - com.nepxion - discovery - 5.2.0-SNAPSHOT - - - - - ${project.groupId} - discovery-plugin-config-center - - - - ${project.groupId} - discovery-common-redis - - - \ No newline at end of file diff --git a/discovery-plugin-config-center-starter-redis/src/main/java/com/nepxion/discovery/plugin/configcenter/redis/adapter/RedisConfigAdapter.java b/discovery-plugin-config-center-starter-redis/src/main/java/com/nepxion/discovery/plugin/configcenter/redis/adapter/RedisConfigAdapter.java deleted file mode 100644 index d02b3e474d..0000000000 --- a/discovery-plugin-config-center-starter-redis/src/main/java/com/nepxion/discovery/plugin/configcenter/redis/adapter/RedisConfigAdapter.java +++ /dev/null @@ -1,144 +0,0 @@ -package com.nepxion.discovery.plugin.configcenter.redis.adapter; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @author JiKai Sun - * @version 1.0 - */ - -import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.redis.listener.PatternTopic; -import org.springframework.data.redis.listener.RedisMessageListenerContainer; -import org.springframework.data.redis.listener.adapter.MessageListenerAdapter; - -import com.nepxion.discovery.common.constant.DiscoveryConstant; -import com.nepxion.discovery.common.entity.RuleEntity; -import com.nepxion.discovery.common.redis.constant.RedisConstant; -import com.nepxion.discovery.common.redis.operation.RedisOperation; -import com.nepxion.discovery.common.redis.operation.RedisSubscribeCallback; -import com.nepxion.discovery.plugin.configcenter.adapter.ConfigAdapter; -import com.nepxion.discovery.plugin.framework.adapter.PluginAdapter; -import com.nepxion.discovery.plugin.framework.event.RuleClearedEvent; -import com.nepxion.discovery.plugin.framework.event.RuleUpdatedEvent; - -public class RedisConfigAdapter extends ConfigAdapter { - private static final Logger LOG = LoggerFactory.getLogger(RedisConfigAdapter.class); - - @Autowired - private PluginAdapter pluginAdapter; - - @Autowired - private RedisOperation redisOperation; - - @Autowired - private RedisMessageListenerContainer redisMessageListenerContainer; - - @Autowired - private MessageListenerAdapter partialMessageListenerAdapter; - - @Autowired - private MessageListenerAdapter globalMessageListenerAdapter; - - @Override - public String getConfig() throws Exception { - String config = getConfig(false); - if (StringUtils.isNotEmpty(config)) { - return config; - } else { - LOG.info("No {} config is retrieved from {} server", getConfigScope(false), getConfigType()); - } - - config = getConfig(true); - if (StringUtils.isNotEmpty(config)) { - return config; - } else { - LOG.info("No {} config is retrieved from {} server", getConfigScope(true), getConfigType()); - } - - return null; - } - - private String getConfig(boolean globalConfig) throws Exception { - String groupKey = pluginAdapter.getGroupKey(); - String group = pluginAdapter.getGroup(); - String serviceId = pluginAdapter.getServiceId(); - - LOG.info("Get {} config from {} server, {}={}, serviceId={}", getConfigScope(globalConfig), getConfigType(), groupKey, group, serviceId); - - return redisOperation.getConfig(group, globalConfig ? group : serviceId); - } - - public void subscribePartialConfig(String config) { - subscribeConfig(config, false); - } - - public void subscribeGlobalConfig(String config) { - subscribeConfig(config, true); - } - - private void subscribeConfig(String config, boolean globalConfig) { - String groupKey = pluginAdapter.getGroupKey(); - String group = pluginAdapter.getGroup(); - String serviceId = pluginAdapter.getServiceId(); - - try { - redisOperation.subscribeConfig(config, new RedisSubscribeCallback() { - @Override - public void callback(String config) { - if (StringUtils.isNotEmpty(config)) { - LOG.info("Get {} config updated event from {} server, {}={}, serviceId={}", getConfigScope(globalConfig), getConfigType(), groupKey, group, serviceId); - - RuleEntity ruleEntity = pluginAdapter.getRule(); - String rule = null; - if (ruleEntity != null) { - rule = ruleEntity.getContent(); - } - if (!StringUtils.equals(rule, config)) { - fireRuleUpdated(new RuleUpdatedEvent(config), true); - } else { - LOG.info("Retrieved {} config from {} server is same as current config, ignore to update, {}={}, serviceId={}", getConfigScope(globalConfig), getConfigType(), groupKey, group, serviceId); - } - } else { - LOG.info("Get {} config cleared event from {} server, {}={}, serviceId={}", getConfigScope(globalConfig), getConfigType(), groupKey, group, serviceId); - - fireRuleCleared(new RuleClearedEvent(), true); - } - } - }); - } catch (Exception e) { - LOG.error("Subscribe {} config from {} server failed, {}={}, serviceId={}", getConfigScope(globalConfig), getConfigType(), groupKey, group, serviceId, e); - } - } - - @Override - public void close() { - unsubscribeConfig(partialMessageListenerAdapter, false); - unsubscribeConfig(globalMessageListenerAdapter, true); - } - - private void unsubscribeConfig(MessageListenerAdapter messageListenerAdapter, boolean globalConfig) { - String groupKey = pluginAdapter.getGroupKey(); - String group = pluginAdapter.getGroup(); - String serviceId = pluginAdapter.getServiceId(); - - LOG.info("Unsubscribe {} config from {} server, {}={}, serviceId={}", getConfigScope(globalConfig), getConfigType(), groupKey, group, serviceId); - - redisMessageListenerContainer.removeMessageListener(messageListenerAdapter, new PatternTopic(group + "-" + (globalConfig ? group : serviceId))); - } - - public String getConfigScope(boolean globalConfig) { - return globalConfig ? DiscoveryConstant.GLOBAL : DiscoveryConstant.PARTIAL; - } - - @Override - public String getConfigType() { - return RedisConstant.TYPE; - } -} \ No newline at end of file diff --git a/discovery-plugin-config-center-starter-redis/src/main/java/com/nepxion/discovery/plugin/configcenter/redis/configuration/RedisConfigAutoConfiguration.java b/discovery-plugin-config-center-starter-redis/src/main/java/com/nepxion/discovery/plugin/configcenter/redis/configuration/RedisConfigAutoConfiguration.java deleted file mode 100644 index 8f12380cf8..0000000000 --- a/discovery-plugin-config-center-starter-redis/src/main/java/com/nepxion/discovery/plugin/configcenter/redis/configuration/RedisConfigAutoConfiguration.java +++ /dev/null @@ -1,101 +0,0 @@ -package com.nepxion.discovery.plugin.configcenter.redis.configuration; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @author JiKai Sun - * @version 1.0 - */ - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.data.redis.connection.RedisConnectionFactory; -import org.springframework.data.redis.listener.PatternTopic; -import org.springframework.data.redis.listener.RedisMessageListenerContainer; -import org.springframework.data.redis.listener.adapter.MessageListenerAdapter; - -import com.nepxion.banner.BannerConstant; -import com.nepxion.banner.Description; -import com.nepxion.banner.LogoBanner; -import com.nepxion.banner.NepxionBanner; -import com.nepxion.discovery.common.redis.constant.RedisConstant; -import com.nepxion.discovery.plugin.configcenter.adapter.ConfigAdapter; -import com.nepxion.discovery.plugin.configcenter.redis.adapter.RedisConfigAdapter; -import com.nepxion.discovery.plugin.framework.adapter.PluginAdapter; -import com.taobao.text.Color; - -@Configuration -public class RedisConfigAutoConfiguration { - private static final Logger LOG = LoggerFactory.getLogger(RedisConfigAutoConfiguration.class); - - static { - /*String bannerShown = System.getProperty(BannerConstant.BANNER_SHOWN, "true"); - if (Boolean.valueOf(bannerShown)) { - System.out.println(""); - System.out.println("╔═══╗ ╔╗"); - System.out.println("║╔═╗║ ║║"); - System.out.println("║╚═╝╠══╦═╝╠╦══╗"); - System.out.println("║╔╗╔╣║═╣╔╗╠╣══╣"); - System.out.println("║║║╚╣║═╣╚╝║╠══║"); - System.out.println("╚╝╚═╩══╩══╩╩══╝"); - System.out.println(RedisConstant.TYPE + " Config"); - System.out.println(""); - }*/ - - LogoBanner logoBanner = new LogoBanner(RedisConfigAutoConfiguration.class, "/com/nepxion/redis/resource/logo.txt", "Welcome to Nepxion", 5, 5, new Color[] { Color.red, Color.green, Color.cyan, Color.blue, Color.yellow }, true); - - NepxionBanner.show(logoBanner, new Description("Config:", RedisConstant.TYPE, 0, 1), new Description(BannerConstant.GITHUB + ":", BannerConstant.NEPXION_GITHUB + "/Discovery", 0, 1)); - } - - @Autowired - private RedisConnectionFactory redisConnectionFactory; - - @Autowired - private PluginAdapter pluginAdapter; - - @Bean - public RedisMessageListenerContainer redisMessageListenerContainer(MessageListenerAdapter partialMessageListenerAdapter, MessageListenerAdapter globalMessageListenerAdapter) { - String group = pluginAdapter.getGroup(); - String serviceId = pluginAdapter.getServiceId(); - - RedisMessageListenerContainer redisMessageListenerContainer = new RedisMessageListenerContainer(); - redisMessageListenerContainer.setConnectionFactory(redisConnectionFactory); - redisMessageListenerContainer.addMessageListener(partialMessageListenerAdapter, new PatternTopic(group + "-" + serviceId)); - redisMessageListenerContainer.addMessageListener(globalMessageListenerAdapter, new PatternTopic(group + "-" + group)); - - return redisMessageListenerContainer; - } - - @Bean - public MessageListenerAdapter partialMessageListenerAdapter(RedisConfigAdapter configAdapter) { - String groupKey = pluginAdapter.getGroupKey(); - String group = pluginAdapter.getGroup(); - String serviceId = pluginAdapter.getServiceId(); - - LOG.info("Subscribe {} config from {} server, {}={}, serviceId={}", configAdapter.getConfigScope(false), configAdapter.getConfigType(), groupKey, group, serviceId); - - return new MessageListenerAdapter(configAdapter, "subscribePartialConfig"); - } - - @Bean - public MessageListenerAdapter globalMessageListenerAdapter(RedisConfigAdapter configAdapter) { - String groupKey = pluginAdapter.getGroupKey(); - String group = pluginAdapter.getGroup(); - String serviceId = pluginAdapter.getServiceId(); - - LOG.info("Subscribe {} config from {} server, {}={}, serviceId={}", configAdapter.getConfigScope(true), configAdapter.getConfigType(), groupKey, group, serviceId); - - return new MessageListenerAdapter(configAdapter, "subscribeGlobalConfig"); - } - - @Bean - public ConfigAdapter configAdapter() { - return new RedisConfigAdapter(); - } -} \ No newline at end of file diff --git a/discovery-plugin-config-center-starter-redis/src/main/resources/META-INF/spring.factories b/discovery-plugin-config-center-starter-redis/src/main/resources/META-INF/spring.factories deleted file mode 100644 index 300bfa2063..0000000000 --- a/discovery-plugin-config-center-starter-redis/src/main/resources/META-INF/spring.factories +++ /dev/null @@ -1,3 +0,0 @@ -org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ -com.nepxion.discovery.common.redis.configuration.RedisAutoConfiguration,\ -com.nepxion.discovery.plugin.configcenter.redis.configuration.RedisConfigAutoConfiguration \ No newline at end of file diff --git a/discovery-plugin-config-center/discovery-plugin-config-center-starter-apollo/pom.xml b/discovery-plugin-config-center/discovery-plugin-config-center-starter-apollo/pom.xml new file mode 100644 index 0000000000..397978006a --- /dev/null +++ b/discovery-plugin-config-center/discovery-plugin-config-center-starter-apollo/pom.xml @@ -0,0 +1,28 @@ + + + discovery-plugin-config-center-starter-apollo + Nepxion Discovery Plugin Config Center Starter Apollo + jar + 4.0.0 + Nepxion Discovery is a solution for Spring Cloud with blue green, gray, weight, limitation, circuit breaker, degrade, isolation, monitor, tracing, dye, failover, async agent + http://www.nepxion.com + + + com.nepxion + discovery-plugin-config-center + 6.23.0 + + + + + ${project.groupId} + discovery-plugin-config-center-starter + + + + ${project.groupId} + discovery-common-apollo + + + \ No newline at end of file diff --git a/discovery-plugin-config-center/discovery-plugin-config-center-starter-apollo/src/main/java/com/nepxion/discovery/plugin/configcenter/apollo/adapter/ApolloApplicationInfoAdapter.java b/discovery-plugin-config-center/discovery-plugin-config-center-starter-apollo/src/main/java/com/nepxion/discovery/plugin/configcenter/apollo/adapter/ApolloApplicationInfoAdapter.java new file mode 100644 index 0000000000..71a35ee2b8 --- /dev/null +++ b/discovery-plugin-config-center/discovery-plugin-config-center-starter-apollo/src/main/java/com/nepxion/discovery/plugin/configcenter/apollo/adapter/ApolloApplicationInfoAdapter.java @@ -0,0 +1,20 @@ +package com.nepxion.discovery.plugin.configcenter.apollo.adapter; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import com.ctrip.framework.foundation.Foundation; +import com.nepxion.discovery.plugin.framework.adapter.ApplicationInfoAdapter; + +public class ApolloApplicationInfoAdapter implements ApplicationInfoAdapter { + @Override + public String getAppId() { + return Foundation.app().getAppId(); + } +} \ No newline at end of file diff --git a/discovery-plugin-config-center/discovery-plugin-config-center-starter-apollo/src/main/java/com/nepxion/discovery/plugin/configcenter/apollo/adapter/ApolloConfigAdapter.java b/discovery-plugin-config-center/discovery-plugin-config-center-starter-apollo/src/main/java/com/nepxion/discovery/plugin/configcenter/apollo/adapter/ApolloConfigAdapter.java new file mode 100644 index 0000000000..f7bdf4b9ff --- /dev/null +++ b/discovery-plugin-config-center/discovery-plugin-config-center-starter-apollo/src/main/java/com/nepxion/discovery/plugin/configcenter/apollo/adapter/ApolloConfigAdapter.java @@ -0,0 +1,88 @@ +package com.nepxion.discovery.plugin.configcenter.apollo.adapter; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import javax.annotation.PostConstruct; + +import org.springframework.beans.factory.annotation.Autowired; + +import com.ctrip.framework.apollo.ConfigChangeListener; +import com.nepxion.discovery.common.apollo.operation.ApolloOperation; +import com.nepxion.discovery.common.apollo.operation.ApolloSubscribeCallback; +import com.nepxion.discovery.common.entity.ConfigType; +import com.nepxion.discovery.plugin.configcenter.adapter.ConfigAdapter; + +public class ApolloConfigAdapter extends ConfigAdapter { + @Autowired + private ApolloOperation apolloOperation; + + private ConfigChangeListener partialConfigChangeListener; + private ConfigChangeListener globalConfigChangeListener; + + @Override + public String getConfig(String group, String dataId) throws Exception { + return apolloOperation.getConfig(group, dataId); + } + + @PostConstruct + @Override + public void subscribeConfig() { + partialConfigChangeListener = subscribeConfig(false); + globalConfigChangeListener = subscribeConfig(true); + } + + private ConfigChangeListener subscribeConfig(boolean globalConfig) { + String group = getGroup(); + String dataId = getDataId(globalConfig); + + logSubscribeStarted(globalConfig); + + try { + return apolloOperation.subscribeConfig(group, dataId, new ApolloSubscribeCallback() { + @Override + public void callback(String config) { + callbackConfig(config, globalConfig); + } + }); + } catch (Exception e) { + logSubscribeFailed(e, globalConfig); + } + + return null; + } + + @Override + public void unsubscribeConfig() { + unsubscribeConfig(partialConfigChangeListener, false); + unsubscribeConfig(globalConfigChangeListener, true); + } + + private void unsubscribeConfig(ConfigChangeListener configChangeListener, boolean globalConfig) { + if (configChangeListener == null) { + return; + } + + String group = getGroup(); + String dataId = getDataId(globalConfig); + + logUnsubscribeStarted(globalConfig); + + try { + apolloOperation.unsubscribeConfig(group, dataId, configChangeListener); + } catch (Exception e) { + logUnsubscribeFailed(e, globalConfig); + } + } + + @Override + public ConfigType getConfigType() { + return ConfigType.APOLLO; + } +} \ No newline at end of file diff --git a/discovery-plugin-config-center/discovery-plugin-config-center-starter-apollo/src/main/java/com/nepxion/discovery/plugin/configcenter/apollo/configuration/ApolloConfigAutoConfiguration.java b/discovery-plugin-config-center/discovery-plugin-config-center-starter-apollo/src/main/java/com/nepxion/discovery/plugin/configcenter/apollo/configuration/ApolloConfigAutoConfiguration.java new file mode 100644 index 0000000000..848616c730 --- /dev/null +++ b/discovery-plugin-config-center/discovery-plugin-config-center-starter-apollo/src/main/java/com/nepxion/discovery/plugin/configcenter/apollo/configuration/ApolloConfigAutoConfiguration.java @@ -0,0 +1,58 @@ +package com.nepxion.discovery.plugin.configcenter.apollo.configuration; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import com.nepxion.banner.BannerConstant; +import com.nepxion.banner.Description; +import com.nepxion.banner.LogoBanner; +import com.nepxion.banner.NepxionBanner; +import com.nepxion.discovery.common.entity.ConfigType; +import com.nepxion.discovery.plugin.configcenter.adapter.ConfigAdapter; +import com.nepxion.discovery.plugin.configcenter.apollo.adapter.ApolloApplicationInfoAdapter; +import com.nepxion.discovery.plugin.configcenter.apollo.adapter.ApolloConfigAdapter; +import com.nepxion.discovery.plugin.framework.adapter.ApplicationInfoAdapter; +import com.taobao.text.Color; + +@Configuration +public class ApolloConfigAutoConfiguration { + static { + /*String bannerShown = System.getProperty(BannerConstant.BANNER_SHOWN, "true"); + if (Boolean.valueOf(bannerShown)) { + System.out.println(""); + System.out.println("╔═══╗ ╔╗╔╗"); + System.out.println("║╔═╗║ ║║║║"); + System.out.println("║║ ║╠══╦══╣║║║╔══╗"); + System.out.println("║╚═╝║╔╗║╔╗║║║║║╔╗║"); + System.out.println("║╔═╗║╚╝║╚╝║╚╣╚╣╚╝║"); + System.out.println("╚╝ ╚╣╔═╩══╩═╩═╩══╝"); + System.out.println(" ║║"); + System.out.println(" ╚╝"); + System.out.println(ApolloConstant.TYPE + " Config"); + System.out.println(""); + }*/ + + LogoBanner logoBanner = new LogoBanner(ApolloConfigAutoConfiguration.class, "/com/nepxion/apollo/resource/logo.txt", "Welcome to Nepxion", 6, 5, new Color[] { Color.red, Color.green, Color.cyan, Color.blue, Color.yellow, Color.magenta }, true); + + NepxionBanner.show(logoBanner, new Description("Config:", ConfigType.APOLLO.toString(), 0, 1), new Description(BannerConstant.GITHUB + ":", BannerConstant.NEPXION_GITHUB + "/Discovery", 0, 1)); + } + + @Bean + public ConfigAdapter configAdapter() { + return new ApolloConfigAdapter(); + } + + @Bean + public ApplicationInfoAdapter applicationInfoAdapter() { + return new ApolloApplicationInfoAdapter(); + } +} \ No newline at end of file diff --git a/discovery-plugin-config-center/discovery-plugin-config-center-starter-apollo/src/main/resources/META-INF/spring.factories b/discovery-plugin-config-center/discovery-plugin-config-center-starter-apollo/src/main/resources/META-INF/spring.factories new file mode 100644 index 0000000000..c7a4d7945c --- /dev/null +++ b/discovery-plugin-config-center/discovery-plugin-config-center-starter-apollo/src/main/resources/META-INF/spring.factories @@ -0,0 +1,2 @@ +org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ +com.nepxion.discovery.plugin.configcenter.apollo.configuration.ApolloConfigAutoConfiguration \ No newline at end of file diff --git a/discovery-plugin-config-center/discovery-plugin-config-center-starter-consul/pom.xml b/discovery-plugin-config-center/discovery-plugin-config-center-starter-consul/pom.xml new file mode 100644 index 0000000000..833d395e63 --- /dev/null +++ b/discovery-plugin-config-center/discovery-plugin-config-center-starter-consul/pom.xml @@ -0,0 +1,28 @@ + + + discovery-plugin-config-center-starter-consul + Nepxion Discovery Plugin Config Center Starter Consul + jar + 4.0.0 + Nepxion Discovery is a solution for Spring Cloud with blue green, gray, weight, limitation, circuit breaker, degrade, isolation, monitor, tracing, dye, failover, async agent + http://www.nepxion.com + + + com.nepxion + discovery-plugin-config-center + 6.23.0 + + + + + ${project.groupId} + discovery-plugin-config-center-starter + + + + ${project.groupId} + discovery-common-consul + + + \ No newline at end of file diff --git a/discovery-plugin-config-center/discovery-plugin-config-center-starter-consul/src/main/java/com/nepxion/discovery/plugin/configcenter/consul/adapter/ConsulConfigAdapter.java b/discovery-plugin-config-center/discovery-plugin-config-center-starter-consul/src/main/java/com/nepxion/discovery/plugin/configcenter/consul/adapter/ConsulConfigAdapter.java new file mode 100644 index 0000000000..8f97319ae8 --- /dev/null +++ b/discovery-plugin-config-center/discovery-plugin-config-center-starter-consul/src/main/java/com/nepxion/discovery/plugin/configcenter/consul/adapter/ConsulConfigAdapter.java @@ -0,0 +1,95 @@ +package com.nepxion.discovery.plugin.configcenter.consul.adapter; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Congwei Xu + * @version 1.0 + */ + +import java.util.concurrent.ExecutorService; + +import javax.annotation.PostConstruct; + +import org.springframework.beans.factory.annotation.Autowired; + +import com.nepxion.discovery.common.consul.operation.ConsulListener; +import com.nepxion.discovery.common.consul.operation.ConsulOperation; +import com.nepxion.discovery.common.consul.operation.ConsulSubscribeCallback; +import com.nepxion.discovery.common.entity.ConfigType; +import com.nepxion.discovery.common.thread.DiscoveryThreadPoolFactory; +import com.nepxion.discovery.plugin.configcenter.adapter.ConfigAdapter; + +public class ConsulConfigAdapter extends ConfigAdapter { + private ExecutorService executorService = DiscoveryThreadPoolFactory.getExecutorService("consul-config"); + + @Autowired + private ConsulOperation consulOperation; + + private ConsulListener partialConsulListener; + private ConsulListener globalConsulListener; + + @Override + public String getConfig(String group, String dataId) throws Exception { + return consulOperation.getConfig(group, dataId); + } + + @PostConstruct + @Override + public void subscribeConfig() { + partialConsulListener = subscribeConfig(false); + globalConsulListener = subscribeConfig(true); + } + + private ConsulListener subscribeConfig(boolean globalConfig) { + String group = getGroup(); + String dataId = getDataId(globalConfig); + + logSubscribeStarted(globalConfig); + + try { + return consulOperation.subscribeConfig(group, dataId, executorService, new ConsulSubscribeCallback() { + @Override + public void callback(String config) { + callbackConfig(config, globalConfig); + } + }); + } catch (Exception e) { + logSubscribeFailed(e, globalConfig); + } + + return null; + } + + @Override + public void unsubscribeConfig() { + unsubscribeConfig(partialConsulListener, false); + unsubscribeConfig(globalConsulListener, true); + + executorService.shutdownNow(); + } + + private void unsubscribeConfig(ConsulListener consulListener, boolean globalConfig) { + if (consulListener == null) { + return; + } + + String group = getGroup(); + String dataId = getDataId(globalConfig); + + logUnsubscribeStarted(globalConfig); + + try { + consulOperation.unsubscribeConfig(group, dataId, consulListener); + } catch (Exception e) { + logUnsubscribeFailed(e, globalConfig); + } + } + + @Override + public ConfigType getConfigType() { + return ConfigType.CONSUL; + } +} \ No newline at end of file diff --git a/discovery-plugin-config-center/discovery-plugin-config-center-starter-consul/src/main/java/com/nepxion/discovery/plugin/configcenter/consul/configuration/ConsulConfigAutoConfiguration.java b/discovery-plugin-config-center/discovery-plugin-config-center-starter-consul/src/main/java/com/nepxion/discovery/plugin/configcenter/consul/configuration/ConsulConfigAutoConfiguration.java new file mode 100644 index 0000000000..3e440e6ec0 --- /dev/null +++ b/discovery-plugin-config-center/discovery-plugin-config-center-starter-consul/src/main/java/com/nepxion/discovery/plugin/configcenter/consul/configuration/ConsulConfigAutoConfiguration.java @@ -0,0 +1,35 @@ +package com.nepxion.discovery.plugin.configcenter.consul.configuration; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Congwei Xu + * @version 1.0 + */ + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import com.nepxion.banner.BannerConstant; +import com.nepxion.banner.Description; +import com.nepxion.banner.LogoBanner; +import com.nepxion.banner.NepxionBanner; +import com.nepxion.discovery.common.entity.ConfigType; +import com.nepxion.discovery.plugin.configcenter.adapter.ConfigAdapter; +import com.nepxion.discovery.plugin.configcenter.consul.adapter.ConsulConfigAdapter; +import com.taobao.text.Color; + +@Configuration +public class ConsulConfigAutoConfiguration { + static { + LogoBanner logoBanner = new LogoBanner(ConsulConfigAutoConfiguration.class, "/com/nepxion/consul/resource/logo.txt", "Welcome to Nepxion", 6, 5, new Color[] { Color.red, Color.green, Color.cyan, Color.blue, Color.yellow, Color.magenta }, true); + NepxionBanner.show(logoBanner, new Description("Config:", ConfigType.CONSUL.toString(), 0, 1), new Description(BannerConstant.GITHUB + ":", BannerConstant.NEPXION_GITHUB + "/Discovery", 0, 1)); + } + + @Bean + public ConfigAdapter configAdapter() { + return new ConsulConfigAdapter(); + } +} \ No newline at end of file diff --git a/discovery-plugin-config-center/discovery-plugin-config-center-starter-consul/src/main/resources/META-INF/spring.factories b/discovery-plugin-config-center/discovery-plugin-config-center-starter-consul/src/main/resources/META-INF/spring.factories new file mode 100644 index 0000000000..aeea602bad --- /dev/null +++ b/discovery-plugin-config-center/discovery-plugin-config-center-starter-consul/src/main/resources/META-INF/spring.factories @@ -0,0 +1,2 @@ +org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ +com.nepxion.discovery.plugin.configcenter.consul.configuration.ConsulConfigAutoConfiguration \ No newline at end of file diff --git a/discovery-plugin-config-center/discovery-plugin-config-center-starter-etcd/pom.xml b/discovery-plugin-config-center/discovery-plugin-config-center-starter-etcd/pom.xml new file mode 100644 index 0000000000..cca43cea1d --- /dev/null +++ b/discovery-plugin-config-center/discovery-plugin-config-center-starter-etcd/pom.xml @@ -0,0 +1,28 @@ + + + discovery-plugin-config-center-starter-etcd + Nepxion Discovery Plugin Config Center Starter Etcd + jar + 4.0.0 + Nepxion Discovery is a solution for Spring Cloud with blue green, gray, weight, limitation, circuit breaker, degrade, isolation, monitor, tracing, dye, failover, async agent + http://www.nepxion.com + + + com.nepxion + discovery-plugin-config-center + 6.23.0 + + + + + ${project.groupId} + discovery-plugin-config-center-starter + + + + ${project.groupId} + discovery-common-etcd + + + \ No newline at end of file diff --git a/discovery-plugin-config-center/discovery-plugin-config-center-starter-etcd/src/main/java/com/nepxion/discovery/plugin/configcenter/etcd/adapter/EtcdConfigAdapter.java b/discovery-plugin-config-center/discovery-plugin-config-center-starter-etcd/src/main/java/com/nepxion/discovery/plugin/configcenter/etcd/adapter/EtcdConfigAdapter.java new file mode 100644 index 0000000000..1c00c72e3b --- /dev/null +++ b/discovery-plugin-config-center/discovery-plugin-config-center-starter-etcd/src/main/java/com/nepxion/discovery/plugin/configcenter/etcd/adapter/EtcdConfigAdapter.java @@ -0,0 +1,89 @@ +package com.nepxion.discovery.plugin.configcenter.etcd.adapter; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Congwei Xu + * @version 1.0 + */ + +import io.etcd.jetcd.Watch; + +import javax.annotation.PostConstruct; + +import org.springframework.beans.factory.annotation.Autowired; + +import com.nepxion.discovery.common.entity.ConfigType; +import com.nepxion.discovery.common.etcd.operation.EtcdOperation; +import com.nepxion.discovery.common.etcd.operation.EtcdSubscribeCallback; +import com.nepxion.discovery.plugin.configcenter.adapter.ConfigAdapter; + +public class EtcdConfigAdapter extends ConfigAdapter { + @Autowired + private EtcdOperation etcdOperation; + + private Watch partialWatchClient; + private Watch globalWatchClient; + + @Override + public String getConfig(String group, String dataId) throws Exception { + return etcdOperation.getConfig(group, dataId); + } + + @PostConstruct + @Override + public void subscribeConfig() { + partialWatchClient = subscribeConfig(false); + globalWatchClient = subscribeConfig(true); + } + + private Watch subscribeConfig(boolean globalConfig) { + String group = getGroup(); + String dataId = getDataId(globalConfig); + + logSubscribeStarted(globalConfig); + + try { + return etcdOperation.subscribeConfig(group, dataId, new EtcdSubscribeCallback() { + @Override + public void callback(String config) { + callbackConfig(config, globalConfig); + } + }); + } catch (Exception e) { + logSubscribeFailed(e, globalConfig); + } + + return null; + } + + @Override + public void unsubscribeConfig() { + unsubscribeConfig(partialWatchClient, false); + unsubscribeConfig(globalWatchClient, true); + } + + private void unsubscribeConfig(Watch watchClient, boolean globalConfig) { + if (watchClient == null) { + return; + } + + String group = getGroup(); + String dataId = getDataId(globalConfig); + + logUnsubscribeStarted(globalConfig); + + try { + etcdOperation.unsubscribeConfig(group, dataId, watchClient); + } catch (Exception e) { + logUnsubscribeFailed(e, globalConfig); + } + } + + @Override + public ConfigType getConfigType() { + return ConfigType.ETCD; + } +} \ No newline at end of file diff --git a/discovery-plugin-config-center/discovery-plugin-config-center-starter-etcd/src/main/java/com/nepxion/discovery/plugin/configcenter/etcd/configuration/EtcdConfigAutoConfiguration.java b/discovery-plugin-config-center/discovery-plugin-config-center-starter-etcd/src/main/java/com/nepxion/discovery/plugin/configcenter/etcd/configuration/EtcdConfigAutoConfiguration.java new file mode 100644 index 0000000000..72ce16313f --- /dev/null +++ b/discovery-plugin-config-center/discovery-plugin-config-center-starter-etcd/src/main/java/com/nepxion/discovery/plugin/configcenter/etcd/configuration/EtcdConfigAutoConfiguration.java @@ -0,0 +1,35 @@ +package com.nepxion.discovery.plugin.configcenter.etcd.configuration; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Congwei Xu + * @version 1.0 + */ + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import com.nepxion.banner.BannerConstant; +import com.nepxion.banner.Description; +import com.nepxion.banner.LogoBanner; +import com.nepxion.banner.NepxionBanner; +import com.nepxion.discovery.common.entity.ConfigType; +import com.nepxion.discovery.plugin.configcenter.adapter.ConfigAdapter; +import com.nepxion.discovery.plugin.configcenter.etcd.adapter.EtcdConfigAdapter; +import com.taobao.text.Color; + +@Configuration +public class EtcdConfigAutoConfiguration { + static { + LogoBanner logoBanner = new LogoBanner(EtcdConfigAutoConfiguration.class, "/com/nepxion/etcd/resource/logo.txt", "Welcome to Nepxion", 4, 5, new Color[] { Color.red, Color.green, Color.cyan, Color.blue }, true); + NepxionBanner.show(logoBanner, new Description("Config:", ConfigType.ETCD.toString(), 0, 1), new Description(BannerConstant.GITHUB + ":", BannerConstant.NEPXION_GITHUB + "/Discovery", 0, 1)); + } + + @Bean + public ConfigAdapter configAdapter() { + return new EtcdConfigAdapter(); + } +} \ No newline at end of file diff --git a/discovery-plugin-config-center/discovery-plugin-config-center-starter-etcd/src/main/resources/META-INF/spring.factories b/discovery-plugin-config-center/discovery-plugin-config-center-starter-etcd/src/main/resources/META-INF/spring.factories new file mode 100644 index 0000000000..1664c157d7 --- /dev/null +++ b/discovery-plugin-config-center/discovery-plugin-config-center-starter-etcd/src/main/resources/META-INF/spring.factories @@ -0,0 +1,2 @@ +org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ +com.nepxion.discovery.plugin.configcenter.etcd.configuration.EtcdConfigAutoConfiguration \ No newline at end of file diff --git a/discovery-plugin-config-center/discovery-plugin-config-center-starter-nacos/pom.xml b/discovery-plugin-config-center/discovery-plugin-config-center-starter-nacos/pom.xml new file mode 100644 index 0000000000..ab52550e2e --- /dev/null +++ b/discovery-plugin-config-center/discovery-plugin-config-center-starter-nacos/pom.xml @@ -0,0 +1,28 @@ + + + discovery-plugin-config-center-starter-nacos + Nepxion Discovery Plugin Config Center Starter Nacos + jar + 4.0.0 + Nepxion Discovery is a solution for Spring Cloud with blue green, gray, weight, limitation, circuit breaker, degrade, isolation, monitor, tracing, dye, failover, async agent + http://www.nepxion.com + + + com.nepxion + discovery-plugin-config-center + 6.23.0 + + + + + ${project.groupId} + discovery-plugin-config-center-starter + + + + ${project.groupId} + discovery-common-nacos + + + \ No newline at end of file diff --git a/discovery-plugin-config-center/discovery-plugin-config-center-starter-nacos/src/main/java/com/nepxion/discovery/plugin/configcenter/nacos/adapter/NacosConfigAdapter.java b/discovery-plugin-config-center/discovery-plugin-config-center-starter-nacos/src/main/java/com/nepxion/discovery/plugin/configcenter/nacos/adapter/NacosConfigAdapter.java new file mode 100644 index 0000000000..11c199a45a --- /dev/null +++ b/discovery-plugin-config-center/discovery-plugin-config-center-starter-nacos/src/main/java/com/nepxion/discovery/plugin/configcenter/nacos/adapter/NacosConfigAdapter.java @@ -0,0 +1,95 @@ +package com.nepxion.discovery.plugin.configcenter.nacos.adapter; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.concurrent.ExecutorService; + +import javax.annotation.PostConstruct; + +import org.springframework.beans.factory.annotation.Autowired; + +import com.alibaba.nacos.api.config.listener.Listener; +import com.nepxion.discovery.common.entity.ConfigType; +import com.nepxion.discovery.common.nacos.operation.NacosOperation; +import com.nepxion.discovery.common.nacos.operation.NacosSubscribeCallback; +import com.nepxion.discovery.common.thread.DiscoveryThreadPoolFactory; +import com.nepxion.discovery.plugin.configcenter.adapter.ConfigAdapter; + +public class NacosConfigAdapter extends ConfigAdapter { + private ExecutorService executorService = DiscoveryThreadPoolFactory.getExecutorService("nacos-config"); + + @Autowired + private NacosOperation nacosOperation; + + private Listener partialListener; + private Listener globalListener; + + @Override + public String getConfig(String group, String dataId) throws Exception { + return nacosOperation.getConfig(group, dataId); + } + + @PostConstruct + @Override + public void subscribeConfig() { + partialListener = subscribeConfig(false); + globalListener = subscribeConfig(true); + } + + private Listener subscribeConfig(boolean globalConfig) { + String group = getGroup(); + String dataId = getDataId(globalConfig); + + logSubscribeStarted(globalConfig); + + try { + return nacosOperation.subscribeConfig(group, dataId, executorService, new NacosSubscribeCallback() { + @Override + public void callback(String config) { + callbackConfig(config, globalConfig); + } + }); + } catch (Exception e) { + logSubscribeFailed(e, globalConfig); + } + + return null; + } + + @Override + public void unsubscribeConfig() { + unsubscribeConfig(partialListener, false); + unsubscribeConfig(globalListener, true); + + executorService.shutdownNow(); + } + + private void unsubscribeConfig(Listener listener, boolean globalConfig) { + if (listener == null) { + return; + } + + String group = getGroup(); + String dataId = getDataId(globalConfig); + + logUnsubscribeStarted(globalConfig); + + try { + nacosOperation.unsubscribeConfig(group, dataId, listener); + } catch (Exception e) { + logUnsubscribeFailed(e, globalConfig); + } + } + + @Override + public ConfigType getConfigType() { + return ConfigType.NACOS; + } +} \ No newline at end of file diff --git a/discovery-plugin-config-center/discovery-plugin-config-center-starter-nacos/src/main/java/com/nepxion/discovery/plugin/configcenter/nacos/configuration/NacosConfigAutoConfiguration.java b/discovery-plugin-config-center/discovery-plugin-config-center-starter-nacos/src/main/java/com/nepxion/discovery/plugin/configcenter/nacos/configuration/NacosConfigAutoConfiguration.java new file mode 100644 index 0000000000..1db38d0ac3 --- /dev/null +++ b/discovery-plugin-config-center/discovery-plugin-config-center-starter-nacos/src/main/java/com/nepxion/discovery/plugin/configcenter/nacos/configuration/NacosConfigAutoConfiguration.java @@ -0,0 +1,62 @@ +package com.nepxion.discovery.plugin.configcenter.nacos.configuration; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import com.nepxion.banner.BannerConstant; +import com.nepxion.banner.Description; +import com.nepxion.banner.LogoBanner; +import com.nepxion.banner.NepxionBanner; +import com.nepxion.discovery.common.entity.ConfigType; +import com.nepxion.discovery.plugin.configcenter.adapter.ConfigAdapter; +import com.nepxion.discovery.plugin.configcenter.nacos.adapter.NacosConfigAdapter; +import com.taobao.text.Color; + +@Configuration +public class NacosConfigAutoConfiguration { + static { + /*String bannerShown = System.getProperty(BannerConstant.BANNER_SHOWN, "true"); + if (Boolean.valueOf(bannerShown)) { + System.out.println(""); + System.out.println("╔═╗ ╔╗"); + System.out.println("║║╚╗║║"); + System.out.println("║╔╗╚╝╠══╦══╦══╦══╗"); + System.out.println("║║╚╗║║╔╗║╔═╣╔╗║══╣"); + System.out.println("║║ ║║║╔╗║╚═╣╚╝╠══║"); + System.out.println("╚╝ ╚═╩╝╚╩══╩══╩══╝"); + System.out.println(NacosConstant.TYPE + " Config"); + System.out.println(""); + }*/ + + LogoBanner logoBanner = new LogoBanner(NacosConfigAutoConfiguration.class, "/com/nepxion/nacos/resource/logo.txt", "Welcome to Nepxion", 5, 5, new Color[] { Color.red, Color.green, Color.cyan, Color.blue, Color.yellow }, true); + + NepxionBanner.show(logoBanner, new Description("Config:", ConfigType.NACOS.toString(), 0, 1), new Description(BannerConstant.GITHUB + ":", BannerConstant.NEPXION_GITHUB + "/Discovery", 0, 1)); + } + + @Bean + public ConfigAdapter configAdapter() { + return new NacosConfigAdapter(); + } + + // Just for test + /*@Bean + public ApplicationInfoAdapter applicationInfoAdapter() { + String uuid = UUID.randomUUID().toString(); + + return new ApplicationInfoAdapter() { + @Override + public String getAppId() { + return uuid; + } + }; + }*/ +} \ No newline at end of file diff --git a/discovery-plugin-config-center/discovery-plugin-config-center-starter-nacos/src/main/resources/META-INF/spring.factories b/discovery-plugin-config-center/discovery-plugin-config-center-starter-nacos/src/main/resources/META-INF/spring.factories new file mode 100644 index 0000000000..b6672639e6 --- /dev/null +++ b/discovery-plugin-config-center/discovery-plugin-config-center-starter-nacos/src/main/resources/META-INF/spring.factories @@ -0,0 +1,2 @@ +org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ +com.nepxion.discovery.plugin.configcenter.nacos.configuration.NacosConfigAutoConfiguration \ No newline at end of file diff --git a/discovery-plugin-config-center/discovery-plugin-config-center-starter-redis/pom.xml b/discovery-plugin-config-center/discovery-plugin-config-center-starter-redis/pom.xml new file mode 100644 index 0000000000..0ff5709e6c --- /dev/null +++ b/discovery-plugin-config-center/discovery-plugin-config-center-starter-redis/pom.xml @@ -0,0 +1,28 @@ + + + discovery-plugin-config-center-starter-redis + Nepxion Discovery Plugin Config Center Starter Redis + jar + 4.0.0 + Nepxion Discovery is a solution for Spring Cloud with blue green, gray, weight, limitation, circuit breaker, degrade, isolation, monitor, tracing, dye, failover, async agent + http://www.nepxion.com + + + com.nepxion + discovery-plugin-config-center + 6.23.0 + + + + + ${project.groupId} + discovery-plugin-config-center-starter + + + + ${project.groupId} + discovery-common-redis + + + \ No newline at end of file diff --git a/discovery-plugin-config-center/discovery-plugin-config-center-starter-redis/src/main/java/com/nepxion/discovery/plugin/configcenter/redis/adapter/RedisConfigAdapter.java b/discovery-plugin-config-center/discovery-plugin-config-center-starter-redis/src/main/java/com/nepxion/discovery/plugin/configcenter/redis/adapter/RedisConfigAdapter.java new file mode 100644 index 0000000000..0e03627a60 --- /dev/null +++ b/discovery-plugin-config-center/discovery-plugin-config-center-starter-redis/src/main/java/com/nepxion/discovery/plugin/configcenter/redis/adapter/RedisConfigAdapter.java @@ -0,0 +1,102 @@ +package com.nepxion.discovery.plugin.configcenter.redis.adapter; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @author JiKai Sun + * @author Ning Zhang + * @version 1.0 + */ + +import javax.annotation.PostConstruct; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.redis.listener.adapter.MessageListenerAdapter; + +import com.nepxion.discovery.common.entity.ConfigType; +import com.nepxion.discovery.common.redis.operation.RedisOperation; +import com.nepxion.discovery.common.redis.operation.RedisSubscribeCallback; +import com.nepxion.discovery.plugin.configcenter.adapter.ConfigAdapter; + +public class RedisConfigAdapter extends ConfigAdapter { + @Autowired + private RedisOperation redisOperation; + + private MessageListenerAdapter partialMessageListenerAdapter; + private MessageListenerAdapter globalMessageListenerAdapter; + + @Override + public String getConfig(String group, String dataId) throws Exception { + return redisOperation.getConfig(group, dataId); + } + + @PostConstruct + @Override + public void subscribeConfig() { + String group = getGroup(); + + logSubscribeStarted(false); + + try { + partialMessageListenerAdapter = redisOperation.subscribeConfig(group, getDataId(false), this, "subscribePartialConfig"); + } catch (Exception e) { + logSubscribeFailed(e, false); + } + + logSubscribeStarted(true); + + try { + globalMessageListenerAdapter = redisOperation.subscribeConfig(group, getDataId(true), this, "subscribeGlobalConfig"); + } catch (Exception e) { + logSubscribeFailed(e, true); + } + } + + public void subscribePartialConfig(String config) { + subscribeConfig(config, false); + } + + public void subscribeGlobalConfig(String config) { + subscribeConfig(config, true); + } + + private void subscribeConfig(String config, boolean globalConfig) { + redisOperation.subscribeConfig(config, new RedisSubscribeCallback() { + @Override + public void callback(String config) { + callbackConfig(config, globalConfig); + } + }); + } + + @Override + public void unsubscribeConfig() { + unsubscribeConfig(partialMessageListenerAdapter, false); + unsubscribeConfig(globalMessageListenerAdapter, true); + } + + private void unsubscribeConfig(MessageListenerAdapter messageListenerAdapter, boolean globalConfig) { + if (messageListenerAdapter == null) { + return; + } + + String group = getGroup(); + String dataId = getDataId(globalConfig); + + logUnsubscribeStarted(globalConfig); + + try { + redisOperation.unsubscribeConfig(group, dataId, messageListenerAdapter); + } catch (Exception e) { + logUnsubscribeFailed(e, globalConfig); + } + } + + @Override + public ConfigType getConfigType() { + return ConfigType.REDIS; + } +} \ No newline at end of file diff --git a/discovery-plugin-config-center/discovery-plugin-config-center-starter-redis/src/main/java/com/nepxion/discovery/plugin/configcenter/redis/configuration/RedisConfigAutoConfiguration.java b/discovery-plugin-config-center/discovery-plugin-config-center-starter-redis/src/main/java/com/nepxion/discovery/plugin/configcenter/redis/configuration/RedisConfigAutoConfiguration.java new file mode 100644 index 0000000000..e886d9349c --- /dev/null +++ b/discovery-plugin-config-center/discovery-plugin-config-center-starter-redis/src/main/java/com/nepxion/discovery/plugin/configcenter/redis/configuration/RedisConfigAutoConfiguration.java @@ -0,0 +1,50 @@ +package com.nepxion.discovery.plugin.configcenter.redis.configuration; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @author JiKai Sun + * @version 1.0 + */ + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import com.nepxion.banner.BannerConstant; +import com.nepxion.banner.Description; +import com.nepxion.banner.LogoBanner; +import com.nepxion.banner.NepxionBanner; +import com.nepxion.discovery.common.entity.ConfigType; +import com.nepxion.discovery.plugin.configcenter.adapter.ConfigAdapter; +import com.nepxion.discovery.plugin.configcenter.redis.adapter.RedisConfigAdapter; +import com.taobao.text.Color; + +@Configuration +public class RedisConfigAutoConfiguration { + static { + /*String bannerShown = System.getProperty(BannerConstant.BANNER_SHOWN, "true"); + if (Boolean.valueOf(bannerShown)) { + System.out.println(""); + System.out.println("╔═══╗ ╔╗"); + System.out.println("║╔═╗║ ║║"); + System.out.println("║╚═╝╠══╦═╝╠╦══╗"); + System.out.println("║╔╗╔╣║═╣╔╗╠╣══╣"); + System.out.println("║║║╚╣║═╣╚╝║╠══║"); + System.out.println("╚╝╚═╩══╩══╩╩══╝"); + System.out.println(RedisConstant.TYPE + " Config"); + System.out.println(""); + }*/ + + LogoBanner logoBanner = new LogoBanner(RedisConfigAutoConfiguration.class, "/com/nepxion/redis/resource/logo.txt", "Welcome to Nepxion", 5, 5, new Color[] { Color.red, Color.green, Color.cyan, Color.blue, Color.yellow }, true); + + NepxionBanner.show(logoBanner, new Description("Config:", ConfigType.REDIS.toString(), 0, 1), new Description(BannerConstant.GITHUB + ":", BannerConstant.NEPXION_GITHUB + "/Discovery", 0, 1)); + } + + @Bean + public ConfigAdapter configAdapter() { + return new RedisConfigAdapter(); + } +} \ No newline at end of file diff --git a/discovery-plugin-config-center/discovery-plugin-config-center-starter-redis/src/main/resources/META-INF/spring.factories b/discovery-plugin-config-center/discovery-plugin-config-center-starter-redis/src/main/resources/META-INF/spring.factories new file mode 100644 index 0000000000..10d53b1eaf --- /dev/null +++ b/discovery-plugin-config-center/discovery-plugin-config-center-starter-redis/src/main/resources/META-INF/spring.factories @@ -0,0 +1,2 @@ +org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ +com.nepxion.discovery.plugin.configcenter.redis.configuration.RedisConfigAutoConfiguration \ No newline at end of file diff --git a/discovery-plugin-config-center/discovery-plugin-config-center-starter-zookeeper/pom.xml b/discovery-plugin-config-center/discovery-plugin-config-center-starter-zookeeper/pom.xml new file mode 100644 index 0000000000..5eeb9f8f02 --- /dev/null +++ b/discovery-plugin-config-center/discovery-plugin-config-center-starter-zookeeper/pom.xml @@ -0,0 +1,28 @@ + + + discovery-plugin-config-center-starter-zookeeper + Nepxion Discovery Plugin Config Center Starter Zookeeper + jar + 4.0.0 + Nepxion Discovery is a solution for Spring Cloud with blue green, gray, weight, limitation, circuit breaker, degrade, isolation, monitor, tracing, dye, failover, async agent + http://www.nepxion.com + + + com.nepxion + discovery-plugin-config-center + 6.23.0 + + + + + ${project.groupId} + discovery-plugin-config-center-starter + + + + ${project.groupId} + discovery-common-zookeeper + + + \ No newline at end of file diff --git a/discovery-plugin-config-center/discovery-plugin-config-center-starter-zookeeper/src/main/java/com/nepxion/discovery/plugin/configcenter/zookeeper/adapter/ZookeeperConfigAdapter.java b/discovery-plugin-config-center/discovery-plugin-config-center-starter-zookeeper/src/main/java/com/nepxion/discovery/plugin/configcenter/zookeeper/adapter/ZookeeperConfigAdapter.java new file mode 100644 index 0000000000..483051b82e --- /dev/null +++ b/discovery-plugin-config-center/discovery-plugin-config-center-starter-zookeeper/src/main/java/com/nepxion/discovery/plugin/configcenter/zookeeper/adapter/ZookeeperConfigAdapter.java @@ -0,0 +1,89 @@ +package com.nepxion.discovery.plugin.configcenter.zookeeper.adapter; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author rotten + * @author Ning Zhang + * @version 1.0 + */ + +import javax.annotation.PostConstruct; + +import org.springframework.beans.factory.annotation.Autowired; + +import com.nepxion.discovery.common.entity.ConfigType; +import com.nepxion.discovery.common.zookeeper.operation.ZookeeperListener; +import com.nepxion.discovery.common.zookeeper.operation.ZookeeperOperation; +import com.nepxion.discovery.common.zookeeper.operation.ZookeeperSubscribeCallback; +import com.nepxion.discovery.plugin.configcenter.adapter.ConfigAdapter; + +public class ZookeeperConfigAdapter extends ConfigAdapter { + @Autowired + private ZookeeperOperation zookeeperOperation; + + private ZookeeperListener partialZookeeperListener; + private ZookeeperListener globalZookeeperListener; + + @Override + public String getConfig(String group, String dataId) throws Exception { + return zookeeperOperation.getConfig(group, dataId); + } + + @PostConstruct + @Override + public void subscribeConfig() { + partialZookeeperListener = subscribeConfig(false); + globalZookeeperListener = subscribeConfig(true); + } + + private ZookeeperListener subscribeConfig(boolean globalConfig) { + String group = getGroup(); + String dataId = getDataId(globalConfig); + + logSubscribeStarted(globalConfig); + + try { + return zookeeperOperation.subscribeConfig(group, dataId, new ZookeeperSubscribeCallback() { + @Override + public void callback(String config) { + callbackConfig(config, globalConfig); + } + }); + } catch (Exception e) { + logSubscribeFailed(e, globalConfig); + } + + return null; + } + + @Override + public void unsubscribeConfig() { + unsubscribeConfig(partialZookeeperListener, false); + unsubscribeConfig(globalZookeeperListener, true); + } + + private void unsubscribeConfig(ZookeeperListener zookeeperListener, boolean globalConfig) { + if (zookeeperListener == null) { + return; + } + + String group = getGroup(); + String dataId = getDataId(globalConfig); + + logUnsubscribeStarted(globalConfig); + + try { + zookeeperOperation.unsubscribeConfig(group, dataId, zookeeperListener); + } catch (Exception e) { + logUnsubscribeFailed(e, globalConfig); + } + } + + @Override + public ConfigType getConfigType() { + return ConfigType.ZOOKEEPER; + } +} \ No newline at end of file diff --git a/discovery-plugin-config-center/discovery-plugin-config-center-starter-zookeeper/src/main/java/com/nepxion/discovery/plugin/configcenter/zookeeper/configuration/ZookeeperConfigAutoConfiguration.java b/discovery-plugin-config-center/discovery-plugin-config-center-starter-zookeeper/src/main/java/com/nepxion/discovery/plugin/configcenter/zookeeper/configuration/ZookeeperConfigAutoConfiguration.java new file mode 100644 index 0000000000..1b6bd4cca4 --- /dev/null +++ b/discovery-plugin-config-center/discovery-plugin-config-center-starter-zookeeper/src/main/java/com/nepxion/discovery/plugin/configcenter/zookeeper/configuration/ZookeeperConfigAutoConfiguration.java @@ -0,0 +1,50 @@ +package com.nepxion.discovery.plugin.configcenter.zookeeper.configuration; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author rotten + * @version 1.0 + */ + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import com.nepxion.banner.BannerConstant; +import com.nepxion.banner.Description; +import com.nepxion.banner.LogoBanner; +import com.nepxion.banner.NepxionBanner; +import com.nepxion.discovery.common.entity.ConfigType; +import com.nepxion.discovery.plugin.configcenter.adapter.ConfigAdapter; +import com.nepxion.discovery.plugin.configcenter.zookeeper.adapter.ZookeeperConfigAdapter; +import com.taobao.text.Color; + +@Configuration +public class ZookeeperConfigAutoConfiguration { + static { + /*String bannerShown = System.getProperty(BannerConstant.BANNER_SHOWN, "true"); + if (Boolean.valueOf(bannerShown)) { + System.out.println(""); + System.out.println("╔════╗ ╔╗"); + System.out.println("╚══╗═║ ║║"); + System.out.println(" ╔╝╔╬══╦══╣║╔╦══╦══╦══╦══╦═╗"); + System.out.println(" ╔╝╔╝║╔╗║╔╗║╚╝╣║═╣║═╣╔╗║║═╣╔╝"); + System.out.println("╔╝═╚═╣╚╝║╚╝║╔╗╣║═╣║═╣╚╝║║═╣║"); + System.out.println("╚════╩══╩══╩╝╚╩══╩══╣╔═╩══╩╝"); + System.out.println(" ║║"); + System.out.println(" ╚╝"); + System.out.println(ZookeeperConstant.DISCOVERY_PLUGIN + " Discovery"); + System.out.println(""); + }*/ + + LogoBanner logoBanner = new LogoBanner(ZookeeperConfigAutoConfiguration.class, "/com/nepxion/zookeeper/resource/logo.txt", "Welcome to Nepxion", 9, 5, new Color[] { Color.red, Color.green, Color.cyan, Color.blue, Color.yellow, Color.magenta, Color.red, Color.green, Color.cyan }, true); + NepxionBanner.show(logoBanner, new Description("Config:", ConfigType.ZOOKEEPER.toString(), 0, 1), new Description(BannerConstant.GITHUB + ":", BannerConstant.NEPXION_GITHUB + "/Discovery", 0, 1)); + } + + @Bean + public ConfigAdapter configAdapter() { + return new ZookeeperConfigAdapter(); + } +} \ No newline at end of file diff --git a/discovery-plugin-config-center/discovery-plugin-config-center-starter-zookeeper/src/main/resources/META-INF/spring.factories b/discovery-plugin-config-center/discovery-plugin-config-center-starter-zookeeper/src/main/resources/META-INF/spring.factories new file mode 100644 index 0000000000..a8919f1e3a --- /dev/null +++ b/discovery-plugin-config-center/discovery-plugin-config-center-starter-zookeeper/src/main/resources/META-INF/spring.factories @@ -0,0 +1,2 @@ +org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ +com.nepxion.discovery.plugin.configcenter.zookeeper.configuration.ZookeeperConfigAutoConfiguration \ No newline at end of file diff --git a/discovery-plugin-config-center/discovery-plugin-config-center-starter/pom.xml b/discovery-plugin-config-center/discovery-plugin-config-center-starter/pom.xml new file mode 100644 index 0000000000..ac621ae39f --- /dev/null +++ b/discovery-plugin-config-center/discovery-plugin-config-center-starter/pom.xml @@ -0,0 +1,23 @@ + + + discovery-plugin-config-center-starter + Nepxion Discovery Plugin Config Center Starter + jar + 4.0.0 + Nepxion Discovery is a solution for Spring Cloud with blue green, gray, weight, limitation, circuit breaker, degrade, isolation, monitor, tracing, dye, failover, async agent + http://www.nepxion.com + + + com.nepxion + discovery-plugin-config-center + 6.23.0 + + + + + ${project.groupId} + discovery-plugin-framework-starter + + + \ No newline at end of file diff --git a/discovery-plugin-config-center/discovery-plugin-config-center-starter/src/main/java/com/nepxion/discovery/plugin/configcenter/adapter/ConfigAdapter.java b/discovery-plugin-config-center/discovery-plugin-config-center-starter/src/main/java/com/nepxion/discovery/plugin/configcenter/adapter/ConfigAdapter.java new file mode 100644 index 0000000000..d539a64edf --- /dev/null +++ b/discovery-plugin-config-center/discovery-plugin-config-center-starter/src/main/java/com/nepxion/discovery/plugin/configcenter/adapter/ConfigAdapter.java @@ -0,0 +1,165 @@ +package com.nepxion.discovery.plugin.configcenter.adapter; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; + +import com.nepxion.discovery.common.entity.ConfigType; +import com.nepxion.discovery.common.entity.RuleEntity; +import com.nepxion.discovery.common.entity.SubscriptionType; +import com.nepxion.discovery.plugin.configcenter.loader.RemoteConfigLoader; +import com.nepxion.discovery.plugin.configcenter.logger.ConfigLogger; +import com.nepxion.discovery.plugin.framework.adapter.PluginAdapter; +import com.nepxion.discovery.plugin.framework.adapter.PluginConfigAdapter; +import com.nepxion.discovery.plugin.framework.event.PluginEventWapper; +import com.nepxion.discovery.plugin.framework.event.RuleClearedEvent; +import com.nepxion.discovery.plugin.framework.event.RuleUpdatedEvent; + +public abstract class ConfigAdapter extends RemoteConfigLoader implements PluginConfigAdapter { + @Autowired + private PluginAdapter pluginAdapter; + + @Autowired + private PluginEventWapper pluginEventWapper; + + @Autowired + private ConfigLogger configLogger; + + @Override + public String[] getConfigList() throws Exception { + String[] configList = new String[2]; + configList[0] = getConfig(false); + configList[1] = getConfig(true); + + return configList; + } + + public String getConfig(boolean globalConfig) throws Exception { + logGetStarted(globalConfig); + + String group = getGroup(); + String dataId = getDataId(globalConfig); + + String config = getConfig(group, dataId); + + if (StringUtils.isNotBlank(config)) { + logFound(globalConfig); + } else { + logNotFound(globalConfig); + } + + return config; + } + + public void callbackConfig(String config, boolean globalConfig) { + SubscriptionType subscriptionType = getSubscriptionType(globalConfig); + + if (StringUtils.isNotBlank(config)) { + logUpdatedEvent(globalConfig); + + RuleEntity ruleEntity = null; + if (globalConfig) { + ruleEntity = pluginAdapter.getDynamicGlobalRule(); + } else { + ruleEntity = pluginAdapter.getDynamicPartialRule(); + } + + String rule = null; + if (ruleEntity != null) { + rule = ruleEntity.getContent(); + } + if (!StringUtils.equals(rule, config)) { + fireRuleUpdated(new RuleUpdatedEvent(subscriptionType, config), true); + } else { + logUpdatedSame(globalConfig); + } + } else { + logClearedEvent(globalConfig); + + fireRuleCleared(new RuleClearedEvent(subscriptionType), true); + } + } + + public String getGroup() { + return pluginAdapter.getGroup(); + } + + public String getServiceId() { + return pluginAdapter.getServiceId(); + } + + public String getDataId(boolean globalConfig) { + String group = getGroup(); + String serviceId = getServiceId(); + + return globalConfig ? group : serviceId; + } + + public void fireRuleUpdated(RuleUpdatedEvent ruleUpdatedEvent, boolean async) { + pluginEventWapper.fireRuleUpdated(ruleUpdatedEvent, async); + } + + public void fireRuleCleared(RuleClearedEvent ruleClearedEvent, boolean async) { + pluginEventWapper.fireRuleCleared(ruleClearedEvent, async); + } + + public SubscriptionType getSubscriptionType(boolean globalConfig) { + return globalConfig ? SubscriptionType.GLOBAL : SubscriptionType.PARTIAL; + } + + public void logGetStarted(boolean globalConfig) { + configLogger.logGetStarted(globalConfig); + } + + public void logSubscribeStarted(boolean globalConfig) { + configLogger.logSubscribeStarted(globalConfig); + } + + public void logSubscribeFailed(Exception e, boolean globalConfig) { + configLogger.logSubscribeFailed(e, globalConfig); + } + + public void logUnsubscribeStarted(boolean globalConfig) { + configLogger.logUnsubscribeStarted(globalConfig); + } + + public void logUnsubscribeFailed(Exception e, boolean globalConfig) { + configLogger.logUnsubscribeFailed(e, globalConfig); + } + + public void logFound(boolean globalConfig) { + configLogger.logFound(globalConfig); + } + + public void logNotFound(boolean globalConfig) { + configLogger.logNotFound(globalConfig); + } + + public void logUpdatedEvent(boolean globalConfig) { + configLogger.logUpdatedEvent(globalConfig); + } + + public void logClearedEvent(boolean globalConfig) { + configLogger.logClearedEvent(globalConfig); + } + + public void logUpdatedSame(boolean globalConfig) { + configLogger.logUpdatedSame(globalConfig); + } + + public boolean isConfigSingleKey() { + ConfigType configType = getConfigType(); + + return ConfigType.isSingleKey(configType); + } + + public abstract String getConfig(String group, String dataId) throws Exception; +} \ No newline at end of file diff --git a/discovery-plugin-config-center/discovery-plugin-config-center-starter/src/main/java/com/nepxion/discovery/plugin/configcenter/configuration/ConfigAutoConfiguration.java b/discovery-plugin-config-center/discovery-plugin-config-center-starter/src/main/java/com/nepxion/discovery/plugin/configcenter/configuration/ConfigAutoConfiguration.java new file mode 100644 index 0000000000..e9f0ea3dee --- /dev/null +++ b/discovery-plugin-config-center/discovery-plugin-config-center-starter/src/main/java/com/nepxion/discovery/plugin/configcenter/configuration/ConfigAutoConfiguration.java @@ -0,0 +1,45 @@ +package com.nepxion.discovery.plugin.configcenter.configuration; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import com.nepxion.discovery.plugin.configcenter.initializer.ConfigInitializer; +import com.nepxion.discovery.plugin.configcenter.loader.LocalConfigLoader; +import com.nepxion.discovery.plugin.configcenter.logger.ConfigLogger; +import com.nepxion.discovery.plugin.framework.context.PluginContextAware; + +@Configuration +public class ConfigAutoConfiguration { + @Autowired + private PluginContextAware pluginContextAware; + + @Bean + public LocalConfigLoader localConfigLoader() { + return new LocalConfigLoader() { + @Override + protected String getPath() { + return pluginContextAware.getConfigPath(); + } + }; + } + + @Bean + public ConfigInitializer configInitializer() { + return new ConfigInitializer(); + } + + @Bean + public ConfigLogger configLogger() { + return new ConfigLogger(); + } +} \ No newline at end of file diff --git a/discovery-plugin-config-center/discovery-plugin-config-center-starter/src/main/java/com/nepxion/discovery/plugin/configcenter/initializer/ConfigInitializer.java b/discovery-plugin-config-center/discovery-plugin-config-center-starter/src/main/java/com/nepxion/discovery/plugin/configcenter/initializer/ConfigInitializer.java new file mode 100644 index 0000000000..c4d9434e02 --- /dev/null +++ b/discovery-plugin-config-center/discovery-plugin-config-center-starter/src/main/java/com/nepxion/discovery/plugin/configcenter/initializer/ConfigInitializer.java @@ -0,0 +1,142 @@ +package com.nepxion.discovery.plugin.configcenter.initializer; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import javax.annotation.PostConstruct; + +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; + +import com.nepxion.discovery.common.constant.DiscoveryConstant; +import com.nepxion.discovery.common.entity.RuleEntity; +import com.nepxion.discovery.common.entity.SubscriptionType; +import com.nepxion.discovery.plugin.configcenter.loader.LocalConfigLoader; +import com.nepxion.discovery.plugin.configcenter.loader.RemoteConfigLoader; +import com.nepxion.discovery.plugin.framework.adapter.PluginAdapter; +import com.nepxion.discovery.plugin.framework.event.PluginEventWapper; +import com.nepxion.discovery.plugin.framework.event.RuleFailureEvent; +import com.nepxion.discovery.plugin.framework.parser.PluginConfigParser; + +public class ConfigInitializer { + private static final Logger LOG = LoggerFactory.getLogger(ConfigInitializer.class); + + @Autowired + private PluginAdapter pluginAdapter; + + @Autowired + private PluginConfigParser pluginConfigParser; + + @Autowired + private PluginEventWapper pluginEventWapper; + + @Autowired + private LocalConfigLoader localConfigLoader; + + @Autowired(required = false) + private RemoteConfigLoader remoteConfigLoader; + + @Value("${" + DiscoveryConstant.SPRING_APPLICATION_PARAMETER_EVENT_ONSTART_ENABLED + ":true}") + private Boolean parameterEventOnstartEnabled; + + @PostConstruct + public void initialize() { + LOG.info("------------- Load Discovery Config --------------"); + + String[] remoteConfigList = getRemoteConfigList(); + if (remoteConfigList != null) { + String partialRemoteConfig = remoteConfigList[0]; + if (StringUtils.isNotEmpty(partialRemoteConfig)) { + LOG.info("Initialize partial remote config..."); + + try { + RuleEntity ruleEntity = pluginConfigParser.parse(partialRemoteConfig); + pluginAdapter.setDynamicPartialRule(ruleEntity); + } catch (Exception e) { + LOG.error("Initialize partial remote config failed", e); + + pluginEventWapper.fireRuleFailure(new RuleFailureEvent(SubscriptionType.PARTIAL, partialRemoteConfig, e)); + } + } + + String globalRemoteConfig = remoteConfigList[1]; + if (StringUtils.isNotEmpty(globalRemoteConfig)) { + LOG.info("Initialize global remote config..."); + + try { + RuleEntity ruleEntity = pluginConfigParser.parse(globalRemoteConfig); + pluginAdapter.setDynamicGlobalRule(ruleEntity); + } catch (Exception e) { + LOG.error("Initialize global remote config failed", e); + + pluginEventWapper.fireRuleFailure(new RuleFailureEvent(SubscriptionType.GLOBAL, globalRemoteConfig, e)); + } + } + } + + String[] localConfigList = getLocalConfigList(); + if (localConfigList != null) { + String localConfig = localConfigList[0]; + if (StringUtils.isNotEmpty(localConfig)) { + LOG.info("Initialize local config..."); + + try { + RuleEntity ruleEntity = pluginConfigParser.parse(localConfig); + pluginAdapter.setLocalRule(ruleEntity); + } catch (Exception e) { + LOG.error("Initialize local config failed", e); + } + } + } + + if (remoteConfigList == null && localConfigList == null) { + LOG.info("No configs are found"); + } + + // 初始化配置的时候,是否触发fireParameterChanged的EventBus事件 + if (parameterEventOnstartEnabled) { + pluginEventWapper.fireParameterChanged(); + } + + LOG.info("--------------------------------------------------"); + } + + private String[] getRemoteConfigList() { + if (remoteConfigLoader != null) { + String[] configList = null; + + try { + configList = remoteConfigLoader.getConfigList(); + } catch (Exception e) { + LOG.warn("Get remote config list failed", e); + } + + return configList; + } else { + LOG.info("Remote config loader isn't provided"); + } + + return null; + } + + private String[] getLocalConfigList() { + String[] configList = null; + + try { + configList = localConfigLoader.getConfigList(); + } catch (Exception e) { + LOG.warn("Get local config list failed", e); + } + + return configList; + } +} \ No newline at end of file diff --git a/discovery-plugin-config-center/src/main/java/com/nepxion/discovery/plugin/configcenter/loader/ConfigLoader.java b/discovery-plugin-config-center/discovery-plugin-config-center-starter/src/main/java/com/nepxion/discovery/plugin/configcenter/loader/ConfigLoader.java similarity index 85% rename from discovery-plugin-config-center/src/main/java/com/nepxion/discovery/plugin/configcenter/loader/ConfigLoader.java rename to discovery-plugin-config-center/discovery-plugin-config-center-starter/src/main/java/com/nepxion/discovery/plugin/configcenter/loader/ConfigLoader.java index 415db258d3..4633f2a085 100644 --- a/discovery-plugin-config-center/src/main/java/com/nepxion/discovery/plugin/configcenter/loader/ConfigLoader.java +++ b/discovery-plugin-config-center/discovery-plugin-config-center-starter/src/main/java/com/nepxion/discovery/plugin/configcenter/loader/ConfigLoader.java @@ -10,5 +10,5 @@ */ public interface ConfigLoader { - String getConfig() throws Exception; + String[] getConfigList() throws Exception; } \ No newline at end of file diff --git a/discovery-plugin-config-center/discovery-plugin-config-center-starter/src/main/java/com/nepxion/discovery/plugin/configcenter/loader/LocalConfigLoader.java b/discovery-plugin-config-center/discovery-plugin-config-center-starter/src/main/java/com/nepxion/discovery/plugin/configcenter/loader/LocalConfigLoader.java new file mode 100644 index 0000000000..bb8f40dc16 --- /dev/null +++ b/discovery-plugin-config-center/discovery-plugin-config-center-starter/src/main/java/com/nepxion/discovery/plugin/configcenter/loader/LocalConfigLoader.java @@ -0,0 +1,32 @@ +package com.nepxion.discovery.plugin.configcenter.loader; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; + +import com.nepxion.discovery.common.util.FileUtil; + +public abstract class LocalConfigLoader implements ConfigLoader { + @Autowired + private ApplicationContext applicationContext; + + @Override + public String[] getConfigList() throws Exception { + String path = getPath(); + + String[] config = new String[1]; + config[0] = FileUtil.getText(applicationContext, path); + + return config; + } + + protected abstract String getPath(); +} \ No newline at end of file diff --git a/discovery-plugin-config-center/discovery-plugin-config-center-starter/src/main/java/com/nepxion/discovery/plugin/configcenter/loader/RemoteConfigLoader.java b/discovery-plugin-config-center/discovery-plugin-config-center-starter/src/main/java/com/nepxion/discovery/plugin/configcenter/loader/RemoteConfigLoader.java new file mode 100644 index 0000000000..aaa5b34aeb --- /dev/null +++ b/discovery-plugin-config-center/discovery-plugin-config-center-starter/src/main/java/com/nepxion/discovery/plugin/configcenter/loader/RemoteConfigLoader.java @@ -0,0 +1,23 @@ +package com.nepxion.discovery.plugin.configcenter.loader; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.springframework.beans.factory.DisposableBean; + +public abstract class RemoteConfigLoader implements ConfigLoader, DisposableBean { + public abstract void subscribeConfig(); + + public abstract void unsubscribeConfig(); + + @Override + public void destroy() throws Exception { + unsubscribeConfig(); + } +} \ No newline at end of file diff --git a/discovery-plugin-config-center/discovery-plugin-config-center-starter/src/main/java/com/nepxion/discovery/plugin/configcenter/logger/ConfigLogger.java b/discovery-plugin-config-center/discovery-plugin-config-center-starter/src/main/java/com/nepxion/discovery/plugin/configcenter/logger/ConfigLogger.java new file mode 100644 index 0000000000..a576716a27 --- /dev/null +++ b/discovery-plugin-config-center/discovery-plugin-config-center-starter/src/main/java/com/nepxion/discovery/plugin/configcenter/logger/ConfigLogger.java @@ -0,0 +1,159 @@ +package com.nepxion.discovery.plugin.configcenter.logger; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; + +import com.nepxion.discovery.common.entity.ConfigType; +import com.nepxion.discovery.common.entity.SubscriptionType; +import com.nepxion.discovery.plugin.configcenter.adapter.ConfigAdapter; + +public class ConfigLogger { + private static final Logger LOG = LoggerFactory.getLogger(ConfigLogger.class); + + @Autowired(required = false) + private ConfigAdapter configAdapter; + + public void logGetStarted(boolean globalConfig) { + if (configAdapter == null) { + return; + } + + String group = configAdapter.getGroup(); + String dataId = configAdapter.getDataId(globalConfig); + SubscriptionType subscriptionType = configAdapter.getSubscriptionType(globalConfig); + ConfigType configType = configAdapter.getConfigType(); + + LOG.info("Get {} config from {} server, " + getLogKey(), subscriptionType, configType, group, dataId); + } + + public void logSubscribeStarted(boolean globalConfig) { + if (configAdapter == null) { + return; + } + + String group = configAdapter.getGroup(); + String dataId = configAdapter.getDataId(globalConfig); + SubscriptionType subscriptionType = configAdapter.getSubscriptionType(globalConfig); + ConfigType configType = configAdapter.getConfigType(); + + LOG.info("Subscribe {} config from {} server, " + getLogKey(), subscriptionType, configType, group, dataId); + } + + public void logSubscribeFailed(Exception e, boolean globalConfig) { + if (configAdapter == null) { + return; + } + + String group = configAdapter.getGroup(); + String dataId = configAdapter.getDataId(globalConfig); + SubscriptionType subscriptionType = configAdapter.getSubscriptionType(globalConfig); + ConfigType configType = configAdapter.getConfigType(); + + LOG.error("Subscribe {} config from {} server failed, " + getLogKey(), subscriptionType, configType, group, dataId, e); + } + + public void logUnsubscribeStarted(boolean globalConfig) { + if (configAdapter == null) { + return; + } + + String group = configAdapter.getGroup(); + String dataId = configAdapter.getDataId(globalConfig); + SubscriptionType subscriptionType = configAdapter.getSubscriptionType(globalConfig); + ConfigType configType = configAdapter.getConfigType(); + + LOG.info("Unsubscribe {} config from {} server, " + getLogKey(), subscriptionType, configType, group, dataId); + } + + public void logUnsubscribeFailed(Exception e, boolean globalConfig) { + if (configAdapter == null) { + return; + } + + String group = configAdapter.getGroup(); + String dataId = configAdapter.getDataId(globalConfig); + SubscriptionType subscriptionType = configAdapter.getSubscriptionType(globalConfig); + ConfigType configType = configAdapter.getConfigType(); + + LOG.error("Unsubscribe {} config from {} server failed, " + getLogKey(), subscriptionType, configType, group, dataId, e); + } + + public void logFound(boolean globalConfig) { + if (configAdapter == null) { + return; + } + + SubscriptionType subscriptionType = configAdapter.getSubscriptionType(globalConfig); + ConfigType configType = configAdapter.getConfigType(); + + LOG.info("Found {} config from {} server", subscriptionType, configType); + } + + public void logNotFound(boolean globalConfig) { + if (configAdapter == null) { + return; + } + + SubscriptionType subscriptionType = configAdapter.getSubscriptionType(globalConfig); + ConfigType configType = configAdapter.getConfigType(); + + LOG.info("Not found {} config from {} server", subscriptionType, configType); + } + + public void logUpdatedEvent(boolean globalConfig) { + if (configAdapter == null) { + return; + } + + String group = configAdapter.getGroup(); + String dataId = configAdapter.getDataId(globalConfig); + SubscriptionType subscriptionType = configAdapter.getSubscriptionType(globalConfig); + ConfigType configType = configAdapter.getConfigType(); + + LOG.info("Get {} config updated event from {} server, " + getLogKey(), subscriptionType, configType, group, dataId); + } + + public void logClearedEvent(boolean globalConfig) { + if (configAdapter == null) { + return; + } + + String group = configAdapter.getGroup(); + String dataId = configAdapter.getDataId(globalConfig); + SubscriptionType subscriptionType = configAdapter.getSubscriptionType(globalConfig); + ConfigType configType = configAdapter.getConfigType(); + + LOG.info("Get {} config cleared event from {} server, " + getLogKey(), subscriptionType, configType, group, dataId); + } + + public void logUpdatedSame(boolean globalConfig) { + if (configAdapter == null) { + return; + } + + String group = configAdapter.getGroup(); + String dataId = configAdapter.getDataId(globalConfig); + SubscriptionType subscriptionType = configAdapter.getSubscriptionType(globalConfig); + ConfigType configType = configAdapter.getConfigType(); + + LOG.info("Updated {} config from {} server is same as current config, ignore to update, " + getLogKey(), subscriptionType, configType, group, dataId); + } + + private String getLogKey() { + if (configAdapter == null) { + return null; + } + + return configAdapter.isConfigSingleKey() ? "key={}-{}" : "group={}, dataId={}"; + } +} \ No newline at end of file diff --git a/discovery-plugin-config-center/discovery-plugin-config-center-starter/src/main/resources/META-INF/spring.factories b/discovery-plugin-config-center/discovery-plugin-config-center-starter/src/main/resources/META-INF/spring.factories new file mode 100644 index 0000000000..46cc718147 --- /dev/null +++ b/discovery-plugin-config-center/discovery-plugin-config-center-starter/src/main/resources/META-INF/spring.factories @@ -0,0 +1,2 @@ +org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ +com.nepxion.discovery.plugin.configcenter.configuration.ConfigAutoConfiguration \ No newline at end of file diff --git a/discovery-plugin-config-center/pom.xml b/discovery-plugin-config-center/pom.xml index a0ca865fbd..299ecf193c 100644 --- a/discovery-plugin-config-center/pom.xml +++ b/discovery-plugin-config-center/pom.xml @@ -3,31 +3,24 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> discovery-plugin-config-center Nepxion Discovery Plugin Config Center - jar + pom 4.0.0 - Nepxion Discovery is an enhancement for Spring Cloud Discovery + Nepxion Discovery is a solution for Spring Cloud with blue green, gray, weight, limitation, circuit breaker, degrade, isolation, monitor, tracing, dye, failover, async agent http://www.nepxion.com com.nepxion discovery - 5.2.0-SNAPSHOT + 6.23.0 - - - ${project.groupId} - discovery-plugin-framework - - - - dom4j - dom4j - - - - com.fasterxml.jackson.core - jackson-databind - - + + discovery-plugin-config-center-starter + discovery-plugin-config-center-starter-apollo + discovery-plugin-config-center-starter-nacos + discovery-plugin-config-center-starter-redis + discovery-plugin-config-center-starter-zookeeper + discovery-plugin-config-center-starter-consul + discovery-plugin-config-center-starter-etcd + \ No newline at end of file diff --git a/discovery-plugin-config-center/src/main/java/com/nepxion/discovery/plugin/configcenter/adapter/ConfigAdapter.java b/discovery-plugin-config-center/src/main/java/com/nepxion/discovery/plugin/configcenter/adapter/ConfigAdapter.java deleted file mode 100644 index 9af2fc9953..0000000000 --- a/discovery-plugin-config-center/src/main/java/com/nepxion/discovery/plugin/configcenter/adapter/ConfigAdapter.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.nepxion.discovery.plugin.configcenter.adapter; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import org.springframework.beans.factory.annotation.Autowired; - -import com.nepxion.discovery.plugin.configcenter.loader.RemoteConfigLoader; -import com.nepxion.discovery.plugin.framework.event.PluginEventWapper; -import com.nepxion.discovery.plugin.framework.event.RuleClearedEvent; -import com.nepxion.discovery.plugin.framework.event.RuleUpdatedEvent; - -public abstract class ConfigAdapter extends RemoteConfigLoader { - @Autowired - private PluginEventWapper pluginEventWapper; - - public void fireRuleUpdated(RuleUpdatedEvent ruleUpdatedEvent, boolean async) { - pluginEventWapper.fireRuleUpdated(ruleUpdatedEvent, async); - } - - public void fireRuleCleared(RuleClearedEvent ruleClearedEvent, boolean async) { - pluginEventWapper.fireRuleCleared(ruleClearedEvent, async); - } -} \ No newline at end of file diff --git a/discovery-plugin-config-center/src/main/java/com/nepxion/discovery/plugin/configcenter/configuration/ConfigAutoConfiguration.java b/discovery-plugin-config-center/src/main/java/com/nepxion/discovery/plugin/configcenter/configuration/ConfigAutoConfiguration.java deleted file mode 100644 index ac5ef79e43..0000000000 --- a/discovery-plugin-config-center/src/main/java/com/nepxion/discovery/plugin/configcenter/configuration/ConfigAutoConfiguration.java +++ /dev/null @@ -1,63 +0,0 @@ -package com.nepxion.discovery.plugin.configcenter.configuration; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import org.apache.commons.lang3.StringUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -import com.nepxion.discovery.common.constant.DiscoveryConstant; -import com.nepxion.discovery.common.exception.DiscoveryException; -import com.nepxion.discovery.plugin.configcenter.context.ConfigContextClosedHandler; -import com.nepxion.discovery.plugin.configcenter.initializer.ConfigInitializer; -import com.nepxion.discovery.plugin.configcenter.loader.LocalConfigLoader; -import com.nepxion.discovery.plugin.configcenter.parser.json.JsonConfigParser; -import com.nepxion.discovery.plugin.configcenter.parser.xml.XmlConfigParser; -import com.nepxion.discovery.plugin.framework.config.PluginConfigParser; -import com.nepxion.discovery.plugin.framework.context.PluginContextAware; - -@Configuration -public class ConfigAutoConfiguration { - @Autowired - private PluginContextAware pluginContextAware; - - @Bean - public PluginConfigParser pluginConfigParser() { - String configFormat = pluginContextAware.getConfigFormat(); - if (StringUtils.equals(configFormat, DiscoveryConstant.XML_FORMAT)) { - return new XmlConfigParser(); - } else if (StringUtils.equals(configFormat, DiscoveryConstant.JSON_FORMAT)) { - return new JsonConfigParser(); - } - - throw new DiscoveryException("Invalid config format for '" + configFormat + "'"); - } - - @Bean - public LocalConfigLoader localConfigLoader() { - return new LocalConfigLoader() { - @Override - protected String getPath() { - return pluginContextAware.getConfigPath(); - } - }; - } - - @Bean - public ConfigInitializer configInitializer() { - return new ConfigInitializer(); - } - - @Bean - public ConfigContextClosedHandler configContextClosedHandler() { - return new ConfigContextClosedHandler(); - } -} \ No newline at end of file diff --git a/discovery-plugin-config-center/src/main/java/com/nepxion/discovery/plugin/configcenter/constant/ConfigConstant.java b/discovery-plugin-config-center/src/main/java/com/nepxion/discovery/plugin/configcenter/constant/ConfigConstant.java deleted file mode 100644 index 6b9fb0bdda..0000000000 --- a/discovery-plugin-config-center/src/main/java/com/nepxion/discovery/plugin/configcenter/constant/ConfigConstant.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.nepxion.discovery.plugin.configcenter.constant; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import com.nepxion.discovery.common.constant.DiscoveryConstant; - -public class ConfigConstant { - public static final String RULE_ELEMENT_NAME = "rule"; - public static final String REGISTER_ELEMENT_NAME = "register"; - public static final String DISCOVERY_ELEMENT_NAME = "discovery"; - public static final String STRATEGY_ELEMENT_NAME = "strategy"; - public static final String CUSTOMIZATION_ELEMENT_NAME = "customization"; - public static final String STRATEGY_CUSTOMIZATION_ELEMENT_NAME = "strategy-customization"; - public static final String CONDITIONS_ELEMENT_NAME = "conditions"; - public static final String CONDITION_ELEMENT_NAME = "condition"; - public static final String ROUTES_ELEMENT_NAME = "routes"; - public static final String ROUTE_ELEMENT_NAME = "route"; - public static final String SERVICE_ELEMENT_NAME = "service"; - public static final String BLACKLIST_ELEMENT_NAME = "blacklist"; - public static final String WHITELIST_ELEMENT_NAME = "whitelist"; - public static final String COUNT_ELEMENT_NAME = "count"; - public static final String WEIGHT_ELEMENT_NAME = "weight"; - public static final String VERSION_ELEMENT_NAME = DiscoveryConstant.VERSION; - public static final String REGION_ELEMENT_NAME = DiscoveryConstant.REGION; - public static final String ADDRESS_ELEMENT_NAME = DiscoveryConstant.ADDRESS; - public static final String VERSION_WEIGHT_ELEMENT_NAME = DiscoveryConstant.VERSION_WEIGHT; - public static final String REGION_WEIGHT_ELEMENT_NAME = DiscoveryConstant.REGION_WEIGHT; - - public static final String FILTER_VALUE_ATTRIBUTE_NAME = "filter-value"; - public static final String SERVICE_NAME_ATTRIBUTE_NAME = "service-name"; - public static final String CONSUMER_SERVICE_NAME_ATTRIBUTE_NAME = "consumer-service-name"; - public static final String PROVIDER_SERVICE_NAME_ATTRIBUTE_NAME = "provider-service-name"; - public static final String CONSUMER_VERSION_VALUE_ATTRIBUTE_NAME = "consumer-version-value"; - public static final String PROVIDER_VERSION_VALUE_ATTRIBUTE_NAME = "provider-version-value"; - public static final String PROVIDER_WEIGHT_VALUE_ATTRIBUTE_NAME = "provider-weight-value"; - public static final String KEY_ATTRIBUTE_NAME = "key"; - public static final String VALUE_ATTRIBUTE_NAME = "value"; - public static final String ID_ATTRIBUTE_NAME = "id"; - public static final String HEADER_ATTRIBUTE_NAME = "header"; - public static final String TYPE_ATTRIBUTE_NAME = "type"; -} \ No newline at end of file diff --git a/discovery-plugin-config-center/src/main/java/com/nepxion/discovery/plugin/configcenter/context/ConfigContextClosedHandler.java b/discovery-plugin-config-center/src/main/java/com/nepxion/discovery/plugin/configcenter/context/ConfigContextClosedHandler.java deleted file mode 100644 index b9c2a11e3a..0000000000 --- a/discovery-plugin-config-center/src/main/java/com/nepxion/discovery/plugin/configcenter/context/ConfigContextClosedHandler.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.nepxion.discovery.plugin.configcenter.context; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.ApplicationListener; -import org.springframework.context.event.ContextClosedEvent; - -import com.nepxion.discovery.plugin.configcenter.loader.RemoteConfigLoader; - -public class ConfigContextClosedHandler implements ApplicationListener { - @Autowired(required = false) - private RemoteConfigLoader remoteConfigLoader; - - @Override - public void onApplicationEvent(ContextClosedEvent event) { - if (remoteConfigLoader != null) { - remoteConfigLoader.close(); - } - } -} \ No newline at end of file diff --git a/discovery-plugin-config-center/src/main/java/com/nepxion/discovery/plugin/configcenter/initializer/ConfigInitializer.java b/discovery-plugin-config-center/src/main/java/com/nepxion/discovery/plugin/configcenter/initializer/ConfigInitializer.java deleted file mode 100644 index efd4501b48..0000000000 --- a/discovery-plugin-config-center/src/main/java/com/nepxion/discovery/plugin/configcenter/initializer/ConfigInitializer.java +++ /dev/null @@ -1,131 +0,0 @@ -package com.nepxion.discovery.plugin.configcenter.initializer; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import javax.annotation.PostConstruct; - -import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; - -import com.nepxion.discovery.common.entity.RuleEntity; -import com.nepxion.discovery.plugin.configcenter.loader.LocalConfigLoader; -import com.nepxion.discovery.plugin.configcenter.loader.RemoteConfigLoader; -import com.nepxion.discovery.plugin.framework.adapter.PluginAdapter; -import com.nepxion.discovery.plugin.framework.config.PluginConfigParser; -import com.nepxion.discovery.plugin.framework.context.PluginContextAware; - -public class ConfigInitializer { - private static final Logger LOG = LoggerFactory.getLogger(ConfigInitializer.class); - - @Autowired - private PluginContextAware pluginContextAware; - - @Autowired - private PluginAdapter pluginAdapter; - - @Autowired - private PluginConfigParser pluginConfigParser; - - // @Autowired - // private PluginEventWapper pluginEventWapper; - - @Autowired - private LocalConfigLoader localConfigLoader; - - @Autowired(required = false) - private RemoteConfigLoader remoteConfigLoader; - - @PostConstruct - public void initialize() { - Boolean registerControlEnabled = pluginContextAware.isRegisterControlEnabled(); - Boolean discoveryControlEnabled = pluginContextAware.isDiscoveryControlEnabled(); - - if (!registerControlEnabled && !discoveryControlEnabled) { - LOG.info("Register and Discovery controls are all disabled, ignore to initialize"); - - return; - } - - LOG.info("Rule starts to initialize..."); - - String remoteConfig = getRemoteConfig(); - if (StringUtils.isNotEmpty(remoteConfig)) { - try { - RuleEntity ruleEntity = pluginConfigParser.parse(remoteConfig); - pluginAdapter.setDynamicRule(ruleEntity); - } catch (Exception e) { - LOG.error("Parse rule xml failed", e); - } - } - - String localConfig = getLocalConfig(); - if (StringUtils.isNotEmpty(localConfig)) { - try { - RuleEntity ruleEntity = pluginConfigParser.parse(localConfig); - pluginAdapter.setLocalRule(ruleEntity); - } catch (Exception e) { - LOG.error("Parse rule xml failed", e); - } - } - - if (StringUtils.isEmpty(remoteConfig) && StringUtils.isEmpty(localConfig)) { - LOG.info("No config is retrieved"); - } - - // 初始化配置的时候,不应该触发fireCustomization的EventBus事件 - // pluginEventWapper.fireCustomization(); - } - - private String getRemoteConfig() { - if (remoteConfigLoader != null) { - String config = null; - - try { - config = remoteConfigLoader.getConfig(); - } catch (Exception e) { - LOG.warn("Get remote config failed", e); - } - - if (StringUtils.isNotEmpty(config)) { - LOG.info("Remote config is retrieved"); - - return config; - } else { - LOG.info("Remote config isn't retrieved"); - } - } else { - LOG.info("Remote config loader isn't provided"); - } - - return null; - } - - private String getLocalConfig() { - String config = null; - - try { - config = localConfigLoader.getConfig(); - } catch (Exception e) { - LOG.warn("Get local config failed", e); - } - - if (StringUtils.isNotEmpty(config)) { - LOG.info("Local config is retrieved"); - - return config; - } else { - LOG.info("Local config isn't retrieved"); - } - - return null; - } -} \ No newline at end of file diff --git a/discovery-plugin-config-center/src/main/java/com/nepxion/discovery/plugin/configcenter/loader/LocalConfigLoader.java b/discovery-plugin-config-center/src/main/java/com/nepxion/discovery/plugin/configcenter/loader/LocalConfigLoader.java deleted file mode 100644 index e9d588a729..0000000000 --- a/discovery-plugin-config-center/src/main/java/com/nepxion/discovery/plugin/configcenter/loader/LocalConfigLoader.java +++ /dev/null @@ -1,56 +0,0 @@ -package com.nepxion.discovery.plugin.configcenter.loader; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import java.io.InputStream; - -import org.apache.commons.io.IOUtils; -import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.ApplicationContext; - -import com.nepxion.discovery.common.constant.DiscoveryConstant; - -public abstract class LocalConfigLoader implements ConfigLoader { - private static final Logger LOG = LoggerFactory.getLogger(LocalConfigLoader.class); - - @Autowired - private ApplicationContext applicationContext; - - @Override - public String getConfig() throws Exception { - String path = getPath(); - if (StringUtils.isEmpty(path)) { - throw new IllegalArgumentException("Config local path isn't set"); - } - - LOG.info("Config local path is {}", path); - - InputStream inputStream = null; - try { - String filePath = applicationContext.getEnvironment().resolvePlaceholders(path); - inputStream = applicationContext.getResource(filePath).getInputStream(); - - return IOUtils.toString(inputStream, DiscoveryConstant.ENCODING_UTF_8); - } catch (Exception e) { - LOG.warn("File [{}] isn't found or invalid, ignore to load...", path); - - return null; - } finally { - if (inputStream != null) { - IOUtils.closeQuietly(inputStream); - } - } - } - - protected abstract String getPath(); -} \ No newline at end of file diff --git a/discovery-plugin-config-center/src/main/java/com/nepxion/discovery/plugin/configcenter/loader/RemoteConfigLoader.java b/discovery-plugin-config-center/src/main/java/com/nepxion/discovery/plugin/configcenter/loader/RemoteConfigLoader.java deleted file mode 100644 index a28d9b303c..0000000000 --- a/discovery-plugin-config-center/src/main/java/com/nepxion/discovery/plugin/configcenter/loader/RemoteConfigLoader.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.nepxion.discovery.plugin.configcenter.loader; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -public abstract class RemoteConfigLoader implements ConfigLoader { - public abstract String getConfigType(); - - public abstract void close(); -} \ No newline at end of file diff --git a/discovery-plugin-config-center/src/main/java/com/nepxion/discovery/plugin/configcenter/parser/xml/XmlConfigParser.java b/discovery-plugin-config-center/src/main/java/com/nepxion/discovery/plugin/configcenter/parser/xml/XmlConfigParser.java deleted file mode 100644 index ac218a9dc3..0000000000 --- a/discovery-plugin-config-center/src/main/java/com/nepxion/discovery/plugin/configcenter/parser/xml/XmlConfigParser.java +++ /dev/null @@ -1,692 +0,0 @@ -package com.nepxion.discovery.plugin.configcenter.parser.xml; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -import org.apache.commons.lang3.StringUtils; -import org.dom4j.Attribute; -import org.dom4j.Document; -import org.dom4j.Element; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.nepxion.discovery.common.constant.DiscoveryConstant; -import com.nepxion.discovery.common.entity.CountFilterEntity; -import com.nepxion.discovery.common.entity.CustomizationEntity; -import com.nepxion.discovery.common.entity.DiscoveryEntity; -import com.nepxion.discovery.common.entity.FilterHolderEntity; -import com.nepxion.discovery.common.entity.FilterType; -import com.nepxion.discovery.common.entity.HostFilterEntity; -import com.nepxion.discovery.common.entity.RegionWeightEntity; -import com.nepxion.discovery.common.entity.RegisterEntity; -import com.nepxion.discovery.common.entity.RuleEntity; -import com.nepxion.discovery.common.entity.StrategyConditionEntity; -import com.nepxion.discovery.common.entity.StrategyCustomizationEntity; -import com.nepxion.discovery.common.entity.StrategyEntity; -import com.nepxion.discovery.common.entity.StrategyRouteEntity; -import com.nepxion.discovery.common.entity.StrategyType; -import com.nepxion.discovery.common.entity.VersionEntity; -import com.nepxion.discovery.common.entity.VersionFilterEntity; -import com.nepxion.discovery.common.entity.VersionWeightEntity; -import com.nepxion.discovery.common.entity.WeightEntity; -import com.nepxion.discovery.common.entity.WeightEntityWrapper; -import com.nepxion.discovery.common.entity.WeightFilterEntity; -import com.nepxion.discovery.common.entity.WeightType; -import com.nepxion.discovery.common.exception.DiscoveryException; -import com.nepxion.discovery.common.util.StringUtil; -import com.nepxion.discovery.plugin.configcenter.constant.ConfigConstant; -import com.nepxion.discovery.plugin.configcenter.parser.xml.dom4j.Dom4JReader; -import com.nepxion.discovery.plugin.framework.config.PluginConfigParser; - -public class XmlConfigParser implements PluginConfigParser { - private static final Logger LOG = LoggerFactory.getLogger(XmlConfigParser.class); - - @Override - public RuleEntity parse(String config) { - if (StringUtils.isEmpty(config)) { - throw new DiscoveryException("Config is null or empty"); - } - - try { - Document document = Dom4JReader.getDocument(config); - - Element rootElement = document.getRootElement(); - - RuleEntity ruleEntity = parseRoot(config, rootElement); - - // Just for Json text print - // System.out.println(JsonUtil.toJson(ruleEntity)); - - return ruleEntity; - } catch (Exception e) { - throw new DiscoveryException(e.getMessage(), e); - } - } - - @SuppressWarnings("rawtypes") - private RuleEntity parseRoot(String config, Element element) { - LOG.info("Start to parse rule xml..."); - - int registerElementCount = element.elements(ConfigConstant.REGISTER_ELEMENT_NAME).size(); - if (registerElementCount > 1) { - throw new DiscoveryException("Allow only one element[" + ConfigConstant.REGISTER_ELEMENT_NAME + "] to be configed"); - } - - int discoveryElementCount = element.elements(ConfigConstant.DISCOVERY_ELEMENT_NAME).size(); - if (discoveryElementCount > 1) { - throw new DiscoveryException("Allow only one element[" + ConfigConstant.DISCOVERY_ELEMENT_NAME + "] to be configed"); - } - - int strategyElementCount = element.elements(ConfigConstant.STRATEGY_ELEMENT_NAME).size(); - if (strategyElementCount > 1) { - throw new DiscoveryException("Allow only one element[" + ConfigConstant.STRATEGY_ELEMENT_NAME + "] to be configed"); - } - - int strategyCustomizationElementCount = element.elements(ConfigConstant.STRATEGY_CUSTOMIZATION_ELEMENT_NAME).size(); - if (strategyCustomizationElementCount > 1) { - throw new DiscoveryException("Allow only one element[" + ConfigConstant.STRATEGY_CUSTOMIZATION_ELEMENT_NAME + "] to be configed"); - } - - int customizationElementCount = element.elements(ConfigConstant.CUSTOMIZATION_ELEMENT_NAME).size(); - if (customizationElementCount > 1) { - throw new DiscoveryException("Allow only one element[" + ConfigConstant.CUSTOMIZATION_ELEMENT_NAME + "] to be configed"); - } - - RegisterEntity registerEntity = null; - DiscoveryEntity discoveryEntity = null; - StrategyEntity strategyEntity = null; - StrategyCustomizationEntity strategyCustomizationEntity = null; - CustomizationEntity customizationEntity = null; - for (Iterator elementIterator = element.elementIterator(); elementIterator.hasNext();) { - Object childElementObject = elementIterator.next(); - if (childElementObject instanceof Element) { - Element childElement = (Element) childElementObject; - - if (StringUtils.equals(childElement.getName(), ConfigConstant.REGISTER_ELEMENT_NAME)) { - registerEntity = new RegisterEntity(); - parseRegister(childElement, registerEntity); - } else if (StringUtils.equals(childElement.getName(), ConfigConstant.DISCOVERY_ELEMENT_NAME)) { - discoveryEntity = new DiscoveryEntity(); - parseDiscovery(childElement, discoveryEntity); - } else if (StringUtils.equals(childElement.getName(), ConfigConstant.STRATEGY_ELEMENT_NAME)) { - strategyEntity = new StrategyEntity(); - parseStrategy(childElement, strategyEntity); - } else if (StringUtils.equals(childElement.getName(), ConfigConstant.STRATEGY_CUSTOMIZATION_ELEMENT_NAME)) { - strategyCustomizationEntity = new StrategyCustomizationEntity(); - parseStrategyCustomization(childElement, strategyCustomizationEntity); - } else if (StringUtils.equals(childElement.getName(), ConfigConstant.CUSTOMIZATION_ELEMENT_NAME)) { - customizationEntity = new CustomizationEntity(); - parseCustomization(childElement, customizationEntity); - } - } - } - - RuleEntity ruleEntity = new RuleEntity(); - ruleEntity.setRegisterEntity(registerEntity); - ruleEntity.setDiscoveryEntity(discoveryEntity); - ruleEntity.setStrategyEntity(strategyEntity); - ruleEntity.setStrategyCustomizationEntity(strategyCustomizationEntity); - ruleEntity.setCustomizationEntity(customizationEntity); - ruleEntity.setContent(config); - - LOG.info("Rule content=\n{}", config); - - return ruleEntity; - } - - @SuppressWarnings("rawtypes") - private void parseRegister(Element element, RegisterEntity registerEntity) { - for (Iterator elementIterator = element.elementIterator(); elementIterator.hasNext();) { - Object childElementObject = elementIterator.next(); - if (childElementObject instanceof Element) { - Element childElement = (Element) childElementObject; - - if (StringUtils.equals(childElement.getName(), ConfigConstant.BLACKLIST_ELEMENT_NAME)) { - parseHostFilter(childElement, ConfigConstant.BLACKLIST_ELEMENT_NAME, registerEntity); - } else if (StringUtils.equals(childElement.getName(), ConfigConstant.WHITELIST_ELEMENT_NAME)) { - parseHostFilter(childElement, ConfigConstant.WHITELIST_ELEMENT_NAME, registerEntity); - } else if (StringUtils.equals(childElement.getName(), ConfigConstant.COUNT_ELEMENT_NAME)) { - parseCountFilter(childElement, registerEntity); - } - } - } - } - - @SuppressWarnings("rawtypes") - private void parseDiscovery(Element element, DiscoveryEntity discoveryEntity) { - for (Iterator elementIterator = element.elementIterator(); elementIterator.hasNext();) { - Object childElementObject = elementIterator.next(); - if (childElementObject instanceof Element) { - Element childElement = (Element) childElementObject; - - if (StringUtils.equals(childElement.getName(), ConfigConstant.BLACKLIST_ELEMENT_NAME)) { - parseHostFilter(childElement, ConfigConstant.BLACKLIST_ELEMENT_NAME, discoveryEntity); - } else if (StringUtils.equals(childElement.getName(), ConfigConstant.WHITELIST_ELEMENT_NAME)) { - parseHostFilter(childElement, ConfigConstant.WHITELIST_ELEMENT_NAME, discoveryEntity); - } else if (StringUtils.equals(childElement.getName(), ConfigConstant.VERSION_ELEMENT_NAME)) { - parseVersionFilter(childElement, discoveryEntity); - } else if (StringUtils.equals(childElement.getName(), ConfigConstant.WEIGHT_ELEMENT_NAME)) { - parseWeightFilter(childElement, discoveryEntity); - } - } - } - } - - @SuppressWarnings("rawtypes") - private void parseStrategy(Element element, StrategyEntity strategyEntity) { - int versionElementCount = element.elements(ConfigConstant.VERSION_ELEMENT_NAME).size(); - if (versionElementCount > 1) { - throw new DiscoveryException("Allow only one element[" + ConfigConstant.VERSION_ELEMENT_NAME + "] of element[" + ConfigConstant.STRATEGY_ELEMENT_NAME + "] to be configed"); - } - - int regionElementCount = element.elements(ConfigConstant.REGION_ELEMENT_NAME).size(); - if (regionElementCount > 1) { - throw new DiscoveryException("Allow only one element[" + ConfigConstant.REGION_ELEMENT_NAME + "] of element[" + ConfigConstant.STRATEGY_ELEMENT_NAME + "] to be configed"); - } - - int addressElementCount = element.elements(ConfigConstant.ADDRESS_ELEMENT_NAME).size(); - if (addressElementCount > 1) { - throw new DiscoveryException("Allow only one element[" + ConfigConstant.ADDRESS_ELEMENT_NAME + "] of element[" + ConfigConstant.STRATEGY_ELEMENT_NAME + "] to be configed"); - } - - int versionWeightElementCount = element.elements(ConfigConstant.VERSION_WEIGHT_ELEMENT_NAME).size(); - if (versionWeightElementCount > 1) { - throw new DiscoveryException("Allow only one element[" + ConfigConstant.VERSION_WEIGHT_ELEMENT_NAME + "] of element[" + ConfigConstant.STRATEGY_ELEMENT_NAME + "] to be configed"); - } - - int regionWeightElementCount = element.elements(ConfigConstant.REGION_WEIGHT_ELEMENT_NAME).size(); - if (regionWeightElementCount > 1) { - throw new DiscoveryException("Allow only one element[" + ConfigConstant.REGION_WEIGHT_ELEMENT_NAME + "] of element[" + ConfigConstant.STRATEGY_ELEMENT_NAME + "] to be configed"); - } - - for (Iterator elementIterator = element.elementIterator(); elementIterator.hasNext();) { - Object childElementObject = elementIterator.next(); - if (childElementObject instanceof Element) { - Element childElement = (Element) childElementObject; - - if (StringUtils.equals(childElement.getName(), ConfigConstant.VERSION_ELEMENT_NAME)) { - String versionValue = childElement.getTextTrim(); - strategyEntity.setVersionValue(versionValue); - } else if (StringUtils.equals(childElement.getName(), ConfigConstant.REGION_ELEMENT_NAME)) { - String regionValue = childElement.getTextTrim(); - strategyEntity.setRegionValue(regionValue); - } else if (StringUtils.equals(childElement.getName(), ConfigConstant.ADDRESS_ELEMENT_NAME)) { - String addressValue = childElement.getTextTrim(); - strategyEntity.setAddressValue(addressValue); - } else if (StringUtils.equals(childElement.getName(), ConfigConstant.VERSION_WEIGHT_ELEMENT_NAME)) { - String versionWeightValue = childElement.getTextTrim(); - strategyEntity.setVersionWeightValue(versionWeightValue); - } else if (StringUtils.equals(childElement.getName(), ConfigConstant.REGION_WEIGHT_ELEMENT_NAME)) { - String regionWeightValue = childElement.getTextTrim(); - strategyEntity.setRegionWeightValue(regionWeightValue); - } - } - } - } - - @SuppressWarnings("rawtypes") - private void parseStrategyCustomization(Element element, StrategyCustomizationEntity strategyCustomizationEntity) { - int conditionsElementCount = element.elements(ConfigConstant.CONDITIONS_ELEMENT_NAME).size(); - if (conditionsElementCount > 1) { - throw new DiscoveryException("Allow only one element[" + ConfigConstant.CONDITIONS_ELEMENT_NAME + "] of element[" + ConfigConstant.STRATEGY_CUSTOMIZATION_ELEMENT_NAME + "] to be configed"); - } - - int routesElementCount = element.elements(ConfigConstant.ROUTES_ELEMENT_NAME).size(); - if (routesElementCount > 1) { - throw new DiscoveryException("Allow only one element[" + ConfigConstant.ROUTES_ELEMENT_NAME + "] of element[" + ConfigConstant.STRATEGY_CUSTOMIZATION_ELEMENT_NAME + "] to be configed"); - } - - List strategyConditionEntityList = new ArrayList(); - List strategyRouteEntityList = new ArrayList(); - for (Iterator elementIterator = element.elementIterator(); elementIterator.hasNext();) { - Object childElementObject = elementIterator.next(); - if (childElementObject instanceof Element) { - Element childElement = (Element) childElementObject; - - if (StringUtils.equals(childElement.getName(), ConfigConstant.CONDITIONS_ELEMENT_NAME)) { - parseStrategyCondition(childElement, strategyConditionEntityList); - } else if (StringUtils.equals(childElement.getName(), ConfigConstant.ROUTES_ELEMENT_NAME)) { - parseStrategyRoute(childElement, strategyRouteEntityList); - } - } - } - - strategyCustomizationEntity.setStrategyConditionEntityList(strategyConditionEntityList); - strategyCustomizationEntity.setStrategyRouteEntityList(strategyRouteEntityList); - } - - @SuppressWarnings("rawtypes") - private void parseCustomization(Element element, CustomizationEntity customizationEntity) { - Map> customizationMap = customizationEntity.getCustomizationMap(); - for (Iterator elementIterator = element.elementIterator(); elementIterator.hasNext();) { - Object childElementObject = elementIterator.next(); - if (childElementObject instanceof Element) { - Element childElement = (Element) childElementObject; - - if (StringUtils.equals(childElement.getName(), ConfigConstant.SERVICE_ELEMENT_NAME)) { - Attribute serviceNameAttribute = childElement.attribute(ConfigConstant.SERVICE_NAME_ATTRIBUTE_NAME); - if (serviceNameAttribute == null) { - throw new DiscoveryException("Attribute[" + ConfigConstant.SERVICE_NAME_ATTRIBUTE_NAME + "] in element[" + childElement.getName() + "] is missing"); - } - String serviceName = serviceNameAttribute.getData().toString().trim(); - - Attribute keyAttribute = childElement.attribute(ConfigConstant.KEY_ATTRIBUTE_NAME); - if (keyAttribute == null) { - throw new DiscoveryException("Attribute[" + ConfigConstant.KEY_ATTRIBUTE_NAME + "] in element[" + childElement.getName() + "] is missing"); - } - String key = keyAttribute.getData().toString().trim(); - - Attribute valueAttribute = childElement.attribute(ConfigConstant.VALUE_ATTRIBUTE_NAME); - if (valueAttribute == null) { - throw new DiscoveryException("Attribute[" + ConfigConstant.VALUE_ATTRIBUTE_NAME + "] in element[" + childElement.getName() + "] is missing"); - } - String value = valueAttribute.getData().toString().trim(); - - Map customizationParameter = customizationMap.get(serviceName); - if (customizationParameter == null) { - customizationParameter = new LinkedHashMap(); - customizationMap.put(serviceName, customizationParameter); - } - customizationParameter.put(key, value); - } - } - } - } - - @SuppressWarnings("rawtypes") - private void parseHostFilter(Element element, String filterTypeValue, FilterHolderEntity filterHolderEntity) { - HostFilterEntity hostFilterEntity = filterHolderEntity.getHostFilterEntity(); - if (hostFilterEntity != null) { - throw new DiscoveryException("Allow only one filter element to be configed, [" + ConfigConstant.BLACKLIST_ELEMENT_NAME + "] or [" + ConfigConstant.WHITELIST_ELEMENT_NAME + "]"); - } - - hostFilterEntity = new HostFilterEntity(); - hostFilterEntity.setFilterType(FilterType.fromString(filterTypeValue)); - - Attribute globalFilterAttribute = element.attribute(ConfigConstant.FILTER_VALUE_ATTRIBUTE_NAME); - if (globalFilterAttribute != null) { - String globalFilterValue = globalFilterAttribute.getData().toString().trim(); - List globalFilterValueList = StringUtil.splitToList(globalFilterValue, DiscoveryConstant.SEPARATE); - hostFilterEntity.setFilterValueList(globalFilterValueList); - } - - Map> filterMap = hostFilterEntity.getFilterMap(); - for (Iterator elementIterator = element.elementIterator(); elementIterator.hasNext();) { - Object childElementObject = elementIterator.next(); - if (childElementObject instanceof Element) { - Element childElement = (Element) childElementObject; - - if (StringUtils.equals(childElement.getName(), ConfigConstant.SERVICE_ELEMENT_NAME)) { - Attribute serviceNameAttribute = childElement.attribute(ConfigConstant.SERVICE_NAME_ATTRIBUTE_NAME); - if (serviceNameAttribute == null) { - throw new DiscoveryException("Attribute[" + ConfigConstant.SERVICE_NAME_ATTRIBUTE_NAME + "] in element[" + childElement.getName() + "] is missing"); - } - String serviceName = serviceNameAttribute.getData().toString().trim(); - - Attribute filterValueAttribute = childElement.attribute(ConfigConstant.FILTER_VALUE_ATTRIBUTE_NAME); - List filterValueList = null; - if (filterValueAttribute != null) { - String filterValue = filterValueAttribute.getData().toString().trim(); - filterValueList = StringUtil.splitToList(filterValue, DiscoveryConstant.SEPARATE); - } - filterMap.put(serviceName, filterValueList); - } - } - } - - filterHolderEntity.setHostFilterEntity(hostFilterEntity); - } - - @SuppressWarnings("rawtypes") - private void parseCountFilter(Element element, RegisterEntity registerEntity) { - CountFilterEntity countFilterEntity = registerEntity.getCountFilterEntity(); - if (countFilterEntity != null) { - throw new DiscoveryException("Allow only one element[" + ConfigConstant.COUNT_ELEMENT_NAME + "] to be configed"); - } - - countFilterEntity = new CountFilterEntity(); - - Attribute globalFilterAttribute = element.attribute(ConfigConstant.FILTER_VALUE_ATTRIBUTE_NAME); - if (globalFilterAttribute != null) { - String globalFilterValue = globalFilterAttribute.getData().toString().trim(); - if (StringUtils.isNotEmpty(globalFilterValue)) { - Integer globalValue = null; - try { - globalValue = Integer.valueOf(globalFilterValue); - } catch (NumberFormatException e) { - throw new DiscoveryException("Attribute[" + ConfigConstant.FILTER_VALUE_ATTRIBUTE_NAME + "] value in element[" + element.getName() + "] is invalid, must be int type", e); - } - countFilterEntity.setFilterValue(globalValue); - } - } - - Map filterMap = countFilterEntity.getFilterMap(); - for (Iterator elementIterator = element.elementIterator(); elementIterator.hasNext();) { - Object childElementObject = elementIterator.next(); - if (childElementObject instanceof Element) { - Element childElement = (Element) childElementObject; - - if (StringUtils.equals(childElement.getName(), ConfigConstant.SERVICE_ELEMENT_NAME)) { - Attribute serviceNameAttribute = childElement.attribute(ConfigConstant.SERVICE_NAME_ATTRIBUTE_NAME); - if (serviceNameAttribute == null) { - throw new DiscoveryException("Attribute[" + ConfigConstant.SERVICE_NAME_ATTRIBUTE_NAME + "] in element[" + childElement.getName() + "] is missing"); - } - String serviceName = serviceNameAttribute.getData().toString().trim(); - - Integer value = null; - Attribute filterValueAttribute = childElement.attribute(ConfigConstant.FILTER_VALUE_ATTRIBUTE_NAME); - if (filterValueAttribute != null) { - String filterValue = filterValueAttribute.getData().toString().trim(); - if (StringUtils.isNotEmpty(filterValue)) { - try { - value = Integer.valueOf(filterValue); - } catch (NumberFormatException e) { - throw new DiscoveryException("Attribute[" + ConfigConstant.FILTER_VALUE_ATTRIBUTE_NAME + "] value in element[" + childElement.getName() + "] is invalid, must be int type", e); - } - } - } - - filterMap.put(serviceName, value); - } - } - } - - registerEntity.setCountFilterEntity(countFilterEntity); - } - - @SuppressWarnings("rawtypes") - private void parseVersionFilter(Element element, DiscoveryEntity discoveryEntity) { - VersionFilterEntity versionFilterEntity = discoveryEntity.getVersionFilterEntity(); - if (versionFilterEntity != null) { - throw new DiscoveryException("Allow only one element[" + ConfigConstant.VERSION_ELEMENT_NAME + "] to be configed"); - } - - versionFilterEntity = new VersionFilterEntity(); - - Map> versionEntityMap = versionFilterEntity.getVersionEntityMap(); - for (Iterator elementIterator = element.elementIterator(); elementIterator.hasNext();) { - Object childElementObject = elementIterator.next(); - if (childElementObject instanceof Element) { - Element childElement = (Element) childElementObject; - - if (StringUtils.equals(childElement.getName(), ConfigConstant.SERVICE_ELEMENT_NAME)) { - VersionEntity versionEntity = new VersionEntity(); - - Attribute consumerServiceNameAttribute = childElement.attribute(ConfigConstant.CONSUMER_SERVICE_NAME_ATTRIBUTE_NAME); - if (consumerServiceNameAttribute == null) { - throw new DiscoveryException("Attribute[" + ConfigConstant.CONSUMER_SERVICE_NAME_ATTRIBUTE_NAME + "] in element[" + childElement.getName() + "] is missing"); - } - String consumerServiceName = consumerServiceNameAttribute.getData().toString().trim(); - versionEntity.setConsumerServiceName(consumerServiceName); - - Attribute providerServiceNameAttribute = childElement.attribute(ConfigConstant.PROVIDER_SERVICE_NAME_ATTRIBUTE_NAME); - if (providerServiceNameAttribute == null) { - throw new DiscoveryException("Attribute[" + ConfigConstant.PROVIDER_SERVICE_NAME_ATTRIBUTE_NAME + "] in element[" + childElement.getName() + "] is missing"); - } - String providerServiceName = providerServiceNameAttribute.getData().toString().trim(); - versionEntity.setProviderServiceName(providerServiceName); - - Attribute consumerVersionValueAttribute = childElement.attribute(ConfigConstant.CONSUMER_VERSION_VALUE_ATTRIBUTE_NAME); - if (consumerVersionValueAttribute != null) { - String consumerVersionValue = consumerVersionValueAttribute.getData().toString().trim(); - List consumerVersionValueList = StringUtil.splitToList(consumerVersionValue, DiscoveryConstant.SEPARATE); - versionEntity.setConsumerVersionValueList(consumerVersionValueList); - } - - Attribute providerVersionValueAttribute = childElement.attribute(ConfigConstant.PROVIDER_VERSION_VALUE_ATTRIBUTE_NAME); - if (providerVersionValueAttribute != null) { - String providerVersionValue = providerVersionValueAttribute.getData().toString().trim(); - List providerVersionValueList = StringUtil.splitToList(providerVersionValue, DiscoveryConstant.SEPARATE); - versionEntity.setProviderVersionValueList(providerVersionValueList); - } - - List versionEntityList = versionEntityMap.get(consumerServiceName); - if (versionEntityList == null) { - versionEntityList = new ArrayList(); - versionEntityMap.put(consumerServiceName, versionEntityList); - } - - versionEntityList.add(versionEntity); - } - } - } - - discoveryEntity.setVersionFilterEntity(versionFilterEntity); - } - - @SuppressWarnings("rawtypes") - private void parseWeightFilter(Element element, DiscoveryEntity discoveryEntity) { - WeightFilterEntity weightFilterEntity = discoveryEntity.getWeightFilterEntity(); - if (weightFilterEntity != null) { - throw new DiscoveryException("Allow only one element[" + ConfigConstant.WEIGHT_ELEMENT_NAME + "] to be configed"); - } - - weightFilterEntity = new WeightFilterEntity(); - - Map> versionWeightEntityMap = new LinkedHashMap>(); - List versionWeightEntityList = new ArrayList(); - weightFilterEntity.setVersionWeightEntityMap(versionWeightEntityMap); - weightFilterEntity.setVersionWeightEntityList(versionWeightEntityList); - - Map> regionWeightEntityMap = new LinkedHashMap>(); - List regionWeightEntityList = new ArrayList(); - weightFilterEntity.setRegionWeightEntityMap(regionWeightEntityMap); - weightFilterEntity.setRegionWeightEntityList(regionWeightEntityList); - - for (Iterator elementIterator = element.elementIterator(); elementIterator.hasNext();) { - Object childElementObject = elementIterator.next(); - if (childElementObject instanceof Element) { - Element childElement = (Element) childElementObject; - - if (StringUtils.equals(childElement.getName(), ConfigConstant.SERVICE_ELEMENT_NAME)) { - WeightEntity weightEntity = new WeightEntity(); - - Attribute typeAttribute = childElement.attribute(ConfigConstant.TYPE_ATTRIBUTE_NAME); - if (typeAttribute == null) { - throw new DiscoveryException("Attribute[" + ConfigConstant.TYPE_ATTRIBUTE_NAME + "] in element[" + childElement.getName() + "] is missing"); - } - String type = typeAttribute.getData().toString().trim(); - WeightType weightType = WeightType.fromString(type); - weightEntity.setType(weightType); - - Attribute consumerServiceNameAttribute = childElement.attribute(ConfigConstant.CONSUMER_SERVICE_NAME_ATTRIBUTE_NAME); - String consumerServiceName = null; - if (consumerServiceNameAttribute != null) { - consumerServiceName = consumerServiceNameAttribute.getData().toString().trim(); - } - weightEntity.setConsumerServiceName(consumerServiceName); - - Attribute providerServiceNameAttribute = childElement.attribute(ConfigConstant.PROVIDER_SERVICE_NAME_ATTRIBUTE_NAME); - if (providerServiceNameAttribute == null) { - throw new DiscoveryException("Attribute[" + ConfigConstant.PROVIDER_SERVICE_NAME_ATTRIBUTE_NAME + "] in element[" + childElement.getName() + "] is missing"); - } - String providerServiceName = providerServiceNameAttribute.getData().toString().trim(); - weightEntity.setProviderServiceName(providerServiceName); - - Attribute providerWeightValueAttribute = childElement.attribute(ConfigConstant.PROVIDER_WEIGHT_VALUE_ATTRIBUTE_NAME); - if (providerWeightValueAttribute == null) { - throw new DiscoveryException("Attribute[" + ConfigConstant.PROVIDER_WEIGHT_VALUE_ATTRIBUTE_NAME + "] in element[" + childElement.getName() + "] is missing"); - } - String providerWeightValue = providerWeightValueAttribute.getData().toString().trim(); - - WeightEntityWrapper.parseWeightEntity(weightEntity, providerWeightValue); - - if (StringUtils.isNotEmpty(consumerServiceName)) { - if (weightType == WeightType.VERSION) { - List list = versionWeightEntityMap.get(consumerServiceName); - if (list == null) { - list = new ArrayList(); - versionWeightEntityMap.put(consumerServiceName, list); - } - - list.add(weightEntity); - } else if (weightType == WeightType.REGION) { - List list = regionWeightEntityMap.get(consumerServiceName); - if (list == null) { - list = new ArrayList(); - regionWeightEntityMap.put(consumerServiceName, list); - } - - list.add(weightEntity); - } - } else { - if (weightType == WeightType.VERSION) { - versionWeightEntityList.add(weightEntity); - } else if (weightType == WeightType.REGION) { - regionWeightEntityList.add(weightEntity); - } - } - } else if (StringUtils.equals(childElement.getName(), ConfigConstant.VERSION_ELEMENT_NAME)) { - VersionWeightEntity versionWeightEntity = weightFilterEntity.getVersionWeightEntity(); - if (versionWeightEntity != null) { - throw new DiscoveryException("Allow only one element[" + ConfigConstant.VERSION_ELEMENT_NAME + "] to be configed"); - } - - versionWeightEntity = new VersionWeightEntity(); - - Attribute providerWeightValueAttribute = childElement.attribute(ConfigConstant.PROVIDER_WEIGHT_VALUE_ATTRIBUTE_NAME); - if (providerWeightValueAttribute == null) { - throw new DiscoveryException("Attribute[" + ConfigConstant.PROVIDER_WEIGHT_VALUE_ATTRIBUTE_NAME + "] in element[" + childElement.getName() + "] is missing"); - } - String providerWeightValue = providerWeightValueAttribute.getData().toString().trim(); - - WeightEntityWrapper.parseWeightEntity(versionWeightEntity, providerWeightValue); - - weightFilterEntity.setVersionWeightEntity(versionWeightEntity); - } else if (StringUtils.equals(childElement.getName(), ConfigConstant.REGION_ELEMENT_NAME)) { - RegionWeightEntity regionWeightEntity = weightFilterEntity.getRegionWeightEntity(); - if (regionWeightEntity != null) { - throw new DiscoveryException("Allow only one element[" + ConfigConstant.REGION_ELEMENT_NAME + "] to be configed"); - } - - regionWeightEntity = new RegionWeightEntity(); - - Attribute providerWeightValueAttribute = childElement.attribute(ConfigConstant.PROVIDER_WEIGHT_VALUE_ATTRIBUTE_NAME); - if (providerWeightValueAttribute == null) { - throw new DiscoveryException("Attribute[" + ConfigConstant.PROVIDER_WEIGHT_VALUE_ATTRIBUTE_NAME + "] in element[" + childElement.getName() + "] is missing"); - } - String providerWeightValue = providerWeightValueAttribute.getData().toString().trim(); - - WeightEntityWrapper.parseWeightEntity(regionWeightEntity, providerWeightValue); - - weightFilterEntity.setRegionWeightEntity(regionWeightEntity); - } - } - } - - discoveryEntity.setWeightFilterEntity(weightFilterEntity); - } - - @SuppressWarnings("rawtypes") - private void parseStrategyCondition(Element element, List strategyConditionEntityList) { - for (Iterator elementIterator = element.elementIterator(); elementIterator.hasNext();) { - Object childElementObject = elementIterator.next(); - if (childElementObject instanceof Element) { - Element childElement = (Element) childElementObject; - - if (StringUtils.equals(childElement.getName(), ConfigConstant.CONDITION_ELEMENT_NAME)) { - StrategyConditionEntity strategyConditionEntity = new StrategyConditionEntity(); - - Attribute idAttribute = childElement.attribute(ConfigConstant.ID_ATTRIBUTE_NAME); - if (idAttribute == null) { - throw new DiscoveryException("Attribute[" + ConfigConstant.ID_ATTRIBUTE_NAME + "] in element[" + childElement.getName() + "] is missing"); - } - String id = idAttribute.getData().toString().trim(); - strategyConditionEntity.setId(id); - - Attribute headerAttribute = childElement.attribute(ConfigConstant.HEADER_ATTRIBUTE_NAME); - if (headerAttribute == null) { - throw new DiscoveryException("Attribute[" + ConfigConstant.HEADER_ATTRIBUTE_NAME + "] in element[" + childElement.getName() + "] is missing"); - } - String header = headerAttribute.getData().toString().trim(); - List headerList = StringUtil.splitToList(header, DiscoveryConstant.SEPARATE); - for (String value : headerList) { - String[] valueArray = StringUtils.split(value, DiscoveryConstant.EQUALS); - String headerName = valueArray[0].trim(); - String headerValue = valueArray[1].trim(); - - strategyConditionEntity.getHeaderMap().put(headerName, headerValue); - } - - Attribute versionIdAttribute = childElement.attribute(ConfigConstant.VERSION_ELEMENT_NAME + DiscoveryConstant.DASH + ConfigConstant.ID_ATTRIBUTE_NAME); - if (versionIdAttribute != null) { - String versionId = versionIdAttribute.getData().toString().trim(); - strategyConditionEntity.setVersionId(versionId); - } - - Attribute regionIdAttribute = childElement.attribute(ConfigConstant.REGION_ELEMENT_NAME + DiscoveryConstant.DASH + ConfigConstant.ID_ATTRIBUTE_NAME); - if (regionIdAttribute != null) { - String regionId = regionIdAttribute.getData().toString().trim(); - strategyConditionEntity.setRegionId(regionId); - } - - Attribute addressIdAttribute = childElement.attribute(ConfigConstant.ADDRESS_ELEMENT_NAME + DiscoveryConstant.DASH + ConfigConstant.ID_ATTRIBUTE_NAME); - if (addressIdAttribute != null) { - String addressId = addressIdAttribute.getData().toString().trim(); - strategyConditionEntity.setAddressId(addressId); - } - - Attribute versionWeightIdAttribute = childElement.attribute(ConfigConstant.VERSION_WEIGHT_ELEMENT_NAME + DiscoveryConstant.DASH + ConfigConstant.ID_ATTRIBUTE_NAME); - if (versionWeightIdAttribute != null) { - String versionWeightId = versionWeightIdAttribute.getData().toString().trim(); - strategyConditionEntity.setVersionWeightId(versionWeightId); - } - - Attribute regionWeightIdAttribute = childElement.attribute(ConfigConstant.REGION_WEIGHT_ELEMENT_NAME + DiscoveryConstant.DASH + ConfigConstant.ID_ATTRIBUTE_NAME); - if (regionWeightIdAttribute != null) { - String regionWeightId = regionWeightIdAttribute.getData().toString().trim(); - strategyConditionEntity.setRegionWeightId(regionWeightId); - } - - strategyConditionEntityList.add(strategyConditionEntity); - } - } - } - } - - @SuppressWarnings("rawtypes") - private void parseStrategyRoute(Element element, List strategyRouteEntityList) { - for (Iterator elementIterator = element.elementIterator(); elementIterator.hasNext();) { - Object childElementObject = elementIterator.next(); - if (childElementObject instanceof Element) { - Element childElement = (Element) childElementObject; - - if (StringUtils.equals(childElement.getName(), ConfigConstant.ROUTE_ELEMENT_NAME)) { - StrategyRouteEntity strategyRouteEntity = new StrategyRouteEntity(); - - Attribute idAttribute = childElement.attribute(ConfigConstant.ID_ATTRIBUTE_NAME); - if (idAttribute == null) { - throw new DiscoveryException("Attribute[" + ConfigConstant.ID_ATTRIBUTE_NAME + "] in element[" + childElement.getName() + "] is missing"); - } - String id = idAttribute.getData().toString().trim(); - strategyRouteEntity.setId(id); - - Attribute typeAttribute = childElement.attribute(ConfigConstant.TYPE_ATTRIBUTE_NAME); - if (typeAttribute == null) { - throw new DiscoveryException("Attribute[" + ConfigConstant.TYPE_ATTRIBUTE_NAME + "] in element[" + childElement.getName() + "] is missing"); - } - String type = typeAttribute.getData().toString().trim(); - StrategyType strategyType = StrategyType.fromString(type); - strategyRouteEntity.setType(strategyType); - - String value = childElement.getTextTrim(); - strategyRouteEntity.setValue(value); - - strategyRouteEntityList.add(strategyRouteEntity); - } - } - } - } -} \ No newline at end of file diff --git a/discovery-plugin-framework-consul/pom.xml b/discovery-plugin-framework-consul/pom.xml deleted file mode 100644 index 0383ea02b4..0000000000 --- a/discovery-plugin-framework-consul/pom.xml +++ /dev/null @@ -1,28 +0,0 @@ - - - discovery-plugin-framework-consul - Nepxion Discovery Plugin Framework Consul - jar - 4.0.0 - Nepxion Discovery is an enhancement for Spring Cloud Discovery - http://www.nepxion.com - - - com.nepxion - discovery - 5.2.0-SNAPSHOT - - - - - ${project.groupId} - discovery-plugin-framework - - - - org.springframework.cloud - spring-cloud-starter-consul-discovery - - - \ No newline at end of file diff --git a/discovery-plugin-framework-consul/src/main/java/com/nepxion/discovery/plugin/framework/adapter/ConsulAdapter.java b/discovery-plugin-framework-consul/src/main/java/com/nepxion/discovery/plugin/framework/adapter/ConsulAdapter.java deleted file mode 100644 index 2f5ed7ca2c..0000000000 --- a/discovery-plugin-framework-consul/src/main/java/com/nepxion/discovery/plugin/framework/adapter/ConsulAdapter.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.nepxion.discovery.plugin.framework.adapter; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import java.util.Map; - -import org.springframework.cloud.consul.discovery.ConsulServer; - -import com.nepxion.discovery.common.exception.DiscoveryException; -import com.netflix.loadbalancer.Server; - -public class ConsulAdapter extends AbstractPluginAdapter { - @Override - public Map getServerMetadata(Server server) { - if (server instanceof ConsulServer) { - ConsulServer consulServer = (ConsulServer) server; - - return consulServer.getMetadata(); - } - - throw new DiscoveryException("Server instance isn't the type of ConsulServer"); - } -} \ No newline at end of file diff --git a/discovery-plugin-framework-consul/src/main/java/com/nepxion/discovery/plugin/framework/configuration/ConsulAutoConfiguration.java b/discovery-plugin-framework-consul/src/main/java/com/nepxion/discovery/plugin/framework/configuration/ConsulAutoConfiguration.java deleted file mode 100644 index aa3674d4fa..0000000000 --- a/discovery-plugin-framework-consul/src/main/java/com/nepxion/discovery/plugin/framework/configuration/ConsulAutoConfiguration.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.nepxion.discovery.plugin.framework.configuration; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import org.springframework.cloud.netflix.ribbon.RibbonClients; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -import com.nepxion.banner.BannerConstant; -import com.nepxion.banner.Description; -import com.nepxion.banner.LogoBanner; -import com.nepxion.banner.NepxionBanner; -import com.nepxion.discovery.plugin.framework.adapter.ConsulAdapter; -import com.nepxion.discovery.plugin.framework.adapter.PluginAdapter; -import com.nepxion.discovery.plugin.framework.constant.ConsulConstant; -import com.taobao.text.Color; - -@Configuration -@RibbonClients(defaultConfiguration = { PluginLoadBalanceConfiguration.class, ConsulLoadBalanceConfiguration.class }) -public class ConsulAutoConfiguration { - static { - /*String bannerShown = System.getProperty(BannerConstant.BANNER_SHOWN, "true"); - if (Boolean.valueOf(bannerShown)) { - System.out.println(""); - System.out.println("╔═══╗ ╔╗"); - System.out.println("║╔═╗║ ║║"); - System.out.println("║║ ╚╬══╦═╗╔══╦╗╔╣║"); - System.out.println("║║ ╔╣╔╗║╔╗╣══╣║║║║"); - System.out.println("║╚═╝║╚╝║║║╠══║╚╝║╚╗"); - System.out.println("╚═══╩══╩╝╚╩══╩══╩═╝"); - System.out.println(ConsulConstant.DISCOVERY_PLUGIN + " Discovery"); - System.out.println(""); - }*/ - - LogoBanner logoBanner = new LogoBanner(ConsulAutoConfiguration.class, "/com/nepxion/consul/resource/logo.txt", "Welcome to Nepxion", 6, 5, new Color[] { Color.red, Color.green, Color.cyan, Color.blue, Color.yellow, Color.magenta }, true); - - NepxionBanner.show(logoBanner, new Description("Discovery:", ConsulConstant.DISCOVERY_PLUGIN, 0, 1), new Description(BannerConstant.GITHUB + ":", BannerConstant.NEPXION_GITHUB + "/Discovery", 0, 1)); - } - - @Bean - public PluginAdapter pluginAdapter() { - return new ConsulAdapter(); - } -} \ No newline at end of file diff --git a/discovery-plugin-framework-consul/src/main/java/com/nepxion/discovery/plugin/framework/constant/ConsulConstant.java b/discovery-plugin-framework-consul/src/main/java/com/nepxion/discovery/plugin/framework/constant/ConsulConstant.java deleted file mode 100644 index 3319330006..0000000000 --- a/discovery-plugin-framework-consul/src/main/java/com/nepxion/discovery/plugin/framework/constant/ConsulConstant.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.nepxion.discovery.plugin.framework.constant; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -public class ConsulConstant { - public static final String DISCOVERY_PLUGIN = "Consul"; -} \ No newline at end of file diff --git a/discovery-plugin-framework-consul/src/main/java/com/nepxion/discovery/plugin/framework/context/ConsulApplicationContextInitializer.java b/discovery-plugin-framework-consul/src/main/java/com/nepxion/discovery/plugin/framework/context/ConsulApplicationContextInitializer.java deleted file mode 100644 index 0e1d92aabf..0000000000 --- a/discovery-plugin-framework-consul/src/main/java/com/nepxion/discovery/plugin/framework/context/ConsulApplicationContextInitializer.java +++ /dev/null @@ -1,56 +0,0 @@ -package com.nepxion.discovery.plugin.framework.context; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import java.util.List; - -import org.springframework.beans.BeansException; -import org.springframework.cloud.consul.discovery.ConsulDiscoveryProperties; -import org.springframework.cloud.consul.serviceregistry.ConsulServiceRegistry; -import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.core.env.ConfigurableEnvironment; - -import com.nepxion.discovery.common.constant.DiscoveryConstant; -import com.nepxion.discovery.plugin.framework.constant.ConsulConstant; -import com.nepxion.discovery.plugin.framework.decorator.ConsulServiceRegistryDecorator; -import com.nepxion.discovery.plugin.framework.util.MetadataUtil; - -public class ConsulApplicationContextInitializer extends PluginApplicationContextInitializer { - @Override - protected Object afterInitialization(ConfigurableApplicationContext applicationContext, Object bean, String beanName) throws BeansException { - if (bean instanceof ConsulServiceRegistry) { - ConsulServiceRegistry consulServiceRegistry = (ConsulServiceRegistry) bean; - - return new ConsulServiceRegistryDecorator(consulServiceRegistry, applicationContext); - } else if (bean instanceof ConsulDiscoveryProperties) { - ConfigurableEnvironment environment = applicationContext.getEnvironment(); - - ConsulDiscoveryProperties consulDiscoveryProperties = (ConsulDiscoveryProperties) bean; - consulDiscoveryProperties.setPreferIpAddress(true); - - List tags = consulDiscoveryProperties.getTags(); - tags.add(DiscoveryConstant.SPRING_APPLICATION_NAME + "=" + PluginContextAware.getApplicationName(environment)); - tags.add(DiscoveryConstant.SPRING_APPLICATION_TYPE + "=" + PluginContextAware.getApplicationType(environment)); - tags.add(DiscoveryConstant.SPRING_APPLICATION_DISCOVERY_PLUGIN + "=" + ConsulConstant.DISCOVERY_PLUGIN); - tags.add(DiscoveryConstant.SPRING_APPLICATION_DISCOVERY_VERSION + "=" + DiscoveryConstant.DISCOVERY_VERSION); - tags.add(DiscoveryConstant.SPRING_APPLICATION_REGISTER_CONTROL_ENABLED + "=" + PluginContextAware.isRegisterControlEnabled(environment)); - tags.add(DiscoveryConstant.SPRING_APPLICATION_DISCOVERY_CONTROL_ENABLED + "=" + PluginContextAware.isDiscoveryControlEnabled(environment)); - tags.add(DiscoveryConstant.SPRING_APPLICATION_CONFIG_REST_CONTROL_ENABLED + "=" + PluginContextAware.isConfigRestControlEnabled(environment)); - tags.add(DiscoveryConstant.SPRING_APPLICATION_GROUP_KEY + "=" + PluginContextAware.getGroupKey(environment)); - tags.add(DiscoveryConstant.SPRING_APPLICATION_CONTEXT_PATH + "=" + PluginContextAware.getContextPath(environment)); - - MetadataUtil.filter(tags); - - return bean; - } else { - return bean; - } - } -} \ No newline at end of file diff --git a/discovery-plugin-framework-consul/src/main/java/com/nepxion/discovery/plugin/framework/decorator/ConsulServerListDecorator.java b/discovery-plugin-framework-consul/src/main/java/com/nepxion/discovery/plugin/framework/decorator/ConsulServerListDecorator.java deleted file mode 100644 index b4e036bb3f..0000000000 --- a/discovery-plugin-framework-consul/src/main/java/com/nepxion/discovery/plugin/framework/decorator/ConsulServerListDecorator.java +++ /dev/null @@ -1,65 +0,0 @@ -package com.nepxion.discovery.plugin.framework.decorator; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import java.util.List; - -import org.springframework.cloud.consul.discovery.ConsulDiscoveryProperties; -import org.springframework.cloud.consul.discovery.ConsulServer; -import org.springframework.cloud.consul.discovery.ConsulServerList; -import org.springframework.core.env.ConfigurableEnvironment; - -import com.ecwid.consul.v1.ConsulClient; -import com.nepxion.discovery.plugin.framework.context.PluginContextAware; -import com.nepxion.discovery.plugin.framework.listener.loadbalance.LoadBalanceListenerExecutor; - -public class ConsulServerListDecorator extends ConsulServerList { - private ConfigurableEnvironment environment; - - private LoadBalanceListenerExecutor loadBalanceListenerExecutor; - - public ConsulServerListDecorator(ConsulClient client, ConsulDiscoveryProperties properties) { - super(client, properties); - } - - @Override - public List getInitialListOfServers() { - List servers = super.getInitialListOfServers(); - - filter(servers); - - return servers; - } - - @Override - public List getUpdatedListOfServers() { - List servers = super.getUpdatedListOfServers(); - - filter(servers); - - return servers; - } - - private void filter(List servers) { - Boolean discoveryControlEnabled = PluginContextAware.isDiscoveryControlEnabled(environment); - if (discoveryControlEnabled) { - String serviceId = getServiceId(); - loadBalanceListenerExecutor.onGetServers(serviceId, servers); - } - } - - public void setEnvironment(ConfigurableEnvironment environment) { - this.environment = environment; - } - - public void setLoadBalanceListenerExecutor(LoadBalanceListenerExecutor loadBalanceListenerExecutor) { - this.loadBalanceListenerExecutor = loadBalanceListenerExecutor; - } -} \ No newline at end of file diff --git a/discovery-plugin-framework-consul/src/main/java/com/nepxion/discovery/plugin/framework/decorator/ConsulServiceRegistryDecorator.java b/discovery-plugin-framework-consul/src/main/java/com/nepxion/discovery/plugin/framework/decorator/ConsulServiceRegistryDecorator.java deleted file mode 100644 index 87e396f516..0000000000 --- a/discovery-plugin-framework-consul/src/main/java/com/nepxion/discovery/plugin/framework/decorator/ConsulServiceRegistryDecorator.java +++ /dev/null @@ -1,104 +0,0 @@ -package com.nepxion.discovery.plugin.framework.decorator; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import org.springframework.beans.BeansException; -import org.springframework.cloud.consul.serviceregistry.ConsulRegistration; -import org.springframework.cloud.consul.serviceregistry.ConsulServiceRegistry; -import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.core.env.ConfigurableEnvironment; - -import com.nepxion.discovery.plugin.framework.context.PluginContextAware; -import com.nepxion.discovery.plugin.framework.listener.register.RegisterListenerExecutor; - -public class ConsulServiceRegistryDecorator extends ConsulServiceRegistry { - // private static final Logger LOG = LoggerFactory.getLogger(ConsulServiceRegistryDecorator.class); - - private ConsulServiceRegistry serviceRegistry; - private ConfigurableApplicationContext applicationContext; - private ConfigurableEnvironment environment; - - public ConsulServiceRegistryDecorator(ConsulServiceRegistry serviceRegistry, ConfigurableApplicationContext applicationContext) { - super(null, null, null, null); - - this.serviceRegistry = serviceRegistry; - this.applicationContext = applicationContext; - this.environment = applicationContext.getEnvironment(); - } - - @Override - public void register(ConsulRegistration registration) { - Boolean registerControlEnabled = PluginContextAware.isRegisterControlEnabled(environment); - if (registerControlEnabled) { - try { - RegisterListenerExecutor registerListenerExecutor = applicationContext.getBean(RegisterListenerExecutor.class); - registerListenerExecutor.onRegister(registration); - } catch (BeansException e) { - // LOG.warn("Get bean for RegisterListenerExecutor failed, ignore to executor listener"); - } - } - - serviceRegistry.register(registration); - } - - @Override - public void deregister(ConsulRegistration registration) { - Boolean registerControlEnabled = PluginContextAware.isRegisterControlEnabled(environment); - if (registerControlEnabled) { - try { - RegisterListenerExecutor registerListenerExecutor = applicationContext.getBean(RegisterListenerExecutor.class); - registerListenerExecutor.onDeregister(registration); - } catch (BeansException e) { - // LOG.warn("Get bean for RegisterListenerExecutor failed, ignore to executor listener"); - } - } - - serviceRegistry.deregister(registration); - } - - @Override - public void setStatus(ConsulRegistration registration, String status) { - Boolean registerControlEnabled = PluginContextAware.isRegisterControlEnabled(environment); - if (registerControlEnabled) { - try { - RegisterListenerExecutor registerListenerExecutor = applicationContext.getBean(RegisterListenerExecutor.class); - registerListenerExecutor.onSetStatus(registration, status); - } catch (BeansException e) { - // LOG.warn("Get bean for RegisterListenerExecutor failed, ignore to executor listener"); - } - } - - serviceRegistry.setStatus(registration, status); - } - - @Override - public Object getStatus(ConsulRegistration registration) { - return serviceRegistry.getStatus(registration); - } - - @Override - public void close() { - Boolean registerControlEnabled = PluginContextAware.isRegisterControlEnabled(environment); - if (registerControlEnabled) { - try { - RegisterListenerExecutor registerListenerExecutor = applicationContext.getBean(RegisterListenerExecutor.class); - registerListenerExecutor.onClose(); - } catch (BeansException e) { - // LOG.warn("Get bean for RegisterListenerExecutor failed, ignore to executor listener"); - } - } - - serviceRegistry.close(); - } - - public ConfigurableEnvironment getEnvironment() { - return environment; - } -} \ No newline at end of file diff --git a/discovery-plugin-framework-eureka/pom.xml b/discovery-plugin-framework-eureka/pom.xml deleted file mode 100644 index 86ef12f5df..0000000000 --- a/discovery-plugin-framework-eureka/pom.xml +++ /dev/null @@ -1,35 +0,0 @@ - - - discovery-plugin-framework-eureka - Nepxion Discovery Plugin Framework Eureka - jar - 4.0.0 - Nepxion Discovery is an enhancement for Spring Cloud Discovery - http://www.nepxion.com - - - com.nepxion - discovery - 5.2.0-SNAPSHOT - - - - - ${project.groupId} - discovery-plugin-framework - - - - org.springframework.cloud - spring-cloud-starter-netflix-eureka-client - - - - javax.inject - javax.inject - 1 - provided - - - \ No newline at end of file diff --git a/discovery-plugin-framework-eureka/src/main/java/com/nepxion/discovery/plugin/framework/adapter/EurekaAdapter.java b/discovery-plugin-framework-eureka/src/main/java/com/nepxion/discovery/plugin/framework/adapter/EurekaAdapter.java deleted file mode 100644 index 5f2f55ddcb..0000000000 --- a/discovery-plugin-framework-eureka/src/main/java/com/nepxion/discovery/plugin/framework/adapter/EurekaAdapter.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.nepxion.discovery.plugin.framework.adapter; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import java.util.Map; - -import com.nepxion.discovery.common.exception.DiscoveryException; -import com.netflix.loadbalancer.Server; -import com.netflix.niws.loadbalancer.DiscoveryEnabledServer; - -public class EurekaAdapter extends AbstractPluginAdapter { - @Override - public Map getServerMetadata(Server server) { - if (server instanceof DiscoveryEnabledServer) { - DiscoveryEnabledServer discoveryEnabledServer = (DiscoveryEnabledServer) server; - - return discoveryEnabledServer.getInstanceInfo().getMetadata(); - } - - throw new DiscoveryException("Server instance isn't the type of DiscoveryEnabledServer"); - } -} \ No newline at end of file diff --git a/discovery-plugin-framework-eureka/src/main/java/com/nepxion/discovery/plugin/framework/constant/EurekaConstant.java b/discovery-plugin-framework-eureka/src/main/java/com/nepxion/discovery/plugin/framework/constant/EurekaConstant.java deleted file mode 100644 index bbc7910a6f..0000000000 --- a/discovery-plugin-framework-eureka/src/main/java/com/nepxion/discovery/plugin/framework/constant/EurekaConstant.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.nepxion.discovery.plugin.framework.constant; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -public class EurekaConstant { - public static final String DISCOVERY_PLUGIN = "Eureka"; -} \ No newline at end of file diff --git a/discovery-plugin-framework-eureka/src/main/java/com/nepxion/discovery/plugin/framework/context/EurekaApplicationContextInitializer.java b/discovery-plugin-framework-eureka/src/main/java/com/nepxion/discovery/plugin/framework/context/EurekaApplicationContextInitializer.java deleted file mode 100644 index 8fb8cbbe18..0000000000 --- a/discovery-plugin-framework-eureka/src/main/java/com/nepxion/discovery/plugin/framework/context/EurekaApplicationContextInitializer.java +++ /dev/null @@ -1,56 +0,0 @@ -package com.nepxion.discovery.plugin.framework.context; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import java.util.Map; - -import org.springframework.beans.BeansException; -import org.springframework.cloud.netflix.eureka.EurekaInstanceConfigBean; -import org.springframework.cloud.netflix.eureka.serviceregistry.EurekaServiceRegistry; -import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.core.env.ConfigurableEnvironment; - -import com.nepxion.discovery.common.constant.DiscoveryConstant; -import com.nepxion.discovery.plugin.framework.constant.EurekaConstant; -import com.nepxion.discovery.plugin.framework.decorator.EurekaServiceRegistryDecorator; -import com.nepxion.discovery.plugin.framework.util.MetadataUtil; - -public class EurekaApplicationContextInitializer extends PluginApplicationContextInitializer { - @Override - protected Object afterInitialization(ConfigurableApplicationContext applicationContext, Object bean, String beanName) throws BeansException { - if (bean instanceof EurekaServiceRegistry) { - EurekaServiceRegistry eurekaServiceRegistry = (EurekaServiceRegistry) bean; - - return new EurekaServiceRegistryDecorator(eurekaServiceRegistry, applicationContext); - } else if (bean instanceof EurekaInstanceConfigBean) { - ConfigurableEnvironment environment = applicationContext.getEnvironment(); - - EurekaInstanceConfigBean eurekaInstanceConfig = (EurekaInstanceConfigBean) bean; - eurekaInstanceConfig.setPreferIpAddress(true); - - Map metadataMap = eurekaInstanceConfig.getMetadataMap(); - metadataMap.put(DiscoveryConstant.SPRING_APPLICATION_NAME, PluginContextAware.getApplicationName(environment)); - metadataMap.put(DiscoveryConstant.SPRING_APPLICATION_TYPE, PluginContextAware.getApplicationType(environment)); - metadataMap.put(DiscoveryConstant.SPRING_APPLICATION_DISCOVERY_PLUGIN, EurekaConstant.DISCOVERY_PLUGIN); - metadataMap.put(DiscoveryConstant.SPRING_APPLICATION_DISCOVERY_VERSION, DiscoveryConstant.DISCOVERY_VERSION); - metadataMap.put(DiscoveryConstant.SPRING_APPLICATION_REGISTER_CONTROL_ENABLED, PluginContextAware.isRegisterControlEnabled(environment).toString()); - metadataMap.put(DiscoveryConstant.SPRING_APPLICATION_DISCOVERY_CONTROL_ENABLED, PluginContextAware.isDiscoveryControlEnabled(environment).toString()); - metadataMap.put(DiscoveryConstant.SPRING_APPLICATION_CONFIG_REST_CONTROL_ENABLED, PluginContextAware.isConfigRestControlEnabled(environment).toString()); - metadataMap.put(DiscoveryConstant.SPRING_APPLICATION_GROUP_KEY, PluginContextAware.getGroupKey(environment)); - metadataMap.put(DiscoveryConstant.SPRING_APPLICATION_CONTEXT_PATH, PluginContextAware.getContextPath(environment)); - - MetadataUtil.filter(metadataMap); - - return bean; - } else { - return bean; - } - } -} \ No newline at end of file diff --git a/discovery-plugin-framework-eureka/src/main/java/com/nepxion/discovery/plugin/framework/decorator/EurekaServerListDecorator.java b/discovery-plugin-framework-eureka/src/main/java/com/nepxion/discovery/plugin/framework/decorator/EurekaServerListDecorator.java deleted file mode 100644 index bb2bf8033b..0000000000 --- a/discovery-plugin-framework-eureka/src/main/java/com/nepxion/discovery/plugin/framework/decorator/EurekaServerListDecorator.java +++ /dev/null @@ -1,70 +0,0 @@ -package com.nepxion.discovery.plugin.framework.decorator; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import java.util.List; - -import org.springframework.cloud.netflix.ribbon.eureka.DomainExtractingServerList; -import org.springframework.core.env.ConfigurableEnvironment; - -import com.nepxion.discovery.plugin.framework.context.PluginContextAware; -import com.nepxion.discovery.plugin.framework.listener.loadbalance.LoadBalanceListenerExecutor; -import com.netflix.client.config.IClientConfig; -import com.netflix.loadbalancer.ServerList; -import com.netflix.niws.loadbalancer.DiscoveryEnabledServer; - -public class EurekaServerListDecorator extends DomainExtractingServerList { - private ConfigurableEnvironment environment; - - private LoadBalanceListenerExecutor loadBalanceListenerExecutor; - - private String serviceId; - - public EurekaServerListDecorator(ServerList list, IClientConfig clientConfig, boolean approximateZoneFromHostname) { - super(list, clientConfig, approximateZoneFromHostname); - } - - @Override - public List getInitialListOfServers() { - List servers = super.getInitialListOfServers(); - - filter(servers); - - return servers; - } - - @Override - public List getUpdatedListOfServers() { - List servers = super.getUpdatedListOfServers(); - - filter(servers); - - return servers; - } - - private void filter(List servers) { - Boolean discoveryControlEnabled = PluginContextAware.isDiscoveryControlEnabled(environment); - if (discoveryControlEnabled) { - loadBalanceListenerExecutor.onGetServers(serviceId, servers); - } - } - - public void setEnvironment(ConfigurableEnvironment environment) { - this.environment = environment; - } - - public void setLoadBalanceListenerExecutor(LoadBalanceListenerExecutor loadBalanceListenerExecutor) { - this.loadBalanceListenerExecutor = loadBalanceListenerExecutor; - } - - public void setServiceId(String serviceId) { - this.serviceId = serviceId; - } -} \ No newline at end of file diff --git a/discovery-plugin-framework-eureka/src/main/java/com/nepxion/discovery/plugin/framework/decorator/EurekaServiceRegistryDecorator.java b/discovery-plugin-framework-eureka/src/main/java/com/nepxion/discovery/plugin/framework/decorator/EurekaServiceRegistryDecorator.java deleted file mode 100644 index 46c6919222..0000000000 --- a/discovery-plugin-framework-eureka/src/main/java/com/nepxion/discovery/plugin/framework/decorator/EurekaServiceRegistryDecorator.java +++ /dev/null @@ -1,102 +0,0 @@ -package com.nepxion.discovery.plugin.framework.decorator; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import org.springframework.beans.BeansException; -import org.springframework.cloud.netflix.eureka.serviceregistry.EurekaRegistration; -import org.springframework.cloud.netflix.eureka.serviceregistry.EurekaServiceRegistry; -import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.core.env.ConfigurableEnvironment; - -import com.nepxion.discovery.plugin.framework.context.PluginContextAware; -import com.nepxion.discovery.plugin.framework.listener.register.RegisterListenerExecutor; - -public class EurekaServiceRegistryDecorator extends EurekaServiceRegistry { - // private static final Logger LOG = LoggerFactory.getLogger(EurekaServiceRegistryDecorator.class); - - private EurekaServiceRegistry serviceRegistry; - private ConfigurableApplicationContext applicationContext; - private ConfigurableEnvironment environment; - - public EurekaServiceRegistryDecorator(EurekaServiceRegistry serviceRegistry, ConfigurableApplicationContext applicationContext) { - this.serviceRegistry = serviceRegistry; - this.applicationContext = applicationContext; - this.environment = applicationContext.getEnvironment(); - } - - @Override - public void register(EurekaRegistration registration) { - Boolean registerControlEnabled = PluginContextAware.isRegisterControlEnabled(environment); - if (registerControlEnabled) { - try { - RegisterListenerExecutor registerListenerExecutor = applicationContext.getBean(RegisterListenerExecutor.class); - registerListenerExecutor.onRegister(registration); - } catch (BeansException e) { - // LOG.warn("Get bean for RegisterListenerExecutor failed, ignore to executor listener"); - } - } - - serviceRegistry.register(registration); - } - - @Override - public void deregister(EurekaRegistration registration) { - Boolean registerControlEnabled = PluginContextAware.isRegisterControlEnabled(environment); - if (registerControlEnabled) { - try { - RegisterListenerExecutor registerListenerExecutor = applicationContext.getBean(RegisterListenerExecutor.class); - registerListenerExecutor.onDeregister(registration); - } catch (BeansException e) { - // LOG.warn("Get bean for RegisterListenerExecutor failed, ignore to executor listener"); - } - } - - serviceRegistry.deregister(registration); - } - - @Override - public void setStatus(EurekaRegistration registration, String status) { - Boolean registerControlEnabled = PluginContextAware.isRegisterControlEnabled(environment); - if (registerControlEnabled) { - try { - RegisterListenerExecutor registerListenerExecutor = applicationContext.getBean(RegisterListenerExecutor.class); - registerListenerExecutor.onSetStatus(registration, status); - } catch (BeansException e) { - // LOG.warn("Get bean for RegisterListenerExecutor failed, ignore to executor listener"); - } - } - - serviceRegistry.setStatus(registration, status); - } - - @Override - public Object getStatus(EurekaRegistration registration) { - return serviceRegistry.getStatus(registration); - } - - @Override - public void close() { - Boolean registerControlEnabled = PluginContextAware.isRegisterControlEnabled(environment); - if (registerControlEnabled) { - try { - RegisterListenerExecutor registerListenerExecutor = applicationContext.getBean(RegisterListenerExecutor.class); - registerListenerExecutor.onClose(); - } catch (BeansException e) { - // LOG.warn("Get bean for RegisterListenerExecutor failed, ignore to executor listener"); - } - } - - serviceRegistry.close(); - } - - public ConfigurableEnvironment getEnvironment() { - return environment; - } -} \ No newline at end of file diff --git a/discovery-plugin-framework-nacos/pom.xml b/discovery-plugin-framework-nacos/pom.xml deleted file mode 100644 index 0929428ef5..0000000000 --- a/discovery-plugin-framework-nacos/pom.xml +++ /dev/null @@ -1,28 +0,0 @@ - - - discovery-plugin-framework-nacos - Nepxion Discovery Plugin Framework Nacos - jar - 4.0.0 - Nepxion Discovery is an enhancement for Spring Cloud Discovery - http://www.nepxion.com - - - com.nepxion - discovery - 5.2.0-SNAPSHOT - - - - - ${project.groupId} - discovery-plugin-framework - - - - org.springframework.cloud - spring-cloud-starter-alibaba-nacos-discovery - - - \ No newline at end of file diff --git a/discovery-plugin-framework-nacos/src/main/java/com/nepxion/discovery/plugin/framework/adapter/NacosAdapter.java b/discovery-plugin-framework-nacos/src/main/java/com/nepxion/discovery/plugin/framework/adapter/NacosAdapter.java deleted file mode 100644 index 50447d1b79..0000000000 --- a/discovery-plugin-framework-nacos/src/main/java/com/nepxion/discovery/plugin/framework/adapter/NacosAdapter.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.nepxion.discovery.plugin.framework.adapter; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import java.util.Map; - -import org.springframework.cloud.alibaba.nacos.ribbon.NacosServer; - -import com.nepxion.discovery.common.exception.DiscoveryException; -import com.netflix.loadbalancer.Server; - -public class NacosAdapter extends AbstractPluginAdapter { - @Override - public Map getServerMetadata(Server server) { - if (server instanceof NacosServer) { - NacosServer nacosServer = (NacosServer) server; - - return nacosServer.getMetadata(); - } - - throw new DiscoveryException("Server instance isn't the type of NacosServer"); - } -} \ No newline at end of file diff --git a/discovery-plugin-framework-nacos/src/main/java/com/nepxion/discovery/plugin/framework/configuration/NacosAutoConfiguration.java b/discovery-plugin-framework-nacos/src/main/java/com/nepxion/discovery/plugin/framework/configuration/NacosAutoConfiguration.java deleted file mode 100644 index e7b7969a1d..0000000000 --- a/discovery-plugin-framework-nacos/src/main/java/com/nepxion/discovery/plugin/framework/configuration/NacosAutoConfiguration.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.nepxion.discovery.plugin.framework.configuration; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import org.springframework.cloud.netflix.ribbon.RibbonClients; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -import com.nepxion.banner.BannerConstant; -import com.nepxion.banner.Description; -import com.nepxion.banner.LogoBanner; -import com.nepxion.banner.NepxionBanner; -import com.nepxion.discovery.plugin.framework.adapter.NacosAdapter; -import com.nepxion.discovery.plugin.framework.adapter.PluginAdapter; -import com.nepxion.discovery.plugin.framework.constant.NacosConstant; -import com.taobao.text.Color; - -@Configuration -@RibbonClients(defaultConfiguration = { PluginLoadBalanceConfiguration.class, NacosLoadBalanceConfiguration.class }) -public class NacosAutoConfiguration { - static { - /*String bannerShown = System.getProperty(BannerConstant.BANNER_SHOWN, "true"); - if (Boolean.valueOf(bannerShown)) { - System.out.println(""); - System.out.println("╔═╗ ╔╗"); - System.out.println("║║╚╗║║"); - System.out.println("║╔╗╚╝╠══╦══╦══╦══╗"); - System.out.println("║║╚╗║║╔╗║╔═╣╔╗║══╣"); - System.out.println("║║ ║║║╔╗║╚═╣╚╝╠══║"); - System.out.println("╚╝ ╚═╩╝╚╩══╩══╩══╝"); - System.out.println(NacosConstant.DISCOVERY_PLUGIN + " Discovery"); - System.out.println(""); - }*/ - - LogoBanner logoBanner = new LogoBanner(NacosAutoConfiguration.class, "/com/nepxion/nacos/resource/logo.txt", "Welcome to Nepxion", 5, 5, new Color[] { Color.red, Color.green, Color.cyan, Color.blue, Color.yellow }, true); - - NepxionBanner.show(logoBanner, new Description("Discovery:", NacosConstant.DISCOVERY_PLUGIN, 0, 1), new Description(BannerConstant.GITHUB + ":", BannerConstant.NEPXION_GITHUB + "/Discovery", 0, 1)); - } - - @Bean - public PluginAdapter pluginAdapter() { - return new NacosAdapter(); - } -} \ No newline at end of file diff --git a/discovery-plugin-framework-nacos/src/main/java/com/nepxion/discovery/plugin/framework/configuration/NacosLoadBalanceConfiguration.java b/discovery-plugin-framework-nacos/src/main/java/com/nepxion/discovery/plugin/framework/configuration/NacosLoadBalanceConfiguration.java deleted file mode 100644 index 0d4f4afc36..0000000000 --- a/discovery-plugin-framework-nacos/src/main/java/com/nepxion/discovery/plugin/framework/configuration/NacosLoadBalanceConfiguration.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.nepxion.discovery.plugin.framework.configuration; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.AutoConfigureAfter; -import org.springframework.cloud.alibaba.nacos.NacosDiscoveryProperties; -import org.springframework.cloud.alibaba.nacos.ribbon.NacosRibbonClientConfiguration; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.core.env.ConfigurableEnvironment; - -import com.nepxion.discovery.plugin.framework.decorator.NacosServerListDecorator; -import com.nepxion.discovery.plugin.framework.listener.loadbalance.LoadBalanceListenerExecutor; -import com.netflix.client.config.IClientConfig; -import com.netflix.loadbalancer.ServerList; - -@Configuration -@AutoConfigureAfter(NacosRibbonClientConfiguration.class) -public class NacosLoadBalanceConfiguration { - - @Autowired - private ConfigurableEnvironment environment; - - @Autowired - private LoadBalanceListenerExecutor loadBalanceListenerExecutor; - - @Bean - public ServerList ribbonServerList(IClientConfig config, NacosDiscoveryProperties nacosDiscoveryProperties) { - NacosServerListDecorator serverList = new NacosServerListDecorator(nacosDiscoveryProperties); - serverList.initWithNiwsConfig(config); - serverList.setEnvironment(environment); - serverList.setLoadBalanceListenerExecutor(loadBalanceListenerExecutor); - - return serverList; - } -} \ No newline at end of file diff --git a/discovery-plugin-framework-nacos/src/main/java/com/nepxion/discovery/plugin/framework/constant/NacosConstant.java b/discovery-plugin-framework-nacos/src/main/java/com/nepxion/discovery/plugin/framework/constant/NacosConstant.java deleted file mode 100644 index 69e204ae90..0000000000 --- a/discovery-plugin-framework-nacos/src/main/java/com/nepxion/discovery/plugin/framework/constant/NacosConstant.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.nepxion.discovery.plugin.framework.constant; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -public class NacosConstant { - public static final String DISCOVERY_PLUGIN = "Nacos"; -} \ No newline at end of file diff --git a/discovery-plugin-framework-nacos/src/main/java/com/nepxion/discovery/plugin/framework/context/NacosApplicationContextInitializer.java b/discovery-plugin-framework-nacos/src/main/java/com/nepxion/discovery/plugin/framework/context/NacosApplicationContextInitializer.java deleted file mode 100644 index a203fcd0ec..0000000000 --- a/discovery-plugin-framework-nacos/src/main/java/com/nepxion/discovery/plugin/framework/context/NacosApplicationContextInitializer.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.nepxion.discovery.plugin.framework.context; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import java.util.Map; - -import org.springframework.beans.BeansException; -import org.springframework.cloud.alibaba.nacos.NacosDiscoveryProperties; -import org.springframework.cloud.alibaba.nacos.registry.NacosServiceRegistry; -import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.core.env.ConfigurableEnvironment; - -import com.nepxion.discovery.common.constant.DiscoveryConstant; -import com.nepxion.discovery.plugin.framework.constant.NacosConstant; -import com.nepxion.discovery.plugin.framework.decorator.NacosServiceRegistryDecorator; -import com.nepxion.discovery.plugin.framework.util.MetadataUtil; - -public class NacosApplicationContextInitializer extends PluginApplicationContextInitializer { - @Override - protected Object afterInitialization(ConfigurableApplicationContext applicationContext, Object bean, String beanName) throws BeansException { - if (bean instanceof NacosServiceRegistry) { - NacosServiceRegistry nacosServiceRegistry = (NacosServiceRegistry) bean; - - NacosDiscoveryProperties nacosDiscoveryProperties = applicationContext.getBean(NacosDiscoveryProperties.class); - - return new NacosServiceRegistryDecorator(nacosDiscoveryProperties, nacosServiceRegistry, applicationContext); - } else if (bean instanceof NacosDiscoveryProperties) { - ConfigurableEnvironment environment = applicationContext.getEnvironment(); - - NacosDiscoveryProperties nacosDiscoveryProperties = (NacosDiscoveryProperties) bean; - - Map metadata = nacosDiscoveryProperties.getMetadata(); - metadata.put(DiscoveryConstant.SPRING_APPLICATION_NAME, PluginContextAware.getApplicationName(environment)); - metadata.put(DiscoveryConstant.SPRING_APPLICATION_TYPE, PluginContextAware.getApplicationType(environment)); - metadata.put(DiscoveryConstant.SPRING_APPLICATION_DISCOVERY_PLUGIN, NacosConstant.DISCOVERY_PLUGIN); - metadata.put(DiscoveryConstant.SPRING_APPLICATION_DISCOVERY_VERSION, DiscoveryConstant.DISCOVERY_VERSION); - metadata.put(DiscoveryConstant.SPRING_APPLICATION_REGISTER_CONTROL_ENABLED, PluginContextAware.isRegisterControlEnabled(environment).toString()); - metadata.put(DiscoveryConstant.SPRING_APPLICATION_DISCOVERY_CONTROL_ENABLED, PluginContextAware.isDiscoveryControlEnabled(environment).toString()); - metadata.put(DiscoveryConstant.SPRING_APPLICATION_CONFIG_REST_CONTROL_ENABLED, PluginContextAware.isConfigRestControlEnabled(environment).toString()); - metadata.put(DiscoveryConstant.SPRING_APPLICATION_GROUP_KEY, PluginContextAware.getGroupKey(environment)); - metadata.put(DiscoveryConstant.SPRING_APPLICATION_CONTEXT_PATH, PluginContextAware.getContextPath(environment)); - - MetadataUtil.filter(metadata); - - return bean; - } else { - return bean; - } - } -} \ No newline at end of file diff --git a/discovery-plugin-framework-nacos/src/main/java/com/nepxion/discovery/plugin/framework/decorator/NacosServerListDecorator.java b/discovery-plugin-framework-nacos/src/main/java/com/nepxion/discovery/plugin/framework/decorator/NacosServerListDecorator.java deleted file mode 100644 index 342205158c..0000000000 --- a/discovery-plugin-framework-nacos/src/main/java/com/nepxion/discovery/plugin/framework/decorator/NacosServerListDecorator.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.nepxion.discovery.plugin.framework.decorator; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import java.util.List; - -import org.springframework.cloud.alibaba.nacos.NacosDiscoveryProperties; -import org.springframework.cloud.alibaba.nacos.ribbon.NacosServer; -import org.springframework.cloud.alibaba.nacos.ribbon.NacosServerList; -import org.springframework.core.env.ConfigurableEnvironment; - -import com.nepxion.discovery.plugin.framework.context.PluginContextAware; -import com.nepxion.discovery.plugin.framework.listener.loadbalance.LoadBalanceListenerExecutor; - -public class NacosServerListDecorator extends NacosServerList { - private ConfigurableEnvironment environment; - - private LoadBalanceListenerExecutor loadBalanceListenerExecutor; - - public NacosServerListDecorator(NacosDiscoveryProperties discoveryProperties) { - super(discoveryProperties); - } - - @Override - public List getInitialListOfServers() { - List servers = super.getInitialListOfServers(); - - filter(servers); - - return servers; - } - - @Override - public List getUpdatedListOfServers() { - List servers = super.getUpdatedListOfServers(); - - filter(servers); - - return servers; - } - - private void filter(List servers) { - Boolean discoveryControlEnabled = PluginContextAware.isDiscoveryControlEnabled(environment); - if (discoveryControlEnabled) { - String serviceId = getServiceId(); - loadBalanceListenerExecutor.onGetServers(serviceId, servers); - } - } - - public void setEnvironment(ConfigurableEnvironment environment) { - this.environment = environment; - } - - public void setLoadBalanceListenerExecutor(LoadBalanceListenerExecutor loadBalanceListenerExecutor) { - this.loadBalanceListenerExecutor = loadBalanceListenerExecutor; - } -} \ No newline at end of file diff --git a/discovery-plugin-framework-nacos/src/main/java/com/nepxion/discovery/plugin/framework/decorator/NacosServiceRegistryDecorator.java b/discovery-plugin-framework-nacos/src/main/java/com/nepxion/discovery/plugin/framework/decorator/NacosServiceRegistryDecorator.java deleted file mode 100644 index b2ae0b5729..0000000000 --- a/discovery-plugin-framework-nacos/src/main/java/com/nepxion/discovery/plugin/framework/decorator/NacosServiceRegistryDecorator.java +++ /dev/null @@ -1,105 +0,0 @@ -package com.nepxion.discovery.plugin.framework.decorator; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import org.springframework.beans.BeansException; -import org.springframework.cloud.alibaba.nacos.NacosDiscoveryProperties; -import org.springframework.cloud.alibaba.nacos.registry.NacosServiceRegistry; -import org.springframework.cloud.client.serviceregistry.Registration; -import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.core.env.ConfigurableEnvironment; - -import com.nepxion.discovery.plugin.framework.context.PluginContextAware; -import com.nepxion.discovery.plugin.framework.listener.register.RegisterListenerExecutor; - -public class NacosServiceRegistryDecorator extends NacosServiceRegistry { - // private static final Logger LOG = LoggerFactory.getLogger(NacosServiceRegistryDecorator.class); - - private NacosServiceRegistry serviceRegistry; - private ConfigurableApplicationContext applicationContext; - private ConfigurableEnvironment environment; - - public NacosServiceRegistryDecorator(NacosDiscoveryProperties nacosDiscoveryProperties, NacosServiceRegistry serviceRegistry, ConfigurableApplicationContext applicationContext) { - super(nacosDiscoveryProperties); - - this.serviceRegistry = serviceRegistry; - this.applicationContext = applicationContext; - this.environment = applicationContext.getEnvironment(); - } - - @Override - public void register(Registration registration) { - Boolean registerControlEnabled = PluginContextAware.isRegisterControlEnabled(environment); - if (registerControlEnabled) { - try { - RegisterListenerExecutor registerListenerExecutor = applicationContext.getBean(RegisterListenerExecutor.class); - registerListenerExecutor.onRegister(registration); - } catch (BeansException e) { - // LOG.warn("Get bean for RegisterListenerExecutor failed, ignore to executor listener"); - } - } - - serviceRegistry.register(registration); - } - - @Override - public void deregister(Registration registration) { - Boolean registerControlEnabled = PluginContextAware.isRegisterControlEnabled(environment); - if (registerControlEnabled) { - try { - RegisterListenerExecutor registerListenerExecutor = applicationContext.getBean(RegisterListenerExecutor.class); - registerListenerExecutor.onDeregister(registration); - } catch (BeansException e) { - // LOG.warn("Get bean for RegisterListenerExecutor failed, ignore to executor listener"); - } - } - - serviceRegistry.deregister(registration); - } - - @Override - public void setStatus(Registration registration, String status) { - Boolean registerControlEnabled = PluginContextAware.isRegisterControlEnabled(environment); - if (registerControlEnabled) { - try { - RegisterListenerExecutor registerListenerExecutor = applicationContext.getBean(RegisterListenerExecutor.class); - registerListenerExecutor.onSetStatus(registration, status); - } catch (BeansException e) { - // LOG.warn("Get bean for RegisterListenerExecutor failed, ignore to executor listener"); - } - } - - serviceRegistry.setStatus(registration, status); - } - - @Override - public T getStatus(Registration registration) { - return serviceRegistry.getStatus(registration); - } - - @Override - public void close() { - Boolean registerControlEnabled = PluginContextAware.isRegisterControlEnabled(environment); - if (registerControlEnabled) { - try { - RegisterListenerExecutor registerListenerExecutor = applicationContext.getBean(RegisterListenerExecutor.class); - registerListenerExecutor.onClose(); - } catch (BeansException e) { - // LOG.warn("Get bean for RegisterListenerExecutor failed, ignore to executor listener"); - } - } - - serviceRegistry.close(); - } - - public ConfigurableEnvironment getEnvironment() { - return environment; - } -} \ No newline at end of file diff --git a/discovery-plugin-framework-zookeeper/pom.xml b/discovery-plugin-framework-zookeeper/pom.xml deleted file mode 100644 index e9d21d70d1..0000000000 --- a/discovery-plugin-framework-zookeeper/pom.xml +++ /dev/null @@ -1,28 +0,0 @@ - - - discovery-plugin-framework-zookeeper - Nepxion Discovery Plugin Framework Zookeeper - jar - 4.0.0 - Nepxion Discovery is an enhancement for Spring Cloud Discovery - http://www.nepxion.com - - - com.nepxion - discovery - 5.2.0-SNAPSHOT - - - - - ${project.groupId} - discovery-plugin-framework - - - - org.springframework.cloud - spring-cloud-starter-zookeeper-discovery - - - \ No newline at end of file diff --git a/discovery-plugin-framework-zookeeper/src/main/java/com/nepxion/discovery/plugin/framework/adapter/ZookeeperAdapter.java b/discovery-plugin-framework-zookeeper/src/main/java/com/nepxion/discovery/plugin/framework/adapter/ZookeeperAdapter.java deleted file mode 100644 index 2c7fa63318..0000000000 --- a/discovery-plugin-framework-zookeeper/src/main/java/com/nepxion/discovery/plugin/framework/adapter/ZookeeperAdapter.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.nepxion.discovery.plugin.framework.adapter; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import java.util.Map; - -import javax.annotation.PostConstruct; - -import org.springframework.cloud.zookeeper.discovery.ZookeeperServer; -import org.springframework.cloud.zookeeper.serviceregistry.ZookeeperRegistration; - -import com.nepxion.discovery.common.exception.DiscoveryException; -import com.nepxion.discovery.plugin.framework.constant.ZookeeperConstant; -import com.netflix.loadbalancer.Server; - -public class ZookeeperAdapter extends AbstractPluginAdapter { - // Zookeeper比较特殊,getServiceInstance是Lazy Initialize模式 - @PostConstruct - private void initialize() { - if (registration instanceof ZookeeperRegistration) { - ZookeeperRegistration zookeeperRegistration = (ZookeeperRegistration) registration; - - zookeeperRegistration.getServiceInstance(); - - return; - } - - throw new DiscoveryException("Registration isn't the type of ZookeeperRegistration"); - } - - // Zookeeper比较特殊,父类中getMetadata().get(groupKey)方法不行,执行该方法的时候Metadata还没初始化 - @Override - protected String getGroup(String groupKey) { - return pluginContextAware.getEnvironment().getProperty(ZookeeperConstant.META_DATA + "." + groupKey); - } - - @Override - public Map getServerMetadata(Server server) { - if (server instanceof ZookeeperServer) { - ZookeeperServer zookeeperServer = (ZookeeperServer) server; - - return zookeeperServer.getInstance().getPayload().getMetadata(); - } - - throw new DiscoveryException("Server instance isn't the type of ZookeeperServer"); - } -} \ No newline at end of file diff --git a/discovery-plugin-framework-zookeeper/src/main/java/com/nepxion/discovery/plugin/framework/configuration/ZookeeperAutoConfiguration.java b/discovery-plugin-framework-zookeeper/src/main/java/com/nepxion/discovery/plugin/framework/configuration/ZookeeperAutoConfiguration.java deleted file mode 100644 index c11af63678..0000000000 --- a/discovery-plugin-framework-zookeeper/src/main/java/com/nepxion/discovery/plugin/framework/configuration/ZookeeperAutoConfiguration.java +++ /dev/null @@ -1,53 +0,0 @@ -package com.nepxion.discovery.plugin.framework.configuration; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import org.springframework.cloud.netflix.ribbon.RibbonClients; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -import com.nepxion.banner.BannerConstant; -import com.nepxion.banner.Description; -import com.nepxion.banner.LogoBanner; -import com.nepxion.banner.NepxionBanner; -import com.nepxion.discovery.plugin.framework.adapter.PluginAdapter; -import com.nepxion.discovery.plugin.framework.adapter.ZookeeperAdapter; -import com.nepxion.discovery.plugin.framework.constant.ZookeeperConstant; -import com.taobao.text.Color; - -@Configuration -@RibbonClients(defaultConfiguration = { PluginLoadBalanceConfiguration.class, ZookeeperLoadBalanceConfiguration.class }) -public class ZookeeperAutoConfiguration { - static { - /*String bannerShown = System.getProperty(BannerConstant.BANNER_SHOWN, "true"); - if (Boolean.valueOf(bannerShown)) { - System.out.println(""); - System.out.println("╔════╗ ╔╗"); - System.out.println("╚══╗═║ ║║"); - System.out.println(" ╔╝╔╬══╦══╣║╔╦══╦══╦══╦══╦═╗"); - System.out.println(" ╔╝╔╝║╔╗║╔╗║╚╝╣║═╣║═╣╔╗║║═╣╔╝"); - System.out.println("╔╝═╚═╣╚╝║╚╝║╔╗╣║═╣║═╣╚╝║║═╣║"); - System.out.println("╚════╩══╩══╩╝╚╩══╩══╣╔═╩══╩╝"); - System.out.println(" ║║"); - System.out.println(" ╚╝"); - System.out.println(ZookeeperConstant.DISCOVERY_PLUGIN + " Discovery"); - System.out.println(""); - }*/ - - LogoBanner logoBanner = new LogoBanner(ZookeeperAutoConfiguration.class, "/com/nepxion/zookeeper/resource/logo.txt", "Welcome to Nepxion", 9, 5, new Color[] { Color.red, Color.green, Color.cyan, Color.blue, Color.yellow, Color.magenta, Color.red, Color.green, Color.cyan }, true); - - NepxionBanner.show(logoBanner, new Description("Discovery:", ZookeeperConstant.DISCOVERY_PLUGIN, 0, 1), new Description(BannerConstant.GITHUB + ":", BannerConstant.NEPXION_GITHUB + "/Discovery", 0, 1)); - } - - @Bean - public PluginAdapter pluginAdapter() { - return new ZookeeperAdapter(); - } -} \ No newline at end of file diff --git a/discovery-plugin-framework-zookeeper/src/main/java/com/nepxion/discovery/plugin/framework/constant/ZookeeperConstant.java b/discovery-plugin-framework-zookeeper/src/main/java/com/nepxion/discovery/plugin/framework/constant/ZookeeperConstant.java deleted file mode 100644 index 4317412ad3..0000000000 --- a/discovery-plugin-framework-zookeeper/src/main/java/com/nepxion/discovery/plugin/framework/constant/ZookeeperConstant.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.nepxion.discovery.plugin.framework.constant; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -public class ZookeeperConstant { - public static final String DISCOVERY_PLUGIN = "Zookeeper"; - - public static final String META_DATA = "spring.cloud.zookeeper.discovery.metadata"; -} \ No newline at end of file diff --git a/discovery-plugin-framework-zookeeper/src/main/java/com/nepxion/discovery/plugin/framework/context/ZookeeperApplicationContextInitializer.java b/discovery-plugin-framework-zookeeper/src/main/java/com/nepxion/discovery/plugin/framework/context/ZookeeperApplicationContextInitializer.java deleted file mode 100644 index 34accb5d45..0000000000 --- a/discovery-plugin-framework-zookeeper/src/main/java/com/nepxion/discovery/plugin/framework/context/ZookeeperApplicationContextInitializer.java +++ /dev/null @@ -1,56 +0,0 @@ -package com.nepxion.discovery.plugin.framework.context; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import java.util.Map; - -import org.springframework.beans.BeansException; -import org.springframework.cloud.zookeeper.discovery.ZookeeperDiscoveryProperties; -import org.springframework.cloud.zookeeper.serviceregistry.ZookeeperServiceRegistry; -import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.core.env.ConfigurableEnvironment; - -import com.nepxion.discovery.common.constant.DiscoveryConstant; -import com.nepxion.discovery.plugin.framework.constant.ZookeeperConstant; -import com.nepxion.discovery.plugin.framework.decorator.ZookeeperServiceRegistryDecorator; -import com.nepxion.discovery.plugin.framework.util.MetadataUtil; - -public class ZookeeperApplicationContextInitializer extends PluginApplicationContextInitializer { - @Override - protected Object afterInitialization(ConfigurableApplicationContext applicationContext, Object bean, String beanName) throws BeansException { - if (bean instanceof ZookeeperServiceRegistry) { - ZookeeperServiceRegistry zookeeperServiceRegistry = (ZookeeperServiceRegistry) bean; - - return new ZookeeperServiceRegistryDecorator(zookeeperServiceRegistry, applicationContext); - } else if (bean instanceof ZookeeperDiscoveryProperties) { - ConfigurableEnvironment environment = applicationContext.getEnvironment(); - - ZookeeperDiscoveryProperties zookeeperDiscoveryProperties = (ZookeeperDiscoveryProperties) bean; - zookeeperDiscoveryProperties.setPreferIpAddress(true); - - Map metadata = zookeeperDiscoveryProperties.getMetadata(); - metadata.put(DiscoveryConstant.SPRING_APPLICATION_NAME, PluginContextAware.getApplicationName(environment)); - metadata.put(DiscoveryConstant.SPRING_APPLICATION_TYPE, PluginContextAware.getApplicationType(environment)); - metadata.put(DiscoveryConstant.SPRING_APPLICATION_DISCOVERY_PLUGIN, ZookeeperConstant.DISCOVERY_PLUGIN); - metadata.put(DiscoveryConstant.SPRING_APPLICATION_DISCOVERY_VERSION, DiscoveryConstant.DISCOVERY_VERSION); - metadata.put(DiscoveryConstant.SPRING_APPLICATION_REGISTER_CONTROL_ENABLED, PluginContextAware.isRegisterControlEnabled(environment).toString()); - metadata.put(DiscoveryConstant.SPRING_APPLICATION_DISCOVERY_CONTROL_ENABLED, PluginContextAware.isDiscoveryControlEnabled(environment).toString()); - metadata.put(DiscoveryConstant.SPRING_APPLICATION_CONFIG_REST_CONTROL_ENABLED, PluginContextAware.isConfigRestControlEnabled(environment).toString()); - metadata.put(DiscoveryConstant.SPRING_APPLICATION_GROUP_KEY, PluginContextAware.getGroupKey(environment)); - metadata.put(DiscoveryConstant.SPRING_APPLICATION_CONTEXT_PATH, PluginContextAware.getContextPath(environment)); - - MetadataUtil.filter(metadata); - - return bean; - } else { - return bean; - } - } -} \ No newline at end of file diff --git a/discovery-plugin-framework-zookeeper/src/main/java/com/nepxion/discovery/plugin/framework/decorator/ZookeeperServerListDecorator.java b/discovery-plugin-framework-zookeeper/src/main/java/com/nepxion/discovery/plugin/framework/decorator/ZookeeperServerListDecorator.java deleted file mode 100644 index 6f7ec34754..0000000000 --- a/discovery-plugin-framework-zookeeper/src/main/java/com/nepxion/discovery/plugin/framework/decorator/ZookeeperServerListDecorator.java +++ /dev/null @@ -1,70 +0,0 @@ -package com.nepxion.discovery.plugin.framework.decorator; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import java.util.List; - -import org.apache.curator.x.discovery.ServiceDiscovery; -import org.springframework.cloud.zookeeper.discovery.ZookeeperInstance; -import org.springframework.cloud.zookeeper.discovery.ZookeeperServer; -import org.springframework.cloud.zookeeper.discovery.ZookeeperServerList; -import org.springframework.core.env.ConfigurableEnvironment; - -import com.nepxion.discovery.plugin.framework.context.PluginContextAware; -import com.nepxion.discovery.plugin.framework.listener.loadbalance.LoadBalanceListenerExecutor; - -public class ZookeeperServerListDecorator extends ZookeeperServerList { - private ConfigurableEnvironment environment; - - private LoadBalanceListenerExecutor loadBalanceListenerExecutor; - - private String serviceId; - - public ZookeeperServerListDecorator(ServiceDiscovery serviceDiscovery) { - super(serviceDiscovery); - } - - @Override - public List getInitialListOfServers() { - List servers = super.getInitialListOfServers(); - - filter(servers); - - return servers; - } - - @Override - public List getUpdatedListOfServers() { - List servers = super.getUpdatedListOfServers(); - - filter(servers); - - return servers; - } - - private void filter(List servers) { - Boolean discoveryControlEnabled = PluginContextAware.isDiscoveryControlEnabled(environment); - if (discoveryControlEnabled) { - loadBalanceListenerExecutor.onGetServers(serviceId, servers); - } - } - - public void setEnvironment(ConfigurableEnvironment environment) { - this.environment = environment; - } - - public void setLoadBalanceListenerExecutor(LoadBalanceListenerExecutor loadBalanceListenerExecutor) { - this.loadBalanceListenerExecutor = loadBalanceListenerExecutor; - } - - public void setServiceId(String serviceId) { - this.serviceId = serviceId; - } -} \ No newline at end of file diff --git a/discovery-plugin-framework-zookeeper/src/main/java/com/nepxion/discovery/plugin/framework/decorator/ZookeeperServiceRegistryDecorator.java b/discovery-plugin-framework-zookeeper/src/main/java/com/nepxion/discovery/plugin/framework/decorator/ZookeeperServiceRegistryDecorator.java deleted file mode 100644 index ca23e914ec..0000000000 --- a/discovery-plugin-framework-zookeeper/src/main/java/com/nepxion/discovery/plugin/framework/decorator/ZookeeperServiceRegistryDecorator.java +++ /dev/null @@ -1,109 +0,0 @@ -package com.nepxion.discovery.plugin.framework.decorator; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import org.springframework.beans.BeansException; -import org.springframework.cloud.zookeeper.serviceregistry.ZookeeperRegistration; -import org.springframework.cloud.zookeeper.serviceregistry.ZookeeperServiceRegistry; -import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.core.env.ConfigurableEnvironment; - -import com.nepxion.discovery.plugin.framework.context.PluginContextAware; -import com.nepxion.discovery.plugin.framework.listener.register.RegisterListenerExecutor; - -public class ZookeeperServiceRegistryDecorator extends ZookeeperServiceRegistry { - // private static final Logger LOG = LoggerFactory.getLogger(ZookeeperServiceRegistryDecorator.class); - - private ZookeeperServiceRegistry serviceRegistry; - private ConfigurableApplicationContext applicationContext; - private ConfigurableEnvironment environment; - - public ZookeeperServiceRegistryDecorator(ZookeeperServiceRegistry serviceRegistry, ConfigurableApplicationContext applicationContext) { - super(null); - - this.serviceRegistry = serviceRegistry; - this.applicationContext = applicationContext; - this.environment = applicationContext.getEnvironment(); - } - - @Override - public void register(ZookeeperRegistration registration) { - Boolean registerControlEnabled = PluginContextAware.isRegisterControlEnabled(environment); - if (registerControlEnabled) { - try { - RegisterListenerExecutor registerListenerExecutor = applicationContext.getBean(RegisterListenerExecutor.class); - registerListenerExecutor.onRegister(registration); - } catch (BeansException e) { - // LOG.warn("Get bean for RegisterListenerExecutor failed, ignore to executor listener"); - } - } - - serviceRegistry.register(registration); - } - - @Override - public void deregister(ZookeeperRegistration registration) { - Boolean registerControlEnabled = PluginContextAware.isRegisterControlEnabled(environment); - if (registerControlEnabled) { - try { - RegisterListenerExecutor registerListenerExecutor = applicationContext.getBean(RegisterListenerExecutor.class); - registerListenerExecutor.onDeregister(registration); - } catch (BeansException e) { - // LOG.warn("Get bean for RegisterListenerExecutor failed, ignore to executor listener"); - } - } - - serviceRegistry.deregister(registration); - } - - @Override - public void setStatus(ZookeeperRegistration registration, String status) { - Boolean registerControlEnabled = PluginContextAware.isRegisterControlEnabled(environment); - if (registerControlEnabled) { - try { - RegisterListenerExecutor registerListenerExecutor = applicationContext.getBean(RegisterListenerExecutor.class); - registerListenerExecutor.onSetStatus(registration, status); - } catch (BeansException e) { - // LOG.warn("Get bean for RegisterListenerExecutor failed, ignore to executor listener"); - } - } - - serviceRegistry.setStatus(registration, status); - } - - @Override - public Object getStatus(ZookeeperRegistration registration) { - return serviceRegistry.getStatus(registration); - } - - @Override - public void close() { - Boolean registerControlEnabled = PluginContextAware.isRegisterControlEnabled(environment); - if (registerControlEnabled) { - try { - RegisterListenerExecutor registerListenerExecutor = applicationContext.getBean(RegisterListenerExecutor.class); - registerListenerExecutor.onClose(); - } catch (BeansException e) { - // LOG.warn("Get bean for RegisterListenerExecutor failed, ignore to executor listener"); - } - } - - serviceRegistry.close(); - } - - @Override - public void afterSingletonsInstantiated() { - serviceRegistry.afterSingletonsInstantiated(); - } - - public ConfigurableEnvironment getEnvironment() { - return environment; - } -} \ No newline at end of file diff --git a/discovery-plugin-framework/discovery-plugin-framework-starter-parser/pom.xml b/discovery-plugin-framework/discovery-plugin-framework-starter-parser/pom.xml new file mode 100644 index 0000000000..8f51d79f74 --- /dev/null +++ b/discovery-plugin-framework/discovery-plugin-framework-starter-parser/pom.xml @@ -0,0 +1,23 @@ + + + discovery-plugin-framework-starter-parser + Nepxion Discovery Plugin Framework Starter Parser + jar + 4.0.0 + Nepxion Discovery is a solution for Spring Cloud with blue green, gray, weight, limitation, circuit breaker, degrade, isolation, monitor, tracing, dye, failover, async agent + http://www.nepxion.com + + + com.nepxion + discovery-plugin-framework + 6.23.0 + + + + + ${project.groupId} + discovery-common + + + \ No newline at end of file diff --git a/discovery-plugin-framework/discovery-plugin-framework-starter-parser/src/main/java/com/nepxion/discovery/plugin/framework/configuration/PluginParserAutoConfiguration.java b/discovery-plugin-framework/discovery-plugin-framework-starter-parser/src/main/java/com/nepxion/discovery/plugin/framework/configuration/PluginParserAutoConfiguration.java new file mode 100644 index 0000000000..32eb9067c7 --- /dev/null +++ b/discovery-plugin-framework/discovery-plugin-framework-starter-parser/src/main/java/com/nepxion/discovery/plugin/framework/configuration/PluginParserAutoConfiguration.java @@ -0,0 +1,59 @@ +package com.nepxion.discovery.plugin.framework.configuration; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.env.Environment; + +import com.nepxion.discovery.common.constant.DiscoveryConstant; +import com.nepxion.discovery.common.entity.ConfigFormatType; +import com.nepxion.discovery.common.exception.DiscoveryException; +import com.nepxion.discovery.plugin.framework.parser.PluginConfigDeparser; +import com.nepxion.discovery.plugin.framework.parser.PluginConfigParser; +import com.nepxion.discovery.plugin.framework.parser.json.JsonConfigDeparser; +import com.nepxion.discovery.plugin.framework.parser.json.JsonConfigParser; +import com.nepxion.discovery.plugin.framework.parser.xml.XmlConfigDeparser; +import com.nepxion.discovery.plugin.framework.parser.xml.XmlConfigParser; + +@Configuration +public class PluginParserAutoConfiguration { + @Autowired + private Environment environment; + + @Bean + public PluginConfigParser pluginConfigParser() { + String configFormat = environment.getProperty(DiscoveryConstant.SPRING_APPLICATION_CONFIG_FORMAT, String.class, DiscoveryConstant.XML_FORMAT); + ConfigFormatType configFormatType = ConfigFormatType.fromString(configFormat); + switch (configFormatType) { + case XML_FORMAT: + return new XmlConfigParser(); + case JSON_FORMAT: + return new JsonConfigParser(); + } + + throw new DiscoveryException("Invalid config format for '" + configFormat + "'"); + } + + @Bean + public PluginConfigDeparser pluginDeconfigParser() { + String configFormat = environment.getProperty(DiscoveryConstant.SPRING_APPLICATION_CONFIG_FORMAT, String.class, DiscoveryConstant.XML_FORMAT); + ConfigFormatType configFormatType = ConfigFormatType.fromString(configFormat); + switch (configFormatType) { + case XML_FORMAT: + return new XmlConfigDeparser(); + case JSON_FORMAT: + return new JsonConfigDeparser(); + } + + throw new DiscoveryException("Invalid config format for '" + configFormat + "'"); + } +} \ No newline at end of file diff --git a/discovery-plugin-framework/discovery-plugin-framework-starter-parser/src/main/java/com/nepxion/discovery/plugin/framework/parser/PluginConfigDeparser.java b/discovery-plugin-framework/discovery-plugin-framework-starter-parser/src/main/java/com/nepxion/discovery/plugin/framework/parser/PluginConfigDeparser.java new file mode 100644 index 0000000000..0b704dbd24 --- /dev/null +++ b/discovery-plugin-framework/discovery-plugin-framework-starter-parser/src/main/java/com/nepxion/discovery/plugin/framework/parser/PluginConfigDeparser.java @@ -0,0 +1,16 @@ +package com.nepxion.discovery.plugin.framework.parser; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import com.nepxion.discovery.common.entity.RuleEntity; + +public interface PluginConfigDeparser { + String deparse(RuleEntity ruleEntity); +} \ No newline at end of file diff --git a/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/config/PluginConfigParser.java b/discovery-plugin-framework/discovery-plugin-framework-starter-parser/src/main/java/com/nepxion/discovery/plugin/framework/parser/PluginConfigParser.java similarity index 85% rename from discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/config/PluginConfigParser.java rename to discovery-plugin-framework/discovery-plugin-framework-starter-parser/src/main/java/com/nepxion/discovery/plugin/framework/parser/PluginConfigParser.java index 3e591a0fab..66caf5acda 100644 --- a/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/config/PluginConfigParser.java +++ b/discovery-plugin-framework/discovery-plugin-framework-starter-parser/src/main/java/com/nepxion/discovery/plugin/framework/parser/PluginConfigParser.java @@ -1,4 +1,4 @@ -package com.nepxion.discovery.plugin.framework.config; +package com.nepxion.discovery.plugin.framework.parser; /** *

Title: Nepxion Discovery

diff --git a/discovery-plugin-framework/discovery-plugin-framework-starter-parser/src/main/java/com/nepxion/discovery/plugin/framework/parser/json/JsonConfigDeparser.java b/discovery-plugin-framework/discovery-plugin-framework-starter-parser/src/main/java/com/nepxion/discovery/plugin/framework/parser/json/JsonConfigDeparser.java new file mode 100644 index 0000000000..9e95ea15e1 --- /dev/null +++ b/discovery-plugin-framework/discovery-plugin-framework-starter-parser/src/main/java/com/nepxion/discovery/plugin/framework/parser/json/JsonConfigDeparser.java @@ -0,0 +1,41 @@ +package com.nepxion.discovery.plugin.framework.parser.json; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.nepxion.discovery.common.entity.RuleEntity; +import com.nepxion.discovery.common.exception.DiscoveryException; +import com.nepxion.discovery.common.util.JsonUtil; +import com.nepxion.discovery.plugin.framework.parser.PluginConfigDeparser; + +public class JsonConfigDeparser implements PluginConfigDeparser { + private static final Logger LOG = LoggerFactory.getLogger(JsonConfigDeparser.class); + + @Override + public String deparse(RuleEntity ruleEntity) { + if (ruleEntity == null) { + throw new DiscoveryException("RuleEntity is null"); + } + + LOG.info("Start to deparse RuleEntity to json..."); + + try { + String config = JsonUtil.toPrettyJson(ruleEntity); + + LOG.info("Rule content=\n{}", config); + + return config; + } catch (Exception e) { + throw new DiscoveryException(e.getMessage(), e); + } + } +} \ No newline at end of file diff --git a/discovery-plugin-config-center/src/main/java/com/nepxion/discovery/plugin/configcenter/parser/json/JsonConfigParser.java b/discovery-plugin-framework/discovery-plugin-framework-starter-parser/src/main/java/com/nepxion/discovery/plugin/framework/parser/json/JsonConfigParser.java similarity index 84% rename from discovery-plugin-config-center/src/main/java/com/nepxion/discovery/plugin/configcenter/parser/json/JsonConfigParser.java rename to discovery-plugin-framework/discovery-plugin-framework-starter-parser/src/main/java/com/nepxion/discovery/plugin/framework/parser/json/JsonConfigParser.java index 3d993ee0f9..ebb486b600 100644 --- a/discovery-plugin-config-center/src/main/java/com/nepxion/discovery/plugin/configcenter/parser/json/JsonConfigParser.java +++ b/discovery-plugin-framework/discovery-plugin-framework-starter-parser/src/main/java/com/nepxion/discovery/plugin/framework/parser/json/JsonConfigParser.java @@ -1,4 +1,4 @@ -package com.nepxion.discovery.plugin.configcenter.parser.json; +package com.nepxion.discovery.plugin.framework.parser.json; /** *

Title: Nepxion Discovery

@@ -16,7 +16,7 @@ import com.nepxion.discovery.common.entity.RuleEntity; import com.nepxion.discovery.common.exception.DiscoveryException; import com.nepxion.discovery.common.util.JsonUtil; -import com.nepxion.discovery.plugin.framework.config.PluginConfigParser; +import com.nepxion.discovery.plugin.framework.parser.PluginConfigParser; public class JsonConfigParser implements PluginConfigParser { private static final Logger LOG = LoggerFactory.getLogger(JsonConfigParser.class); @@ -27,15 +27,14 @@ public RuleEntity parse(String config) { throw new DiscoveryException("Config is null or empty"); } + LOG.info("Start to parse rule from json..."); + try { RuleEntity ruleEntity = JsonUtil.fromJson(config, RuleEntity.class); ruleEntity.setContent(config); LOG.info("Rule content=\n{}", config); - // Just for RuleEntity print - // System.out.println(ruleEntity); - return ruleEntity; } catch (Exception e) { throw new DiscoveryException(e.getMessage(), e); diff --git a/discovery-plugin-framework/discovery-plugin-framework-starter-parser/src/main/java/com/nepxion/discovery/plugin/framework/parser/xml/XmlConfigConstant.java b/discovery-plugin-framework/discovery-plugin-framework-starter-parser/src/main/java/com/nepxion/discovery/plugin/framework/parser/xml/XmlConfigConstant.java new file mode 100644 index 0000000000..df95be8b5d --- /dev/null +++ b/discovery-plugin-framework/discovery-plugin-framework-starter-parser/src/main/java/com/nepxion/discovery/plugin/framework/parser/xml/XmlConfigConstant.java @@ -0,0 +1,60 @@ +package com.nepxion.discovery.plugin.framework.parser.xml; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import com.nepxion.discovery.common.constant.DiscoveryConstant; + +public class XmlConfigConstant { + public static final String RULE_ELEMENT_NAME = "rule"; + public static final String REGISTER_ELEMENT_NAME = "register"; + public static final String DISCOVERY_ELEMENT_NAME = "discovery"; + public static final String STRATEGY_ELEMENT_NAME = "strategy"; + public static final String STRATEGY_RELEASE_ELEMENT_NAME = "strategy-release"; + public static final String STRATEGY_FAILOVER_ELEMENT_NAME = "strategy-failover"; + public static final String STRATEGY_BLACKLIST_ELEMENT_NAME = "strategy-blacklist"; + public static final String PARAMETER_ELEMENT_NAME = "parameter"; + public static final String CONDITIONS_ELEMENT_NAME = "conditions"; + public static final String CONDITION_ELEMENT_NAME = "condition"; + public static final String ROUTES_ELEMENT_NAME = "routes"; + public static final String ROUTE_ELEMENT_NAME = "route"; + public static final String HEADER_ELEMENT_NAME = "header"; + public static final String VERSION_PREFER_ELEMENT_NAME = DiscoveryConstant.VERSION_PREFER; + public static final String VERSION_FAILOVER_ELEMENT_NAME = DiscoveryConstant.VERSION_FAILOVER; + public static final String REGION_TRANSFER_ELEMENT_NAME = DiscoveryConstant.REGION_TRANSFER; + public static final String REGION_FAILOVER_ELEMENT_NAME = DiscoveryConstant.REGION_FAILOVER; + public static final String ENVIRONMENT_FAILOVER_ELEMENT_NAME = DiscoveryConstant.ENVIRONMENT_FAILOVER; + public static final String ZONE_FAILOVER_ELEMENT_NAME = DiscoveryConstant.ZONE_FAILOVER; + public static final String ADDRESS_FAILOVER_ELEMENT_NAME = DiscoveryConstant.ADDRESS_FAILOVER; + public static final String ID_ELEMENT_NAME = "id"; + public static final String SERVICE_ELEMENT_NAME = "service"; + public static final String BLACKLIST_ELEMENT_NAME = "blacklist"; + public static final String WHITELIST_ELEMENT_NAME = "whitelist"; + public static final String COUNT_ELEMENT_NAME = "count"; + public static final String WEIGHT_ELEMENT_NAME = "weight"; + public static final String VERSION_ELEMENT_NAME = DiscoveryConstant.VERSION; + public static final String REGION_ELEMENT_NAME = DiscoveryConstant.REGION; + public static final String ADDRESS_ELEMENT_NAME = DiscoveryConstant.ADDRESS; + public static final String VERSION_WEIGHT_ELEMENT_NAME = DiscoveryConstant.VERSION_WEIGHT; + public static final String REGION_WEIGHT_ELEMENT_NAME = DiscoveryConstant.REGION_WEIGHT; + + public static final String FILTER_VALUE_ATTRIBUTE_NAME = "filter-value"; + public static final String SERVICE_NAME_ATTRIBUTE_NAME = "service-name"; + public static final String CONSUMER_SERVICE_NAME_ATTRIBUTE_NAME = "consumer-service-name"; + public static final String PROVIDER_SERVICE_NAME_ATTRIBUTE_NAME = "provider-service-name"; + public static final String CONSUMER_VERSION_VALUE_ATTRIBUTE_NAME = "consumer-version-value"; + public static final String PROVIDER_VERSION_VALUE_ATTRIBUTE_NAME = "provider-version-value"; + public static final String CONSUMER_REGION_VALUE_ATTRIBUTE_NAME = "consumer-region-value"; + public static final String PROVIDER_REGION_VALUE_ATTRIBUTE_NAME = "provider-region-value"; + public static final String PROVIDER_WEIGHT_VALUE_ATTRIBUTE_NAME = "provider-weight-value"; + public static final String ID_ATTRIBUTE_NAME = "id"; + public static final String EXPRESSION_ATTRIBUTE_NAME = "expression"; + public static final String HEADER_ATTRIBUTE_NAME = "header"; + public static final String TYPE_ATTRIBUTE_NAME = "type"; +} \ No newline at end of file diff --git a/discovery-plugin-framework/discovery-plugin-framework-starter-parser/src/main/java/com/nepxion/discovery/plugin/framework/parser/xml/XmlConfigDeparser.java b/discovery-plugin-framework/discovery-plugin-framework-starter-parser/src/main/java/com/nepxion/discovery/plugin/framework/parser/xml/XmlConfigDeparser.java new file mode 100644 index 0000000000..48962cccbd --- /dev/null +++ b/discovery-plugin-framework/discovery-plugin-framework-starter-parser/src/main/java/com/nepxion/discovery/plugin/framework/parser/xml/XmlConfigDeparser.java @@ -0,0 +1,560 @@ +package com.nepxion.discovery.plugin.framework.parser.xml; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.List; +import java.util.Map; + +import org.apache.commons.collections4.CollectionUtils; +import org.apache.commons.collections4.MapUtils; +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.nepxion.discovery.common.constant.DiscoveryConstant; +import com.nepxion.discovery.common.entity.AddressWeightEntity; +import com.nepxion.discovery.common.entity.ConditionType; +import com.nepxion.discovery.common.entity.CountFilterEntity; +import com.nepxion.discovery.common.entity.DiscoveryEntity; +import com.nepxion.discovery.common.entity.EscapeType; +import com.nepxion.discovery.common.entity.FilterType; +import com.nepxion.discovery.common.entity.HostFilterEntity; +import com.nepxion.discovery.common.entity.ParameterEntity; +import com.nepxion.discovery.common.entity.ParameterServiceEntity; +import com.nepxion.discovery.common.entity.RegionEntity; +import com.nepxion.discovery.common.entity.RegionFilterEntity; +import com.nepxion.discovery.common.entity.RegionWeightEntity; +import com.nepxion.discovery.common.entity.RegisterEntity; +import com.nepxion.discovery.common.entity.RuleEntity; +import com.nepxion.discovery.common.entity.StrategyBlacklistEntity; +import com.nepxion.discovery.common.entity.StrategyConditionBlueGreenEntity; +import com.nepxion.discovery.common.entity.StrategyConditionGrayEntity; +import com.nepxion.discovery.common.entity.StrategyEntity; +import com.nepxion.discovery.common.entity.StrategyFailoverEntity; +import com.nepxion.discovery.common.entity.StrategyHeaderEntity; +import com.nepxion.discovery.common.entity.StrategyReleaseEntity; +import com.nepxion.discovery.common.entity.StrategyRouteEntity; +import com.nepxion.discovery.common.entity.StrategyRouteType; +import com.nepxion.discovery.common.entity.VersionEntity; +import com.nepxion.discovery.common.entity.VersionFilterEntity; +import com.nepxion.discovery.common.entity.VersionWeightEntity; +import com.nepxion.discovery.common.entity.WeightEntity; +import com.nepxion.discovery.common.entity.WeightFilterEntity; +import com.nepxion.discovery.common.entity.WeightType; +import com.nepxion.discovery.common.exception.DiscoveryException; +import com.nepxion.discovery.common.util.JsonUtil; +import com.nepxion.discovery.common.util.StringUtil; +import com.nepxion.discovery.plugin.framework.parser.PluginConfigDeparser; + +public class XmlConfigDeparser implements PluginConfigDeparser { + private static final Logger LOG = LoggerFactory.getLogger(XmlConfigDeparser.class); + + private static final String INDENT = " "; + + @Override + public String deparse(RuleEntity ruleEntity) { + if (ruleEntity == null) { + throw new DiscoveryException("RuleEntity is null"); + } + + StringBuilder stringBuilder = new StringBuilder(); + deparseRoot(stringBuilder, ruleEntity); + + String config = stringBuilder.toString(); + ruleEntity.setContent(config); + + LOG.info("Rule content=\n{}", config); + + return config; + } + + private void deparseRoot(StringBuilder stringBuilder, RuleEntity ruleEntity) { + LOG.info("Start to deparse RuleEntity to xml..."); + + RegisterEntity registerEntity = ruleEntity.getRegisterEntity(); + DiscoveryEntity discoveryEntity = ruleEntity.getDiscoveryEntity(); + StrategyEntity strategyEntity = ruleEntity.getStrategyEntity(); + StrategyReleaseEntity strategyReleaseEntity = ruleEntity.getStrategyReleaseEntity(); + StrategyFailoverEntity strategyFailoverEntity = ruleEntity.getStrategyFailoverEntity(); + StrategyBlacklistEntity strategyBlacklistEntity = ruleEntity.getStrategyBlacklistEntity(); + ParameterEntity parameterEntity = ruleEntity.getParameterEntity(); + + stringBuilder.append("\n"); + stringBuilder.append("<" + XmlConfigConstant.RULE_ELEMENT_NAME + ">\n"); + if (registerEntity != null) { + deparseRegister(stringBuilder, registerEntity); + } + if (discoveryEntity != null) { + deparseDiscovery(stringBuilder, discoveryEntity); + } + if (strategyEntity != null) { + deparseStrategy(stringBuilder, strategyEntity); + } + if (strategyReleaseEntity != null) { + deparseStrategyRelease(stringBuilder, strategyReleaseEntity); + } + if (strategyFailoverEntity != null) { + deparseStrategyFailover(stringBuilder, strategyFailoverEntity); + } + if (strategyBlacklistEntity != null) { + deparseStrategyBlacklist(stringBuilder, strategyBlacklistEntity); + } + if (parameterEntity != null) { + deparseParameter(stringBuilder, parameterEntity); + } + stringBuilder.append(""); + } + + private void deparseRegister(StringBuilder stringBuilder, RegisterEntity registerEntity) { + HostFilterEntity hostFilterEntity = registerEntity.getHostFilterEntity(); + CountFilterEntity countFilterEntity = registerEntity.getCountFilterEntity(); + + if (hostFilterEntity != null || countFilterEntity != null) { + stringBuilder.append(INDENT + "<" + XmlConfigConstant.REGISTER_ELEMENT_NAME + ">\n"); + } + if (hostFilterEntity != null) { + deparseHostFilter(stringBuilder, hostFilterEntity); + } + if (countFilterEntity != null) { + deparseCountFilter(stringBuilder, countFilterEntity); + } + if (hostFilterEntity != null || countFilterEntity != null) { + stringBuilder.append(INDENT + "\n"); + } + } + + private void deparseDiscovery(StringBuilder stringBuilder, DiscoveryEntity discoveryEntity) { + HostFilterEntity hostFilterEntity = discoveryEntity.getHostFilterEntity(); + VersionFilterEntity versionFilterEntity = discoveryEntity.getVersionFilterEntity(); + RegionFilterEntity regionFilterEntity = discoveryEntity.getRegionFilterEntity(); + WeightFilterEntity weightFilterEntity = discoveryEntity.getWeightFilterEntity(); + + if (hostFilterEntity != null || versionFilterEntity != null || regionFilterEntity != null || weightFilterEntity != null) { + stringBuilder.append(INDENT + "<" + XmlConfigConstant.DISCOVERY_ELEMENT_NAME + ">\n"); + } + if (hostFilterEntity != null) { + deparseHostFilter(stringBuilder, hostFilterEntity); + } + if (versionFilterEntity != null) { + deparseVersionFilter(stringBuilder, versionFilterEntity); + } + if (regionFilterEntity != null) { + deparseRegionFilter(stringBuilder, regionFilterEntity); + } + if (weightFilterEntity != null) { + deparseWeightFilter(stringBuilder, weightFilterEntity); + } + if (hostFilterEntity != null || versionFilterEntity != null || regionFilterEntity != null || weightFilterEntity != null) { + stringBuilder.append(INDENT + "\n"); + } + } + + private void deparseStrategy(StringBuilder stringBuilder, StrategyEntity strategyEntity) { + String versionValue = strategyEntity.getVersionValue(); + String regionValue = strategyEntity.getRegionValue(); + String addressValue = strategyEntity.getAddressValue(); + String versionWeightValue = strategyEntity.getVersionWeightValue(); + String regionWeightValue = strategyEntity.getRegionWeightValue(); + + if (versionValue != null || regionValue != null || addressValue != null || versionWeightValue != null || regionWeightValue != null) { + stringBuilder.append(INDENT + "<" + XmlConfigConstant.STRATEGY_ELEMENT_NAME + ">\n"); + } + if (versionValue != null) { + stringBuilder.append(INDENT + INDENT + "<" + XmlConfigConstant.VERSION_ELEMENT_NAME + ">" + versionValue + "\n"); + } + if (regionValue != null) { + stringBuilder.append(INDENT + INDENT + "<" + XmlConfigConstant.REGION_ELEMENT_NAME + ">" + regionValue + "\n"); + } + if (addressValue != null) { + stringBuilder.append(INDENT + INDENT + "<" + XmlConfigConstant.ADDRESS_ELEMENT_NAME + ">" + addressValue + "\n"); + } + if (versionWeightValue != null) { + stringBuilder.append(INDENT + INDENT + "<" + XmlConfigConstant.VERSION_WEIGHT_ELEMENT_NAME + ">" + versionWeightValue + "\n"); + } + if (regionWeightValue != null) { + stringBuilder.append(INDENT + INDENT + "<" + XmlConfigConstant.REGION_WEIGHT_ELEMENT_NAME + ">" + regionWeightValue + "\n"); + } + if (versionValue != null || regionValue != null || addressValue != null || versionWeightValue != null || regionWeightValue != null) { + stringBuilder.append(INDENT + "\n"); + } + } + + private void deparseStrategyRelease(StringBuilder stringBuilder, StrategyReleaseEntity strategyReleaseEntity) { + List strategyConditionBlueGreenEntityList = strategyReleaseEntity.getStrategyConditionBlueGreenEntityList(); + List strategyConditionGrayEntityList = strategyReleaseEntity.getStrategyConditionGrayEntityList(); + List strategyRouteEntityList = strategyReleaseEntity.getStrategyRouteEntityList(); + StrategyHeaderEntity strategyHeaderEntity = strategyReleaseEntity.getStrategyHeaderEntity(); + + if (CollectionUtils.isNotEmpty(strategyConditionBlueGreenEntityList) || CollectionUtils.isNotEmpty(strategyConditionGrayEntityList) || CollectionUtils.isNotEmpty(strategyRouteEntityList) || strategyHeaderEntity != null) { + stringBuilder.append(INDENT + "<" + XmlConfigConstant.STRATEGY_RELEASE_ELEMENT_NAME + ">\n"); + } + if (CollectionUtils.isNotEmpty(strategyConditionBlueGreenEntityList)) { + deparseStrategyConditionBlueGreen(stringBuilder, strategyConditionBlueGreenEntityList); + } + if (CollectionUtils.isNotEmpty(strategyConditionGrayEntityList)) { + deparseStrategyConditionGray(stringBuilder, strategyConditionGrayEntityList); + } + if (CollectionUtils.isNotEmpty(strategyRouteEntityList)) { + deparseStrategyRoute(stringBuilder, strategyRouteEntityList); + } + if (strategyHeaderEntity != null) { + deparseStrategyHeader(stringBuilder, strategyHeaderEntity); + } + if (CollectionUtils.isNotEmpty(strategyConditionBlueGreenEntityList) || CollectionUtils.isNotEmpty(strategyConditionGrayEntityList) || CollectionUtils.isNotEmpty(strategyRouteEntityList) || strategyHeaderEntity != null) { + stringBuilder.append(INDENT + "\n"); + } + } + + private void deparseStrategyFailover(StringBuilder stringBuilder, StrategyFailoverEntity strategyFailoverEntity) { + String versionPreferValue = strategyFailoverEntity.getVersionPreferValue(); + String versionFailoverValue = strategyFailoverEntity.getVersionFailoverValue(); + String regionTransferValue = strategyFailoverEntity.getRegionTransferValue(); + String regionFailoverValue = strategyFailoverEntity.getRegionFailoverValue(); + String environmentFailoverValue = strategyFailoverEntity.getEnvironmentFailoverValue(); + String zoneFailoverValue = strategyFailoverEntity.getZoneFailoverValue(); + String addressFailoverValue = strategyFailoverEntity.getAddressFailoverValue(); + if (versionPreferValue != null || versionFailoverValue != null || regionTransferValue != null || regionFailoverValue != null || environmentFailoverValue != null || zoneFailoverValue != null || addressFailoverValue != null) { + stringBuilder.append(INDENT + "<" + XmlConfigConstant.STRATEGY_FAILOVER_ELEMENT_NAME + ">\n"); + } + if (versionPreferValue != null) { + stringBuilder.append(INDENT + INDENT + "<" + XmlConfigConstant.VERSION_PREFER_ELEMENT_NAME + ">" + versionPreferValue + "\n"); + } + if (versionFailoverValue != null) { + stringBuilder.append(INDENT + INDENT + "<" + XmlConfigConstant.VERSION_FAILOVER_ELEMENT_NAME + ">" + versionFailoverValue + "\n"); + } + if (regionTransferValue != null) { + stringBuilder.append(INDENT + INDENT + "<" + XmlConfigConstant.REGION_TRANSFER_ELEMENT_NAME + ">" + regionTransferValue + "\n"); + } + if (regionFailoverValue != null) { + stringBuilder.append(INDENT + INDENT + "<" + XmlConfigConstant.REGION_FAILOVER_ELEMENT_NAME + ">" + regionFailoverValue + "\n"); + } + if (environmentFailoverValue != null) { + stringBuilder.append(INDENT + INDENT + "<" + XmlConfigConstant.ENVIRONMENT_FAILOVER_ELEMENT_NAME + ">" + environmentFailoverValue + "\n"); + } + if (zoneFailoverValue != null) { + stringBuilder.append(INDENT + INDENT + "<" + XmlConfigConstant.ZONE_FAILOVER_ELEMENT_NAME + ">" + zoneFailoverValue + "\n"); + } + if (addressFailoverValue != null) { + stringBuilder.append(INDENT + INDENT + "<" + XmlConfigConstant.ADDRESS_FAILOVER_ELEMENT_NAME + ">" + addressFailoverValue + "\n"); + } + if (versionPreferValue != null || versionFailoverValue != null || regionTransferValue != null || regionFailoverValue != null || environmentFailoverValue != null || zoneFailoverValue != null || addressFailoverValue != null) { + stringBuilder.append(INDENT + "\n"); + } + } + + private void deparseStrategyBlacklist(StringBuilder stringBuilder, StrategyBlacklistEntity strategyBlacklistEntity) { + String idValue = strategyBlacklistEntity.getIdValue(); + String addressValue = strategyBlacklistEntity.getAddressValue(); + if (idValue != null || addressValue != null) { + stringBuilder.append(INDENT + "<" + XmlConfigConstant.STRATEGY_BLACKLIST_ELEMENT_NAME + ">\n"); + } + if (idValue != null) { + stringBuilder.append(INDENT + INDENT + "<" + XmlConfigConstant.ID_ELEMENT_NAME + ">" + idValue + "\n"); + } + if (addressValue != null) { + stringBuilder.append(INDENT + INDENT + "<" + XmlConfigConstant.ADDRESS_ELEMENT_NAME + ">" + addressValue + "\n"); + } + if (idValue != null || addressValue != null) { + stringBuilder.append(INDENT + "\n"); + } + } + + private void deparseParameter(StringBuilder stringBuilder, ParameterEntity parameterEntity) { + Map> parameterServiceMap = parameterEntity.getParameterServiceMap(); + if (MapUtils.isNotEmpty(parameterServiceMap)) { + stringBuilder.append(INDENT + "<" + XmlConfigConstant.PARAMETER_ELEMENT_NAME + ">\n"); + for (Map.Entry> parameterServiceEntry : parameterServiceMap.entrySet()) { + List parameterServiceEntityList = parameterServiceEntry.getValue(); + if (CollectionUtils.isNotEmpty(parameterServiceEntityList)) { + for (ParameterServiceEntity parameterServiceEntity : parameterServiceEntityList) { + stringBuilder.append(INDENT + INDENT + "<" + XmlConfigConstant.SERVICE_ELEMENT_NAME); + + Map parameterMap = parameterServiceEntity.getParameterMap(); + for (Map.Entry parameterEntry : parameterMap.entrySet()) { + String key = parameterEntry.getKey(); + String value = parameterEntry.getValue(); + + stringBuilder.append(" " + key + "=\"" + value + "\""); + } + stringBuilder.append("/>\n"); + } + } + } + stringBuilder.append(INDENT + "\n"); + } + } + + private void deparseHostFilter(StringBuilder stringBuilder, HostFilterEntity hostFilterEntity) { + FilterType filterType = hostFilterEntity.getFilterType(); + List globalFilterValueList = hostFilterEntity.getFilterValueList(); + Map> filterMap = hostFilterEntity.getFilterMap(); + + if (CollectionUtils.isNotEmpty(globalFilterValueList) || MapUtils.isNotEmpty(filterMap)) { + if (CollectionUtils.isEmpty(globalFilterValueList)) { + stringBuilder.append(INDENT + INDENT + "<" + filterType.toString() + ">\n"); + } else { + stringBuilder.append(INDENT + INDENT + "<" + filterType.toString() + " " + XmlConfigConstant.FILTER_VALUE_ATTRIBUTE_NAME + "=\"" + StringUtil.convertToString(globalFilterValueList) + "\">\n"); + } + } + if (MapUtils.isNotEmpty(filterMap)) { + for (Map.Entry> entry : filterMap.entrySet()) { + String serviceName = entry.getKey(); + List filterValueList = entry.getValue(); + if (CollectionUtils.isEmpty(filterValueList)) { + stringBuilder.append(INDENT + INDENT + INDENT + "<" + XmlConfigConstant.SERVICE_ELEMENT_NAME + " " + XmlConfigConstant.SERVICE_NAME_ATTRIBUTE_NAME + "=\"" + serviceName + "\"/>\n"); + } else { + stringBuilder.append(INDENT + INDENT + INDENT + "<" + XmlConfigConstant.SERVICE_ELEMENT_NAME + " " + XmlConfigConstant.SERVICE_NAME_ATTRIBUTE_NAME + "=\"" + serviceName + "\" " + XmlConfigConstant.FILTER_VALUE_ATTRIBUTE_NAME + "=\"" + StringUtil.convertToString(filterValueList) + "\"/>\n"); + } + } + } + if (CollectionUtils.isNotEmpty(globalFilterValueList) || MapUtils.isNotEmpty(filterMap)) { + stringBuilder.append(INDENT + INDENT + "\n"); + } + } + + private void deparseCountFilter(StringBuilder stringBuilder, CountFilterEntity countFilterEntity) { + Integer globalFilterValue = countFilterEntity.getFilterValue(); + Map filterMap = countFilterEntity.getFilterMap(); + + if (globalFilterValue != null || MapUtils.isNotEmpty(filterMap)) { + if (globalFilterValue == null) { + stringBuilder.append(INDENT + INDENT + "<" + XmlConfigConstant.COUNT_ELEMENT_NAME + ">\n"); + } else { + stringBuilder.append(INDENT + INDENT + "<" + XmlConfigConstant.COUNT_ELEMENT_NAME + " " + XmlConfigConstant.FILTER_VALUE_ATTRIBUTE_NAME + "=\"" + globalFilterValue + "\">\n"); + } + } + if (MapUtils.isNotEmpty(filterMap)) { + for (Map.Entry entry : filterMap.entrySet()) { + String serviceName = entry.getKey(); + Integer filterValue = entry.getValue(); + if (filterValue == null) { + stringBuilder.append(INDENT + INDENT + INDENT + "<" + XmlConfigConstant.SERVICE_ELEMENT_NAME + " " + XmlConfigConstant.SERVICE_NAME_ATTRIBUTE_NAME + "=\"" + serviceName + "\"/>\n"); + } else { + stringBuilder.append(INDENT + INDENT + INDENT + "<" + XmlConfigConstant.SERVICE_ELEMENT_NAME + " " + XmlConfigConstant.SERVICE_NAME_ATTRIBUTE_NAME + "=\"" + serviceName + "\" " + XmlConfigConstant.FILTER_VALUE_ATTRIBUTE_NAME + "=\"" + filterValue + "\"/>\n"); + } + } + } + if (globalFilterValue != null || MapUtils.isNotEmpty(filterMap)) { + stringBuilder.append(INDENT + INDENT + "\n"); + } + } + + private void deparseVersionFilter(StringBuilder stringBuilder, VersionFilterEntity versionFilterEntity) { + Map> versionEntityMap = versionFilterEntity.getVersionEntityMap(); + if (MapUtils.isNotEmpty(versionEntityMap)) { + stringBuilder.append(INDENT + INDENT + "<" + XmlConfigConstant.VERSION_ELEMENT_NAME + ">\n"); + for (Map.Entry> entry : versionEntityMap.entrySet()) { + List versionEntityList = entry.getValue(); + for (VersionEntity versionEntity : versionEntityList) { + String consumerServiceName = versionEntity.getConsumerServiceName(); + String providerServiceName = versionEntity.getProviderServiceName(); + List consumerVersionValueList = versionEntity.getConsumerVersionValueList(); + List providerVersionValueList = versionEntity.getProviderVersionValueList(); + + stringBuilder.append(INDENT + INDENT + INDENT + "<" + XmlConfigConstant.SERVICE_ELEMENT_NAME + " " + XmlConfigConstant.CONSUMER_SERVICE_NAME_ATTRIBUTE_NAME + "=\"" + consumerServiceName + "\" " + XmlConfigConstant.PROVIDER_SERVICE_NAME_ATTRIBUTE_NAME + "=\"" + providerServiceName + "\""); + if (CollectionUtils.isNotEmpty(consumerVersionValueList)) { + stringBuilder.append(" " + XmlConfigConstant.CONSUMER_VERSION_VALUE_ATTRIBUTE_NAME + "=\"" + StringUtil.convertToString(consumerVersionValueList) + "\""); + } + if (CollectionUtils.isNotEmpty(providerVersionValueList)) { + stringBuilder.append(" " + XmlConfigConstant.PROVIDER_VERSION_VALUE_ATTRIBUTE_NAME + "=\"" + StringUtil.convertToString(providerVersionValueList) + "\""); + } + stringBuilder.append("/>\n"); + } + } + stringBuilder.append(INDENT + INDENT + "\n"); + } + } + + private void deparseRegionFilter(StringBuilder stringBuilder, RegionFilterEntity regionFilterEntity) { + Map> regionEntityMap = regionFilterEntity.getRegionEntityMap(); + if (MapUtils.isNotEmpty(regionEntityMap)) { + stringBuilder.append(INDENT + INDENT + "<" + XmlConfigConstant.REGION_ELEMENT_NAME + ">\n"); + for (Map.Entry> entry : regionEntityMap.entrySet()) { + List regionEntityList = entry.getValue(); + for (RegionEntity regionEntity : regionEntityList) { + String consumerServiceName = regionEntity.getConsumerServiceName(); + String providerServiceName = regionEntity.getProviderServiceName(); + List consumerVersionValueList = regionEntity.getConsumerRegionValueList(); + List providerVersionValueList = regionEntity.getProviderRegionValueList(); + + stringBuilder.append(INDENT + INDENT + INDENT + "<" + XmlConfigConstant.SERVICE_ELEMENT_NAME + " " + XmlConfigConstant.CONSUMER_SERVICE_NAME_ATTRIBUTE_NAME + "=\"" + consumerServiceName + "\" " + XmlConfigConstant.PROVIDER_SERVICE_NAME_ATTRIBUTE_NAME + "=\"" + providerServiceName + "\""); + if (CollectionUtils.isNotEmpty(consumerVersionValueList)) { + stringBuilder.append(" " + XmlConfigConstant.CONSUMER_REGION_VALUE_ATTRIBUTE_NAME + "=\"" + StringUtil.convertToString(consumerVersionValueList) + "\""); + } + if (CollectionUtils.isNotEmpty(providerVersionValueList)) { + stringBuilder.append(" " + XmlConfigConstant.PROVIDER_REGION_VALUE_ATTRIBUTE_NAME + "=\"" + StringUtil.convertToString(providerVersionValueList) + "\""); + } + stringBuilder.append("/>\n"); + } + } + stringBuilder.append(INDENT + INDENT + "\n"); + } + } + + private void deparseWeightFilter(StringBuilder stringBuilder, WeightFilterEntity weightFilterEntity) { + Map> versionWeightEntityMap = weightFilterEntity.getVersionWeightEntityMap(); + List versionWeightEntityList = weightFilterEntity.getVersionWeightEntityList(); + VersionWeightEntity versionWeightEntity = weightFilterEntity.getVersionWeightEntity(); + Map versionWeightMap = versionWeightEntity.getWeightMap(); + + Map> regionWeightEntityMap = weightFilterEntity.getRegionWeightEntityMap(); + List regionWeightEntityList = weightFilterEntity.getRegionWeightEntityList(); + RegionWeightEntity regionWeightEntity = weightFilterEntity.getRegionWeightEntity(); + Map regionWeightMap = regionWeightEntity.getWeightMap(); + + stringBuilder.append(INDENT + INDENT + "<" + XmlConfigConstant.WEIGHT_ELEMENT_NAME + ">\n"); + if (MapUtils.isNotEmpty(versionWeightEntityMap)) { + for (Map.Entry> entry : versionWeightEntityMap.entrySet()) { + List weightEntityList = entry.getValue(); + + if (CollectionUtils.isNotEmpty(weightEntityList)) { + for (WeightEntity weightEntity : weightEntityList) { + String consumerServiceName = weightEntity.getConsumerServiceName(); + String providerServiceName = weightEntity.getProviderServiceName(); + Map weightMap = weightEntity.getWeightMap(); + WeightType type = weightEntity.getType(); + + stringBuilder.append(INDENT + INDENT + INDENT + "<" + XmlConfigConstant.SERVICE_ELEMENT_NAME + " " + XmlConfigConstant.CONSUMER_SERVICE_NAME_ATTRIBUTE_NAME + "=\"" + consumerServiceName + "\" " + XmlConfigConstant.PROVIDER_SERVICE_NAME_ATTRIBUTE_NAME + "=\"" + providerServiceName + "\" " + XmlConfigConstant.PROVIDER_WEIGHT_VALUE_ATTRIBUTE_NAME + "=\"" + StringUtil.convertToString(weightMap) + "\" " + XmlConfigConstant.TYPE_ATTRIBUTE_NAME + "=\"" + type + "\"/>\n"); + } + } + } + } + if (CollectionUtils.isNotEmpty(versionWeightEntityList)) { + for (WeightEntity weightEntity : versionWeightEntityList) { + String providerServiceName = weightEntity.getProviderServiceName(); + Map weightMap = weightEntity.getWeightMap(); + WeightType type = weightEntity.getType(); + + stringBuilder.append(INDENT + INDENT + INDENT + "<" + XmlConfigConstant.SERVICE_ELEMENT_NAME + " " + XmlConfigConstant.PROVIDER_SERVICE_NAME_ATTRIBUTE_NAME + "=\"" + providerServiceName + "\" " + XmlConfigConstant.PROVIDER_WEIGHT_VALUE_ATTRIBUTE_NAME + "=\"" + StringUtil.convertToString(weightMap) + "\" " + XmlConfigConstant.TYPE_ATTRIBUTE_NAME + "=\"" + type + "\"/>\n"); + } + } + if (MapUtils.isNotEmpty(versionWeightMap)) { + stringBuilder.append(INDENT + INDENT + INDENT + "<" + XmlConfigConstant.VERSION_ELEMENT_NAME + " " + XmlConfigConstant.PROVIDER_WEIGHT_VALUE_ATTRIBUTE_NAME + "=\"" + StringUtil.convertToString(versionWeightMap) + "\"/>\n"); + } + if (MapUtils.isNotEmpty(regionWeightEntityMap)) { + for (Map.Entry> entry : regionWeightEntityMap.entrySet()) { + List weightEntityList = entry.getValue(); + + if (CollectionUtils.isNotEmpty(weightEntityList)) { + for (WeightEntity weightEntity : weightEntityList) { + String consumerServiceName = weightEntity.getConsumerServiceName(); + String providerServiceName = weightEntity.getProviderServiceName(); + Map weightMap = weightEntity.getWeightMap(); + WeightType type = weightEntity.getType(); + + stringBuilder.append(INDENT + INDENT + INDENT + "<" + XmlConfigConstant.SERVICE_ELEMENT_NAME + " " + XmlConfigConstant.CONSUMER_SERVICE_NAME_ATTRIBUTE_NAME + "=\"" + consumerServiceName + "\" " + XmlConfigConstant.PROVIDER_SERVICE_NAME_ATTRIBUTE_NAME + "=\"" + providerServiceName + "\" " + XmlConfigConstant.PROVIDER_WEIGHT_VALUE_ATTRIBUTE_NAME + "=\"" + StringUtil.convertToString(weightMap) + "\" " + XmlConfigConstant.TYPE_ATTRIBUTE_NAME + "=\"" + type + "\"/>\n"); + } + } + } + } + if (CollectionUtils.isNotEmpty(regionWeightEntityList)) { + for (WeightEntity weightEntity : regionWeightEntityList) { + String providerServiceName = weightEntity.getProviderServiceName(); + Map weightMap = weightEntity.getWeightMap(); + WeightType type = weightEntity.getType(); + + stringBuilder.append(INDENT + INDENT + INDENT + "<" + XmlConfigConstant.SERVICE_ELEMENT_NAME + " " + XmlConfigConstant.PROVIDER_SERVICE_NAME_ATTRIBUTE_NAME + "=\"" + providerServiceName + "\" " + XmlConfigConstant.PROVIDER_WEIGHT_VALUE_ATTRIBUTE_NAME + "=\"" + StringUtil.convertToString(weightMap) + "\" " + XmlConfigConstant.TYPE_ATTRIBUTE_NAME + "=\"" + type + "\"/>\n"); + } + } + if (MapUtils.isNotEmpty(regionWeightMap)) { + stringBuilder.append(INDENT + INDENT + INDENT + "<" + XmlConfigConstant.REGION_ELEMENT_NAME + " " + XmlConfigConstant.PROVIDER_WEIGHT_VALUE_ATTRIBUTE_NAME + "=\"" + StringUtil.convertToString(regionWeightMap) + "\"/>\n"); + } + stringBuilder.append(INDENT + INDENT + "\n"); + } + + private void deparseStrategyConditionBlueGreen(StringBuilder stringBuilder, List strategyConditionBlueGreenEntityList) { + if (CollectionUtils.isNotEmpty(strategyConditionBlueGreenEntityList)) { + stringBuilder.append(INDENT + INDENT + "<" + XmlConfigConstant.CONDITIONS_ELEMENT_NAME + " " + XmlConfigConstant.TYPE_ATTRIBUTE_NAME + "=\"" + ConditionType.BLUE_GREEN.toString() + "\">\n"); + for (StrategyConditionBlueGreenEntity strategyConditionBlueGreenEntity : strategyConditionBlueGreenEntityList) { + String id = strategyConditionBlueGreenEntity.getId(); + String expression = EscapeType.escape(strategyConditionBlueGreenEntity.getExpression(), true); + String versionId = strategyConditionBlueGreenEntity.getVersionId(); + String regionId = strategyConditionBlueGreenEntity.getRegionId(); + String addressId = strategyConditionBlueGreenEntity.getAddressId(); + String versionWeightId = strategyConditionBlueGreenEntity.getVersionWeightId(); + String regionWeightId = strategyConditionBlueGreenEntity.getRegionWeightId(); + + if (StringUtils.isNotEmpty(expression)) { + stringBuilder.append(INDENT + INDENT + INDENT + "<" + XmlConfigConstant.CONDITION_ELEMENT_NAME + " " + XmlConfigConstant.ID_ATTRIBUTE_NAME + "=\"" + id + "\" " + XmlConfigConstant.EXPRESSION_ATTRIBUTE_NAME + "=\"" + expression + "\""); + } else { + stringBuilder.append(INDENT + INDENT + INDENT + "<" + XmlConfigConstant.CONDITION_ELEMENT_NAME + " " + XmlConfigConstant.ID_ATTRIBUTE_NAME + "=\"" + id + "\""); + } + if (versionId != null) { + stringBuilder.append(" " + XmlConfigConstant.VERSION_ELEMENT_NAME + DiscoveryConstant.DASH + XmlConfigConstant.ID_ATTRIBUTE_NAME + "=\"" + versionId + "\""); + } + if (regionId != null) { + stringBuilder.append(" " + XmlConfigConstant.REGION_ELEMENT_NAME + DiscoveryConstant.DASH + XmlConfigConstant.ID_ATTRIBUTE_NAME + "=\"" + regionId + "\""); + } + if (addressId != null) { + stringBuilder.append(" " + XmlConfigConstant.ADDRESS_ELEMENT_NAME + DiscoveryConstant.DASH + XmlConfigConstant.ID_ATTRIBUTE_NAME + "=\"" + addressId + "\""); + } + if (versionWeightId != null) { + stringBuilder.append(" " + XmlConfigConstant.VERSION_WEIGHT_ELEMENT_NAME + DiscoveryConstant.DASH + XmlConfigConstant.ID_ATTRIBUTE_NAME + "=\"" + versionWeightId + "\""); + } + if (regionWeightId != null) { + stringBuilder.append(" " + XmlConfigConstant.REGION_WEIGHT_ELEMENT_NAME + DiscoveryConstant.DASH + XmlConfigConstant.ID_ATTRIBUTE_NAME + "=\"" + regionWeightId + "\""); + } + stringBuilder.append("/>\n"); + } + stringBuilder.append(INDENT + INDENT + "\n"); + } + } + + private void deparseStrategyConditionGray(StringBuilder stringBuilder, List strategyConditionGrayEntityList) { + if (CollectionUtils.isNotEmpty(strategyConditionGrayEntityList)) { + stringBuilder.append(INDENT + INDENT + "<" + XmlConfigConstant.CONDITIONS_ELEMENT_NAME + " " + XmlConfigConstant.TYPE_ATTRIBUTE_NAME + "=\"" + ConditionType.GRAY.toString() + "\">\n"); + for (StrategyConditionGrayEntity strategyConditionGrayEntity : strategyConditionGrayEntityList) { + String id = strategyConditionGrayEntity.getId(); + String expression = EscapeType.escape(strategyConditionGrayEntity.getExpression(), true); + VersionWeightEntity versionWeightEntity = strategyConditionGrayEntity.getVersionWeightEntity(); + RegionWeightEntity regionWeightEntity = strategyConditionGrayEntity.getRegionWeightEntity(); + AddressWeightEntity addressWeightEntity = strategyConditionGrayEntity.getAddressWeightEntity(); + + if (StringUtils.isNotEmpty(expression)) { + stringBuilder.append(INDENT + INDENT + INDENT + "<" + XmlConfigConstant.CONDITION_ELEMENT_NAME + " " + XmlConfigConstant.ID_ATTRIBUTE_NAME + "=\"" + id + "\" " + XmlConfigConstant.EXPRESSION_ATTRIBUTE_NAME + "=\"" + expression + "\""); + } else { + stringBuilder.append(INDENT + INDENT + INDENT + "<" + XmlConfigConstant.CONDITION_ELEMENT_NAME + " " + XmlConfigConstant.ID_ATTRIBUTE_NAME + "=\"" + id + "\""); + } + if (versionWeightEntity != null) { + stringBuilder.append(" " + XmlConfigConstant.VERSION_ELEMENT_NAME + DiscoveryConstant.DASH + XmlConfigConstant.ID_ATTRIBUTE_NAME + "=\"" + StringUtil.convertToString(versionWeightEntity.getWeightMap()) + "\""); + } + if (regionWeightEntity != null) { + stringBuilder.append(" " + XmlConfigConstant.REGION_ELEMENT_NAME + DiscoveryConstant.DASH + XmlConfigConstant.ID_ATTRIBUTE_NAME + "=\"" + StringUtil.convertToString(regionWeightEntity.getWeightMap()) + "\""); + } + if (addressWeightEntity != null) { + stringBuilder.append(" " + XmlConfigConstant.ADDRESS_ELEMENT_NAME + DiscoveryConstant.DASH + XmlConfigConstant.ID_ATTRIBUTE_NAME + "=\"" + StringUtil.convertToString(addressWeightEntity.getWeightMap()) + "\""); + } + stringBuilder.append("/>\n"); + } + stringBuilder.append(INDENT + INDENT + "\n"); + } + } + + private void deparseStrategyRoute(StringBuilder stringBuilder, List strategyRouteEntityList) { + if (CollectionUtils.isNotEmpty(strategyRouteEntityList)) { + stringBuilder.append(INDENT + INDENT + "<" + XmlConfigConstant.ROUTES_ELEMENT_NAME + ">\n"); + for (StrategyRouteEntity strategyRouteEntity : strategyRouteEntityList) { + String id = strategyRouteEntity.getId(); + StrategyRouteType type = strategyRouteEntity.getType(); + String value = strategyRouteEntity.getValue(); + + stringBuilder.append(INDENT + INDENT + INDENT + "<" + XmlConfigConstant.ROUTE_ELEMENT_NAME + " " + XmlConfigConstant.ID_ATTRIBUTE_NAME + "=\"" + id + "\" " + XmlConfigConstant.TYPE_ATTRIBUTE_NAME + "=\"" + type + "\">" + value + "\n"); + } + stringBuilder.append(INDENT + INDENT + "\n"); + } + } + + private void deparseStrategyHeader(StringBuilder stringBuilder, StrategyHeaderEntity strategyHeaderEntity) { + Map headerMap = strategyHeaderEntity.getHeaderMap(); + if (MapUtils.isNotEmpty(headerMap)) { + stringBuilder.append(INDENT + INDENT + "<" + XmlConfigConstant.HEADER_ELEMENT_NAME + ">" + JsonUtil.toJson(headerMap) + "\n"); + } + } +} \ No newline at end of file diff --git a/discovery-plugin-framework/discovery-plugin-framework-starter-parser/src/main/java/com/nepxion/discovery/plugin/framework/parser/xml/XmlConfigParser.java b/discovery-plugin-framework/discovery-plugin-framework-starter-parser/src/main/java/com/nepxion/discovery/plugin/framework/parser/xml/XmlConfigParser.java new file mode 100644 index 0000000000..96e9f3c66a --- /dev/null +++ b/discovery-plugin-framework/discovery-plugin-framework-starter-parser/src/main/java/com/nepxion/discovery/plugin/framework/parser/xml/XmlConfigParser.java @@ -0,0 +1,913 @@ +package com.nepxion.discovery.plugin.framework.parser.xml; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import org.apache.commons.lang3.StringUtils; +import org.dom4j.Attribute; +import org.dom4j.Document; +import org.dom4j.Element; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.nepxion.discovery.common.constant.DiscoveryConstant; +import com.nepxion.discovery.common.dom4j.Dom4JReader; +import com.nepxion.discovery.common.entity.AddressWeightEntity; +import com.nepxion.discovery.common.entity.ConditionType; +import com.nepxion.discovery.common.entity.CountFilterEntity; +import com.nepxion.discovery.common.entity.DiscoveryEntity; +import com.nepxion.discovery.common.entity.FilterHolderEntity; +import com.nepxion.discovery.common.entity.FilterType; +import com.nepxion.discovery.common.entity.HostFilterEntity; +import com.nepxion.discovery.common.entity.ParameterEntity; +import com.nepxion.discovery.common.entity.ParameterServiceEntity; +import com.nepxion.discovery.common.entity.RegionEntity; +import com.nepxion.discovery.common.entity.RegionFilterEntity; +import com.nepxion.discovery.common.entity.RegionWeightEntity; +import com.nepxion.discovery.common.entity.RegisterEntity; +import com.nepxion.discovery.common.entity.RuleEntity; +import com.nepxion.discovery.common.entity.StrategyBlacklistEntity; +import com.nepxion.discovery.common.entity.StrategyConditionBlueGreenEntity; +import com.nepxion.discovery.common.entity.StrategyConditionGrayEntity; +import com.nepxion.discovery.common.entity.StrategyEntity; +import com.nepxion.discovery.common.entity.StrategyFailoverEntity; +import com.nepxion.discovery.common.entity.StrategyHeaderEntity; +import com.nepxion.discovery.common.entity.StrategyReleaseEntity; +import com.nepxion.discovery.common.entity.StrategyRouteEntity; +import com.nepxion.discovery.common.entity.StrategyRouteType; +import com.nepxion.discovery.common.entity.VersionEntity; +import com.nepxion.discovery.common.entity.VersionFilterEntity; +import com.nepxion.discovery.common.entity.VersionWeightEntity; +import com.nepxion.discovery.common.entity.WeightEntity; +import com.nepxion.discovery.common.entity.WeightEntityWrapper; +import com.nepxion.discovery.common.entity.WeightFilterEntity; +import com.nepxion.discovery.common.entity.WeightType; +import com.nepxion.discovery.common.exception.DiscoveryException; +import com.nepxion.discovery.common.util.JsonUtil; +import com.nepxion.discovery.common.util.StringUtil; +import com.nepxion.discovery.plugin.framework.parser.PluginConfigParser; + +public class XmlConfigParser implements PluginConfigParser { + private static final Logger LOG = LoggerFactory.getLogger(XmlConfigParser.class); + + @Override + public RuleEntity parse(String config) { + if (StringUtils.isEmpty(config)) { + throw new DiscoveryException("Config is null or empty"); + } + + try { + Document document = Dom4JReader.getDocument(config); + + Element rootElement = document.getRootElement(); + + return parseRoot(config, rootElement); + } catch (Exception e) { + throw new DiscoveryException(e.getMessage(), e); + } + } + + private RuleEntity parseRoot(String config, Element element) { + LOG.info("Start to parse rule from xml..."); + + int registerElementCount = element.elements(XmlConfigConstant.REGISTER_ELEMENT_NAME).size(); + if (registerElementCount > 1) { + throw new DiscoveryException("Allow only one element[" + XmlConfigConstant.REGISTER_ELEMENT_NAME + "] to be configed"); + } + + int discoveryElementCount = element.elements(XmlConfigConstant.DISCOVERY_ELEMENT_NAME).size(); + if (discoveryElementCount > 1) { + throw new DiscoveryException("Allow only one element[" + XmlConfigConstant.DISCOVERY_ELEMENT_NAME + "] to be configed"); + } + + int strategyElementCount = element.elements(XmlConfigConstant.STRATEGY_ELEMENT_NAME).size(); + if (strategyElementCount > 1) { + throw new DiscoveryException("Allow only one element[" + XmlConfigConstant.STRATEGY_ELEMENT_NAME + "] to be configed"); + } + + int strategyReleaseElementCount = element.elements(XmlConfigConstant.STRATEGY_RELEASE_ELEMENT_NAME).size(); + if (strategyReleaseElementCount > 1) { + throw new DiscoveryException("Allow only one element[" + XmlConfigConstant.STRATEGY_RELEASE_ELEMENT_NAME + "] to be configed"); + } + + int strategyFailoverElementCount = element.elements(XmlConfigConstant.STRATEGY_FAILOVER_ELEMENT_NAME).size(); + if (strategyFailoverElementCount > 1) { + throw new DiscoveryException("Allow only one element[" + XmlConfigConstant.STRATEGY_FAILOVER_ELEMENT_NAME + "] to be configed"); + } + + int strategyBlacklistElementCount = element.elements(XmlConfigConstant.STRATEGY_BLACKLIST_ELEMENT_NAME).size(); + if (strategyBlacklistElementCount > 1) { + throw new DiscoveryException("Allow only one element[" + XmlConfigConstant.STRATEGY_BLACKLIST_ELEMENT_NAME + "] to be configed"); + } + + int parameterElementCount = element.elements(XmlConfigConstant.PARAMETER_ELEMENT_NAME).size(); + if (parameterElementCount > 1) { + throw new DiscoveryException("Allow only one element[" + XmlConfigConstant.PARAMETER_ELEMENT_NAME + "] to be configed"); + } + + RegisterEntity registerEntity = null; + DiscoveryEntity discoveryEntity = null; + StrategyEntity strategyEntity = null; + StrategyReleaseEntity strategyReleaseEntity = null; + StrategyFailoverEntity strategyFailoverEntity = null; + StrategyBlacklistEntity strategyBlacklistEntity = null; + ParameterEntity parameterEntity = null; + for (Iterator elementIterator = element.elementIterator(); elementIterator.hasNext();) { + Element childElement = elementIterator.next(); + + if (StringUtils.equals(childElement.getName(), XmlConfigConstant.REGISTER_ELEMENT_NAME)) { + registerEntity = new RegisterEntity(); + parseRegister(childElement, registerEntity); + } else if (StringUtils.equals(childElement.getName(), XmlConfigConstant.DISCOVERY_ELEMENT_NAME)) { + discoveryEntity = new DiscoveryEntity(); + parseDiscovery(childElement, discoveryEntity); + } else if (StringUtils.equals(childElement.getName(), XmlConfigConstant.STRATEGY_ELEMENT_NAME)) { + strategyEntity = new StrategyEntity(); + parseStrategy(childElement, strategyEntity); + } else if (StringUtils.equals(childElement.getName(), XmlConfigConstant.STRATEGY_RELEASE_ELEMENT_NAME)) { + strategyReleaseEntity = new StrategyReleaseEntity(); + parseStrategyRelease(childElement, strategyReleaseEntity); + } else if (StringUtils.equals(childElement.getName(), XmlConfigConstant.STRATEGY_FAILOVER_ELEMENT_NAME)) { + strategyFailoverEntity = new StrategyFailoverEntity(); + parseStrategyFailover(childElement, strategyFailoverEntity); + } else if (StringUtils.equals(childElement.getName(), XmlConfigConstant.STRATEGY_BLACKLIST_ELEMENT_NAME)) { + strategyBlacklistEntity = new StrategyBlacklistEntity(); + parseStrategyBlacklist(childElement, strategyBlacklistEntity); + } else if (StringUtils.equals(childElement.getName(), XmlConfigConstant.PARAMETER_ELEMENT_NAME)) { + parameterEntity = new ParameterEntity(); + parseParameter(childElement, parameterEntity); + } + } + + RuleEntity ruleEntity = new RuleEntity(); + ruleEntity.setRegisterEntity(registerEntity); + ruleEntity.setDiscoveryEntity(discoveryEntity); + ruleEntity.setStrategyEntity(strategyEntity); + ruleEntity.setStrategyReleaseEntity(strategyReleaseEntity); + ruleEntity.setStrategyFailoverEntity(strategyFailoverEntity); + ruleEntity.setStrategyBlacklistEntity(strategyBlacklistEntity); + ruleEntity.setParameterEntity(parameterEntity); + ruleEntity.setContent(config); + + LOG.info("Rule content=\n{}", config); + + return ruleEntity; + } + + private void parseRegister(Element element, RegisterEntity registerEntity) { + for (Iterator elementIterator = element.elementIterator(); elementIterator.hasNext();) { + Element childElement = elementIterator.next(); + + if (StringUtils.equals(childElement.getName(), XmlConfigConstant.BLACKLIST_ELEMENT_NAME)) { + parseHostFilter(childElement, XmlConfigConstant.BLACKLIST_ELEMENT_NAME, registerEntity); + } else if (StringUtils.equals(childElement.getName(), XmlConfigConstant.WHITELIST_ELEMENT_NAME)) { + parseHostFilter(childElement, XmlConfigConstant.WHITELIST_ELEMENT_NAME, registerEntity); + } else if (StringUtils.equals(childElement.getName(), XmlConfigConstant.COUNT_ELEMENT_NAME)) { + parseCountFilter(childElement, registerEntity); + } + } + } + + private void parseDiscovery(Element element, DiscoveryEntity discoveryEntity) { + for (Iterator elementIterator = element.elementIterator(); elementIterator.hasNext();) { + Element childElement = elementIterator.next(); + + if (StringUtils.equals(childElement.getName(), XmlConfigConstant.BLACKLIST_ELEMENT_NAME)) { + parseHostFilter(childElement, XmlConfigConstant.BLACKLIST_ELEMENT_NAME, discoveryEntity); + } else if (StringUtils.equals(childElement.getName(), XmlConfigConstant.WHITELIST_ELEMENT_NAME)) { + parseHostFilter(childElement, XmlConfigConstant.WHITELIST_ELEMENT_NAME, discoveryEntity); + } else if (StringUtils.equals(childElement.getName(), XmlConfigConstant.VERSION_ELEMENT_NAME)) { + parseVersionFilter(childElement, discoveryEntity); + } else if (StringUtils.equals(childElement.getName(), XmlConfigConstant.REGION_ELEMENT_NAME)) { + parseRegionFilter(childElement, discoveryEntity); + } else if (StringUtils.equals(childElement.getName(), XmlConfigConstant.WEIGHT_ELEMENT_NAME)) { + parseWeightFilter(childElement, discoveryEntity); + } + } + } + + private void parseStrategy(Element element, StrategyEntity strategyEntity) { + int versionElementCount = element.elements(XmlConfigConstant.VERSION_ELEMENT_NAME).size(); + if (versionElementCount > 1) { + throw new DiscoveryException("Allow only one element[" + XmlConfigConstant.VERSION_ELEMENT_NAME + "] to be configed"); + } + + int regionElementCount = element.elements(XmlConfigConstant.REGION_ELEMENT_NAME).size(); + if (regionElementCount > 1) { + throw new DiscoveryException("Allow only one element[" + XmlConfigConstant.REGION_ELEMENT_NAME + "] to be configed"); + } + + int addressElementCount = element.elements(XmlConfigConstant.ADDRESS_ELEMENT_NAME).size(); + if (addressElementCount > 1) { + throw new DiscoveryException("Allow only one element[" + XmlConfigConstant.ADDRESS_ELEMENT_NAME + "] to be configed"); + } + + int versionWeightElementCount = element.elements(XmlConfigConstant.VERSION_WEIGHT_ELEMENT_NAME).size(); + if (versionWeightElementCount > 1) { + throw new DiscoveryException("Allow only one element[" + XmlConfigConstant.VERSION_WEIGHT_ELEMENT_NAME + "] to be configed"); + } + + int regionWeightElementCount = element.elements(XmlConfigConstant.REGION_WEIGHT_ELEMENT_NAME).size(); + if (regionWeightElementCount > 1) { + throw new DiscoveryException("Allow only one element[" + XmlConfigConstant.REGION_WEIGHT_ELEMENT_NAME + "] to be configed"); + } + + for (Iterator elementIterator = element.elementIterator(); elementIterator.hasNext();) { + Element childElement = elementIterator.next(); + + if (StringUtils.equals(childElement.getName(), XmlConfigConstant.VERSION_ELEMENT_NAME)) { + String versionValue = childElement.getTextTrim(); + strategyEntity.setVersionValue(versionValue); + } else if (StringUtils.equals(childElement.getName(), XmlConfigConstant.REGION_ELEMENT_NAME)) { + String regionValue = childElement.getTextTrim(); + strategyEntity.setRegionValue(regionValue); + } else if (StringUtils.equals(childElement.getName(), XmlConfigConstant.ADDRESS_ELEMENT_NAME)) { + String addressValue = childElement.getTextTrim(); + strategyEntity.setAddressValue(addressValue); + } else if (StringUtils.equals(childElement.getName(), XmlConfigConstant.VERSION_WEIGHT_ELEMENT_NAME)) { + String versionWeightValue = childElement.getTextTrim(); + strategyEntity.setVersionWeightValue(versionWeightValue); + } else if (StringUtils.equals(childElement.getName(), XmlConfigConstant.REGION_WEIGHT_ELEMENT_NAME)) { + String regionWeightValue = childElement.getTextTrim(); + strategyEntity.setRegionWeightValue(regionWeightValue); + } + } + } + + private void parseStrategyRelease(Element element, StrategyReleaseEntity strategyReleaseEntity) { + for (Iterator elementIterator = element.elementIterator(); elementIterator.hasNext();) { + Element childElement = elementIterator.next(); + + if (StringUtils.equals(childElement.getName(), XmlConfigConstant.CONDITIONS_ELEMENT_NAME)) { + Attribute typeAttribute = childElement.attribute(XmlConfigConstant.TYPE_ATTRIBUTE_NAME); + if (typeAttribute == null) { + throw new DiscoveryException("Attribute[" + XmlConfigConstant.TYPE_ATTRIBUTE_NAME + "] in element[" + childElement.getName() + "] is missing"); + } + String type = typeAttribute.getData().toString().trim(); + ConditionType conditionType = ConditionType.fromString(type); + switch (conditionType) { + case BLUE_GREEN: + parseStrategyConditionBlueGreen(childElement, strategyReleaseEntity); + break; + case GRAY: + parseStrategyConditionGray(childElement, strategyReleaseEntity); + break; + } + } else if (StringUtils.equals(childElement.getName(), XmlConfigConstant.ROUTES_ELEMENT_NAME)) { + parseStrategyRoute(childElement, strategyReleaseEntity); + } else if (StringUtils.equals(childElement.getName(), XmlConfigConstant.HEADER_ELEMENT_NAME)) { + parseStrategyHeader(childElement, strategyReleaseEntity); + } + } + } + + private void parseStrategyFailover(Element element, StrategyFailoverEntity strategyFailoverEntity) { + int versionPreferElementCount = element.elements(XmlConfigConstant.VERSION_PREFER_ELEMENT_NAME).size(); + if (versionPreferElementCount > 1) { + throw new DiscoveryException("Allow only one element[" + XmlConfigConstant.VERSION_PREFER_ELEMENT_NAME + "] to be configed"); + } + + int versionFailoverElementCount = element.elements(XmlConfigConstant.VERSION_FAILOVER_ELEMENT_NAME).size(); + if (versionFailoverElementCount > 1) { + throw new DiscoveryException("Allow only one element[" + XmlConfigConstant.VERSION_FAILOVER_ELEMENT_NAME + "] to be configed"); + } + + int regionTransferElementCount = element.elements(XmlConfigConstant.REGION_TRANSFER_ELEMENT_NAME).size(); + if (regionTransferElementCount > 1) { + throw new DiscoveryException("Allow only one element[" + XmlConfigConstant.REGION_TRANSFER_ELEMENT_NAME + "] to be configed"); + } + + int regionFailoverElementCount = element.elements(XmlConfigConstant.REGION_FAILOVER_ELEMENT_NAME).size(); + if (regionFailoverElementCount > 1) { + throw new DiscoveryException("Allow only one element[" + XmlConfigConstant.REGION_FAILOVER_ELEMENT_NAME + "] to be configed"); + } + + int environmentFailoverElementCount = element.elements(XmlConfigConstant.ENVIRONMENT_FAILOVER_ELEMENT_NAME).size(); + if (environmentFailoverElementCount > 1) { + throw new DiscoveryException("Allow only one element[" + XmlConfigConstant.ENVIRONMENT_FAILOVER_ELEMENT_NAME + "] to be configed"); + } + + int zoneFailoverElementCount = element.elements(XmlConfigConstant.ZONE_FAILOVER_ELEMENT_NAME).size(); + if (zoneFailoverElementCount > 1) { + throw new DiscoveryException("Allow only one element[" + XmlConfigConstant.ZONE_FAILOVER_ELEMENT_NAME + "] to be configed"); + } + + int addressFailoverElementCount = element.elements(XmlConfigConstant.ADDRESS_FAILOVER_ELEMENT_NAME).size(); + if (addressFailoverElementCount > 1) { + throw new DiscoveryException("Allow only one element[" + XmlConfigConstant.ADDRESS_FAILOVER_ELEMENT_NAME + "] to be configed"); + } + + for (Iterator elementIterator = element.elementIterator(); elementIterator.hasNext();) { + Element childElement = elementIterator.next(); + + if (StringUtils.equals(childElement.getName(), XmlConfigConstant.VERSION_PREFER_ELEMENT_NAME)) { + String versionPreferValue = childElement.getTextTrim(); + strategyFailoverEntity.setVersionPreferValue(versionPreferValue); + } else if (StringUtils.equals(childElement.getName(), XmlConfigConstant.VERSION_FAILOVER_ELEMENT_NAME)) { + String versionFailoverValue = childElement.getTextTrim(); + strategyFailoverEntity.setVersionFailoverValue(versionFailoverValue); + } else if (StringUtils.equals(childElement.getName(), XmlConfigConstant.REGION_TRANSFER_ELEMENT_NAME)) { + String regionTransferValue = childElement.getTextTrim(); + strategyFailoverEntity.setRegionTransferValue(regionTransferValue); + } else if (StringUtils.equals(childElement.getName(), XmlConfigConstant.REGION_FAILOVER_ELEMENT_NAME)) { + String regionFailoverValue = childElement.getTextTrim(); + strategyFailoverEntity.setRegionFailoverValue(regionFailoverValue); + } else if (StringUtils.equals(childElement.getName(), XmlConfigConstant.ENVIRONMENT_FAILOVER_ELEMENT_NAME)) { + String environmentFailoverValue = childElement.getTextTrim(); + strategyFailoverEntity.setEnvironmentFailoverValue(environmentFailoverValue); + } else if (StringUtils.equals(childElement.getName(), XmlConfigConstant.ZONE_FAILOVER_ELEMENT_NAME)) { + String zoneFailoverValue = childElement.getTextTrim(); + strategyFailoverEntity.setZoneFailoverValue(zoneFailoverValue); + } else if (StringUtils.equals(childElement.getName(), XmlConfigConstant.ADDRESS_FAILOVER_ELEMENT_NAME)) { + String addressFailoverValue = childElement.getTextTrim(); + strategyFailoverEntity.setAddressFailoverValue(addressFailoverValue); + } + } + } + + private void parseStrategyBlacklist(Element element, StrategyBlacklistEntity strategyBlacklistEntity) { + int idElementCount = element.elements(XmlConfigConstant.ID_ELEMENT_NAME).size(); + if (idElementCount > 1) { + throw new DiscoveryException("Allow only one element[" + XmlConfigConstant.ID_ELEMENT_NAME + "] to be configed"); + } + + int addressElementCount = element.elements(XmlConfigConstant.ADDRESS_ELEMENT_NAME).size(); + if (addressElementCount > 1) { + throw new DiscoveryException("Allow only one element[" + XmlConfigConstant.ADDRESS_ELEMENT_NAME + "] to be configed"); + } + + for (Iterator elementIterator = element.elementIterator(); elementIterator.hasNext();) { + Element childElement = elementIterator.next(); + + if (StringUtils.equals(childElement.getName(), XmlConfigConstant.ID_ELEMENT_NAME)) { + String idValue = childElement.getTextTrim(); + strategyBlacklistEntity.setIdValue(idValue); + } else if (StringUtils.equals(childElement.getName(), XmlConfigConstant.ADDRESS_ELEMENT_NAME)) { + String addressValue = childElement.getTextTrim(); + strategyBlacklistEntity.setAddressValue(addressValue); + } + } + } + + private void parseParameter(Element element, ParameterEntity parameterEntity) { + Map> parameterServiceMap = parameterEntity.getParameterServiceMap(); + for (Iterator elementIterator = element.elementIterator(); elementIterator.hasNext();) { + Element childElement = elementIterator.next(); + + if (StringUtils.equals(childElement.getName(), XmlConfigConstant.SERVICE_ELEMENT_NAME)) { + Attribute serviceNameAttribute = childElement.attribute(XmlConfigConstant.SERVICE_NAME_ATTRIBUTE_NAME); + if (serviceNameAttribute == null) { + throw new DiscoveryException("Attribute[" + XmlConfigConstant.SERVICE_NAME_ATTRIBUTE_NAME + "] in element[" + childElement.getName() + "] is missing"); + } + String serviceName = serviceNameAttribute.getData().toString().trim(); + + ParameterServiceEntity parameterServiceEntity = new ParameterServiceEntity(); + + for (Iterator iterator = childElement.attributeIterator(); iterator.hasNext();) { + Attribute attribute = iterator.next(); + String key = attribute.getName(); + String value = attribute.getData().toString().trim(); + + parameterServiceEntity.getParameterMap().put(key, value); + } + + List parameterServiceEntityList = parameterServiceMap.get(serviceName); + if (parameterServiceEntityList == null) { + parameterServiceEntityList = new ArrayList(); + parameterServiceMap.put(serviceName, parameterServiceEntityList); + } + parameterServiceEntityList.add(parameterServiceEntity); + } + } + } + + private void parseHostFilter(Element element, String filterTypeValue, FilterHolderEntity filterHolderEntity) { + HostFilterEntity hostFilterEntity = filterHolderEntity.getHostFilterEntity(); + if (hostFilterEntity != null) { + throw new DiscoveryException("Allow only one filter element to be configed, [" + XmlConfigConstant.BLACKLIST_ELEMENT_NAME + "] or [" + XmlConfigConstant.WHITELIST_ELEMENT_NAME + "]"); + } + + hostFilterEntity = new HostFilterEntity(); + hostFilterEntity.setFilterType(FilterType.fromString(filterTypeValue)); + + Attribute globalFilterAttribute = element.attribute(XmlConfigConstant.FILTER_VALUE_ATTRIBUTE_NAME); + if (globalFilterAttribute != null) { + String globalFilterValue = globalFilterAttribute.getData().toString().trim(); + List globalFilterValueList = StringUtil.splitToList(globalFilterValue); + hostFilterEntity.setFilterValueList(globalFilterValueList); + } + + Map> filterMap = hostFilterEntity.getFilterMap(); + for (Iterator elementIterator = element.elementIterator(); elementIterator.hasNext();) { + Element childElement = elementIterator.next(); + + if (StringUtils.equals(childElement.getName(), XmlConfigConstant.SERVICE_ELEMENT_NAME)) { + Attribute serviceNameAttribute = childElement.attribute(XmlConfigConstant.SERVICE_NAME_ATTRIBUTE_NAME); + if (serviceNameAttribute == null) { + throw new DiscoveryException("Attribute[" + XmlConfigConstant.SERVICE_NAME_ATTRIBUTE_NAME + "] in element[" + childElement.getName() + "] is missing"); + } + String serviceName = serviceNameAttribute.getData().toString().trim(); + + Attribute filterValueAttribute = childElement.attribute(XmlConfigConstant.FILTER_VALUE_ATTRIBUTE_NAME); + List filterValueList = null; + if (filterValueAttribute != null) { + String filterValue = filterValueAttribute.getData().toString().trim(); + filterValueList = StringUtil.splitToList(filterValue); + } + filterMap.put(serviceName, filterValueList); + } + } + + filterHolderEntity.setHostFilterEntity(hostFilterEntity); + } + + private void parseCountFilter(Element element, RegisterEntity registerEntity) { + CountFilterEntity countFilterEntity = registerEntity.getCountFilterEntity(); + if (countFilterEntity != null) { + throw new DiscoveryException("Allow only one element[" + XmlConfigConstant.COUNT_ELEMENT_NAME + "] to be configed"); + } + + countFilterEntity = new CountFilterEntity(); + + Attribute globalFilterAttribute = element.attribute(XmlConfigConstant.FILTER_VALUE_ATTRIBUTE_NAME); + if (globalFilterAttribute != null) { + String globalFilterValue = globalFilterAttribute.getData().toString().trim(); + if (StringUtils.isNotEmpty(globalFilterValue)) { + Integer globalValue = null; + try { + globalValue = Integer.valueOf(globalFilterValue); + } catch (Exception e) { + throw new DiscoveryException("Attribute[" + XmlConfigConstant.FILTER_VALUE_ATTRIBUTE_NAME + "] value in element[" + element.getName() + "] is invalid, must be int type", e); + } + countFilterEntity.setFilterValue(globalValue); + } + } + + Map filterMap = countFilterEntity.getFilterMap(); + for (Iterator elementIterator = element.elementIterator(); elementIterator.hasNext();) { + Element childElement = elementIterator.next(); + + if (StringUtils.equals(childElement.getName(), XmlConfigConstant.SERVICE_ELEMENT_NAME)) { + Attribute serviceNameAttribute = childElement.attribute(XmlConfigConstant.SERVICE_NAME_ATTRIBUTE_NAME); + if (serviceNameAttribute == null) { + throw new DiscoveryException("Attribute[" + XmlConfigConstant.SERVICE_NAME_ATTRIBUTE_NAME + "] in element[" + childElement.getName() + "] is missing"); + } + String serviceName = serviceNameAttribute.getData().toString().trim(); + + Integer value = null; + Attribute filterValueAttribute = childElement.attribute(XmlConfigConstant.FILTER_VALUE_ATTRIBUTE_NAME); + if (filterValueAttribute != null) { + String filterValue = filterValueAttribute.getData().toString().trim(); + if (StringUtils.isNotEmpty(filterValue)) { + try { + value = Integer.valueOf(filterValue); + } catch (Exception e) { + throw new DiscoveryException("Attribute[" + XmlConfigConstant.FILTER_VALUE_ATTRIBUTE_NAME + "] value in element[" + childElement.getName() + "] is invalid, must be int type", e); + } + } + } + + filterMap.put(serviceName, value); + } + } + + registerEntity.setCountFilterEntity(countFilterEntity); + } + + private void parseVersionFilter(Element element, DiscoveryEntity discoveryEntity) { + VersionFilterEntity versionFilterEntity = discoveryEntity.getVersionFilterEntity(); + if (versionFilterEntity != null) { + throw new DiscoveryException("Allow only one element[" + XmlConfigConstant.VERSION_ELEMENT_NAME + "] to be configed"); + } + + versionFilterEntity = new VersionFilterEntity(); + + Map> versionEntityMap = versionFilterEntity.getVersionEntityMap(); + for (Iterator elementIterator = element.elementIterator(); elementIterator.hasNext();) { + Element childElement = elementIterator.next(); + + if (StringUtils.equals(childElement.getName(), XmlConfigConstant.SERVICE_ELEMENT_NAME)) { + VersionEntity versionEntity = new VersionEntity(); + + Attribute consumerServiceNameAttribute = childElement.attribute(XmlConfigConstant.CONSUMER_SERVICE_NAME_ATTRIBUTE_NAME); + if (consumerServiceNameAttribute == null) { + throw new DiscoveryException("Attribute[" + XmlConfigConstant.CONSUMER_SERVICE_NAME_ATTRIBUTE_NAME + "] in element[" + childElement.getName() + "] is missing"); + } + String consumerServiceName = consumerServiceNameAttribute.getData().toString().trim(); + versionEntity.setConsumerServiceName(consumerServiceName); + + Attribute providerServiceNameAttribute = childElement.attribute(XmlConfigConstant.PROVIDER_SERVICE_NAME_ATTRIBUTE_NAME); + if (providerServiceNameAttribute == null) { + throw new DiscoveryException("Attribute[" + XmlConfigConstant.PROVIDER_SERVICE_NAME_ATTRIBUTE_NAME + "] in element[" + childElement.getName() + "] is missing"); + } + String providerServiceName = providerServiceNameAttribute.getData().toString().trim(); + versionEntity.setProviderServiceName(providerServiceName); + + Attribute consumerVersionValueAttribute = childElement.attribute(XmlConfigConstant.CONSUMER_VERSION_VALUE_ATTRIBUTE_NAME); + if (consumerVersionValueAttribute != null) { + String consumerVersionValue = consumerVersionValueAttribute.getData().toString().trim(); + List consumerVersionValueList = StringUtil.splitToList(consumerVersionValue); + versionEntity.setConsumerVersionValueList(consumerVersionValueList); + } + + Attribute providerVersionValueAttribute = childElement.attribute(XmlConfigConstant.PROVIDER_VERSION_VALUE_ATTRIBUTE_NAME); + if (providerVersionValueAttribute != null) { + String providerVersionValue = providerVersionValueAttribute.getData().toString().trim(); + List providerVersionValueList = StringUtil.splitToList(providerVersionValue); + versionEntity.setProviderVersionValueList(providerVersionValueList); + } + + List versionEntityList = versionEntityMap.get(consumerServiceName); + if (versionEntityList == null) { + versionEntityList = new ArrayList(); + versionEntityMap.put(consumerServiceName, versionEntityList); + } + + versionEntityList.add(versionEntity); + } + } + + discoveryEntity.setVersionFilterEntity(versionFilterEntity); + } + + private void parseRegionFilter(Element element, DiscoveryEntity discoveryEntity) { + RegionFilterEntity regionFilterEntity = discoveryEntity.getRegionFilterEntity(); + if (regionFilterEntity != null) { + throw new DiscoveryException("Allow only one element[" + XmlConfigConstant.REGION_ELEMENT_NAME + "] to be configed"); + } + + regionFilterEntity = new RegionFilterEntity(); + + Map> regionEntityMap = regionFilterEntity.getRegionEntityMap(); + for (Iterator elementIterator = element.elementIterator(); elementIterator.hasNext();) { + Element childElement = elementIterator.next(); + + if (StringUtils.equals(childElement.getName(), XmlConfigConstant.SERVICE_ELEMENT_NAME)) { + RegionEntity regionEntity = new RegionEntity(); + + Attribute consumerServiceNameAttribute = childElement.attribute(XmlConfigConstant.CONSUMER_SERVICE_NAME_ATTRIBUTE_NAME); + if (consumerServiceNameAttribute == null) { + throw new DiscoveryException("Attribute[" + XmlConfigConstant.CONSUMER_SERVICE_NAME_ATTRIBUTE_NAME + "] in element[" + childElement.getName() + "] is missing"); + } + String consumerServiceName = consumerServiceNameAttribute.getData().toString().trim(); + regionEntity.setConsumerServiceName(consumerServiceName); + + Attribute providerServiceNameAttribute = childElement.attribute(XmlConfigConstant.PROVIDER_SERVICE_NAME_ATTRIBUTE_NAME); + if (providerServiceNameAttribute == null) { + throw new DiscoveryException("Attribute[" + XmlConfigConstant.PROVIDER_SERVICE_NAME_ATTRIBUTE_NAME + "] in element[" + childElement.getName() + "] is missing"); + } + String providerServiceName = providerServiceNameAttribute.getData().toString().trim(); + regionEntity.setProviderServiceName(providerServiceName); + + Attribute consumerRegionValueAttribute = childElement.attribute(XmlConfigConstant.CONSUMER_REGION_VALUE_ATTRIBUTE_NAME); + if (consumerRegionValueAttribute != null) { + String consumerRegionValue = consumerRegionValueAttribute.getData().toString().trim(); + List consumerRegionValueList = StringUtil.splitToList(consumerRegionValue); + regionEntity.setConsumerRegionValueList(consumerRegionValueList); + } + + Attribute providerRegionValueAttribute = childElement.attribute(XmlConfigConstant.PROVIDER_REGION_VALUE_ATTRIBUTE_NAME); + if (providerRegionValueAttribute != null) { + String providerRegionValue = providerRegionValueAttribute.getData().toString().trim(); + List providerRegionValueList = StringUtil.splitToList(providerRegionValue); + regionEntity.setProviderRegionValueList(providerRegionValueList); + } + + List regionEntityList = regionEntityMap.get(consumerServiceName); + if (regionEntityList == null) { + regionEntityList = new ArrayList(); + regionEntityMap.put(consumerServiceName, regionEntityList); + } + + regionEntityList.add(regionEntity); + } + } + + discoveryEntity.setRegionFilterEntity(regionFilterEntity); + } + + private void parseWeightFilter(Element element, DiscoveryEntity discoveryEntity) { + WeightFilterEntity weightFilterEntity = discoveryEntity.getWeightFilterEntity(); + if (weightFilterEntity != null) { + throw new DiscoveryException("Allow only one element[" + XmlConfigConstant.WEIGHT_ELEMENT_NAME + "] to be configed"); + } + + weightFilterEntity = new WeightFilterEntity(); + + Map> versionWeightEntityMap = new LinkedHashMap>(); + List versionWeightEntityList = new ArrayList(); + weightFilterEntity.setVersionWeightEntityMap(versionWeightEntityMap); + weightFilterEntity.setVersionWeightEntityList(versionWeightEntityList); + + Map> regionWeightEntityMap = new LinkedHashMap>(); + List regionWeightEntityList = new ArrayList(); + weightFilterEntity.setRegionWeightEntityMap(regionWeightEntityMap); + weightFilterEntity.setRegionWeightEntityList(regionWeightEntityList); + + for (Iterator elementIterator = element.elementIterator(); elementIterator.hasNext();) { + Element childElement = elementIterator.next(); + + if (StringUtils.equals(childElement.getName(), XmlConfigConstant.SERVICE_ELEMENT_NAME)) { + WeightEntity weightEntity = new WeightEntity(); + + Attribute typeAttribute = childElement.attribute(XmlConfigConstant.TYPE_ATTRIBUTE_NAME); + if (typeAttribute == null) { + throw new DiscoveryException("Attribute[" + XmlConfigConstant.TYPE_ATTRIBUTE_NAME + "] in element[" + childElement.getName() + "] is missing"); + } + String type = typeAttribute.getData().toString().trim(); + WeightType weightType = WeightType.fromString(type); + weightEntity.setType(weightType); + + Attribute consumerServiceNameAttribute = childElement.attribute(XmlConfigConstant.CONSUMER_SERVICE_NAME_ATTRIBUTE_NAME); + String consumerServiceName = null; + if (consumerServiceNameAttribute != null) { + consumerServiceName = consumerServiceNameAttribute.getData().toString().trim(); + } + weightEntity.setConsumerServiceName(consumerServiceName); + + Attribute providerServiceNameAttribute = childElement.attribute(XmlConfigConstant.PROVIDER_SERVICE_NAME_ATTRIBUTE_NAME); + if (providerServiceNameAttribute == null) { + throw new DiscoveryException("Attribute[" + XmlConfigConstant.PROVIDER_SERVICE_NAME_ATTRIBUTE_NAME + "] in element[" + childElement.getName() + "] is missing"); + } + String providerServiceName = providerServiceNameAttribute.getData().toString().trim(); + weightEntity.setProviderServiceName(providerServiceName); + + Attribute providerWeightValueAttribute = childElement.attribute(XmlConfigConstant.PROVIDER_WEIGHT_VALUE_ATTRIBUTE_NAME); + if (providerWeightValueAttribute == null) { + throw new DiscoveryException("Attribute[" + XmlConfigConstant.PROVIDER_WEIGHT_VALUE_ATTRIBUTE_NAME + "] in element[" + childElement.getName() + "] is missing"); + } + String providerWeightValue = providerWeightValueAttribute.getData().toString().trim(); + + WeightEntityWrapper.parseWeightEntity(weightEntity, providerWeightValue); + + if (StringUtils.isNotEmpty(consumerServiceName)) { + if (weightType == WeightType.VERSION) { + List list = versionWeightEntityMap.get(consumerServiceName); + if (list == null) { + list = new ArrayList(); + versionWeightEntityMap.put(consumerServiceName, list); + } + + list.add(weightEntity); + } else if (weightType == WeightType.REGION) { + List list = regionWeightEntityMap.get(consumerServiceName); + if (list == null) { + list = new ArrayList(); + regionWeightEntityMap.put(consumerServiceName, list); + } + + list.add(weightEntity); + } + } else { + if (weightType == WeightType.VERSION) { + versionWeightEntityList.add(weightEntity); + } else if (weightType == WeightType.REGION) { + regionWeightEntityList.add(weightEntity); + } + } + } else if (StringUtils.equals(childElement.getName(), XmlConfigConstant.VERSION_ELEMENT_NAME)) { + VersionWeightEntity versionWeightEntity = weightFilterEntity.getVersionWeightEntity(); + if (versionWeightEntity != null) { + throw new DiscoveryException("Allow only one element[" + XmlConfigConstant.VERSION_ELEMENT_NAME + "] to be configed"); + } + + versionWeightEntity = new VersionWeightEntity(); + + Attribute providerWeightValueAttribute = childElement.attribute(XmlConfigConstant.PROVIDER_WEIGHT_VALUE_ATTRIBUTE_NAME); + if (providerWeightValueAttribute == null) { + throw new DiscoveryException("Attribute[" + XmlConfigConstant.PROVIDER_WEIGHT_VALUE_ATTRIBUTE_NAME + "] in element[" + childElement.getName() + "] is missing"); + } + String providerWeightValue = providerWeightValueAttribute.getData().toString().trim(); + + WeightEntityWrapper.parseWeightEntity(versionWeightEntity, providerWeightValue); + + weightFilterEntity.setVersionWeightEntity(versionWeightEntity); + } else if (StringUtils.equals(childElement.getName(), XmlConfigConstant.REGION_ELEMENT_NAME)) { + RegionWeightEntity regionWeightEntity = weightFilterEntity.getRegionWeightEntity(); + if (regionWeightEntity != null) { + throw new DiscoveryException("Allow only one element[" + XmlConfigConstant.REGION_ELEMENT_NAME + "] to be configed"); + } + + regionWeightEntity = new RegionWeightEntity(); + + Attribute providerWeightValueAttribute = childElement.attribute(XmlConfigConstant.PROVIDER_WEIGHT_VALUE_ATTRIBUTE_NAME); + if (providerWeightValueAttribute == null) { + throw new DiscoveryException("Attribute[" + XmlConfigConstant.PROVIDER_WEIGHT_VALUE_ATTRIBUTE_NAME + "] in element[" + childElement.getName() + "] is missing"); + } + String providerWeightValue = providerWeightValueAttribute.getData().toString().trim(); + + WeightEntityWrapper.parseWeightEntity(regionWeightEntity, providerWeightValue); + + weightFilterEntity.setRegionWeightEntity(regionWeightEntity); + } + } + + discoveryEntity.setWeightFilterEntity(weightFilterEntity); + } + + private void parseStrategyConditionBlueGreen(Element element, StrategyReleaseEntity strategyReleaseEntity) { + List strategyConditionBlueGreenEntityList = strategyReleaseEntity.getStrategyConditionBlueGreenEntityList(); + if (strategyConditionBlueGreenEntityList != null) { + throw new DiscoveryException("Allow only one element[" + XmlConfigConstant.CONDITIONS_ELEMENT_NAME + "] for attribute[" + XmlConfigConstant.TYPE_ATTRIBUTE_NAME + "]'s value with '" + ConditionType.BLUE_GREEN + "' to be configed"); + } + + strategyConditionBlueGreenEntityList = new ArrayList(); + strategyReleaseEntity.setStrategyConditionBlueGreenEntityList(strategyConditionBlueGreenEntityList); + + for (Iterator elementIterator = element.elementIterator(); elementIterator.hasNext();) { + Element childElement = elementIterator.next(); + + if (StringUtils.equals(childElement.getName(), XmlConfigConstant.CONDITION_ELEMENT_NAME)) { + StrategyConditionBlueGreenEntity strategyConditionBlueGreenEntity = new StrategyConditionBlueGreenEntity(); + + Attribute idAttribute = childElement.attribute(XmlConfigConstant.ID_ATTRIBUTE_NAME); + if (idAttribute == null) { + throw new DiscoveryException("Attribute[" + XmlConfigConstant.ID_ATTRIBUTE_NAME + "] in element[" + childElement.getName() + "] is missing"); + } + String id = idAttribute.getData().toString().trim(); + strategyConditionBlueGreenEntity.setId(id); + + Attribute expressionAttribute = childElement.attribute(XmlConfigConstant.EXPRESSION_ATTRIBUTE_NAME); + Attribute headerAttribute = childElement.attribute(XmlConfigConstant.HEADER_ATTRIBUTE_NAME); + if (expressionAttribute != null && headerAttribute != null) { + throw new DiscoveryException("Attribute[" + XmlConfigConstant.EXPRESSION_ATTRIBUTE_NAME + "] and [" + XmlConfigConstant.HEADER_ATTRIBUTE_NAME + "] in element[" + childElement.getName() + "] are all configed, only one of them exists"); + } + + if (expressionAttribute != null) { + String expression = expressionAttribute.getData().toString().trim(); + strategyConditionBlueGreenEntity.setExpression(expression); + } + + if (headerAttribute != null) { + String expression = headerAttribute.getData().toString().trim(); + strategyConditionBlueGreenEntity.setExpression(expression); + } + + Attribute versionIdAttribute = childElement.attribute(XmlConfigConstant.VERSION_ELEMENT_NAME + DiscoveryConstant.DASH + XmlConfigConstant.ID_ATTRIBUTE_NAME); + if (versionIdAttribute != null) { + String versionId = versionIdAttribute.getData().toString().trim(); + strategyConditionBlueGreenEntity.setVersionId(versionId); + } + + Attribute regionIdAttribute = childElement.attribute(XmlConfigConstant.REGION_ELEMENT_NAME + DiscoveryConstant.DASH + XmlConfigConstant.ID_ATTRIBUTE_NAME); + if (regionIdAttribute != null) { + String regionId = regionIdAttribute.getData().toString().trim(); + strategyConditionBlueGreenEntity.setRegionId(regionId); + } + + Attribute addressIdAttribute = childElement.attribute(XmlConfigConstant.ADDRESS_ELEMENT_NAME + DiscoveryConstant.DASH + XmlConfigConstant.ID_ATTRIBUTE_NAME); + if (addressIdAttribute != null) { + String addressId = addressIdAttribute.getData().toString().trim(); + strategyConditionBlueGreenEntity.setAddressId(addressId); + } + + Attribute versionWeightIdAttribute = childElement.attribute(XmlConfigConstant.VERSION_WEIGHT_ELEMENT_NAME + DiscoveryConstant.DASH + XmlConfigConstant.ID_ATTRIBUTE_NAME); + if (versionWeightIdAttribute != null) { + String versionWeightId = versionWeightIdAttribute.getData().toString().trim(); + strategyConditionBlueGreenEntity.setVersionWeightId(versionWeightId); + } + + Attribute regionWeightIdAttribute = childElement.attribute(XmlConfigConstant.REGION_WEIGHT_ELEMENT_NAME + DiscoveryConstant.DASH + XmlConfigConstant.ID_ATTRIBUTE_NAME); + if (regionWeightIdAttribute != null) { + String regionWeightId = regionWeightIdAttribute.getData().toString().trim(); + strategyConditionBlueGreenEntity.setRegionWeightId(regionWeightId); + } + + strategyConditionBlueGreenEntityList.add(strategyConditionBlueGreenEntity); + } + } + } + + private void parseStrategyConditionGray(Element element, StrategyReleaseEntity strategyReleaseEntity) { + List strategyConditionGrayEntityList = strategyReleaseEntity.getStrategyConditionGrayEntityList(); + if (strategyConditionGrayEntityList != null) { + throw new DiscoveryException("Allow only one element[" + XmlConfigConstant.CONDITIONS_ELEMENT_NAME + "] for attribute[" + XmlConfigConstant.TYPE_ATTRIBUTE_NAME + "]'s value with '" + ConditionType.GRAY + "' to be configed"); + } + + strategyConditionGrayEntityList = new ArrayList(); + strategyReleaseEntity.setStrategyConditionGrayEntityList(strategyConditionGrayEntityList); + + for (Iterator elementIterator = element.elementIterator(); elementIterator.hasNext();) { + Element childElement = elementIterator.next(); + + if (StringUtils.equals(childElement.getName(), XmlConfigConstant.CONDITION_ELEMENT_NAME)) { + StrategyConditionGrayEntity strategyConditionGrayEntity = new StrategyConditionGrayEntity(); + + Attribute idAttribute = childElement.attribute(XmlConfigConstant.ID_ATTRIBUTE_NAME); + if (idAttribute == null) { + throw new DiscoveryException("Attribute[" + XmlConfigConstant.ID_ATTRIBUTE_NAME + "] in element[" + childElement.getName() + "] is missing"); + } + String id = idAttribute.getData().toString().trim(); + strategyConditionGrayEntity.setId(id); + + Attribute expressionAttribute = childElement.attribute(XmlConfigConstant.EXPRESSION_ATTRIBUTE_NAME); + Attribute headerAttribute = childElement.attribute(XmlConfigConstant.HEADER_ATTRIBUTE_NAME); + if (expressionAttribute != null && headerAttribute != null) { + throw new DiscoveryException("Attribute[" + XmlConfigConstant.EXPRESSION_ATTRIBUTE_NAME + "] and [" + XmlConfigConstant.HEADER_ATTRIBUTE_NAME + "] in element[" + childElement.getName() + "] are all configed, only one of them exists"); + } + + if (expressionAttribute != null) { + String expression = expressionAttribute.getData().toString().trim(); + strategyConditionGrayEntity.setExpression(expression); + } + + if (headerAttribute != null) { + String expression = headerAttribute.getData().toString().trim(); + strategyConditionGrayEntity.setExpression(expression); + } + + Attribute versionIdAttribute = childElement.attribute(XmlConfigConstant.VERSION_ELEMENT_NAME + DiscoveryConstant.DASH + XmlConfigConstant.ID_ATTRIBUTE_NAME); + if (versionIdAttribute != null) { + String versionId = versionIdAttribute.getData().toString().trim(); + VersionWeightEntity versionWeightEntity = new VersionWeightEntity(); + WeightEntityWrapper.parseWeightEntity(versionWeightEntity, versionId); + strategyConditionGrayEntity.setVersionWeightEntity(versionWeightEntity); + } + + Attribute regionIdAttribute = childElement.attribute(XmlConfigConstant.REGION_ELEMENT_NAME + DiscoveryConstant.DASH + XmlConfigConstant.ID_ATTRIBUTE_NAME); + if (regionIdAttribute != null) { + String regionId = regionIdAttribute.getData().toString().trim(); + RegionWeightEntity regionWeightEntity = new RegionWeightEntity(); + WeightEntityWrapper.parseWeightEntity(regionWeightEntity, regionId); + strategyConditionGrayEntity.setRegionWeightEntity(regionWeightEntity); + } + + Attribute addressIdAttribute = childElement.attribute(XmlConfigConstant.ADDRESS_ELEMENT_NAME + DiscoveryConstant.DASH + XmlConfigConstant.ID_ATTRIBUTE_NAME); + if (addressIdAttribute != null) { + String addressId = addressIdAttribute.getData().toString().trim(); + AddressWeightEntity addressWeightEntity = new AddressWeightEntity(); + WeightEntityWrapper.parseWeightEntity(addressWeightEntity, addressId); + strategyConditionGrayEntity.setAddressWeightEntity(addressWeightEntity); + } + + strategyConditionGrayEntityList.add(strategyConditionGrayEntity); + } + } + } + + private void parseStrategyRoute(Element element, StrategyReleaseEntity strategyReleaseEntity) { + List strategyRouteEntityList = strategyReleaseEntity.getStrategyRouteEntityList(); + if (strategyRouteEntityList != null) { + throw new DiscoveryException("Allow only one element[" + XmlConfigConstant.ROUTES_ELEMENT_NAME + "] to be configed"); + } + + strategyRouteEntityList = new ArrayList(); + strategyReleaseEntity.setStrategyRouteEntityList(strategyRouteEntityList); + + for (Iterator elementIterator = element.elementIterator(); elementIterator.hasNext();) { + Element childElement = elementIterator.next(); + + if (StringUtils.equals(childElement.getName(), XmlConfigConstant.ROUTE_ELEMENT_NAME)) { + StrategyRouteEntity strategyRouteEntity = new StrategyRouteEntity(); + + Attribute idAttribute = childElement.attribute(XmlConfigConstant.ID_ATTRIBUTE_NAME); + if (idAttribute == null) { + throw new DiscoveryException("Attribute[" + XmlConfigConstant.ID_ATTRIBUTE_NAME + "] in element[" + childElement.getName() + "] is missing"); + } + String id = idAttribute.getData().toString().trim(); + strategyRouteEntity.setId(id); + + Attribute typeAttribute = childElement.attribute(XmlConfigConstant.TYPE_ATTRIBUTE_NAME); + if (typeAttribute == null) { + throw new DiscoveryException("Attribute[" + XmlConfigConstant.TYPE_ATTRIBUTE_NAME + "] in element[" + childElement.getName() + "] is missing"); + } + String type = typeAttribute.getData().toString().trim(); + StrategyRouteType strategyRouteType = StrategyRouteType.fromString(type); + strategyRouteEntity.setType(strategyRouteType); + + String value = childElement.getTextTrim(); + strategyRouteEntity.setValue(value); + + strategyRouteEntityList.add(strategyRouteEntity); + } + } + } + + @SuppressWarnings("unchecked") + private void parseStrategyHeader(Element element, StrategyReleaseEntity strategyReleaseEntity) { + StrategyHeaderEntity strategyHeaderEntity = strategyReleaseEntity.getStrategyHeaderEntity(); + if (strategyHeaderEntity != null) { + throw new DiscoveryException("Allow only one element[" + XmlConfigConstant.HEADER_ELEMENT_NAME + "] to be configed"); + } + + strategyHeaderEntity = new StrategyHeaderEntity(); + strategyReleaseEntity.setStrategyHeaderEntity(strategyHeaderEntity); + + String headerValue = element.getTextTrim(); + + Map headerMap = JsonUtil.fromJson(headerValue, Map.class); + strategyHeaderEntity.getHeaderMap().putAll(headerMap); + } +} \ No newline at end of file diff --git a/discovery-plugin-framework/discovery-plugin-framework-starter-parser/src/main/resources/META-INF/spring.factories b/discovery-plugin-framework/discovery-plugin-framework-starter-parser/src/main/resources/META-INF/spring.factories new file mode 100644 index 0000000000..a4c4e88150 --- /dev/null +++ b/discovery-plugin-framework/discovery-plugin-framework-starter-parser/src/main/resources/META-INF/spring.factories @@ -0,0 +1,2 @@ +org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ +com.nepxion.discovery.plugin.framework.configuration.PluginParserAutoConfiguration \ No newline at end of file diff --git a/discovery-plugin-framework/discovery-plugin-framework-starter/pom.xml b/discovery-plugin-framework/discovery-plugin-framework-starter/pom.xml new file mode 100644 index 0000000000..d2952c55b5 --- /dev/null +++ b/discovery-plugin-framework/discovery-plugin-framework-starter/pom.xml @@ -0,0 +1,58 @@ + + + discovery-plugin-framework-starter + Nepxion Discovery Plugin Framework Starter + jar + 4.0.0 + Nepxion Discovery is a solution for Spring Cloud with blue green, gray, weight, limitation, circuit breaker, degrade, isolation, monitor, tracing, dye, failover, async agent + http://www.nepxion.com + + + com.nepxion + discovery-plugin-framework + 6.23.0 + + + + + ${project.groupId} + discovery-plugin-framework-starter-parser + + + + ${project.groupId} + eventbus-aop-starter + + + + ${project.groupId} + banner + + + + org.springframework.cloud + spring-cloud-starter + + + + org.springframework.cloud + spring-cloud-starter-netflix-ribbon + + + + com.google.guava + guava + + + + com.github.ben-manes.caffeine + caffeine + + + + com.alibaba.spring + spring-context-support + + + \ No newline at end of file diff --git a/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/adapter/AbstractPluginAdapter.java b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/adapter/AbstractPluginAdapter.java new file mode 100644 index 0000000000..becb21212b --- /dev/null +++ b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/adapter/AbstractPluginAdapter.java @@ -0,0 +1,629 @@ +package com.nepxion.discovery.plugin.framework.adapter; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.HashMap; +import java.util.Map; + +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.cloud.client.ServiceInstance; +import org.springframework.cloud.client.serviceregistry.Registration; + +import com.nepxion.discovery.common.constant.DiscoveryConstant; +import com.nepxion.discovery.common.constant.DiscoveryMetaDataConstant; +import com.nepxion.discovery.common.entity.RuleEntity; +import com.nepxion.discovery.common.entity.RuleEntityWrapper; +import com.nepxion.discovery.common.exception.DiscoveryException; +import com.nepxion.discovery.common.util.UrlUtil; +import com.nepxion.discovery.plugin.framework.cache.PluginCache; +import com.nepxion.discovery.plugin.framework.cache.RuleCache; +import com.nepxion.discovery.plugin.framework.context.PluginContextHolder; +import com.netflix.loadbalancer.Server; + +public abstract class AbstractPluginAdapter implements PluginAdapter { + @Autowired + protected Registration registration; + + @Autowired + protected PluginCache pluginCache; + + @Autowired(required = false) + protected PluginContextHolder pluginContextHolder; + + @Autowired + protected RuleCache ruleCache; + + @Value("${" + DiscoveryConstant.SPRING_APPLICATION_GROUP_KEY + ":" + DiscoveryConstant.GROUP + "}") + private String groupKey; + + @Value("${" + DiscoveryConstant.SPRING_APPLICATION_TYPE + ":" + DiscoveryConstant.UNKNOWN + "}") + private String applicationType; + + protected Map emptyMetadata = new HashMap(); + + @Override + public RuleEntity getRule() { + RuleEntity dynamicRuleEntity = getDynamicRule(); + if (dynamicRuleEntity != null) { + return dynamicRuleEntity; + } + + return getLocalRule(); + } + + @Override + public RuleEntity getLocalRule() { + return ruleCache.get(DiscoveryConstant.RULE); + } + + @Override + public void setLocalRule(RuleEntity ruleEntity) { + ruleCache.put(DiscoveryConstant.RULE, ruleEntity); + } + + @Override + public RuleEntity getDynamicRule() { + return ruleCache.get(DiscoveryConstant.DYNAMIC_RULE); + } + + @Override + public RuleEntity getDynamicPartialRule() { + return ruleCache.get(DiscoveryConstant.DYNAMIC_PARTIAL_RULE); + } + + @Override + public void setDynamicPartialRule(RuleEntity ruleEntity) { + ruleCache.put(DiscoveryConstant.DYNAMIC_PARTIAL_RULE, ruleEntity); + + assembleDynamicRule(); + } + + @Override + public void clearDynamicPartialRule() { + ruleCache.clear(DiscoveryConstant.DYNAMIC_PARTIAL_RULE); + + assembleDynamicRule(); + } + + @Override + public RuleEntity getDynamicGlobalRule() { + return ruleCache.get(DiscoveryConstant.DYNAMIC_GLOBAL_RULE); + } + + @Override + public void setDynamicGlobalRule(RuleEntity ruleEntity) { + ruleCache.put(DiscoveryConstant.DYNAMIC_GLOBAL_RULE, ruleEntity); + + assembleDynamicRule(); + } + + @Override + public void clearDynamicGlobalRule() { + ruleCache.clear(DiscoveryConstant.DYNAMIC_GLOBAL_RULE); + + assembleDynamicRule(); + } + + // 从动态全局规则和动态局部规则缓存组装出最终的动态规则 + private void assembleDynamicRule() { + RuleEntity dynamicPartialRule = getDynamicPartialRule(); + RuleEntity dynamicGlobalRule = getDynamicGlobalRule(); + + RuleEntity dynamicRule = RuleEntityWrapper.assemble(dynamicPartialRule, dynamicGlobalRule); + ruleCache.put(DiscoveryConstant.DYNAMIC_RULE, dynamicRule); + } + + @Override + public String getPlugin() { + String plugin = getMetadata().get(DiscoveryMetaDataConstant.SPRING_APPLICATION_DISCOVERY_PLUGIN); + if (StringUtils.isEmpty(plugin)) { + plugin = DiscoveryConstant.UNKNOWN; + } + + return plugin; + } + + @Override + public String getGroupKey() { + return groupKey; + } + + @Override + public String getGroup() { + String groupKey = getGroupKey(); + + String group = getGroup(groupKey); + if (StringUtils.isEmpty(group)) { + group = DiscoveryConstant.DEFAULT; + } + + return group; + } + + protected String getGroup(String groupKey) { + return getMetadata().get(groupKey); + } + + @Override + public String getServiceType() { + return applicationType; + } + + @Override + public String getServiceId() { + return registration.getServiceId().toLowerCase(); + } + + @Override + public String getServiceAppId() { + return getMetadata().get(DiscoveryMetaDataConstant.SPRING_APPLICATION_APP_ID); + } + + @Override + public String getServiceUUId() { + return getMetadata().get(DiscoveryMetaDataConstant.SPRING_APPLICATION_UUID); + } + + @Override + public String getVersion() { + String dynamicVersion = getDynamicVersion(); + if (StringUtils.isNotEmpty(dynamicVersion)) { + return dynamicVersion; + } + + return getLocalVersion(); + } + + @Override + public String getLocalVersion() { + String version = getMetadata().get(DiscoveryConstant.VERSION); + if (StringUtils.isEmpty(version)) { + version = DiscoveryConstant.DEFAULT; + } + + return version; + } + + @Override + public String getDynamicVersion() { + return pluginCache.get(DiscoveryConstant.DYNAMIC_VERSION); + } + + @Override + public void setDynamicVersion(String version) { + pluginCache.put(DiscoveryConstant.DYNAMIC_VERSION, version); + } + + @Override + public void clearDynamicVersion() { + pluginCache.clear(DiscoveryConstant.DYNAMIC_VERSION); + } + + @Override + public String getRegion() { + String region = getMetadata().get(DiscoveryConstant.REGION); + if (StringUtils.isEmpty(region)) { + region = DiscoveryConstant.DEFAULT; + } + + return region; + } + + @Override + public String getEnvironment() { + String environment = getMetadata().get(DiscoveryConstant.ENVIRONMENT); + if (StringUtils.isEmpty(environment)) { + environment = DiscoveryConstant.DEFAULT; + } + + return environment; + } + + @Override + public String getZone() { + String zone = getMetadata().get(DiscoveryConstant.ZONE); + if (StringUtils.isEmpty(zone)) { + zone = DiscoveryConstant.DEFAULT; + } + + return zone; + } + + @Override + public boolean isActive() { + String active = getMetadata().get(DiscoveryConstant.ACTIVE); + if (StringUtils.isEmpty(active)) { + return false; + } + + return Boolean.valueOf(active); + } + + @Override + public String getProtocol() { + String protocol = getMetadata().get(DiscoveryMetaDataConstant.SPRING_APPLICATION_PROTOCOL); + if (StringUtils.isEmpty(protocol)) { + protocol = "http"; + } + + return protocol; + } + + @Override + public String getContextPath() { + String contextPath = getMetadata().get(DiscoveryMetaDataConstant.SPRING_APPLICATION_CONTEXT_PATH); + if (StringUtils.isEmpty(contextPath)) { + contextPath = "/"; + } + + return contextPath; + } + + @Override + public String getFormatContextPath() { + String contextPath = getContextPath(); + + return UrlUtil.formatContextPath(contextPath); + } + + @Override + public String getHost() { + return registration.getHost(); + } + + @Override + public int getPort() { + return registration.getPort(); + } + + @Override + public Map getMetadata() { + return registration.getMetadata(); + } + + @Override + public String getServerPlugin(Server server) { + String plugin = getServerMetadata(server).get(DiscoveryMetaDataConstant.SPRING_APPLICATION_DISCOVERY_PLUGIN); + if (StringUtils.isEmpty(plugin)) { + plugin = DiscoveryConstant.UNKNOWN; + } + + return plugin; + } + + @Override + public String getServerGroupKey(Server server) { + String groupKey = getServerMetadata(server).get(DiscoveryMetaDataConstant.SPRING_APPLICATION_GROUP_KEY); + + if (StringUtils.isEmpty(groupKey)) { + groupKey = DiscoveryConstant.GROUP; + } + + return groupKey; + } + + @Override + public String getServerGroup(Server server) { + String serverGroupKey = getServerGroupKey(server); + + String serverGroup = getServerMetadata(server).get(serverGroupKey); + if (StringUtils.isEmpty(serverGroup)) { + serverGroup = DiscoveryConstant.DEFAULT; + } + + return serverGroup; + } + + @Override + public String getServerServiceType(Server server) { + return getServerMetadata(server).get(DiscoveryMetaDataConstant.SPRING_APPLICATION_TYPE); + } + + @Override + public String getServerServiceId(Server server) { + String serviceId = getServerMetadata(server).get(DiscoveryMetaDataConstant.SPRING_APPLICATION_NAME); + if (StringUtils.isEmpty(serviceId)) { + serviceId = server.getMetaInfo().getAppName(); + } + + if (StringUtils.isEmpty(serviceId)) { + throw new DiscoveryException("Server ServiceId is null"); + } + + return serviceId.toLowerCase(); + } + + @Override + public String getServerServiceAppId(Server server) { + return getServerMetadata(server).get(DiscoveryMetaDataConstant.SPRING_APPLICATION_APP_ID); + } + + @Override + public String getServerServiceUUId(Server server) { + return getServerMetadata(server).get(DiscoveryMetaDataConstant.SPRING_APPLICATION_UUID); + } + + @Override + public String getServerVersion(Server server) { + String serverVersion = getServerMetadata(server).get(DiscoveryConstant.VERSION); + if (StringUtils.isEmpty(serverVersion)) { + serverVersion = DiscoveryConstant.DEFAULT; + } + + return serverVersion; + } + + @Override + public String getServerRegion(Server server) { + String serverRegion = getServerMetadata(server).get(DiscoveryConstant.REGION); + if (StringUtils.isEmpty(serverRegion)) { + serverRegion = DiscoveryConstant.DEFAULT; + } + + return serverRegion; + } + + @Override + public String getServerEnvironment(Server server) { + String serverEnvironment = getServerMetadata(server).get(DiscoveryConstant.ENVIRONMENT); + if (StringUtils.isEmpty(serverEnvironment)) { + serverEnvironment = DiscoveryConstant.DEFAULT; + } + + return serverEnvironment; + } + + @Override + public String getServerZone(Server server) { + String serverZone = getServerMetadata(server).get(DiscoveryConstant.ZONE); + if (StringUtils.isEmpty(serverZone)) { + serverZone = DiscoveryConstant.DEFAULT; + } + + return serverZone; + } + + @Override + public boolean isServerActive(Server server) { + String active = getServerMetadata(server).get(DiscoveryConstant.ACTIVE); + if (StringUtils.isEmpty(active)) { + return false; + } + + return Boolean.valueOf(active); + } + + @Override + public String getServerProtocol(Server server) { + String protocol = getServerMetadata(server).get(DiscoveryMetaDataConstant.SPRING_APPLICATION_PROTOCOL); + if (StringUtils.isEmpty(protocol)) { + protocol = "http"; + } + + return protocol; + } + + @Override + public String getServerContextPath(Server server) { + String contextPath = getServerMetadata(server).get(DiscoveryMetaDataConstant.SPRING_APPLICATION_CONTEXT_PATH); + if (StringUtils.isEmpty(contextPath)) { + contextPath = "/"; + } + + return contextPath; + } + + @Override + public String getServerFormatContextPath(Server server) { + String contextPath = getServerContextPath(server); + + return UrlUtil.formatContextPath(contextPath); + } + + @Override + public String getInstancePlugin(ServiceInstance instance) { + String plugin = getInstanceMetadata(instance).get(DiscoveryMetaDataConstant.SPRING_APPLICATION_DISCOVERY_PLUGIN); + if (StringUtils.isEmpty(plugin)) { + plugin = DiscoveryConstant.UNKNOWN; + } + + return plugin; + } + + @Override + public String getInstanceGroupKey(ServiceInstance instance) { + String groupKey = getInstanceMetadata(instance).get(DiscoveryMetaDataConstant.SPRING_APPLICATION_GROUP_KEY); + + if (StringUtils.isEmpty(groupKey)) { + groupKey = DiscoveryConstant.GROUP; + } + + return groupKey; + } + + @Override + public String getInstanceGroup(ServiceInstance instance) { + String instanceGroupKey = getInstanceGroupKey(instance); + + String instanceGroup = getInstanceMetadata(instance).get(instanceGroupKey); + if (StringUtils.isEmpty(instanceGroup)) { + instanceGroup = DiscoveryConstant.DEFAULT; + } + + return instanceGroup; + } + + @Override + public String getInstanceServiceType(ServiceInstance instance) { + return getInstanceMetadata(instance).get(DiscoveryMetaDataConstant.SPRING_APPLICATION_TYPE); + } + + @Override + public String getInstanceServiceId(ServiceInstance instance) { + return instance.getServiceId().toLowerCase(); + } + + @Override + public String getInstanceServiceAppId(ServiceInstance instance) { + return getInstanceMetadata(instance).get(DiscoveryMetaDataConstant.SPRING_APPLICATION_APP_ID); + } + + @Override + public String getInstanceServiceUUId(ServiceInstance instance) { + return getInstanceMetadata(instance).get(DiscoveryMetaDataConstant.SPRING_APPLICATION_UUID); + } + + @Override + public String getInstanceVersion(ServiceInstance instance) { + String instanceVersion = getInstanceMetadata(instance).get(DiscoveryConstant.VERSION); + if (StringUtils.isEmpty(instanceVersion)) { + instanceVersion = DiscoveryConstant.DEFAULT; + } + + return instanceVersion; + } + + @Override + public String getInstanceRegion(ServiceInstance instance) { + String instanceRegion = getInstanceMetadata(instance).get(DiscoveryConstant.REGION); + if (StringUtils.isEmpty(instanceRegion)) { + instanceRegion = DiscoveryConstant.DEFAULT; + } + + return instanceRegion; + } + + @Override + public String getInstanceEnvironment(ServiceInstance instance) { + String instanceEnvironment = getInstanceMetadata(instance).get(DiscoveryConstant.ENVIRONMENT); + if (StringUtils.isEmpty(instanceEnvironment)) { + instanceEnvironment = DiscoveryConstant.DEFAULT; + } + + return instanceEnvironment; + } + + @Override + public String getInstanceZone(ServiceInstance instance) { + String instanceZone = getInstanceMetadata(instance).get(DiscoveryConstant.ZONE); + if (StringUtils.isEmpty(instanceZone)) { + instanceZone = DiscoveryConstant.DEFAULT; + } + + return instanceZone; + } + + @Override + public boolean isInstanceActive(ServiceInstance instance) { + String active = getInstanceMetadata(instance).get(DiscoveryConstant.ACTIVE); + if (StringUtils.isEmpty(active)) { + return false; + } + + return Boolean.valueOf(active); + } + + @Override + public String getInstanceProtocol(ServiceInstance instance) { + String protocol = getInstanceMetadata(instance).get(DiscoveryMetaDataConstant.SPRING_APPLICATION_PROTOCOL); + if (StringUtils.isEmpty(protocol)) { + protocol = "http"; + } + + return protocol; + } + + @Override + public String getInstanceContextPath(ServiceInstance instance) { + String contextPath = getInstanceMetadata(instance).get(DiscoveryMetaDataConstant.SPRING_APPLICATION_CONTEXT_PATH); + if (StringUtils.isEmpty(contextPath)) { + contextPath = "/"; + } + + return contextPath; + } + + @Override + public String getInstanceFormatContextPath(ServiceInstance instance) { + String contextPath = getInstanceContextPath(instance); + + return UrlUtil.formatContextPath(contextPath); + } + + @Override + public Map getInstanceMetadata(ServiceInstance instance) { + return instance.getMetadata(); + } + + @Override + public String getPluginInfo(String previousPluginInfo) { + String plugin = getPlugin(); + String serviceId = getServiceId(); + String serviceUUId = getServiceUUId(); + String serviceAppId = getServiceAppId(); + String serviceType = getServiceType(); + String host = getHost(); + int port = getPort(); + String version = getVersion(); + String region = getRegion(); + String environment = getEnvironment(); + String zone = getZone(); + String group = getGroup(); + boolean active = isActive(); + + StringBuilder stringBuilder = new StringBuilder(); + if (StringUtils.isNotEmpty(previousPluginInfo)) { + stringBuilder.append(previousPluginInfo + " -> "); + } + + stringBuilder.append("[ID=" + serviceId + "]"); + if (StringUtils.isNotEmpty(serviceUUId)) { + stringBuilder.append("[UID=" + serviceUUId + "]"); + } + if (StringUtils.isNotEmpty(serviceAppId)) { + stringBuilder.append("[AID=" + serviceAppId + "]"); + } + stringBuilder.append("[T=" + serviceType + "]"); + stringBuilder.append("[P=" + plugin + "]"); + stringBuilder.append("[H=" + host + ":" + port + "]"); + if (StringUtils.isNotEmpty(version)) { + stringBuilder.append("[V=" + version + "]"); + } + if (StringUtils.isNotEmpty(region)) { + stringBuilder.append("[R=" + region + "]"); + } + if (StringUtils.isNotEmpty(environment)) { + stringBuilder.append("[E=" + environment + "]"); + } + if (StringUtils.isNotEmpty(zone)) { + stringBuilder.append("[Z=" + zone + "]"); + } + if (StringUtils.isNotEmpty(group)) { + stringBuilder.append("[G=" + group + "]"); + } + stringBuilder.append("[A=" + active + "]"); + + if (pluginContextHolder != null) { + String traceId = pluginContextHolder.getTraceId(); + if (StringUtils.isNotEmpty(traceId)) { + stringBuilder.append("[TID=" + traceId + "]"); + } + + String spanId = pluginContextHolder.getSpanId(); + if (StringUtils.isNotEmpty(spanId)) { + stringBuilder.append("[SID=" + spanId + "]"); + } + } + + return stringBuilder.toString(); + } +} \ No newline at end of file diff --git a/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/adapter/ApplicationInfoAdapter.java b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/adapter/ApplicationInfoAdapter.java new file mode 100644 index 0000000000..5a44886d85 --- /dev/null +++ b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/adapter/ApplicationInfoAdapter.java @@ -0,0 +1,14 @@ +package com.nepxion.discovery.plugin.framework.adapter; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +public interface ApplicationInfoAdapter { + String getAppId(); +} \ No newline at end of file diff --git a/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/adapter/PluginAdapter.java b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/adapter/PluginAdapter.java new file mode 100644 index 0000000000..f746fd4d4c --- /dev/null +++ b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/adapter/PluginAdapter.java @@ -0,0 +1,149 @@ +package com.nepxion.discovery.plugin.framework.adapter; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.Map; + +import org.springframework.cloud.client.ServiceInstance; + +import com.nepxion.discovery.common.entity.RuleEntity; +import com.netflix.loadbalancer.Server; + +public interface PluginAdapter { + RuleEntity getRule(); + + RuleEntity getLocalRule(); + + void setLocalRule(RuleEntity ruleEntity); + + RuleEntity getDynamicRule(); + + RuleEntity getDynamicPartialRule(); + + void setDynamicPartialRule(RuleEntity ruleEntity); + + void clearDynamicPartialRule(); + + RuleEntity getDynamicGlobalRule(); + + void setDynamicGlobalRule(RuleEntity ruleEntity); + + void clearDynamicGlobalRule(); + + String getPlugin(); + + String getGroupKey(); + + String getGroup(); + + String getServiceType(); + + String getServiceId(); + + String getServiceAppId(); + + String getServiceUUId(); + + String getVersion(); + + String getLocalVersion(); + + String getDynamicVersion(); + + void setDynamicVersion(String version); + + void clearDynamicVersion(); + + String getRegion(); + + String getEnvironment(); + + String getZone(); + + boolean isActive(); + + String getProtocol(); + + String getContextPath(); + + String getFormatContextPath(); + + String getHost(); + + int getPort(); + + Map getMetadata(); + + String getServerPlugin(Server server); + + String getServerGroupKey(Server server); + + String getServerGroup(Server server); + + String getServerServiceType(Server server); + + String getServerServiceId(Server server); + + String getServerServiceAppId(Server server); + + String getServerServiceUUId(Server server); + + String getServerVersion(Server server); + + String getServerRegion(Server server); + + String getServerEnvironment(Server server); + + String getServerZone(Server server); + + boolean isServerActive(Server server); + + String getServerProtocol(Server server); + + String getServerContextPath(Server server); + + String getServerFormatContextPath(Server server); + + Map getServerMetadata(Server server); + + String getInstancePlugin(ServiceInstance instance); + + String getInstanceGroupKey(ServiceInstance instance); + + String getInstanceGroup(ServiceInstance instance); + + String getInstanceServiceType(ServiceInstance instance); + + String getInstanceServiceId(ServiceInstance instance); + + String getInstanceServiceAppId(ServiceInstance instance); + + String getInstanceServiceUUId(ServiceInstance instance); + + String getInstanceVersion(ServiceInstance instance); + + String getInstanceRegion(ServiceInstance instance); + + String getInstanceEnvironment(ServiceInstance instance); + + String getInstanceZone(ServiceInstance instance); + + boolean isInstanceActive(ServiceInstance instance); + + String getInstanceProtocol(ServiceInstance instance); + + String getInstanceContextPath(ServiceInstance instance); + + String getInstanceFormatContextPath(ServiceInstance instance); + + Map getInstanceMetadata(ServiceInstance instance); + + String getPluginInfo(String previousPluginInfo); +} \ No newline at end of file diff --git a/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/adapter/PluginConfigAdapter.java b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/adapter/PluginConfigAdapter.java new file mode 100644 index 0000000000..b69549bb0d --- /dev/null +++ b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/adapter/PluginConfigAdapter.java @@ -0,0 +1,16 @@ +package com.nepxion.discovery.plugin.framework.adapter; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import com.nepxion.discovery.common.entity.ConfigType; + +public interface PluginConfigAdapter { + ConfigType getConfigType(); +} \ No newline at end of file diff --git a/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/cache/PluginCache.java b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/cache/PluginCache.java similarity index 100% rename from discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/cache/PluginCache.java rename to discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/cache/PluginCache.java diff --git a/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/cache/RuleCache.java b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/cache/RuleCache.java similarity index 100% rename from discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/cache/RuleCache.java rename to discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/cache/RuleCache.java diff --git a/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/configuration/PluginAutoConfiguration.java b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/configuration/PluginAutoConfiguration.java new file mode 100644 index 0000000000..719ad3ddf6 --- /dev/null +++ b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/configuration/PluginAutoConfiguration.java @@ -0,0 +1,227 @@ +package com.nepxion.discovery.plugin.framework.configuration; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.cloud.client.loadbalancer.LoadBalanced; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.client.RestTemplate; + +import com.nepxion.discovery.common.constant.DiscoveryConstant; +import com.nepxion.discovery.common.entity.WeightFilterEntity; +import com.nepxion.discovery.common.entity.WeightRandomType; +import com.nepxion.discovery.plugin.framework.adapter.PluginAdapter; +import com.nepxion.discovery.plugin.framework.cache.PluginCache; +import com.nepxion.discovery.plugin.framework.cache.RuleCache; +import com.nepxion.discovery.plugin.framework.context.PluginContextAware; +import com.nepxion.discovery.plugin.framework.context.PluginContextHolder; +import com.nepxion.discovery.plugin.framework.event.PluginEventWapper; +import com.nepxion.discovery.plugin.framework.event.PluginPublisher; +import com.nepxion.discovery.plugin.framework.event.PluginSubscriber; +import com.nepxion.discovery.plugin.framework.generator.GitGenerator; +import com.nepxion.discovery.plugin.framework.generator.GroupGenerator; +import com.nepxion.discovery.plugin.framework.listener.discovery.DiscoveryListenerExecutor; +import com.nepxion.discovery.plugin.framework.listener.discovery.HostFilterDiscoveryListener; +import com.nepxion.discovery.plugin.framework.listener.discovery.RegionFilterDiscoveryListener; +import com.nepxion.discovery.plugin.framework.listener.discovery.VersionFilterDiscoveryListener; +import com.nepxion.discovery.plugin.framework.listener.loadbalance.HostFilterLoadBalanceListener; +import com.nepxion.discovery.plugin.framework.listener.loadbalance.LoadBalanceListenerExecutor; +import com.nepxion.discovery.plugin.framework.listener.loadbalance.NotificationLoadBalanceListener; +import com.nepxion.discovery.plugin.framework.listener.loadbalance.RegionFilterLoadBalanceListener; +import com.nepxion.discovery.plugin.framework.listener.loadbalance.VersionFilterLoadBalanceListener; +import com.nepxion.discovery.plugin.framework.listener.register.CountFilterRegisterListener; +import com.nepxion.discovery.plugin.framework.listener.register.HostFilterRegisterListener; +import com.nepxion.discovery.plugin.framework.listener.register.RegisterListenerExecutor; +import com.nepxion.discovery.plugin.framework.loadbalance.weight.ArrayWeightRandomProcessor; +import com.nepxion.discovery.plugin.framework.loadbalance.weight.MapWeightRandomProcessor; +import com.nepxion.discovery.plugin.framework.loadbalance.weight.RuleArrayWeightRandomLoadBalance; +import com.nepxion.discovery.plugin.framework.loadbalance.weight.RuleMapWeightRandomLoadBalance; +import com.nepxion.discovery.plugin.framework.loadbalance.weight.RuleWeightRandomLoadBalance; +import com.nepxion.discovery.plugin.framework.loadbalance.weight.StrategyArrayWeightRandomLoadBalance; +import com.nepxion.discovery.plugin.framework.loadbalance.weight.StrategyMapWeightRandomLoadBalance; +import com.nepxion.discovery.plugin.framework.loadbalance.weight.StrategyWeightRandomLoadBalance; +import com.nepxion.discovery.plugin.framework.loadbalance.weight.WeightRandomProcessor; +import com.nepxion.eventbus.annotation.EnableEventBus; + +@Configuration +@EnableEventBus +public class PluginAutoConfiguration { + @Value("${" + DiscoveryConstant.SPRING_APPLICATION_WEIGHT_RANDOM_TYPE + ":" + DiscoveryConstant.MAP_WEIGHT_RANDOM + "}") + private String weightRandomType; + + @Bean + @LoadBalanced + public RestTemplate pluginRestTemplate() { + return new RestTemplate(); + } + + @Bean + public PluginContextAware pluginContextAware() { + return new PluginContextAware(); + } + + @Bean + public PluginPublisher pluginPublisher() { + return new PluginPublisher(); + } + + @Bean + public PluginSubscriber pluginSubscriber() { + return new PluginSubscriber(); + } + + @Bean + public PluginEventWapper pluginEventWapper() { + return new PluginEventWapper(); + } + + @Bean + public PluginCache pluginCache() { + return new PluginCache(); + } + + @Bean + public RuleCache ruleCache() { + return new RuleCache(); + } + + @Bean + @ConditionalOnMissingBean + public RuleWeightRandomLoadBalance ruleWeightRandomLoadBalance(PluginAdapter pluginAdapter) { + WeightRandomType type = WeightRandomType.fromString(weightRandomType); + + switch (type) { + case MAP_WEIGHT_RANDOM: + return new RuleMapWeightRandomLoadBalance(pluginAdapter); + case ARRAY_WEIGHT_RANDOM: + return new RuleArrayWeightRandomLoadBalance(pluginAdapter); + } + + return null; + } + + @Bean + @ConditionalOnMissingBean + public StrategyWeightRandomLoadBalance strategyWeightRandomLoadBalance(PluginAdapter pluginAdapter, @Autowired(required = false) PluginContextHolder pluginContextHolder) { + WeightRandomType type = WeightRandomType.fromString(weightRandomType); + + switch (type) { + case MAP_WEIGHT_RANDOM: + return new StrategyMapWeightRandomLoadBalance(pluginAdapter, pluginContextHolder); + case ARRAY_WEIGHT_RANDOM: + return new StrategyArrayWeightRandomLoadBalance(pluginAdapter, pluginContextHolder); + } + + return null; + } + + @Bean + @ConditionalOnMissingBean + public WeightRandomProcessor strategyWeightRandomProcessor() { + WeightRandomType type = WeightRandomType.fromString(weightRandomType); + + switch (type) { + case MAP_WEIGHT_RANDOM: + return new MapWeightRandomProcessor(); + case ARRAY_WEIGHT_RANDOM: + return new ArrayWeightRandomProcessor(); + } + + return null; + } + + @Bean + public RegisterListenerExecutor registerListenerExecutor() { + return new RegisterListenerExecutor(); + } + + @Bean + public DiscoveryListenerExecutor discoveryListenerExecutor() { + return new DiscoveryListenerExecutor(); + } + + @Bean + public LoadBalanceListenerExecutor loadBalanceListenerExecutor() { + return new LoadBalanceListenerExecutor(); + } + + @Bean + @ConditionalOnMissingBean + public HostFilterRegisterListener hostFilterRegisterListener() { + return new HostFilterRegisterListener(); + } + + @Bean + @ConditionalOnMissingBean + public CountFilterRegisterListener countFilterRegisterListener() { + return new CountFilterRegisterListener(); + } + + @Bean + @ConditionalOnMissingBean + public HostFilterDiscoveryListener hostFilterDiscoveryListener() { + return new HostFilterDiscoveryListener(); + } + + @Bean + @ConditionalOnMissingBean + public VersionFilterDiscoveryListener versionFilterDiscoveryListener() { + return new VersionFilterDiscoveryListener(); + } + + @Bean + @ConditionalOnMissingBean + public RegionFilterDiscoveryListener regionFilterDiscoveryListener() { + return new RegionFilterDiscoveryListener(); + } + + @Bean + @ConditionalOnMissingBean + public HostFilterLoadBalanceListener hostFilterLoadBalanceListener() { + return new HostFilterLoadBalanceListener(); + } + + @Bean + @ConditionalOnMissingBean + public VersionFilterLoadBalanceListener versionFilterLoadBalanceListener() { + return new VersionFilterLoadBalanceListener(); + } + + @Bean + @ConditionalOnMissingBean + public RegionFilterLoadBalanceListener regionFilterLoadBalanceListener() { + return new RegionFilterLoadBalanceListener(); + } + + @Bean + @ConditionalOnMissingBean + @ConditionalOnProperty(value = DiscoveryConstant.SPRING_APPLICATION_NO_SERVERS_NOTIFY_ENABLED, matchIfMissing = false) + public NotificationLoadBalanceListener notificationLoadBalanceListener() { + return new NotificationLoadBalanceListener(); + } + + @Bean + @ConditionalOnMissingBean + @ConditionalOnProperty(value = DiscoveryConstant.SPRING_APPLICATION_GROUP_GENERATOR_ENABLED, matchIfMissing = false) + public GroupGenerator groupGenerator() { + return new GroupGenerator(); + } + + @Bean + @ConditionalOnMissingBean + @ConditionalOnProperty(value = DiscoveryConstant.SPRING_APPLICATION_GIT_GENERATOR_ENABLED, matchIfMissing = false) + public GitGenerator gitGenerator() { + return new GitGenerator(); + } +} \ No newline at end of file diff --git a/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/configuration/PluginLoadBalanceConfiguration.java b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/configuration/PluginLoadBalanceConfiguration.java similarity index 100% rename from discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/configuration/PluginLoadBalanceConfiguration.java rename to discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/configuration/PluginLoadBalanceConfiguration.java diff --git a/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/context/PluginApplicationContextInitializer.java b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/context/PluginApplicationContextInitializer.java new file mode 100644 index 0000000000..03f146c7a6 --- /dev/null +++ b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/context/PluginApplicationContextInitializer.java @@ -0,0 +1,138 @@ +package com.nepxion.discovery.plugin.framework.context; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.io.IOException; +import java.util.Map; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.BeansException; +import org.springframework.beans.factory.config.SmartInstantiationAwareBeanPostProcessor; +import org.springframework.cloud.client.discovery.DiscoveryClient; +import org.springframework.context.ApplicationContextInitializer; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.core.Ordered; +import org.springframework.core.env.ConfigurableEnvironment; + +import com.nepxion.banner.BannerConstant; +import com.nepxion.banner.Description; +import com.nepxion.banner.LogoBanner; +import com.nepxion.banner.NepxionBanner; +import com.nepxion.discovery.common.constant.DiscoveryConstant; +import com.nepxion.discovery.common.entity.LoadBalancerType; +import com.nepxion.discovery.common.property.DiscoveryProperties; +import com.nepxion.discovery.plugin.framework.decorator.DiscoveryClientDecorator; +import com.nepxion.discovery.plugin.framework.generator.GitGenerator; +import com.nepxion.discovery.plugin.framework.generator.GroupGenerator; +import com.taobao.text.Color; + +public abstract class PluginApplicationContextInitializer implements ApplicationContextInitializer, Ordered { + private static final Logger LOG = LoggerFactory.getLogger(PluginApplicationContextInitializer.class); + + @Override + public void initialize(ConfigurableApplicationContext applicationContext) { + if (!(applicationContext instanceof AnnotationConfigApplicationContext)) { + /*String bannerShown = System.getProperty(BannerConstant.BANNER_SHOWN, "true"); + if (Boolean.valueOf(bannerShown)) { + System.out.println(""); + System.out.println("╔═══╗"); + System.out.println("╚╗╔╗║"); + System.out.println(" ║║║╠╦══╦══╦══╦╗╔╦══╦═╦╗ ╔╗"); + System.out.println(" ║║║╠╣══╣╔═╣╔╗║╚╝║║═╣╔╣║ ║║"); + System.out.println("╔╝╚╝║╠══║╚═╣╚╝╠╗╔╣║═╣║║╚═╝║"); + System.out.println("╚═══╩╩══╩══╩══╝╚╝╚══╩╝╚═╗╔╝"); + System.out.println(" ╔═╝║"); + System.out.println(" ╚══╝"); + System.out.println("Nepxion Discovery v" + DiscoveryConstant.DISCOVERY_VERSION); + System.out.println(""); + }*/ + + LogoBanner logoBanner = new LogoBanner(PluginApplicationContextInitializer.class, "/com/nepxion/discovery/resource/logo.txt", "Welcome to Nepxion", 9, 5, new Color[] { Color.red, Color.green, Color.cyan, Color.blue, Color.yellow, Color.magenta, Color.red, Color.green, Color.cyan }, true); + + NepxionBanner.show(logoBanner, new Description(BannerConstant.VERSION + ":", DiscoveryConstant.DISCOVERY_VERSION, 0, 1), new Description(BannerConstant.GITHUB + ":", BannerConstant.NEPXION_GITHUB + "/Discovery", 0, 1)); + + logoBanner = new LogoBanner(PluginApplicationContextInitializer.class, "/com/nepxion/ribbon/resource/logo.txt", "Welcome to Nepxion", 6, 5, new Color[] { Color.red, Color.green, Color.cyan, Color.blue, Color.yellow, Color.magenta }, true); + + NepxionBanner.show(logoBanner, new Description("LoadBalancer:", LoadBalancerType.RIBBON.toString(), 0, 1), new Description(BannerConstant.GITHUB + ":", BannerConstant.NEPXION_GITHUB + "/Discovery", 0, 1)); + + initializeDefaultProperties(applicationContext); + } + + applicationContext.getBeanFactory().addBeanPostProcessor(new SmartInstantiationAwareBeanPostProcessor() { + @Override + public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { + if (bean instanceof DiscoveryClient) { + DiscoveryClient discoveryClient = (DiscoveryClient) bean; + + return new DiscoveryClientDecorator(discoveryClient, applicationContext); + } else { + return afterInitialization(applicationContext, bean, beanName); + } + } + }); + } + + private void initializeDefaultProperties(ConfigurableApplicationContext applicationContext) { + ConfigurableEnvironment environment = applicationContext.getEnvironment(); + String path = PluginContextAware.getDefaultPropertiesPath(environment); + + try { + DiscoveryProperties properties = new DiscoveryProperties(path, DiscoveryConstant.ENCODING_GBK, DiscoveryConstant.ENCODING_UTF_8); + Map propertiesMap = properties.getMap(); + for (Map.Entry entry : propertiesMap.entrySet()) { + String key = entry.getKey(); + String value = entry.getValue(); + // 如果已经设置,则尊重已经设置的值 + if (environment.getProperty(key) == null && System.getProperty(key) == null && System.getenv(key.toUpperCase()) == null) { + System.setProperty(key, value); + } + } + + LOG.info("{} is loaded...", path); + } catch (IOException e) { + + } + } + + protected String getPrefixGroup(ConfigurableApplicationContext applicationContext) { + ConfigurableEnvironment environment = applicationContext.getEnvironment(); + + Boolean isGroupGeneratorEnabled = PluginContextAware.isGroupGeneratorEnabled(environment); + if (isGroupGeneratorEnabled) { + GroupGenerator groupGenerator = applicationContext.getBean(GroupGenerator.class); + + return groupGenerator.getGroup(); + } + + return null; + } + + protected String getGitVersion(ConfigurableApplicationContext applicationContext) { + ConfigurableEnvironment environment = applicationContext.getEnvironment(); + + Boolean isGitGeneratorEnabled = PluginContextAware.isGitGeneratorEnabled(environment); + if (isGitGeneratorEnabled) { + GitGenerator gitGenerator = applicationContext.getBean(GitGenerator.class); + + return gitGenerator.getVersion(); + } + + return null; + } + + @Override + public int getOrder() { + return Ordered.HIGHEST_PRECEDENCE + 1; + } + + protected abstract Object afterInitialization(ConfigurableApplicationContext applicationContext, Object bean, String beanName) throws BeansException; +} \ No newline at end of file diff --git a/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/context/PluginContextAware.java b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/context/PluginContextAware.java new file mode 100644 index 0000000000..a7dbb49906 --- /dev/null +++ b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/context/PluginContextAware.java @@ -0,0 +1,222 @@ +package com.nepxion.discovery.plugin.framework.context; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @author Robin.G + * @version 1.0 + */ + +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.BeansException; +import org.springframework.beans.factory.NoSuchBeanDefinitionException; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ApplicationContextAware; +import org.springframework.core.ResolvableType; +import org.springframework.core.env.Environment; + +import com.nepxion.discovery.common.constant.DiscoveryConstant; + +public class PluginContextAware implements ApplicationContextAware { + private ApplicationContext applicationContext; + private Environment environment; + + private static ApplicationContext staticApplicationContext; + private static Environment staticEnvironment; + + @Override + public void setApplicationContext(ApplicationContext applicationContext) { + this.applicationContext = applicationContext; + this.environment = applicationContext.getEnvironment(); + + staticApplicationContext = applicationContext; + staticEnvironment = applicationContext.getEnvironment(); + } + + public Object getBean(String name) throws BeansException { + return applicationContext.getBean(name); + } + + public T getBean(String name, Class requiredType) throws BeansException { + return applicationContext.getBean(name, requiredType); + } + + public Object getBean(String name, Object... args) throws BeansException { + return applicationContext.getBean(name, args); + } + + public T getBean(Class requiredType) throws BeansException { + return applicationContext.getBean(requiredType); + } + + public T getBean(Class requiredType, Object... args) throws BeansException { + return applicationContext.getBean(requiredType, args); + } + + public boolean containsBean(String name) { + return applicationContext.containsBean(name); + } + + public boolean isSingleton(String name) throws NoSuchBeanDefinitionException { + return applicationContext.isSingleton(name); + } + + public boolean isPrototype(String name) throws NoSuchBeanDefinitionException { + return applicationContext.isPrototype(name); + } + + public boolean isTypeMatch(String name, ResolvableType typeToMatch) throws NoSuchBeanDefinitionException { + return applicationContext.isTypeMatch(name, typeToMatch); + } + + public boolean isTypeMatch(String name, Class typeToMatch) throws NoSuchBeanDefinitionException { + return applicationContext.isTypeMatch(name, typeToMatch); + } + + public Class getType(String name) throws NoSuchBeanDefinitionException { + return applicationContext.getType(name); + } + + public String[] getAliases(String name) { + return applicationContext.getAliases(name); + } + + public ApplicationContext getApplicationContext() { + return applicationContext; + } + + public Environment getEnvironment() { + return environment; + } + + public static ApplicationContext getStaticApplicationContext() { + return staticApplicationContext; + } + + public static Environment getStaticEnvironment() { + return staticEnvironment; + } + + public String getConfigFormat() { + return getConfigFormat(environment); + } + + public String getConfigPath() { + return getConfigPath(environment); + } + + public String getApplicationName() { + return getApplicationName(environment); + } + + public String getApplicationType() { + return getApplicationType(environment); + } + + public String getApplicationUUId() { + return getApplicationUUId(environment); + } + + public String getGroupKey() { + return getGroupKey(environment); + } + + public String getDefaultPropertiesPath() { + return getDefaultPropertiesPath(environment); + } + + public Boolean isGroupGeneratorEnabled() { + return isGroupGeneratorEnabled(environment); + } + + public Integer getGroupGeneratorLength() { + return getGroupGeneratorLength(environment); + } + + public String getGroupGeneratorCharacter() { + return getGroupGeneratorCharacter(environment); + } + + public Boolean isGitGeneratorEnabled() { + return isGitGeneratorEnabled(environment); + } + + public String getGitGeneratorPath() { + return getGitGeneratorPath(environment); + } + + public String getGitVersionKey() { + return getGitVersionKey(environment); + } + + public String getContextPath() { + return getContextPath(environment); + } + + public static String getConfigFormat(Environment environment) { + return environment.getProperty(DiscoveryConstant.SPRING_APPLICATION_CONFIG_FORMAT, String.class, DiscoveryConstant.XML_FORMAT); + } + + public static String getConfigPath(Environment environment) { + return environment.getProperty(DiscoveryConstant.SPRING_APPLICATION_CONFIG_PATH, String.class, StringUtils.equals(getConfigFormat(environment), DiscoveryConstant.XML_FORMAT) ? DiscoveryConstant.PREFIX_CLASSPATH + DiscoveryConstant.RULE + "." + DiscoveryConstant.XML_FORMAT : DiscoveryConstant.PREFIX_CLASSPATH + DiscoveryConstant.RULE + "." + DiscoveryConstant.JSON_FORMAT); + } + + public static String getApplicationName(Environment environment) { + return environment.getProperty(DiscoveryConstant.SPRING_APPLICATION_NAME, String.class, DiscoveryConstant.UNKNOWN); + } + + public static String getApplicationType(Environment environment) { + return environment.getProperty(DiscoveryConstant.SPRING_APPLICATION_TYPE, String.class, DiscoveryConstant.UNKNOWN); + } + + public static String getApplicationGatewayType(Environment environment) { + return environment.getProperty(DiscoveryConstant.SPRING_APPLICATION_GATEWAY_TYPE, String.class); + } + + public static String getApplicationProtocol(Environment environment) { + return environment.getProperty(DiscoveryConstant.SPRING_APPLICATION_PROTOCOL, String.class, "http"); + } + + public static String getApplicationUUId(Environment environment) { + return environment.getProperty(DiscoveryConstant.SPRING_APPLICATION_UUID, String.class, DiscoveryConstant.UNKNOWN); + } + + public static String getGroupKey(Environment environment) { + return environment.getProperty(DiscoveryConstant.SPRING_APPLICATION_GROUP_KEY, String.class, DiscoveryConstant.GROUP); + } + + public static String getDefaultPropertiesPath(Environment environment) { + return environment.getProperty(DiscoveryConstant.SPRING_APPLICATION_DEFAULT_PROPERTIES_PATH, String.class, DiscoveryConstant.SPRING_APPLICATION_DEFAULT_PROPERTIES_PATH_VALUE + "." + DiscoveryConstant.PROPERTIES_FORMAT); + } + + public static Boolean isGroupGeneratorEnabled(Environment environment) { + return environment.getProperty(DiscoveryConstant.SPRING_APPLICATION_GROUP_GENERATOR_ENABLED, Boolean.class, Boolean.FALSE); + } + + public static Integer getGroupGeneratorLength(Environment environment) { + return environment.getProperty(DiscoveryConstant.SPRING_APPLICATION_GROUP_GENERATOR_LENGTH, Integer.class, -1); + } + + public static String getGroupGeneratorCharacter(Environment environment) { + return environment.getProperty(DiscoveryConstant.SPRING_APPLICATION_GROUP_GENERATOR_CHARACTER, String.class, StringUtils.EMPTY); + } + + public static Boolean isGitGeneratorEnabled(Environment environment) { + return environment.getProperty(DiscoveryConstant.SPRING_APPLICATION_GIT_GENERATOR_ENABLED, Boolean.class, Boolean.FALSE); + } + + public static String getGitGeneratorPath(Environment environment) { + return environment.getProperty(DiscoveryConstant.SPRING_APPLICATION_GIT_GENERATOR_PATH, String.class, DiscoveryConstant.PREFIX_CLASSPATH + DiscoveryConstant.GIT + "." + DiscoveryConstant.PROPERTIES_FORMAT); + } + + public static String getGitVersionKey(Environment environment) { + return environment.getProperty(DiscoveryConstant.SPRING_APPLICATION_GIT_VERSION_KEY, String.class, "{" + DiscoveryConstant.GIT_COMMIT_TIME + "}-{" + DiscoveryConstant.GIT_TOTAL_COMMIT_COUNT + "}"); + } + + public static String getContextPath(Environment environment) { + return environment.getProperty(DiscoveryConstant.CONTEXT_PATH, String.class, "/"); + } +} \ No newline at end of file diff --git a/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/context/PluginContextHolder.java b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/context/PluginContextHolder.java new file mode 100644 index 0000000000..9c5e511c1c --- /dev/null +++ b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/context/PluginContextHolder.java @@ -0,0 +1,48 @@ +package com.nepxion.discovery.plugin.framework.context; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +public interface PluginContextHolder { + String getContext(String name); + + String getContextRouteVersion(); + + String getContextRouteRegion(); + + String getContextRouteEnvironment(); + + String getContextRouteAddress(); + + String getContextRouteVersionWeight(); + + String getContextRouteRegionWeight(); + + String getContextRouteVersionPrefer(); + + String getContextRouteVersionFailover(); + + String getContextRouteRegionTransfer(); + + String getContextRouteRegionFailover(); + + String getContextRouteEnvironmentFailover(); + + String getContextRouteZoneFailover(); + + String getContextRouteAddressFailover(); + + String getContextRouteIdBlacklist(); + + String getContextRouteAddressBlacklist(); + + String getTraceId(); + + String getSpanId(); +} \ No newline at end of file diff --git a/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/context/PluginEnvironmentPostProcessor.java b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/context/PluginEnvironmentPostProcessor.java new file mode 100644 index 0000000000..d95542a8e6 --- /dev/null +++ b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/context/PluginEnvironmentPostProcessor.java @@ -0,0 +1,34 @@ +package com.nepxion.discovery.plugin.framework.context; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.env.EnvironmentPostProcessor; +import org.springframework.core.Ordered; +import org.springframework.core.env.ConfigurableEnvironment; + +import com.nepxion.discovery.common.constant.DiscoveryConstant; +import com.nepxion.discovery.common.util.EnvironmentUtil; +import com.nepxion.discovery.common.util.UuidUtil; + +public class PluginEnvironmentPostProcessor implements EnvironmentPostProcessor, Ordered { + @Override + public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { + if (EnvironmentUtil.isStandardEnvironment(environment)) { + String uuid = UuidUtil.getTimeUUID(); + System.setProperty(DiscoveryConstant.SPRING_APPLICATION_UUID, uuid); + } + } + + @Override + public int getOrder() { + return Ordered.HIGHEST_PRECEDENCE; + } +} \ No newline at end of file diff --git a/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/decorator/DiscoveryClientDecorator.java b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/decorator/DiscoveryClientDecorator.java new file mode 100644 index 0000000000..38a1b55117 --- /dev/null +++ b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/decorator/DiscoveryClientDecorator.java @@ -0,0 +1,77 @@ +package com.nepxion.discovery.plugin.framework.decorator; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.List; + +import org.springframework.beans.BeansException; +import org.springframework.cloud.client.ServiceInstance; +import org.springframework.cloud.client.discovery.DiscoveryClient; +import org.springframework.context.ConfigurableApplicationContext; + +import com.nepxion.discovery.common.delegate.DiscoveryClientDelegate; +import com.nepxion.discovery.plugin.framework.listener.discovery.DiscoveryListenerExecutor; + +public class DiscoveryClientDecorator implements DiscoveryClient, DiscoveryClientDelegate { + // private static final Logger LOG = LoggerFactory.getLogger(DiscoveryClientDecorator.class); + + private DiscoveryClient discoveryClient; + private ConfigurableApplicationContext applicationContext; + + public DiscoveryClientDecorator(DiscoveryClient discoveryClient, ConfigurableApplicationContext applicationContext) { + this.discoveryClient = discoveryClient; + this.applicationContext = applicationContext; + } + + public DiscoveryClient getDelegate() { + return discoveryClient; + } + + @Override + public List getInstances(String serviceId) { + List instances = getRealInstances(serviceId); + + try { + DiscoveryListenerExecutor discoveryListenerExecutor = applicationContext.getBean(DiscoveryListenerExecutor.class); + discoveryListenerExecutor.onGetInstances(serviceId, instances); + } catch (BeansException e) { + // LOG.warn("Get bean for DiscoveryListenerExecutor failed, ignore to executor listener"); + } + + return instances; + } + + public List getRealInstances(String serviceId) { + return discoveryClient.getInstances(serviceId); + } + + @Override + public List getServices() { + List services = getRealServices(); + + try { + DiscoveryListenerExecutor discoveryListenerExecutor = applicationContext.getBean(DiscoveryListenerExecutor.class); + discoveryListenerExecutor.onGetServices(services); + } catch (BeansException e) { + // LOG.warn("Get bean for DiscoveryListenerExecutor failed, ignore to executor listener"); + } + + return services; + } + + public List getRealServices() { + return discoveryClient.getServices(); + } + + @Override + public String description() { + return discoveryClient.description(); + } +} \ No newline at end of file diff --git a/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/decorator/PredicateBasedRuleDecorator.java b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/decorator/PredicateBasedRuleDecorator.java new file mode 100644 index 0000000000..5cc38a0756 --- /dev/null +++ b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/decorator/PredicateBasedRuleDecorator.java @@ -0,0 +1,108 @@ +package com.nepxion.discovery.plugin.framework.decorator; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.ArrayList; +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; + +import com.google.common.base.Optional; +import com.nepxion.discovery.common.entity.WeightFilterEntity; +import com.nepxion.discovery.plugin.framework.loadbalance.DiscoveryEnabledLoadBalance; +import com.nepxion.discovery.plugin.framework.loadbalance.weight.RuleWeightRandomLoadBalance; +import com.nepxion.discovery.plugin.framework.loadbalance.weight.StrategyWeightRandomLoadBalance; +import com.netflix.loadbalancer.PredicateBasedRule; +import com.netflix.loadbalancer.Server; + +public abstract class PredicateBasedRuleDecorator extends PredicateBasedRule { + @Autowired + private StrategyWeightRandomLoadBalance strategyWeightRandomLoadBalance; + + @Autowired + private RuleWeightRandomLoadBalance ruleWeightRandomLoadBalance; + + @Autowired(required = false) + private DiscoveryEnabledLoadBalance discoveryEnabledLoadBalance; + + // 必须执行getEligibleServers,否则叠加执行权重规则和版本区域策略会失效 + private List getServerList(Object key) { + return getPredicate().getEligibleServers(getLoadBalancer().getAllServers(), key); + } + + @Override + public Server choose(Object key) { + boolean isTriggered = false; + + WeightFilterEntity strategyWeightFilterEntity = strategyWeightRandomLoadBalance.getT(); + if (strategyWeightFilterEntity != null && strategyWeightFilterEntity.hasWeight()) { + isTriggered = true; + + List serverList = getServerList(key); + boolean isWeightChecked = strategyWeightRandomLoadBalance.checkWeight(serverList, strategyWeightFilterEntity); + if (isWeightChecked) { + try { + List filterServerList = filterEnabledServers(serverList); + + return strategyWeightRandomLoadBalance.choose(filterServerList, strategyWeightFilterEntity); + } catch (Exception e) { + return filterChoose(key); + } + } else { + return filterChoose(key); + } + } + + if (!isTriggered) { + WeightFilterEntity ruleWeightFilterEntity = ruleWeightRandomLoadBalance.getT(); + if (ruleWeightFilterEntity != null && ruleWeightFilterEntity.hasWeight()) { + List serverList = getServerList(key); + boolean isWeightChecked = ruleWeightRandomLoadBalance.checkWeight(serverList, ruleWeightFilterEntity); + if (isWeightChecked) { + try { + List filterServerList = filterEnabledServers(serverList); + + return ruleWeightRandomLoadBalance.choose(filterServerList, ruleWeightFilterEntity); + } catch (Exception e) { + return filterChoose(key); + } + } else { + return filterChoose(key); + } + } + } + + return filterChoose(key); + } + + public List filterEnabledServers(List servers) { + List serverList = new ArrayList(); + serverList.addAll(servers); + + if (discoveryEnabledLoadBalance != null) { + discoveryEnabledLoadBalance.filter(serverList); + } + + return serverList; + } + + public Server filterChoose(Object key) { + List servers = getLoadBalancer().getAllServers(); + + List serverList = filterEnabledServers(servers); + + Optional server = getPredicate().chooseRoundRobinAfterFiltering(serverList, key); + if (server.isPresent()) { + return server.get(); + } else { + return null; + } + } +} \ No newline at end of file diff --git a/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/decorator/ZoneAvoidanceRuleDecorator.java b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/decorator/ZoneAvoidanceRuleDecorator.java new file mode 100644 index 0000000000..f30a73506d --- /dev/null +++ b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/decorator/ZoneAvoidanceRuleDecorator.java @@ -0,0 +1,108 @@ +package com.nepxion.discovery.plugin.framework.decorator; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.ArrayList; +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; + +import com.google.common.base.Optional; +import com.nepxion.discovery.common.entity.WeightFilterEntity; +import com.nepxion.discovery.plugin.framework.loadbalance.DiscoveryEnabledLoadBalance; +import com.nepxion.discovery.plugin.framework.loadbalance.weight.RuleWeightRandomLoadBalance; +import com.nepxion.discovery.plugin.framework.loadbalance.weight.StrategyWeightRandomLoadBalance; +import com.netflix.loadbalancer.Server; +import com.netflix.loadbalancer.ZoneAvoidanceRule; + +public class ZoneAvoidanceRuleDecorator extends ZoneAvoidanceRule { + @Autowired + private StrategyWeightRandomLoadBalance strategyWeightRandomLoadBalance; + + @Autowired + private RuleWeightRandomLoadBalance ruleWeightRandomLoadBalance; + + @Autowired(required = false) + private DiscoveryEnabledLoadBalance discoveryEnabledLoadBalance; + + // 必须执行getEligibleServers,否则叠加执行权重规则和版本区域策略会失效 + private List getServerList(Object key) { + return getPredicate().getEligibleServers(getLoadBalancer().getAllServers(), key); + } + + @Override + public Server choose(Object key) { + boolean isTriggered = false; + + WeightFilterEntity strategyWeightFilterEntity = strategyWeightRandomLoadBalance.getT(); + if (strategyWeightFilterEntity != null && strategyWeightFilterEntity.hasWeight()) { + isTriggered = true; + + List serverList = getServerList(key); + boolean isWeightChecked = strategyWeightRandomLoadBalance.checkWeight(serverList, strategyWeightFilterEntity); + if (isWeightChecked) { + try { + List filterServerList = filterEnabledServers(serverList); + + return strategyWeightRandomLoadBalance.choose(filterServerList, strategyWeightFilterEntity); + } catch (Exception e) { + return filterChoose(key); + } + } else { + return filterChoose(key); + } + } + + if (!isTriggered) { + WeightFilterEntity ruleWeightFilterEntity = ruleWeightRandomLoadBalance.getT(); + if (ruleWeightFilterEntity != null && ruleWeightFilterEntity.hasWeight()) { + List serverList = getServerList(key); + boolean isWeightChecked = ruleWeightRandomLoadBalance.checkWeight(serverList, ruleWeightFilterEntity); + if (isWeightChecked) { + try { + List filterServerList = filterEnabledServers(serverList); + + return ruleWeightRandomLoadBalance.choose(filterServerList, ruleWeightFilterEntity); + } catch (Exception e) { + return filterChoose(key); + } + } else { + return filterChoose(key); + } + } + } + + return filterChoose(key); + } + + public List filterEnabledServers(List servers) { + List serverList = new ArrayList(); + serverList.addAll(servers); + + if (discoveryEnabledLoadBalance != null) { + discoveryEnabledLoadBalance.filter(serverList); + } + + return serverList; + } + + public Server filterChoose(Object key) { + List servers = getLoadBalancer().getAllServers(); + + List serverList = filterEnabledServers(servers); + + Optional server = getPredicate().chooseRoundRobinAfterFiltering(serverList, key); + if (server.isPresent()) { + return server.get(); + } else { + return null; + } + } +} \ No newline at end of file diff --git a/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/event/ParameterChangedEvent.java b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/event/ParameterChangedEvent.java new file mode 100644 index 0000000000..ccfeceafb3 --- /dev/null +++ b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/event/ParameterChangedEvent.java @@ -0,0 +1,28 @@ +package com.nepxion.discovery.plugin.framework.event; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.io.Serializable; + +import com.nepxion.discovery.common.entity.ParameterEntity; + +public class ParameterChangedEvent implements Serializable { + private static final long serialVersionUID = 7843872188960155327L; + + private ParameterEntity parameterEntity; + + public ParameterChangedEvent(ParameterEntity parameterEntity) { + this.parameterEntity = parameterEntity; + } + + public ParameterEntity getParameterEntity() { + return parameterEntity; + } +} \ No newline at end of file diff --git a/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/event/PluginEventWapper.java b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/event/PluginEventWapper.java similarity index 81% rename from discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/event/PluginEventWapper.java rename to discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/event/PluginEventWapper.java index 759bedccaa..0e25cd5cf2 100644 --- a/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/event/PluginEventWapper.java +++ b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/event/PluginEventWapper.java @@ -40,6 +40,10 @@ public void fireRuleCleared(RuleClearedEvent ruleClearedEvent, boolean async) { } } + public void fireRuleFailure(RuleFailureEvent ruleFailureEvent) { + pluginPublisher.asyncPublish(ruleFailureEvent); + } + public void fireVersionUpdated(VersionUpdatedEvent versionUpdatedEvent, boolean async) { if (async) { pluginPublisher.asyncPublish(versionUpdatedEvent); @@ -56,16 +60,17 @@ public void fireVersionCleared(VersionClearedEvent versionClearedEvent, boolean } } - public void fireRegisterFailure(RegisterFailureEvent registerFailureEvent) { - pluginPublisher.asyncPublish(registerFailureEvent); + public void fireParameterChanged(ParameterChangedEvent parameterChangedEvent) { + pluginPublisher.asyncPublish(parameterChangedEvent); } - public void fireCustomization(CustomizationEvent customizationEvent) { - pluginPublisher.asyncPublish(customizationEvent); + public void fireParameterChanged() { + RuleEntity ruleEntity = pluginAdapter.getRule(); + + fireParameterChanged(new ParameterChangedEvent(ruleEntity != null ? ruleEntity.getParameterEntity() : null)); } - public void fireCustomization() { - RuleEntity ruleEntity = pluginAdapter.getRule(); - fireCustomization(new CustomizationEvent(ruleEntity != null ? ruleEntity.getCustomizationEntity() : null)); + public void fireRegisterFailure(RegisterFailureEvent registerFailureEvent) { + pluginPublisher.asyncPublish(registerFailureEvent); } } \ No newline at end of file diff --git a/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/event/PluginPublisher.java b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/event/PluginPublisher.java similarity index 100% rename from discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/event/PluginPublisher.java rename to discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/event/PluginPublisher.java diff --git a/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/event/PluginSubscriber.java b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/event/PluginSubscriber.java new file mode 100644 index 0000000000..d6bb033647 --- /dev/null +++ b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/event/PluginSubscriber.java @@ -0,0 +1,167 @@ +package com.nepxion.discovery.plugin.framework.event; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; + +import com.google.common.eventbus.Subscribe; +import com.nepxion.discovery.common.entity.RuleEntity; +import com.nepxion.discovery.common.entity.SubscriptionType; +import com.nepxion.discovery.common.exception.DiscoveryException; +import com.nepxion.discovery.plugin.framework.adapter.PluginAdapter; +import com.nepxion.discovery.plugin.framework.listener.loadbalance.LoadBalanceListenerExecutor; +import com.nepxion.discovery.plugin.framework.parser.PluginConfigParser; +import com.nepxion.eventbus.annotation.EventBus; +import com.netflix.loadbalancer.ZoneAwareLoadBalancer; + +@EventBus +public class PluginSubscriber { + private static final Logger LOG = LoggerFactory.getLogger(PluginSubscriber.class); + + @Autowired + private PluginAdapter pluginAdapter; + + @Autowired + private PluginConfigParser pluginConfigParser; + + @Autowired + private PluginEventWapper pluginEventWapper; + + @Autowired + private LoadBalanceListenerExecutor loadBalanceListenerExecutor; + + @Subscribe + public void onRuleUpdated(RuleUpdatedEvent ruleUpdatedEvent) { + LOG.info("Rule updating has been triggered"); + + if (ruleUpdatedEvent == null) { + throw new DiscoveryException("RuleUpdatedEvent can't be null"); + } + + SubscriptionType subscriptionType = ruleUpdatedEvent.getSubscriptionType(); + String rule = ruleUpdatedEvent.getRule(); + try { + RuleEntity ruleEntity = pluginConfigParser.parse(rule); + switch (subscriptionType) { + case GLOBAL: + pluginAdapter.setDynamicGlobalRule(ruleEntity); + break; + case PARTIAL: + pluginAdapter.setDynamicPartialRule(ruleEntity); + break; + } + + pluginEventWapper.fireParameterChanged(); + } catch (Exception e) { + LOG.error("Parse rule xml failed", e); + + pluginEventWapper.fireRuleFailure(new RuleFailureEvent(subscriptionType, rule, e)); + + throw e; + } + + refreshLoadBalancer(); + } + + @Subscribe + public void onRuleCleared(RuleClearedEvent ruleClearedEvent) { + LOG.info("Rule clearing has been triggered"); + + if (ruleClearedEvent == null) { + throw new DiscoveryException("RuleClearedEvent can't be null"); + } + + SubscriptionType subscriptionType = ruleClearedEvent.getSubscriptionType(); + switch (subscriptionType) { + case GLOBAL: + pluginAdapter.clearDynamicGlobalRule(); + break; + case PARTIAL: + pluginAdapter.clearDynamicPartialRule(); + break; + } + + pluginEventWapper.fireParameterChanged(); + + refreshLoadBalancer(); + } + + @Subscribe + public void onVersionUpdated(VersionUpdatedEvent versionUpdatedEvent) { + LOG.info("Version updating has been triggered"); + + if (versionUpdatedEvent == null) { + throw new DiscoveryException("VersionUpdatedEvent can't be null"); + } + + String dynamicVersion = versionUpdatedEvent.getDynamicVersion(); + String localVersion = versionUpdatedEvent.getLocalVersion(); + + if (StringUtils.isEmpty(localVersion)) { + pluginAdapter.setDynamicVersion(dynamicVersion); + + refreshLoadBalancer(); + + LOG.info("Version has been updated, new version is {}", dynamicVersion); + } else { + if (StringUtils.equals(pluginAdapter.getLocalVersion(), localVersion)) { + pluginAdapter.setDynamicVersion(dynamicVersion); + + refreshLoadBalancer(); + + LOG.info("Version has been updated, new version is {}", dynamicVersion); + } else { + throw new DiscoveryException("Version updating will be ignored, because input localVersion=" + localVersion + ", current localVersion=" + pluginAdapter.getLocalVersion()); + } + } + } + + @Subscribe + public void onVersionCleared(VersionClearedEvent versionClearedEvent) { + LOG.info("Version clearing has been triggered"); + + if (versionClearedEvent == null) { + throw new DiscoveryException("VersionClearedEvent can't be null"); + } + + String localVersion = versionClearedEvent.getLocalVersion(); + + if (StringUtils.isEmpty(localVersion)) { + pluginAdapter.clearDynamicVersion(); + + refreshLoadBalancer(); + + LOG.info("Version has been cleared"); + } else { + if (StringUtils.equals(pluginAdapter.getLocalVersion(), localVersion)) { + pluginAdapter.clearDynamicVersion(); + + refreshLoadBalancer(); + + LOG.info("Version has been cleared"); + } else { + throw new DiscoveryException("Version clearing will be ignored, because input localVersion=" + localVersion + ", current localVersion=" + pluginAdapter.getLocalVersion()); + } + } + } + + // 当规则或者版本更新后,强制刷新负载均衡缓存 + private void refreshLoadBalancer() { + ZoneAwareLoadBalancer loadBalancer = loadBalanceListenerExecutor.getLoadBalancer(); + if (loadBalancer == null) { + return; + } + + loadBalancer.updateListOfServers(); + } +} \ No newline at end of file diff --git a/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/event/RegisterFailureEvent.java b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/event/RegisterFailureEvent.java similarity index 100% rename from discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/event/RegisterFailureEvent.java rename to discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/event/RegisterFailureEvent.java diff --git a/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/event/RuleClearedEvent.java b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/event/RuleClearedEvent.java new file mode 100644 index 0000000000..fb8bd701ad --- /dev/null +++ b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/event/RuleClearedEvent.java @@ -0,0 +1,28 @@ +package com.nepxion.discovery.plugin.framework.event; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.io.Serializable; + +import com.nepxion.discovery.common.entity.SubscriptionType; + +public class RuleClearedEvent implements Serializable { + private static final long serialVersionUID = -4942710381954711909L; + + private SubscriptionType subscriptionType; + + public RuleClearedEvent(SubscriptionType subscriptionType) { + this.subscriptionType = subscriptionType; + } + + public SubscriptionType getSubscriptionType() { + return subscriptionType; + } +} \ No newline at end of file diff --git a/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/event/RuleFailureEvent.java b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/event/RuleFailureEvent.java new file mode 100644 index 0000000000..33c284e247 --- /dev/null +++ b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/event/RuleFailureEvent.java @@ -0,0 +1,44 @@ +package com.nepxion.discovery.plugin.framework.event; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.io.Serializable; + +import com.nepxion.discovery.common.entity.SubscriptionType; + +public class RuleFailureEvent implements Serializable { + private static final long serialVersionUID = 954041724496099958L; + + private SubscriptionType subscriptionType; + private String rule; + private Exception exception; + + public RuleFailureEvent(SubscriptionType subscriptionType, String rule, Exception exception) { + this.subscriptionType = subscriptionType; + this.rule = rule; + this.exception = exception; + } + + public SubscriptionType getSubscriptionType() { + return subscriptionType; + } + + public String getRule() { + return rule; + } + + public Exception getException() { + return exception; + } + + public void setException(Exception exception) { + this.exception = exception; + } +} \ No newline at end of file diff --git a/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/event/RuleUpdatedEvent.java b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/event/RuleUpdatedEvent.java new file mode 100644 index 0000000000..159e0050e5 --- /dev/null +++ b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/event/RuleUpdatedEvent.java @@ -0,0 +1,34 @@ +package com.nepxion.discovery.plugin.framework.event; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.io.Serializable; + +import com.nepxion.discovery.common.entity.SubscriptionType; + +public class RuleUpdatedEvent implements Serializable { + private static final long serialVersionUID = 2315578803987663866L; + + private SubscriptionType subscriptionType; + private String rule; + + public RuleUpdatedEvent(SubscriptionType subscriptionType, String rule) { + this.subscriptionType = subscriptionType; + this.rule = rule; + } + + public SubscriptionType getSubscriptionType() { + return subscriptionType; + } + + public String getRule() { + return rule; + } +} \ No newline at end of file diff --git a/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/event/VersionClearedEvent.java b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/event/VersionClearedEvent.java similarity index 100% rename from discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/event/VersionClearedEvent.java rename to discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/event/VersionClearedEvent.java diff --git a/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/event/VersionUpdatedEvent.java b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/event/VersionUpdatedEvent.java similarity index 100% rename from discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/event/VersionUpdatedEvent.java rename to discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/event/VersionUpdatedEvent.java diff --git a/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/generator/GitGenerator.java b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/generator/GitGenerator.java new file mode 100644 index 0000000000..7da3cce8c9 --- /dev/null +++ b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/generator/GitGenerator.java @@ -0,0 +1,139 @@ +package com.nepxion.discovery.plugin.framework.generator; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @author Yong Chen + * @version 1.0 + */ + +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import javax.annotation.PostConstruct; + +import org.apache.commons.collections4.MapUtils; +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.nepxion.discovery.common.constant.DiscoveryConstant; +import com.nepxion.discovery.common.property.DiscoveryProperties; +import com.nepxion.discovery.common.util.FileUtil; +import com.nepxion.discovery.common.util.JsonUtil; +import com.nepxion.discovery.plugin.framework.context.PluginContextAware; + +public class GitGenerator { + private static final Logger LOG = LoggerFactory.getLogger(GitGenerator.class); + + @Autowired + private ApplicationContext applicationContext; + + private String generatorPath; + private String versionKey; + + private String text; + private Map map; + + @PostConstruct + public void initialize() { + generatorPath = PluginContextAware.getGitGeneratorPath(applicationContext.getEnvironment()); + versionKey = PluginContextAware.getGitVersionKey(applicationContext.getEnvironment()); + + initializeText(); + initializeJsonMap(); + initializePropertiesMap(); + + String version = getVersion(); + LOG.info("--------------------------------------------------"); + if (StringUtils.isNotEmpty(version)) { + LOG.info("Use {}={} as metadata version", versionKey, version); + } else { + LOG.error("Not found value of {}, use default metadata version setting", versionKey); + } + LOG.info("--------------------------------------------------"); + } + + private void initializeText() { + text = FileUtil.getText(applicationContext, generatorPath); + } + + private void initializeJsonMap() { + if (StringUtils.isEmpty(text)) { + return; + } + + if (MapUtils.isNotEmpty(map)) { + return; + } + + try { + map = JsonUtil.fromJson(text, new TypeReference>() { + }); + } catch (Exception e) { + + } + } + + private void initializePropertiesMap() { + if (StringUtils.isEmpty(text)) { + return; + } + + if (MapUtils.isNotEmpty(map)) { + return; + } + + try { + DiscoveryProperties properties = new DiscoveryProperties(text, DiscoveryConstant.ENCODING_UTF_8); + map = properties.getMap(); + } catch (Exception e) { + + } + } + + public String getVersionKey() { + return versionKey; + } + + public String getGeneratorPath() { + return generatorPath; + } + + public String getText() { + return text; + } + + public Map getMap() { + return map; + } + + public String getVersion() { + if (MapUtils.isEmpty(map)) { + return null; + } + + return match(versionKey, map); + // return map.get(versionKey); + } + + private String match(String versionKey, Map map) { + String value = new String(versionKey); + for (Map.Entry entry : map.entrySet()) { + String regex = "\\{" + entry.getKey() + "\\}"; + // String regex = "\\$\\{" + entry.getKey() + "\\}"; + Pattern pattern = Pattern.compile(regex); + Matcher matcher = pattern.matcher(value); + value = matcher.replaceAll(entry.getValue()); + } + + return value; + } +} \ No newline at end of file diff --git a/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/generator/GroupGenerator.java b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/generator/GroupGenerator.java new file mode 100644 index 0000000000..794d40bb07 --- /dev/null +++ b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/generator/GroupGenerator.java @@ -0,0 +1,72 @@ +package com.nepxion.discovery.plugin.framework.generator; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @author Robin.G + * @version 1.0 + */ + +import javax.annotation.PostConstruct; + +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; + +import com.nepxion.discovery.plugin.framework.context.PluginContextAware; + +public class GroupGenerator { + private static final Logger LOG = LoggerFactory.getLogger(GroupGenerator.class); + + @Autowired + private ApplicationContext applicationContext; + + private Integer generatorLength; + private String generatorCharacter; + private String applicationName; + + private String group; + + @PostConstruct + public void initialize() { + generatorLength = PluginContextAware.getGroupGeneratorLength(applicationContext.getEnvironment()); + generatorCharacter = PluginContextAware.getGroupGeneratorCharacter(applicationContext.getEnvironment()); + applicationName = PluginContextAware.getApplicationName(applicationContext.getEnvironment()); + int characterIndex = applicationName.indexOf(generatorCharacter); + + if (generatorLength > 0) { + group = applicationName.substring(0, generatorLength); + } else if (StringUtils.isNotEmpty(generatorCharacter) && characterIndex > 0) { + group = applicationName.substring(0, characterIndex); + } + + LOG.info("--------------------------------------------------"); + if (StringUtils.isNotEmpty(group)) { + LOG.info("Use application name prefix={} as metadata group", group); + } else { + LOG.error("Not substring application name prefix for generator length={} or character={}, use default metadata group setting", generatorLength, generatorCharacter); + } + LOG.info("--------------------------------------------------"); + } + + public Integer getGeneratorLength() { + return generatorLength; + } + + public String getGeneratorCharacter() { + return generatorCharacter; + } + + public String getApplicationName() { + return applicationName; + } + + public String getGroup() { + return group; + } +} \ No newline at end of file diff --git a/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/listener/BasicListener.java b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/listener/BasicListener.java similarity index 100% rename from discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/listener/BasicListener.java rename to discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/listener/BasicListener.java diff --git a/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/listener/Listener.java b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/listener/Listener.java similarity index 100% rename from discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/listener/Listener.java rename to discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/listener/Listener.java diff --git a/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/listener/discovery/AbstractDiscoveryListener.java b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/listener/discovery/AbstractDiscoveryListener.java similarity index 100% rename from discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/listener/discovery/AbstractDiscoveryListener.java rename to discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/listener/discovery/AbstractDiscoveryListener.java diff --git a/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/listener/discovery/DiscoveryListener.java b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/listener/discovery/DiscoveryListener.java similarity index 100% rename from discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/listener/discovery/DiscoveryListener.java rename to discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/listener/discovery/DiscoveryListener.java diff --git a/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/listener/discovery/DiscoveryListenerExecutor.java b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/listener/discovery/DiscoveryListenerExecutor.java similarity index 100% rename from discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/listener/discovery/DiscoveryListenerExecutor.java rename to discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/listener/discovery/DiscoveryListenerExecutor.java diff --git a/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/listener/discovery/HostFilterDiscoveryListener.java b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/listener/discovery/HostFilterDiscoveryListener.java similarity index 96% rename from discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/listener/discovery/HostFilterDiscoveryListener.java rename to discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/listener/discovery/HostFilterDiscoveryListener.java index 83fcdad812..072a5545f0 100644 --- a/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/listener/discovery/HostFilterDiscoveryListener.java +++ b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/listener/discovery/HostFilterDiscoveryListener.java @@ -65,8 +65,8 @@ private void applyHostFilter(String providerServiceId, List ins Iterator iterator = instances.iterator(); while (iterator.hasNext()) { - ServiceInstance serviceInstance = iterator.next(); - String host = serviceInstance.getHost(); + ServiceInstance instance = iterator.next(); + String host = instance.getHost(); switch (filterType) { case BLACKLIST: if (validateBlacklist(allFilterValueList, host)) { diff --git a/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/listener/discovery/RegionFilterDiscoveryListener.java b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/listener/discovery/RegionFilterDiscoveryListener.java new file mode 100644 index 0000000000..fa94e85cd2 --- /dev/null +++ b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/listener/discovery/RegionFilterDiscoveryListener.java @@ -0,0 +1,133 @@ +package com.nepxion.discovery.plugin.framework.listener.discovery; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import org.apache.commons.collections4.CollectionUtils; +import org.apache.commons.collections4.MapUtils; +import org.apache.commons.lang3.StringUtils; +import org.springframework.cloud.client.ServiceInstance; + +import com.nepxion.discovery.common.entity.DiscoveryEntity; +import com.nepxion.discovery.common.entity.RegionEntity; +import com.nepxion.discovery.common.entity.RegionFilterEntity; +import com.nepxion.discovery.common.entity.RuleEntity; + +public class RegionFilterDiscoveryListener extends AbstractDiscoveryListener { + @Override + public void onGetInstances(String serviceId, List instances) { + String consumerServiceId = pluginAdapter.getServiceId(); + String consumerServiceRegion = pluginAdapter.getRegion(); + + applyRegionFilter(consumerServiceId, consumerServiceRegion, serviceId, instances); + } + + private void applyRegionFilter(String consumerServiceId, String consumerServiceRegion, String providerServiceId, List instances) { + // 如果消费端未配置区域号,那么它可以调用提供端所有服务,需要符合规范,极力避免该情况发生 + if (StringUtils.isEmpty(consumerServiceRegion)) { + return; + } + + RuleEntity ruleEntity = pluginAdapter.getRule(); + if (ruleEntity == null) { + return; + } + + DiscoveryEntity discoveryEntity = ruleEntity.getDiscoveryEntity(); + if (discoveryEntity == null) { + return; + } + + RegionFilterEntity regionFilterEntity = discoveryEntity.getRegionFilterEntity(); + if (regionFilterEntity == null) { + return; + } + + Map> regionEntityMap = regionFilterEntity.getRegionEntityMap(); + if (MapUtils.isEmpty(regionEntityMap)) { + return; + } + + List regionEntityList = regionEntityMap.get(consumerServiceId); + if (CollectionUtils.isEmpty(regionEntityList)) { + return; + } + + // 当前区域的消费端所能调用提供端的区域号列表 + List allNoFilterValueList = null; + // 提供端规则未作任何定义 + boolean providerConditionDefined = false; + for (RegionEntity regionEntity : regionEntityList) { + String providerServiceName = regionEntity.getProviderServiceName(); + if (StringUtils.equalsIgnoreCase(providerServiceName, providerServiceId)) { + providerConditionDefined = true; + + List consumerRegionValueList = regionEntity.getConsumerRegionValueList(); + List providerRegionValueList = regionEntity.getProviderRegionValueList(); + + // 判断consumer-region-value值是否包含当前消费端的区域号 + // 如果consumerRegionValueList为空,表示消费端区域列表未指定,那么任意消费端区域可以访问指定区域提供端区域 + if (CollectionUtils.isNotEmpty(consumerRegionValueList)) { + if (consumerRegionValueList.contains(consumerServiceRegion)) { + if (allNoFilterValueList == null) { + allNoFilterValueList = new ArrayList(); + } + if (CollectionUtils.isNotEmpty(providerRegionValueList)) { + allNoFilterValueList.addAll(providerRegionValueList); + } + } // 这里的条件,在每一次循环都不满足,会让allNoFilterValueList为null,意味着定义的区域关系都不匹配 + } else { + if (allNoFilterValueList == null) { + allNoFilterValueList = new ArrayList(); + } + if (CollectionUtils.isNotEmpty(providerRegionValueList)) { + allNoFilterValueList.addAll(providerRegionValueList); + } + } + } + } + + if (allNoFilterValueList != null) { + // 当allNoFilterValueList为空列表,意味着区域对应关系未做任何定义(即所有的providerRegionValueList为空),不需要执行过滤,直接返回 + if (allNoFilterValueList.isEmpty()) { + return; + } else { + Iterator iterator = instances.iterator(); + while (iterator.hasNext()) { + ServiceInstance instance = iterator.next(); + String instanceRegion = pluginAdapter.getInstanceRegion(instance); + if (!allNoFilterValueList.contains(instanceRegion)) { + iterator.remove(); + } + } + } + } else { + if (providerConditionDefined) { + // 当allNoFilterValueList为null, 意味着定义的区域关系都不匹配,直接清空所有实例 + instances.clear(); + } + } + } + + @Override + public void onGetServices(List services) { + + } + + @Override + public int getOrder() { + // After version filter + return HIGHEST_PRECEDENCE + 2; + } +} \ No newline at end of file diff --git a/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/listener/discovery/VersionFilterDiscoveryListener.java b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/listener/discovery/VersionFilterDiscoveryListener.java similarity index 98% rename from discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/listener/discovery/VersionFilterDiscoveryListener.java rename to discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/listener/discovery/VersionFilterDiscoveryListener.java index 7c5b56e35a..02d4e6765d 100644 --- a/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/listener/discovery/VersionFilterDiscoveryListener.java +++ b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/listener/discovery/VersionFilterDiscoveryListener.java @@ -105,8 +105,8 @@ private void applyVersionFilter(String consumerServiceId, String consumerService } else { Iterator iterator = instances.iterator(); while (iterator.hasNext()) { - ServiceInstance serviceInstance = iterator.next(); - String instanceVersion = pluginAdapter.getInstanceVersion(serviceInstance); + ServiceInstance instance = iterator.next(); + String instanceVersion = pluginAdapter.getInstanceVersion(instance); if (!allNoFilterValueList.contains(instanceVersion)) { iterator.remove(); } diff --git a/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/listener/loadbalance/AbstractLoadBalanceListener.java b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/listener/loadbalance/AbstractLoadBalanceListener.java similarity index 100% rename from discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/listener/loadbalance/AbstractLoadBalanceListener.java rename to discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/listener/loadbalance/AbstractLoadBalanceListener.java diff --git a/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/listener/loadbalance/HostFilterLoadBalanceListener.java b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/listener/loadbalance/HostFilterLoadBalanceListener.java similarity index 100% rename from discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/listener/loadbalance/HostFilterLoadBalanceListener.java rename to discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/listener/loadbalance/HostFilterLoadBalanceListener.java diff --git a/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/listener/loadbalance/LoadBalanceListener.java b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/listener/loadbalance/LoadBalanceListener.java similarity index 100% rename from discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/listener/loadbalance/LoadBalanceListener.java rename to discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/listener/loadbalance/LoadBalanceListener.java diff --git a/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/listener/loadbalance/LoadBalanceListenerExecutor.java b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/listener/loadbalance/LoadBalanceListenerExecutor.java similarity index 100% rename from discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/listener/loadbalance/LoadBalanceListenerExecutor.java rename to discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/listener/loadbalance/LoadBalanceListenerExecutor.java diff --git a/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/listener/loadbalance/NotificationLoadBalanceListener.java b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/listener/loadbalance/NotificationLoadBalanceListener.java similarity index 100% rename from discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/listener/loadbalance/NotificationLoadBalanceListener.java rename to discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/listener/loadbalance/NotificationLoadBalanceListener.java diff --git a/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/listener/loadbalance/RegionFilterLoadBalanceListener.java b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/listener/loadbalance/RegionFilterLoadBalanceListener.java new file mode 100644 index 0000000000..a05fb15203 --- /dev/null +++ b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/listener/loadbalance/RegionFilterLoadBalanceListener.java @@ -0,0 +1,128 @@ +package com.nepxion.discovery.plugin.framework.listener.loadbalance; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import org.apache.commons.collections4.CollectionUtils; +import org.apache.commons.collections4.MapUtils; +import org.apache.commons.lang3.StringUtils; + +import com.nepxion.discovery.common.entity.DiscoveryEntity; +import com.nepxion.discovery.common.entity.RegionEntity; +import com.nepxion.discovery.common.entity.RegionFilterEntity; +import com.nepxion.discovery.common.entity.RuleEntity; +import com.netflix.loadbalancer.Server; + +public class RegionFilterLoadBalanceListener extends AbstractLoadBalanceListener { + @Override + public void onGetServers(String serviceId, List servers) { + String consumerServiceId = pluginAdapter.getServiceId(); + String consumerServiceRegion = pluginAdapter.getRegion(); + + applyRegionFilter(consumerServiceId, consumerServiceRegion, serviceId, servers); + } + + private void applyRegionFilter(String consumerServiceId, String consumerServiceRegion, String providerServiceId, List servers) { + // 如果消费端未配置区域号,那么它可以调用提供端所有服务,需要符合规范,极力避免该情况发生 + if (StringUtils.isEmpty(consumerServiceRegion)) { + return; + } + + RuleEntity ruleEntity = pluginAdapter.getRule(); + if (ruleEntity == null) { + return; + } + + DiscoveryEntity discoveryEntity = ruleEntity.getDiscoveryEntity(); + if (discoveryEntity == null) { + return; + } + + RegionFilterEntity regionFilterEntity = discoveryEntity.getRegionFilterEntity(); + if (regionFilterEntity == null) { + return; + } + + Map> regionEntityMap = regionFilterEntity.getRegionEntityMap(); + if (MapUtils.isEmpty(regionEntityMap)) { + return; + } + + List regionEntityList = regionEntityMap.get(consumerServiceId); + if (CollectionUtils.isEmpty(regionEntityList)) { + return; + } + + // 当前区域的消费端所能调用提供端的区域号列表 + List allNoFilterValueList = null; + // 提供端规则未作任何定义 + boolean providerConditionDefined = false; + for (RegionEntity regionEntity : regionEntityList) { + String providerServiceName = regionEntity.getProviderServiceName(); + if (StringUtils.equalsIgnoreCase(providerServiceName, providerServiceId)) { + providerConditionDefined = true; + + List consumerRegionValueList = regionEntity.getConsumerRegionValueList(); + List providerRegionValueList = regionEntity.getProviderRegionValueList(); + + // 判断consumer-region-value值是否包含当前消费端的区域号 + // 如果consumerRegionValueList为空,表示消费端区域列表未指定,那么任意消费端区域可以访问指定区域提供端区域 + if (CollectionUtils.isNotEmpty(consumerRegionValueList)) { + if (consumerRegionValueList.contains(consumerServiceRegion)) { + if (allNoFilterValueList == null) { + allNoFilterValueList = new ArrayList(); + } + if (CollectionUtils.isNotEmpty(providerRegionValueList)) { + allNoFilterValueList.addAll(providerRegionValueList); + } + } // 这里的条件,在每一次循环都不满足,会让allNoFilterValueList为null,意味着定义的区域关系都不匹配 + } else { + if (allNoFilterValueList == null) { + allNoFilterValueList = new ArrayList(); + } + if (CollectionUtils.isNotEmpty(providerRegionValueList)) { + allNoFilterValueList.addAll(providerRegionValueList); + } + } + } + } + + if (allNoFilterValueList != null) { + // 当allNoFilterValueList为空列表,意味着区域对应关系未做任何定义(即所有的providerRegionValueList为空),不需要执行过滤,直接返回 + if (allNoFilterValueList.isEmpty()) { + return; + } else { + Iterator iterator = servers.iterator(); + while (iterator.hasNext()) { + Server server = iterator.next(); + String serverRegion = pluginAdapter.getServerRegion(server); + if (!allNoFilterValueList.contains(serverRegion)) { + iterator.remove(); + } + } + } + } else { + if (providerConditionDefined) { + // 当allNoFilterValueList为null, 意味着定义的区域关系都不匹配,直接清空所有实例 + servers.clear(); + } + } + } + + @Override + public int getOrder() { + // After version filter + return HIGHEST_PRECEDENCE + 2; + } +} \ No newline at end of file diff --git a/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/listener/loadbalance/VersionFilterLoadBalanceListener.java b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/listener/loadbalance/VersionFilterLoadBalanceListener.java similarity index 100% rename from discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/listener/loadbalance/VersionFilterLoadBalanceListener.java rename to discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/listener/loadbalance/VersionFilterLoadBalanceListener.java diff --git a/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/listener/register/AbstractRegisterListener.java b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/listener/register/AbstractRegisterListener.java similarity index 100% rename from discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/listener/register/AbstractRegisterListener.java rename to discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/listener/register/AbstractRegisterListener.java diff --git a/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/listener/register/CountFilterRegisterListener.java b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/listener/register/CountFilterRegisterListener.java similarity index 92% rename from discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/listener/register/CountFilterRegisterListener.java rename to discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/listener/register/CountFilterRegisterListener.java index 924d5016dd..569f5cb886 100644 --- a/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/listener/register/CountFilterRegisterListener.java +++ b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/listener/register/CountFilterRegisterListener.java @@ -13,6 +13,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.client.serviceregistry.Registration; +import org.springframework.context.annotation.Lazy; import com.nepxion.discovery.common.constant.DiscoveryConstant; import com.nepxion.discovery.common.entity.CountFilterEntity; @@ -24,13 +25,14 @@ public class CountFilterRegisterListener extends AbstractRegisterListener { @Autowired - private DiscoveryClientDecorator discoveryClient; + @Lazy + protected DiscoveryClientDecorator discoveryClient; @Override public void onRegister(Registration registration) { - String serviceId = registration.getServiceId().toLowerCase(); - String host = registration.getHost(); - int port = registration.getPort(); + String serviceId = pluginAdapter.getServiceId(); + String host = pluginAdapter.getHost(); + int port = pluginAdapter.getPort(); applyCountFilter(serviceId, host, port); } diff --git a/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/listener/register/HostFilterRegisterListener.java b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/listener/register/HostFilterRegisterListener.java similarity index 96% rename from discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/listener/register/HostFilterRegisterListener.java rename to discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/listener/register/HostFilterRegisterListener.java index 2a19820788..45e1b70996 100644 --- a/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/listener/register/HostFilterRegisterListener.java +++ b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/listener/register/HostFilterRegisterListener.java @@ -26,9 +26,9 @@ public class HostFilterRegisterListener extends AbstractRegisterListener { @Override public void onRegister(Registration registration) { - String serviceId = registration.getServiceId().toLowerCase(); - String host = registration.getHost(); - int port = registration.getPort(); + String serviceId = pluginAdapter.getServiceId(); + String host = pluginAdapter.getHost(); + int port = pluginAdapter.getPort(); applyHostFilter(serviceId, host, port); } diff --git a/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/listener/register/RegisterListener.java b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/listener/register/RegisterListener.java similarity index 100% rename from discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/listener/register/RegisterListener.java rename to discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/listener/register/RegisterListener.java diff --git a/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/listener/register/RegisterListenerExecutor.java b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/listener/register/RegisterListenerExecutor.java similarity index 99% rename from discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/listener/register/RegisterListenerExecutor.java rename to discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/listener/register/RegisterListenerExecutor.java index 2ad5e7fe1b..788d2731df 100644 --- a/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/listener/register/RegisterListenerExecutor.java +++ b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/listener/register/RegisterListenerExecutor.java @@ -28,7 +28,6 @@ public void onRegister(Registration registration) { public void onDeregister(Registration registration) { for (RegisterListener registerListener : registerListenerList) { registerListener.onDeregister(registration); - } } diff --git a/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/loadbalance/DiscoveryEnabledLoadBalance.java b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/loadbalance/DiscoveryEnabledLoadBalance.java new file mode 100644 index 0000000000..71cc0df83e --- /dev/null +++ b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/loadbalance/DiscoveryEnabledLoadBalance.java @@ -0,0 +1,20 @@ +package com.nepxion.discovery.plugin.framework.loadbalance; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.List; + +import com.netflix.loadbalancer.Server; + +public interface DiscoveryEnabledLoadBalance { + void filter(List servers); + + boolean apply(Server server); +} \ No newline at end of file diff --git a/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/loadbalance/WeightRandomLoadBalance.java b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/loadbalance/WeightRandomLoadBalance.java similarity index 89% rename from discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/loadbalance/WeightRandomLoadBalance.java rename to discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/loadbalance/WeightRandomLoadBalance.java index 62122ba464..ab88781ba9 100644 --- a/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/loadbalance/WeightRandomLoadBalance.java +++ b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/loadbalance/WeightRandomLoadBalance.java @@ -18,5 +18,7 @@ public interface WeightRandomLoadBalance { int getWeight(Server server, T t); + boolean checkWeight(List serverList, T t); + Server choose(List serverList, T t); } \ No newline at end of file diff --git a/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/loadbalance/weight/AbstractArrayWeightRandomLoadBalance.java b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/loadbalance/weight/AbstractArrayWeightRandomLoadBalance.java new file mode 100644 index 0000000000..60f060b2b7 --- /dev/null +++ b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/loadbalance/weight/AbstractArrayWeightRandomLoadBalance.java @@ -0,0 +1,39 @@ +package com.nepxion.discovery.plugin.framework.loadbalance.weight; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.ArrayList; +import java.util.List; + +import org.apache.commons.collections4.CollectionUtils; +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.apache.commons.lang3.tuple.Pair; + +import com.nepxion.discovery.plugin.framework.loadbalance.WeightRandomLoadBalance; +import com.netflix.loadbalancer.Server; + +public abstract class AbstractArrayWeightRandomLoadBalance implements WeightRandomLoadBalance { + @Override + public Server choose(List serverList, T t) { + if (CollectionUtils.isEmpty(serverList)) { + return null; + } + + List> weightList = new ArrayList>(); + for (Server server : serverList) { + int weight = getWeight(server, t); + weightList.add(new ImmutablePair(server, weight)); + } + + ArrayWeightRandom weightRandom = new ArrayWeightRandom(weightList); + + return weightRandom.random(); + } +} \ No newline at end of file diff --git a/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/loadbalance/weight/AbstractMapWeightRandomLoadBalance.java b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/loadbalance/weight/AbstractMapWeightRandomLoadBalance.java new file mode 100644 index 0000000000..75835fa985 --- /dev/null +++ b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/loadbalance/weight/AbstractMapWeightRandomLoadBalance.java @@ -0,0 +1,39 @@ +package com.nepxion.discovery.plugin.framework.loadbalance.weight; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.ArrayList; +import java.util.List; + +import org.apache.commons.collections4.CollectionUtils; +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.apache.commons.lang3.tuple.Pair; + +import com.nepxion.discovery.plugin.framework.loadbalance.WeightRandomLoadBalance; +import com.netflix.loadbalancer.Server; + +public abstract class AbstractMapWeightRandomLoadBalance implements WeightRandomLoadBalance { + @Override + public Server choose(List serverList, T t) { + if (CollectionUtils.isEmpty(serverList)) { + return null; + } + + List> weightList = new ArrayList>(); + for (Server server : serverList) { + int weight = getWeight(server, t); + weightList.add(new ImmutablePair(server, weight)); + } + + MapWeightRandom weightRandom = new MapWeightRandom(weightList); + + return weightRandom.random(); + } +} \ No newline at end of file diff --git a/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/loadbalance/weight/AbstractWeightRandomLoadBalanceAdapter.java b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/loadbalance/weight/AbstractWeightRandomLoadBalanceAdapter.java similarity index 78% rename from discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/loadbalance/weight/AbstractWeightRandomLoadBalanceAdapter.java rename to discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/loadbalance/weight/AbstractWeightRandomLoadBalanceAdapter.java index 6ddaa36284..638ff539e4 100644 --- a/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/loadbalance/weight/AbstractWeightRandomLoadBalanceAdapter.java +++ b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/loadbalance/weight/AbstractWeightRandomLoadBalanceAdapter.java @@ -9,6 +9,8 @@ * @version 1.0 */ +import java.util.List; + import com.nepxion.discovery.plugin.framework.adapter.PluginAdapter; import com.nepxion.discovery.plugin.framework.context.PluginContextHolder; import com.netflix.loadbalancer.Server; @@ -26,6 +28,17 @@ public AbstractWeightRandomLoadBalanceAdapter(PluginAdapter pluginAdapter, Plugi this.pluginContextHolder = pluginContextHolder; } + public boolean checkWeight(List serverList, T t) { + for (Server server : serverList) { + int weight = getWeight(server, t); + if (weight < 0) { + return false; + } + } + + return true; + } + public abstract T getT(); public abstract int getWeight(Server server, T t); diff --git a/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/loadbalance/weight/ArrayWeightRandom.java b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/loadbalance/weight/ArrayWeightRandom.java new file mode 100644 index 0000000000..da4d345fa3 --- /dev/null +++ b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/loadbalance/weight/ArrayWeightRandom.java @@ -0,0 +1,88 @@ +package com.nepxion.discovery.plugin.framework.loadbalance.weight; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.ThreadLocalRandom; + +import org.apache.commons.lang3.tuple.Pair; + +// Refactory with code from https://zhuanlan.zhihu.com/p/389788435 +public class ArrayWeightRandom { + private List items = new ArrayList<>(); + private double[] weights; + + public ArrayWeightRandom(List> pairlist) { + calculateWeightS(pairlist); + } + + // 计算权重,初始化或者重新定义权重时使用 + public void calculateWeightS(List> pairlist) { + items.clear(); + + // 计算权重总和 + double originWeightSum = 0; + for (Pair pair : pairlist) { + double weight = pair.getValue().doubleValue(); + if (weight <= 0) { + continue; + } + + items.add(pair.getKey()); + if (Double.isInfinite(weight)) { + weight = 10000.0D; + } + if (Double.isNaN(weight)) { + weight = 1.0D; + } + originWeightSum += weight; + } + + // 计算每个Item的实际权重比例 + double[] actualWeightRatios = new double[items.size()]; + int index = 0; + for (Pair pair : pairlist) { + double weight = pair.getValue().doubleValue(); + if (weight <= 0) { + continue; + } + actualWeightRatios[index++] = weight / originWeightSum; + } + + // 计算每个Item的权重范围 + // 权重范围起始位置 + weights = new double[items.size()]; + double weightRangeStartPos = 0; + for (int i = 0; i < index; i++) { + weights[i] = weightRangeStartPos + actualWeightRatios[i]; + weightRangeStartPos += actualWeightRatios[i]; + } + } + + // 基于权重随机算法选择 + public K random() { + double random = ThreadLocalRandom.current().nextDouble(); + int index = Arrays.binarySearch(weights, random); + if (index < 0) { + index = -index - 1; + } else { + return items.get(index); + } + + if (index < weights.length && random < weights[index]) { + return items.get(index); + } + + // 通常不会走到这里,为了保证能得到正确的返回,这里返回第一个 + return items.get(0); + } +} \ No newline at end of file diff --git a/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/loadbalance/weight/ArrayWeightRandomProcessor.java b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/loadbalance/weight/ArrayWeightRandomProcessor.java new file mode 100644 index 0000000000..16c4a972b5 --- /dev/null +++ b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/loadbalance/weight/ArrayWeightRandomProcessor.java @@ -0,0 +1,28 @@ +package com.nepxion.discovery.plugin.framework.loadbalance.weight; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.List; + +import org.apache.commons.collections4.CollectionUtils; +import org.apache.commons.lang3.tuple.Pair; + +public class ArrayWeightRandomProcessor implements WeightRandomProcessor { + @Override + public T random(List> weightList) { + if (CollectionUtils.isEmpty(weightList)) { + return null; + } + + ArrayWeightRandom weightRandom = new ArrayWeightRandom(weightList); + + return weightRandom.random(); + } +} \ No newline at end of file diff --git a/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/loadbalance/weight/MapWeightRandom.java b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/loadbalance/weight/MapWeightRandom.java new file mode 100644 index 0000000000..db321fc512 --- /dev/null +++ b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/loadbalance/weight/MapWeightRandom.java @@ -0,0 +1,46 @@ +package com.nepxion.discovery.plugin.framework.loadbalance.weight; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.List; +import java.util.SortedMap; +import java.util.TreeMap; + +import org.apache.commons.collections4.MapUtils; +import org.apache.commons.lang3.tuple.Pair; + +import com.nepxion.discovery.common.exception.DiscoveryException; + +public class MapWeightRandom { + private TreeMap weightMap = new TreeMap(); + + public MapWeightRandom(List> pairlist) { + for (Pair pair : pairlist) { + double value = pair.getValue().doubleValue(); + if (value <= 0) { + continue; + } + + double lastWeight = weightMap.size() == 0 ? 0 : weightMap.lastKey().doubleValue(); + weightMap.put(value + lastWeight, pair.getKey()); + } + } + + public K random() { + if (MapUtils.isEmpty(weightMap)) { + throw new DiscoveryException("Weight values are all <= 0 or invalid format"); + } + + double randomWeight = weightMap.lastKey() * Math.random(); + SortedMap tailMap = weightMap.tailMap(randomWeight, false); + + return weightMap.get(tailMap.firstKey()); + } +} \ No newline at end of file diff --git a/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/loadbalance/weight/MapWeightRandomProcessor.java b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/loadbalance/weight/MapWeightRandomProcessor.java new file mode 100644 index 0000000000..0a88b4c663 --- /dev/null +++ b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/loadbalance/weight/MapWeightRandomProcessor.java @@ -0,0 +1,28 @@ +package com.nepxion.discovery.plugin.framework.loadbalance.weight; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.List; + +import org.apache.commons.collections4.CollectionUtils; +import org.apache.commons.lang3.tuple.Pair; + +public class MapWeightRandomProcessor implements WeightRandomProcessor { + @Override + public T random(List> weightList) { + if (CollectionUtils.isEmpty(weightList)) { + return null; + } + + MapWeightRandom weightRandom = new MapWeightRandom(weightList); + + return weightRandom.random(); + } +} \ No newline at end of file diff --git a/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/loadbalance/weight/RuleArrayWeightRandomLoadBalance.java b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/loadbalance/weight/RuleArrayWeightRandomLoadBalance.java similarity index 75% rename from discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/loadbalance/weight/RuleArrayWeightRandomLoadBalance.java rename to discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/loadbalance/weight/RuleArrayWeightRandomLoadBalance.java index 481c1af132..4296ddcde8 100644 --- a/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/loadbalance/weight/RuleArrayWeightRandomLoadBalance.java +++ b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/loadbalance/weight/RuleArrayWeightRandomLoadBalance.java @@ -9,11 +9,13 @@ * @version 1.0 */ +import java.util.List; + import com.nepxion.discovery.common.entity.WeightFilterEntity; import com.nepxion.discovery.plugin.framework.adapter.PluginAdapter; import com.netflix.loadbalancer.Server; -public class RuleArrayWeightRandomLoadBalance extends AbstractArrayWeightRandomLoadBalance { +public class RuleArrayWeightRandomLoadBalance extends AbstractArrayWeightRandomLoadBalance implements RuleWeightRandomLoadBalance { private RuleWeightRandomLoadBalanceAdapter ruleWeightRandomLoadBalanceAdapter; public RuleArrayWeightRandomLoadBalance(PluginAdapter pluginAdapter) { @@ -29,4 +31,9 @@ public WeightFilterEntity getT() { public int getWeight(Server server, WeightFilterEntity weightFilterEntity) { return ruleWeightRandomLoadBalanceAdapter.getWeight(server, weightFilterEntity); } + + @Override + public boolean checkWeight(List serverList, WeightFilterEntity weightFilterEntity) { + return ruleWeightRandomLoadBalanceAdapter.checkWeight(serverList, weightFilterEntity); + } } \ No newline at end of file diff --git a/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/loadbalance/weight/RuleMapWeightRandomLoadBalance.java b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/loadbalance/weight/RuleMapWeightRandomLoadBalance.java similarity index 75% rename from discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/loadbalance/weight/RuleMapWeightRandomLoadBalance.java rename to discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/loadbalance/weight/RuleMapWeightRandomLoadBalance.java index 054776c872..8fd7e55f48 100644 --- a/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/loadbalance/weight/RuleMapWeightRandomLoadBalance.java +++ b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/loadbalance/weight/RuleMapWeightRandomLoadBalance.java @@ -9,11 +9,13 @@ * @version 1.0 */ +import java.util.List; + import com.nepxion.discovery.common.entity.WeightFilterEntity; import com.nepxion.discovery.plugin.framework.adapter.PluginAdapter; import com.netflix.loadbalancer.Server; -public class RuleMapWeightRandomLoadBalance extends AbstractMapWeightRandomLoadBalance { +public class RuleMapWeightRandomLoadBalance extends AbstractMapWeightRandomLoadBalance implements RuleWeightRandomLoadBalance { private RuleWeightRandomLoadBalanceAdapter ruleWeightRandomLoadBalanceAdapter; public RuleMapWeightRandomLoadBalance(PluginAdapter pluginAdapter) { @@ -29,4 +31,9 @@ public WeightFilterEntity getT() { public int getWeight(Server server, WeightFilterEntity weightFilterEntity) { return ruleWeightRandomLoadBalanceAdapter.getWeight(server, weightFilterEntity); } + + @Override + public boolean checkWeight(List serverList, WeightFilterEntity weightFilterEntity) { + return ruleWeightRandomLoadBalanceAdapter.checkWeight(serverList, weightFilterEntity); + } } \ No newline at end of file diff --git a/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/loadbalance/weight/RuleWeightRandomLoadBalance.java b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/loadbalance/weight/RuleWeightRandomLoadBalance.java new file mode 100644 index 0000000000..da12f0009c --- /dev/null +++ b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/loadbalance/weight/RuleWeightRandomLoadBalance.java @@ -0,0 +1,16 @@ +package com.nepxion.discovery.plugin.framework.loadbalance.weight; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import com.nepxion.discovery.plugin.framework.loadbalance.WeightRandomLoadBalance; + +public interface RuleWeightRandomLoadBalance extends WeightRandomLoadBalance { + +} \ No newline at end of file diff --git a/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/loadbalance/weight/RuleWeightRandomLoadBalanceAdapter.java b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/loadbalance/weight/RuleWeightRandomLoadBalanceAdapter.java new file mode 100644 index 0000000000..f8a1e97166 --- /dev/null +++ b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/loadbalance/weight/RuleWeightRandomLoadBalanceAdapter.java @@ -0,0 +1,50 @@ +package com.nepxion.discovery.plugin.framework.loadbalance.weight; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import com.nepxion.discovery.common.entity.DiscoveryEntity; +import com.nepxion.discovery.common.entity.RuleEntity; +import com.nepxion.discovery.common.entity.WeightEntityWrapper; +import com.nepxion.discovery.common.entity.WeightFilterEntity; +import com.nepxion.discovery.plugin.framework.adapter.PluginAdapter; +import com.netflix.loadbalancer.Server; + +public class RuleWeightRandomLoadBalanceAdapter extends AbstractWeightRandomLoadBalanceAdapter { + public RuleWeightRandomLoadBalanceAdapter(PluginAdapter pluginAdapter) { + super(pluginAdapter); + } + + @Override + public WeightFilterEntity getT() { + RuleEntity ruleEntity = pluginAdapter.getRule(); + if (ruleEntity == null) { + return null; + } + + DiscoveryEntity discoveryEntity = ruleEntity.getDiscoveryEntity(); + if (discoveryEntity == null) { + return null; + } + + WeightFilterEntity weightFilterEntity = discoveryEntity.getWeightFilterEntity(); + + return weightFilterEntity; + } + + @Override + public int getWeight(Server server, WeightFilterEntity weightFilterEntity) { + String providerServiceId = pluginAdapter.getServerServiceId(server); + String providerVersion = pluginAdapter.getServerVersion(server); + String providerRegion = pluginAdapter.getServerRegion(server); + String serviceId = pluginAdapter.getServiceId(); + + return WeightEntityWrapper.getWeight(weightFilterEntity, providerServiceId, providerVersion, providerRegion, serviceId); + } +} \ No newline at end of file diff --git a/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/loadbalance/weight/StrategyArrayWeightRandomLoadBalance.java b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/loadbalance/weight/StrategyArrayWeightRandomLoadBalance.java similarity index 77% rename from discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/loadbalance/weight/StrategyArrayWeightRandomLoadBalance.java rename to discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/loadbalance/weight/StrategyArrayWeightRandomLoadBalance.java index 2aa23fc68e..1d4f3608ad 100644 --- a/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/loadbalance/weight/StrategyArrayWeightRandomLoadBalance.java +++ b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/loadbalance/weight/StrategyArrayWeightRandomLoadBalance.java @@ -9,12 +9,14 @@ * @version 1.0 */ +import java.util.List; + import com.nepxion.discovery.common.entity.WeightFilterEntity; import com.nepxion.discovery.plugin.framework.adapter.PluginAdapter; import com.nepxion.discovery.plugin.framework.context.PluginContextHolder; import com.netflix.loadbalancer.Server; -public class StrategyArrayWeightRandomLoadBalance extends AbstractArrayWeightRandomLoadBalance { +public class StrategyArrayWeightRandomLoadBalance extends AbstractArrayWeightRandomLoadBalance implements StrategyWeightRandomLoadBalance { private StrategyWeightRandomLoadBalanceAdapter strategyWeightRandomLoadBalanceAdapter; public StrategyArrayWeightRandomLoadBalance(PluginAdapter pluginAdapter, PluginContextHolder pluginContextHolder) { @@ -30,4 +32,9 @@ public WeightFilterEntity getT() { public int getWeight(Server server, WeightFilterEntity weightFilterEntity) { return strategyWeightRandomLoadBalanceAdapter.getWeight(server, weightFilterEntity); } + + @Override + public boolean checkWeight(List serverList, WeightFilterEntity weightFilterEntity) { + return strategyWeightRandomLoadBalanceAdapter.checkWeight(serverList, weightFilterEntity); + } } \ No newline at end of file diff --git a/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/loadbalance/weight/StrategyMapWeightRandomLoadBalance.java b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/loadbalance/weight/StrategyMapWeightRandomLoadBalance.java similarity index 77% rename from discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/loadbalance/weight/StrategyMapWeightRandomLoadBalance.java rename to discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/loadbalance/weight/StrategyMapWeightRandomLoadBalance.java index 14519040c4..2edbc71e77 100644 --- a/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/loadbalance/weight/StrategyMapWeightRandomLoadBalance.java +++ b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/loadbalance/weight/StrategyMapWeightRandomLoadBalance.java @@ -9,12 +9,14 @@ * @version 1.0 */ +import java.util.List; + import com.nepxion.discovery.common.entity.WeightFilterEntity; import com.nepxion.discovery.plugin.framework.adapter.PluginAdapter; import com.nepxion.discovery.plugin.framework.context.PluginContextHolder; import com.netflix.loadbalancer.Server; -public class StrategyMapWeightRandomLoadBalance extends AbstractMapWeightRandomLoadBalance { +public class StrategyMapWeightRandomLoadBalance extends AbstractMapWeightRandomLoadBalance implements StrategyWeightRandomLoadBalance { private StrategyWeightRandomLoadBalanceAdapter strategyWeightRandomLoadBalanceAdapter; public StrategyMapWeightRandomLoadBalance(PluginAdapter pluginAdapter, PluginContextHolder pluginContextHolder) { @@ -30,4 +32,9 @@ public WeightFilterEntity getT() { public int getWeight(Server server, WeightFilterEntity weightFilterEntity) { return strategyWeightRandomLoadBalanceAdapter.getWeight(server, weightFilterEntity); } + + @Override + public boolean checkWeight(List serverList, WeightFilterEntity weightFilterEntity) { + return strategyWeightRandomLoadBalanceAdapter.checkWeight(serverList, weightFilterEntity); + } } \ No newline at end of file diff --git a/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/loadbalance/weight/StrategyWeightRandomLoadBalance.java b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/loadbalance/weight/StrategyWeightRandomLoadBalance.java new file mode 100644 index 0000000000..42ef624f88 --- /dev/null +++ b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/loadbalance/weight/StrategyWeightRandomLoadBalance.java @@ -0,0 +1,16 @@ +package com.nepxion.discovery.plugin.framework.loadbalance.weight; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import com.nepxion.discovery.plugin.framework.loadbalance.WeightRandomLoadBalance; + +public interface StrategyWeightRandomLoadBalance extends WeightRandomLoadBalance { + +} \ No newline at end of file diff --git a/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/loadbalance/weight/StrategyWeightRandomLoadBalanceAdapter.java b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/loadbalance/weight/StrategyWeightRandomLoadBalanceAdapter.java new file mode 100644 index 0000000000..37f36b088f --- /dev/null +++ b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/loadbalance/weight/StrategyWeightRandomLoadBalanceAdapter.java @@ -0,0 +1,77 @@ +package com.nepxion.discovery.plugin.framework.loadbalance.weight; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.List; + +import org.apache.commons.lang3.StringUtils; + +import com.nepxion.discovery.common.entity.RegionWeightEntity; +import com.nepxion.discovery.common.entity.VersionWeightEntity; +import com.nepxion.discovery.common.entity.WeightEntity; +import com.nepxion.discovery.common.entity.WeightEntityWrapper; +import com.nepxion.discovery.common.entity.WeightFilterEntity; +import com.nepxion.discovery.plugin.framework.adapter.PluginAdapter; +import com.nepxion.discovery.plugin.framework.context.PluginContextHolder; +import com.netflix.loadbalancer.Server; + +public class StrategyWeightRandomLoadBalanceAdapter extends AbstractWeightRandomLoadBalanceAdapter { + public StrategyWeightRandomLoadBalanceAdapter(PluginAdapter pluginAdapter, PluginContextHolder pluginContextHolder) { + super(pluginAdapter, pluginContextHolder); + } + + @Override + public WeightFilterEntity getT() { + if (pluginContextHolder == null) { + return null; + } + + WeightFilterEntity weightFilterEntity = new WeightFilterEntity(); + + String versionWeightValue = pluginContextHolder.getContextRouteVersionWeight(); + if (StringUtils.isNotEmpty(versionWeightValue)) { + try { + List weightEntityList = WeightEntityWrapper.parseWeightEntityList(versionWeightValue); + weightFilterEntity.setVersionWeightEntityList(weightEntityList); + } catch (Exception e) { + VersionWeightEntity weightEntity = new VersionWeightEntity(); + + WeightEntityWrapper.parseWeightEntity(weightEntity, versionWeightValue); + + weightFilterEntity.setVersionWeightEntity(weightEntity); + } + } + + String regionWeightValue = pluginContextHolder.getContextRouteRegionWeight(); + if (StringUtils.isNotEmpty(regionWeightValue)) { + try { + List weightEntityList = WeightEntityWrapper.parseWeightEntityList(regionWeightValue); + weightFilterEntity.setRegionWeightEntityList(weightEntityList); + } catch (Exception e) { + RegionWeightEntity weightEntity = new RegionWeightEntity(); + + WeightEntityWrapper.parseWeightEntity(weightEntity, regionWeightValue); + + weightFilterEntity.setRegionWeightEntity(weightEntity); + } + } + + return weightFilterEntity; + } + + @Override + public int getWeight(Server server, WeightFilterEntity weightFilterEntity) { + String providerServiceId = pluginAdapter.getServerServiceId(server); + String providerVersion = pluginAdapter.getServerVersion(server); + String providerRegion = pluginAdapter.getServerRegion(server); + + return WeightEntityWrapper.getWeight(weightFilterEntity, providerServiceId, providerVersion, providerRegion, null); + } +} \ No newline at end of file diff --git a/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/loadbalance/weight/WeightRandomProcessor.java b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/loadbalance/weight/WeightRandomProcessor.java new file mode 100644 index 0000000000..dbde8f10fe --- /dev/null +++ b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/loadbalance/weight/WeightRandomProcessor.java @@ -0,0 +1,18 @@ +package com.nepxion.discovery.plugin.framework.loadbalance.weight; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.List; + +import org.apache.commons.lang3.tuple.Pair; + +public interface WeightRandomProcessor { + T random(List> weightList); +} \ No newline at end of file diff --git a/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/util/MetadataUtil.java b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/util/MetadataUtil.java new file mode 100644 index 0000000000..2a757a1d55 --- /dev/null +++ b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/util/MetadataUtil.java @@ -0,0 +1,122 @@ +package com.nepxion.discovery.plugin.framework.util; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.Set; + +import org.springframework.core.env.Environment; + +import com.nepxion.discovery.common.constant.DiscoveryConstant; +import com.nepxion.discovery.common.util.PropertiesUtil; + +public class MetadataUtil { + // 过滤设置元数据到Metadata Map + public static void filter(Map metadata, Environment environment) { + // 运维参数元数据的设置方式 + // 支持从-Dmetadata.xyz参数获取 + Properties properties = System.getProperties(); + Set propertyNames = properties.stringPropertyNames(); + for (String propertyName : propertyNames) { + if (propertyName.startsWith(DiscoveryConstant.METADATA + ".")) { + String key = propertyName.substring((DiscoveryConstant.METADATA + ".").length()); + String value = properties.get(propertyName).toString(); + + // -Dmetadata.xyz优先级最高 + // 不管元数据是否存在,直接放入或者覆盖 + metadata.put(key, value); + } + } + + // 统一注册中心元数据的设置方式 + // 支持spring.cloud.discovery.metadata.xyz配置获取 + Properties enrichProperties = new Properties(); + PropertiesUtil.enrichProperties(enrichProperties, environment, DiscoveryConstant.SPRING_CLOUD_DISCOVERY_PREFIX, false, true); + Set enrichPropertyNames = enrichProperties.stringPropertyNames(); + for (String enrichPropertyName : enrichPropertyNames) { + if (enrichPropertyName.startsWith(DiscoveryConstant.METADATA + ".")) { + String key = enrichPropertyName.substring((DiscoveryConstant.METADATA + ".").length()); + String value = enrichProperties.get(enrichPropertyName).toString(); + + // spring.cloud.discovery.metadata.xyz优先级最低 + // 当元数据不存在,才放入 + if (!metadata.containsKey(key)) { + metadata.put(key, value); + } + } + } + } + + // 过滤设置元数据到Metadata List + // 该方式适用于旧版Consul元数据模式 + public static void filter(List metadata, Environment environment) { + // 运维参数元数据的设置方式 + // 支持从-Dmetadata.xyz参数获取 + Properties properties = System.getProperties(); + Set propertyNames = properties.stringPropertyNames(); + for (String propertyName : propertyNames) { + if (propertyName.startsWith(DiscoveryConstant.METADATA + ".")) { + String key = propertyName.substring((DiscoveryConstant.METADATA + ".").length()); + String value = properties.get(propertyName).toString(); + + // -Dmetadata.xyz优先级最高 + // 不管元数据是否存在,直接放入或者覆盖 + int index = getIndex(metadata, key); + if (index > -1) { + metadata.set(index, key + "=" + value); + } else { + metadata.add(key + "=" + value); + } + } + } + + // 统一注册中心元数据的设置方式 + // 支持spring.cloud.discovery.metadata.xyz配置获取 + Properties enrichProperties = new Properties(); + PropertiesUtil.enrichProperties(enrichProperties, environment, DiscoveryConstant.SPRING_CLOUD_DISCOVERY_PREFIX, false, true); + Set enrichPropertyNames = enrichProperties.stringPropertyNames(); + for (String enrichPropertyName : enrichPropertyNames) { + if (enrichPropertyName.startsWith(DiscoveryConstant.METADATA + ".")) { + String key = enrichPropertyName.substring((DiscoveryConstant.METADATA + ".").length()); + String value = enrichProperties.get(enrichPropertyName).toString(); + + // spring.cloud.discovery.metadata.xyz优先级最低 + // 当元数据不存在,才放入 + int index = getIndex(metadata, key); + if (index <= -1) { + metadata.add(key + "=" + value); + } + } + } + } + + public static int getIndex(List metadata, String key) { + for (int i = 0; i < metadata.size(); i++) { + String value = metadata.get(i); + if (value.startsWith(key + "=")) { + return i; + } + } + + return -1; + } + + public static boolean containsKey(List metadata, String key) { + for (String value : metadata) { + if (value.startsWith(key + "=")) { + return true; + } + } + + return false; + } +} \ No newline at end of file diff --git a/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/resources/META-INF/spring.factories b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/resources/META-INF/spring.factories new file mode 100644 index 0000000000..f40a7b13ba --- /dev/null +++ b/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/resources/META-INF/spring.factories @@ -0,0 +1,5 @@ +org.springframework.boot.env.EnvironmentPostProcessor=\ +com.nepxion.discovery.plugin.framework.context.PluginEnvironmentPostProcessor + +org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ +com.nepxion.discovery.plugin.framework.configuration.PluginAutoConfiguration \ No newline at end of file diff --git a/discovery-plugin-framework/discovery-plugin-framework-starter/src/test/java/com/nepxion/discovery/plugin/framework/loadbalance/ArrayWeightRandomLoadBalanceTest.java b/discovery-plugin-framework/discovery-plugin-framework-starter/src/test/java/com/nepxion/discovery/plugin/framework/loadbalance/ArrayWeightRandomLoadBalanceTest.java new file mode 100644 index 0000000000..c98a5915e6 --- /dev/null +++ b/discovery-plugin-framework/discovery-plugin-framework-starter/src/test/java/com/nepxion/discovery/plugin/framework/loadbalance/ArrayWeightRandomLoadBalanceTest.java @@ -0,0 +1,77 @@ +package com.nepxion.discovery.plugin.framework.loadbalance; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.text.DecimalFormat; +import java.util.ArrayList; +import java.util.List; + +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.apache.commons.lang3.tuple.Pair; + +import com.nepxion.discovery.plugin.framework.loadbalance.weight.MapWeightRandom; + +public class ArrayWeightRandomLoadBalanceTest { + public static void main(String[] args) { + test(1000000); + } + + public static void test(int totalCount) { + long t = System.currentTimeMillis(); + + List> list = new ArrayList>(); + list.add(new ImmutablePair("1.0", 10D)); + list.add(new ImmutablePair("2.0", 50D)); + list.add(new ImmutablePair("3.0", 20D)); + list.add(new ImmutablePair("1.0", 10D)); + list.add(new ImmutablePair("2.0", 50D)); + list.add(new ImmutablePair("3.0", 20D)); + list.add(new ImmutablePair("4.0", 5D)); + list.add(new ImmutablePair("4.0", 5D)); + list.add(new ImmutablePair("5.0", 15D)); + list.add(new ImmutablePair("5.0", 15D)); + + int v1Count = 0; + int v2Count = 0; + int v3Count = 0; + int v4Count = 0; + int v5Count = 0; + for (int i = 0; i < totalCount; i++) { + MapWeightRandom weightRandom = new MapWeightRandom(list); + String server = weightRandom.random(); + if (server.startsWith("1.0")) { + v1Count++; + } + if (server.startsWith("2.0")) { + v2Count++; + } + if (server.startsWith("3.0")) { + v3Count++; + } + if (server.startsWith("4.0")) { + v4Count++; + } + if (server.startsWith("5.0")) { + v5Count++; + } + } + + System.out.println("------------------------------"); + System.out.println(totalCount + "次循环,数组方式随机权重准确度和性能:"); + DecimalFormat format = new DecimalFormat("0.0000"); + System.out.println("1.0版本服务随机权重=" + format.format((double) v1Count * 100 / totalCount) + "%"); + System.out.println("2.0版本服务随机权重=" + format.format((double) v2Count * 100 / totalCount) + "%"); + System.out.println("3.0版本服务随机权重=" + format.format((double) v3Count * 100 / totalCount) + "%"); + System.out.println("4.0版本服务随机权重=" + format.format((double) v4Count * 100 / totalCount) + "%"); + System.out.println("5.0版本服务随机权重=" + format.format((double) v5Count * 100 / totalCount) + "%"); + System.out.println("耗时时间:" + (System.currentTimeMillis() - t)); + System.out.println("------------------------------"); + } +} \ No newline at end of file diff --git a/discovery-plugin-framework/discovery-plugin-framework-starter/src/test/java/com/nepxion/discovery/plugin/framework/loadbalance/MapWeightRandomLoadBalanceTest.java b/discovery-plugin-framework/discovery-plugin-framework-starter/src/test/java/com/nepxion/discovery/plugin/framework/loadbalance/MapWeightRandomLoadBalanceTest.java new file mode 100644 index 0000000000..30392493b3 --- /dev/null +++ b/discovery-plugin-framework/discovery-plugin-framework-starter/src/test/java/com/nepxion/discovery/plugin/framework/loadbalance/MapWeightRandomLoadBalanceTest.java @@ -0,0 +1,77 @@ +package com.nepxion.discovery.plugin.framework.loadbalance; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.text.DecimalFormat; +import java.util.ArrayList; +import java.util.List; + +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.apache.commons.lang3.tuple.Pair; + +import com.nepxion.discovery.plugin.framework.loadbalance.weight.MapWeightRandom; + +public class MapWeightRandomLoadBalanceTest { + public static void main(String[] args) { + test(1000000); + } + + public static void test(int totalCount) { + long t = System.currentTimeMillis(); + + List> list = new ArrayList>(); + list.add(new ImmutablePair("1.0", 10D)); + list.add(new ImmutablePair("2.0", 50D)); + list.add(new ImmutablePair("3.0", 20D)); + list.add(new ImmutablePair("1.0", 10D)); + list.add(new ImmutablePair("2.0", 50D)); + list.add(new ImmutablePair("3.0", 20D)); + list.add(new ImmutablePair("4.0", 5D)); + list.add(new ImmutablePair("4.0", 5D)); + list.add(new ImmutablePair("5.0", 15D)); + list.add(new ImmutablePair("5.0", 15D)); + + int v1Count = 0; + int v2Count = 0; + int v3Count = 0; + int v4Count = 0; + int v5Count = 0; + for (int i = 0; i < totalCount; i++) { + MapWeightRandom weightRandom = new MapWeightRandom(list); + String server = weightRandom.random(); + if (server.startsWith("1.0")) { + v1Count++; + } + if (server.startsWith("2.0")) { + v2Count++; + } + if (server.startsWith("3.0")) { + v3Count++; + } + if (server.startsWith("4.0")) { + v4Count++; + } + if (server.startsWith("5.0")) { + v5Count++; + } + } + + System.out.println("------------------------------"); + System.out.println(totalCount + "次循环,散列方式随机权重准确度和性能:"); + DecimalFormat format = new DecimalFormat("0.0000"); + System.out.println("1.0版本服务随机权重=" + format.format((double) v1Count * 100 / totalCount) + "%"); + System.out.println("2.0版本服务随机权重=" + format.format((double) v2Count * 100 / totalCount) + "%"); + System.out.println("3.0版本服务随机权重=" + format.format((double) v3Count * 100 / totalCount) + "%"); + System.out.println("4.0版本服务随机权重=" + format.format((double) v4Count * 100 / totalCount) + "%"); + System.out.println("5.0版本服务随机权重=" + format.format((double) v5Count * 100 / totalCount) + "%"); + System.out.println("耗时时间:" + (System.currentTimeMillis() - t)); + System.out.println("------------------------------"); + } +} \ No newline at end of file diff --git a/discovery-plugin-framework/src/test/java/com/nepxion/discovery/plugin/framework/loadbalance/WeightRandomLoadBalanceTest.java b/discovery-plugin-framework/discovery-plugin-framework-starter/src/test/java/com/nepxion/discovery/plugin/framework/loadbalance/WeightRandomLoadBalanceTest.java similarity index 90% rename from discovery-plugin-framework/src/test/java/com/nepxion/discovery/plugin/framework/loadbalance/WeightRandomLoadBalanceTest.java rename to discovery-plugin-framework/discovery-plugin-framework-starter/src/test/java/com/nepxion/discovery/plugin/framework/loadbalance/WeightRandomLoadBalanceTest.java index f4bc6033c3..7f07481b3d 100644 --- a/discovery-plugin-framework/src/test/java/com/nepxion/discovery/plugin/framework/loadbalance/WeightRandomLoadBalanceTest.java +++ b/discovery-plugin-framework/discovery-plugin-framework-starter/src/test/java/com/nepxion/discovery/plugin/framework/loadbalance/WeightRandomLoadBalanceTest.java @@ -19,7 +19,7 @@ public static void main(String[] args) { System.out.println("5.0版本服务随机权重=15%"); System.out.println(""); - int[] totalCounts = new int[] { 1000000, 2000000, 5000000, 10000000, 50000000, 100000000 }; + int[] totalCounts = new int[] { 100, 1000, 10000, 100000,1000000, 2000000, 5000000, 10000000, 50000000, 100000000 }; for (int i = 0; i < totalCounts.length; i++) { test(i + 1, totalCounts[i]); } diff --git a/discovery-plugin-framework/pom.xml b/discovery-plugin-framework/pom.xml index f0ac020545..a6905bf60d 100644 --- a/discovery-plugin-framework/pom.xml +++ b/discovery-plugin-framework/pom.xml @@ -3,51 +3,19 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> discovery-plugin-framework Nepxion Discovery Plugin Framework - jar + pom 4.0.0 - Nepxion Discovery is an enhancement for Spring Cloud Discovery + Nepxion Discovery is a solution for Spring Cloud with blue green, gray, weight, limitation, circuit breaker, degrade, isolation, monitor, tracing, dye, failover, async agent http://www.nepxion.com com.nepxion discovery - 5.2.0-SNAPSHOT + 6.23.0 - - - ${project.groupId} - discovery-common - - - - ${project.groupId} - eventbus-aop-starter - - - - ${project.groupId} - banner - - - - org.springframework.cloud - spring-cloud-starter - - - - org.springframework.cloud - spring-cloud-starter-netflix-ribbon - - - - com.google.guava - guava - - - - com.github.ben-manes.caffeine - caffeine - - + + discovery-plugin-framework-starter + discovery-plugin-framework-starter-parser + \ No newline at end of file diff --git a/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/adapter/AbstractPluginAdapter.java b/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/adapter/AbstractPluginAdapter.java deleted file mode 100644 index 9961deab22..0000000000 --- a/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/adapter/AbstractPluginAdapter.java +++ /dev/null @@ -1,229 +0,0 @@ -package com.nepxion.discovery.plugin.framework.adapter; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import java.util.Map; - -import org.apache.commons.lang3.StringUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.cloud.client.ServiceInstance; -import org.springframework.cloud.client.serviceregistry.Registration; - -import com.nepxion.discovery.common.constant.DiscoveryConstant; -import com.nepxion.discovery.common.entity.RuleEntity; -import com.nepxion.discovery.common.exception.DiscoveryException; -import com.nepxion.discovery.plugin.framework.cache.PluginCache; -import com.nepxion.discovery.plugin.framework.cache.RuleCache; -import com.nepxion.discovery.plugin.framework.context.PluginContextAware; -import com.netflix.loadbalancer.Server; - -public abstract class AbstractPluginAdapter implements PluginAdapter { - @Autowired - protected Registration registration; - - @Autowired - protected PluginContextAware pluginContextAware; - - @Autowired - protected PluginCache pluginCache; - - @Autowired - protected RuleCache ruleCache; - - @Override - public String getGroupKey() { - return pluginContextAware.getGroupKey(); - } - - @Override - public String getGroup() { - String groupKey = getGroupKey(); - - String group = getGroup(groupKey); - if (StringUtils.isEmpty(group)) { - throw new DiscoveryException("The value is null or empty for metadata key=" + groupKey + ", please check your configuration"); - } - - return group; - } - - protected String getGroup(String groupKey) { - return getMetadata().get(groupKey); - } - - @Override - public String getServiceType() { - return pluginContextAware.getApplicationType(); - } - - @Override - public String getServiceId() { - return registration.getServiceId().toLowerCase(); - } - - @Override - public String getHost() { - return registration.getHost(); - } - - @Override - public int getPort() { - return registration.getPort(); - } - - @Override - public String getContextPath() { - return getMetadata().get(DiscoveryConstant.SPRING_APPLICATION_CONTEXT_PATH); - } - - @Override - public Map getMetadata() { - return registration.getMetadata(); - } - - @Override - public String getVersion() { - String dynamicVersion = getDynamicVersion(); - if (StringUtils.isNotEmpty(dynamicVersion)) { - return dynamicVersion; - } - - return getLocalVersion(); - } - - @Override - public String getLocalVersion() { - return getMetadata().get(DiscoveryConstant.VERSION); - } - - @Override - public String getDynamicVersion() { - return pluginCache.get(DiscoveryConstant.DYNAMIC_VERSION); - } - - @Override - public void setDynamicVersion(String version) { - pluginCache.put(DiscoveryConstant.DYNAMIC_VERSION, version); - } - - @Override - public void clearDynamicVersion() { - pluginCache.clear(DiscoveryConstant.DYNAMIC_VERSION); - } - - @Override - public RuleEntity getRule() { - RuleEntity dynamicRuleEntity = getDynamicRule(); - if (dynamicRuleEntity != null) { - return dynamicRuleEntity; - } - - return getLocalRule(); - } - - @Override - public RuleEntity getLocalRule() { - return ruleCache.get(DiscoveryConstant.RULE); - } - - @Override - public void setLocalRule(RuleEntity ruleEntity) { - ruleCache.put(DiscoveryConstant.RULE, ruleEntity); - } - - @Override - public RuleEntity getDynamicRule() { - return ruleCache.get(DiscoveryConstant.DYNAMIC_RULE); - } - - @Override - public void setDynamicRule(RuleEntity ruleEntity) { - ruleCache.put(DiscoveryConstant.DYNAMIC_RULE, ruleEntity); - } - - @Override - public void clearDynamicRule() { - ruleCache.clear(DiscoveryConstant.DYNAMIC_RULE); - } - - @Override - public String getRegion() { - return getMetadata().get(DiscoveryConstant.REGION); - } - - @Override - public String getServerGroupKey(Server server) { - return getServerMetadata(server).get(DiscoveryConstant.SPRING_APPLICATION_GROUP_KEY); - } - - @Override - public String getServerGroup(Server server) { - String serverGroupKey = getServerGroupKey(server); - - return getServerMetadata(server).get(serverGroupKey); - } - - @Override - public String getServerServiceType(Server server) { - return getServerMetadata(server).get(DiscoveryConstant.SPRING_APPLICATION_TYPE); - } - - @Override - public String getServerServiceId(Server server) { - return getServerMetadata(server).get(DiscoveryConstant.SPRING_APPLICATION_NAME).toLowerCase(); - } - - @Override - public String getServerVersion(Server server) { - return getServerMetadata(server).get(DiscoveryConstant.VERSION); - } - - @Override - public String getServerRegion(Server server) { - return getServerMetadata(server).get(DiscoveryConstant.REGION); - } - - @Override - public Map getInstanceMetadata(ServiceInstance serviceInstance) { - return serviceInstance.getMetadata(); - } - - @Override - public String getInstanceGroupKey(ServiceInstance serviceInstance) { - return getInstanceMetadata(serviceInstance).get(DiscoveryConstant.SPRING_APPLICATION_GROUP_KEY); - } - - @Override - public String getInstanceGroup(ServiceInstance serviceInstance) { - String instanceGroupKey = getInstanceGroupKey(serviceInstance); - - return getInstanceMetadata(serviceInstance).get(instanceGroupKey); - } - - @Override - public String getInstanceServiceType(ServiceInstance serviceInstance) { - return getInstanceMetadata(serviceInstance).get(DiscoveryConstant.SPRING_APPLICATION_TYPE); - } - - @Override - public String getInstanceServiceId(ServiceInstance serviceInstance) { - return serviceInstance.getServiceId().toLowerCase(); - } - - @Override - public String getInstanceVersion(ServiceInstance serviceInstance) { - return getInstanceMetadata(serviceInstance).get(DiscoveryConstant.VERSION); - } - - @Override - public String getInstanceRegion(ServiceInstance serviceInstance) { - return getInstanceMetadata(serviceInstance).get(DiscoveryConstant.REGION); - } -} \ No newline at end of file diff --git a/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/adapter/PluginAdapter.java b/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/adapter/PluginAdapter.java deleted file mode 100644 index 6f97693ab4..0000000000 --- a/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/adapter/PluginAdapter.java +++ /dev/null @@ -1,87 +0,0 @@ -package com.nepxion.discovery.plugin.framework.adapter; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import java.util.Map; - -import org.springframework.cloud.client.ServiceInstance; - -import com.nepxion.discovery.common.entity.RuleEntity; -import com.netflix.loadbalancer.Server; - -public interface PluginAdapter { - String getGroupKey(); - - String getGroup(); - - String getServiceType(); - - String getServiceId(); - - String getHost(); - - int getPort(); - - String getContextPath(); - - Map getMetadata(); - - String getVersion(); - - String getLocalVersion(); - - String getDynamicVersion(); - - void setDynamicVersion(String version); - - void clearDynamicVersion(); - - RuleEntity getRule(); - - RuleEntity getLocalRule(); - - void setLocalRule(RuleEntity ruleEntity); - - RuleEntity getDynamicRule(); - - void setDynamicRule(RuleEntity ruleEntity); - - void clearDynamicRule(); - - String getRegion(); - - Map getServerMetadata(Server server); - - String getServerGroupKey(Server server); - - String getServerGroup(Server server); - - String getServerServiceType(Server server); - - String getServerServiceId(Server server); - - String getServerVersion(Server server); - - String getServerRegion(Server server); - - Map getInstanceMetadata(ServiceInstance serviceInstance); - - String getInstanceGroupKey(ServiceInstance serviceInstance); - - String getInstanceGroup(ServiceInstance serviceInstance); - - String getInstanceServiceType(ServiceInstance serviceInstance); - - String getInstanceServiceId(ServiceInstance serviceInstance); - - String getInstanceVersion(ServiceInstance serviceInstance); - - String getInstanceRegion(ServiceInstance serviceInstance); -} \ No newline at end of file diff --git a/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/configuration/PluginAutoConfiguration.java b/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/configuration/PluginAutoConfiguration.java deleted file mode 100644 index 5f627e5e9e..0000000000 --- a/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/configuration/PluginAutoConfiguration.java +++ /dev/null @@ -1,120 +0,0 @@ -package com.nepxion.discovery.plugin.framework.configuration; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -import com.nepxion.discovery.common.constant.DiscoveryConstant; -import com.nepxion.discovery.plugin.framework.cache.PluginCache; -import com.nepxion.discovery.plugin.framework.cache.RuleCache; -import com.nepxion.discovery.plugin.framework.context.PluginContextAware; -import com.nepxion.discovery.plugin.framework.event.PluginEventWapper; -import com.nepxion.discovery.plugin.framework.event.PluginPublisher; -import com.nepxion.discovery.plugin.framework.event.PluginSubscriber; -import com.nepxion.discovery.plugin.framework.listener.discovery.DiscoveryListenerExecutor; -import com.nepxion.discovery.plugin.framework.listener.discovery.HostFilterDiscoveryListener; -import com.nepxion.discovery.plugin.framework.listener.discovery.VersionFilterDiscoveryListener; -import com.nepxion.discovery.plugin.framework.listener.loadbalance.HostFilterLoadBalanceListener; -import com.nepxion.discovery.plugin.framework.listener.loadbalance.LoadBalanceListenerExecutor; -import com.nepxion.discovery.plugin.framework.listener.loadbalance.NotificationLoadBalanceListener; -import com.nepxion.discovery.plugin.framework.listener.loadbalance.VersionFilterLoadBalanceListener; -import com.nepxion.discovery.plugin.framework.listener.register.CountFilterRegisterListener; -import com.nepxion.discovery.plugin.framework.listener.register.HostFilterRegisterListener; -import com.nepxion.discovery.plugin.framework.listener.register.RegisterListenerExecutor; -import com.nepxion.eventbus.annotation.EnableEventBus; - -@Configuration -@EnableEventBus -public class PluginAutoConfiguration { - @Bean - public PluginContextAware pluginContextAware() { - return new PluginContextAware(); - } - - @Bean - public PluginPublisher pluginPublisher() { - return new PluginPublisher(); - } - - @Bean - public PluginSubscriber pluginSubscriber() { - return new PluginSubscriber(); - } - - @Bean - public PluginEventWapper pluginEventWapper() { - return new PluginEventWapper(); - } - - @Bean - public PluginCache pluginCache() { - return new PluginCache(); - } - - @Bean - public RuleCache ruleCache() { - return new RuleCache(); - } - - @Bean - public RegisterListenerExecutor registerListenerExecutor() { - return new RegisterListenerExecutor(); - } - - @Bean - public DiscoveryListenerExecutor discoveryListenerExecutor() { - return new DiscoveryListenerExecutor(); - } - - @Bean - public LoadBalanceListenerExecutor loadBalanceListenerExecutor() { - return new LoadBalanceListenerExecutor(); - } - - @Bean - public HostFilterRegisterListener hostFilterRegisterListener() { - return new HostFilterRegisterListener(); - } - - @Bean - public CountFilterRegisterListener countFilterRegisterListener() { - return new CountFilterRegisterListener(); - } - - @Bean - public HostFilterDiscoveryListener hostFilterDiscoveryListener() { - return new HostFilterDiscoveryListener(); - } - - @Bean - public VersionFilterDiscoveryListener versionFilterDiscoveryListener() { - return new VersionFilterDiscoveryListener(); - } - - @Bean - public HostFilterLoadBalanceListener hostFilterLoadBalanceListener() { - return new HostFilterLoadBalanceListener(); - } - - @Bean - public VersionFilterLoadBalanceListener versionFilterLoadBalanceListener() { - return new VersionFilterLoadBalanceListener(); - } - - @Bean - @ConditionalOnMissingBean - @ConditionalOnProperty(value = DiscoveryConstant.SPRING_APPLICATION_NO_SERVER_FOUND_NOTIFICATION_ENABLED, matchIfMissing = false) - public NotificationLoadBalanceListener notificationLoadBalanceListener() { - return new NotificationLoadBalanceListener(); - } -} \ No newline at end of file diff --git a/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/context/PluginApplicationContextInitializer.java b/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/context/PluginApplicationContextInitializer.java deleted file mode 100644 index 343d9a6bc5..0000000000 --- a/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/context/PluginApplicationContextInitializer.java +++ /dev/null @@ -1,73 +0,0 @@ -package com.nepxion.discovery.plugin.framework.context; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import org.springframework.beans.BeansException; -import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessorAdapter; -import org.springframework.cloud.client.discovery.DiscoveryClient; -import org.springframework.context.ApplicationContextInitializer; -import org.springframework.context.ConfigurableApplicationContext; - -import com.nepxion.banner.BannerConstant; -import com.nepxion.banner.Description; -import com.nepxion.banner.LogoBanner; -import com.nepxion.banner.NepxionBanner; -import com.nepxion.discovery.common.constant.DiscoveryConstant; -import com.nepxion.discovery.plugin.framework.decorator.DiscoveryClientDecorator; -import com.taobao.text.Color; - -public abstract class PluginApplicationContextInitializer implements ApplicationContextInitializer { - @Override - public void initialize(ConfigurableApplicationContext applicationContext) { - String applicationContextClassName = applicationContext.getClass().getName(); - if (applicationContextClassName.endsWith(DiscoveryConstant.ANNOTATION_CONFIG_SERVLET_WEB_SERVER_APPLICATION_CONTEXT) || applicationContextClassName.endsWith(DiscoveryConstant.ANNOTATION_CONFIG_REACTIVE_WEB_SERVER_APPLICATION_CONTEXT)) { - /*String bannerShown = System.getProperty(BannerConstant.BANNER_SHOWN, "true"); - if (Boolean.valueOf(bannerShown)) { - System.out.println(""); - System.out.println("╔═══╗"); - System.out.println("╚╗╔╗║"); - System.out.println(" ║║║╠╦══╦══╦══╦╗╔╦══╦═╦╗ ╔╗"); - System.out.println(" ║║║╠╣══╣╔═╣╔╗║╚╝║║═╣╔╣║ ║║"); - System.out.println("╔╝╚╝║╠══║╚═╣╚╝╠╗╔╣║═╣║║╚═╝║"); - System.out.println("╚═══╩╩══╩══╩══╝╚╝╚══╩╝╚═╗╔╝"); - System.out.println(" ╔═╝║"); - System.out.println(" ╚══╝"); - System.out.println("Nepxion Discovery v" + DiscoveryConstant.DISCOVERY_VERSION); - System.out.println(""); - }*/ - - LogoBanner logoBanner = new LogoBanner(PluginApplicationContextInitializer.class, "/com/nepxion/discovery/resource/logo.txt", "Welcome to Nepxion", 9, 5, new Color[] { Color.red, Color.green, Color.cyan, Color.blue, Color.yellow, Color.magenta, Color.red, Color.green, Color.cyan }, true); - - NepxionBanner.show(logoBanner, new Description(BannerConstant.VERSION + ":", DiscoveryConstant.DISCOVERY_VERSION, 0, 1), new Description(BannerConstant.GITHUB + ":", BannerConstant.NEPXION_GITHUB + "/Discovery", 0, 1)); - } - - if (applicationContextClassName.endsWith(DiscoveryConstant.ANNOTATION_CONFIG_SERVLET_WEB_SERVER_APPLICATION_CONTEXT)) { - System.setProperty(DiscoveryConstant.SPRING_APPLICATION_SERVLET_WEB_SERVER_ENABLED, Boolean.toString(true)); - } - if (applicationContextClassName.endsWith(DiscoveryConstant.ANNOTATION_CONFIG_REACTIVE_WEB_SERVER_APPLICATION_CONTEXT)) { - System.setProperty(DiscoveryConstant.SPRING_APPLICATION_REACTIVE_WEB_SERVER_ENABLED, Boolean.toString(true)); - } - - applicationContext.getBeanFactory().addBeanPostProcessor(new InstantiationAwareBeanPostProcessorAdapter() { - @Override - public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { - if (bean instanceof DiscoveryClient) { - DiscoveryClient discoveryClient = (DiscoveryClient) bean; - - return new DiscoveryClientDecorator(discoveryClient, applicationContext); - } else { - return afterInitialization(applicationContext, bean, beanName); - } - } - }); - } - - protected abstract Object afterInitialization(ConfigurableApplicationContext applicationContext, Object bean, String beanName) throws BeansException; -} \ No newline at end of file diff --git a/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/context/PluginContextAware.java b/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/context/PluginContextAware.java deleted file mode 100644 index a1c8ff9241..0000000000 --- a/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/context/PluginContextAware.java +++ /dev/null @@ -1,159 +0,0 @@ -package com.nepxion.discovery.plugin.framework.context; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import org.apache.commons.lang3.StringUtils; -import org.springframework.beans.BeansException; -import org.springframework.beans.factory.NoSuchBeanDefinitionException; -import org.springframework.context.ApplicationContext; -import org.springframework.context.ApplicationContextAware; -import org.springframework.core.ResolvableType; -import org.springframework.core.env.Environment; - -import com.nepxion.discovery.common.constant.DiscoveryConstant; - -public class PluginContextAware implements ApplicationContextAware { - private ApplicationContext applicationContext; - private Environment environment; - - @Override - public void setApplicationContext(ApplicationContext applicationContext) { - this.applicationContext = applicationContext; - this.environment = applicationContext.getEnvironment(); - } - - public Object getBean(String name) throws BeansException { - return applicationContext.getBean(name); - } - - public T getBean(String name, Class requiredType) throws BeansException { - return applicationContext.getBean(name, requiredType); - } - - public Object getBean(String name, Object... args) throws BeansException { - return applicationContext.getBean(name, args); - } - - public T getBean(Class requiredType) throws BeansException { - return applicationContext.getBean(requiredType); - } - - public T getBean(Class requiredType, Object... args) throws BeansException { - return applicationContext.getBean(requiredType, args); - } - - public boolean containsBean(String name) { - return applicationContext.containsBean(name); - } - - public boolean isSingleton(String name) throws NoSuchBeanDefinitionException { - return applicationContext.isSingleton(name); - } - - public boolean isPrototype(String name) throws NoSuchBeanDefinitionException { - return applicationContext.isPrototype(name); - } - - public boolean isTypeMatch(String name, ResolvableType typeToMatch) throws NoSuchBeanDefinitionException { - return applicationContext.isTypeMatch(name, typeToMatch); - } - - public boolean isTypeMatch(String name, Class typeToMatch) throws NoSuchBeanDefinitionException { - return applicationContext.isTypeMatch(name, typeToMatch); - } - - public Class getType(String name) throws NoSuchBeanDefinitionException { - return applicationContext.getType(name); - } - - public String[] getAliases(String name) { - return applicationContext.getAliases(name); - } - - public ApplicationContext getApplicationContext() { - return applicationContext; - } - - public Environment getEnvironment() { - return environment; - } - - public Boolean isRegisterControlEnabled() { - return isRegisterControlEnabled(environment); - } - - public Boolean isDiscoveryControlEnabled() { - return isDiscoveryControlEnabled(environment); - } - - public Boolean isConfigRestControlEnabled() { - return isConfigRestControlEnabled(environment); - } - - public String getConfigFormat() { - return getConfigFormat(environment); - } - - public String getConfigPath() { - return getConfigPath(environment); - } - - public String getApplicationName() { - return getApplicationName(environment); - } - - public String getApplicationType() { - return getApplicationType(environment); - } - - public String getGroupKey() { - return getGroupKey(environment); - } - - public String getContextPath() { - return getContextPath(environment); - } - - public static Boolean isRegisterControlEnabled(Environment environment) { - return environment.getProperty(DiscoveryConstant.SPRING_APPLICATION_REGISTER_CONTROL_ENABLED, Boolean.class, Boolean.TRUE); - } - - public static Boolean isDiscoveryControlEnabled(Environment environment) { - return environment.getProperty(DiscoveryConstant.SPRING_APPLICATION_DISCOVERY_CONTROL_ENABLED, Boolean.class, Boolean.TRUE); - } - - public static Boolean isConfigRestControlEnabled(Environment environment) { - return environment.getProperty(DiscoveryConstant.SPRING_APPLICATION_CONFIG_REST_CONTROL_ENABLED, Boolean.class, Boolean.TRUE); - } - - public static String getConfigFormat(Environment environment) { - return environment.getProperty(DiscoveryConstant.SPRING_APPLICATION_CONFIG_FORMAT, String.class, DiscoveryConstant.XML_FORMAT); - } - - public static String getConfigPath(Environment environment) { - return environment.getProperty(DiscoveryConstant.SPRING_APPLICATION_CONFIG_PATH, String.class, StringUtils.equals(getConfigFormat(environment), DiscoveryConstant.XML_FORMAT) ? DiscoveryConstant.PREFIX_CLASSPATH + DiscoveryConstant.RULE + "." + DiscoveryConstant.XML_FORMAT : DiscoveryConstant.PREFIX_CLASSPATH + DiscoveryConstant.RULE + "." + DiscoveryConstant.JSON_FORMAT); - } - - public static String getApplicationName(Environment environment) { - return environment.getProperty(DiscoveryConstant.SPRING_APPLICATION_NAME); - } - - public static String getApplicationType(Environment environment) { - return environment.getProperty(DiscoveryConstant.SPRING_APPLICATION_TYPE); - } - - public static String getGroupKey(Environment environment) { - return environment.getProperty(DiscoveryConstant.SPRING_APPLICATION_GROUP_KEY, String.class, DiscoveryConstant.GROUP); - } - - public static String getContextPath(Environment environment) { - return environment.getProperty(DiscoveryConstant.CONTEXT_PATH, String.class, "/"); - } -} \ No newline at end of file diff --git a/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/context/PluginContextHolder.java b/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/context/PluginContextHolder.java deleted file mode 100644 index 616580eb8b..0000000000 --- a/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/context/PluginContextHolder.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.nepxion.discovery.plugin.framework.context; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -public interface PluginContextHolder { - String getContext(String name); -} \ No newline at end of file diff --git a/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/decorator/DiscoveryClientDecorator.java b/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/decorator/DiscoveryClientDecorator.java deleted file mode 100644 index 1144e4c732..0000000000 --- a/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/decorator/DiscoveryClientDecorator.java +++ /dev/null @@ -1,86 +0,0 @@ -package com.nepxion.discovery.plugin.framework.decorator; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import java.util.List; - -import org.springframework.beans.BeansException; -import org.springframework.cloud.client.ServiceInstance; -import org.springframework.cloud.client.discovery.DiscoveryClient; -import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.core.env.ConfigurableEnvironment; - -import com.nepxion.discovery.plugin.framework.context.PluginContextAware; -import com.nepxion.discovery.plugin.framework.listener.discovery.DiscoveryListenerExecutor; - -public class DiscoveryClientDecorator implements DiscoveryClient { - // private static final Logger LOG = LoggerFactory.getLogger(DiscoveryClientDecorator.class); - - private DiscoveryClient discoveryClient; - private ConfigurableApplicationContext applicationContext; - private ConfigurableEnvironment environment; - - public DiscoveryClientDecorator(DiscoveryClient discoveryClient, ConfigurableApplicationContext applicationContext) { - this.discoveryClient = discoveryClient; - this.applicationContext = applicationContext; - this.environment = applicationContext.getEnvironment(); - } - - @Override - public List getInstances(String serviceId) { - List instances = getRealInstances(serviceId); - - Boolean discoveryControlEnabled = PluginContextAware.isDiscoveryControlEnabled(environment); - if (discoveryControlEnabled) { - try { - DiscoveryListenerExecutor discoveryListenerExecutor = applicationContext.getBean(DiscoveryListenerExecutor.class); - discoveryListenerExecutor.onGetInstances(serviceId, instances); - } catch (BeansException e) { - // LOG.warn("Get bean for DiscoveryListenerExecutor failed, ignore to executor listener"); - } - } - - return instances; - } - - public List getRealInstances(String serviceId) { - return discoveryClient.getInstances(serviceId); - } - - @Override - public List getServices() { - List services = getRealServices(); - - Boolean discoveryControlEnabled = PluginContextAware.isDiscoveryControlEnabled(environment); - if (discoveryControlEnabled) { - try { - DiscoveryListenerExecutor discoveryListenerExecutor = applicationContext.getBean(DiscoveryListenerExecutor.class); - discoveryListenerExecutor.onGetServices(services); - } catch (BeansException e) { - // LOG.warn("Get bean for DiscoveryListenerExecutor failed, ignore to executor listener"); - } - } - - return services; - } - - public List getRealServices() { - return discoveryClient.getServices(); - } - - @Override - public String description() { - return discoveryClient.description(); - } - - public ConfigurableEnvironment getEnvironment() { - return environment; - } -} \ No newline at end of file diff --git a/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/decorator/PredicateBasedRuleDecorator.java b/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/decorator/PredicateBasedRuleDecorator.java deleted file mode 100644 index 938028748b..0000000000 --- a/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/decorator/PredicateBasedRuleDecorator.java +++ /dev/null @@ -1,84 +0,0 @@ -package com.nepxion.discovery.plugin.framework.decorator; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import java.util.List; - -import javax.annotation.PostConstruct; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.ApplicationContext; - -import com.nepxion.discovery.common.entity.WeightFilterEntity; -import com.nepxion.discovery.plugin.framework.adapter.PluginAdapter; -import com.nepxion.discovery.plugin.framework.context.PluginContextHolder; -import com.nepxion.discovery.plugin.framework.loadbalance.weight.RuleMapWeightRandomLoadBalance; -import com.nepxion.discovery.plugin.framework.loadbalance.weight.StrategyMapWeightRandomLoadBalance; -import com.netflix.loadbalancer.PredicateBasedRule; -import com.netflix.loadbalancer.Server; - -public abstract class PredicateBasedRuleDecorator extends PredicateBasedRule { - private static final Logger LOG = LoggerFactory.getLogger(PredicateBasedRuleDecorator.class); - - @Autowired - private ApplicationContext applicationContext; - - @Autowired - private PluginAdapter pluginAdapter; - - private StrategyMapWeightRandomLoadBalance strategyMapWeightRandomLoadBalance; - private RuleMapWeightRandomLoadBalance ruleMapWeightRandomLoadBalance; - - @PostConstruct - private void initialize() { - PluginContextHolder pluginContextHolder = applicationContext.getBean(PluginContextHolder.class); - strategyMapWeightRandomLoadBalance = new StrategyMapWeightRandomLoadBalance(pluginAdapter, pluginContextHolder); - ruleMapWeightRandomLoadBalance = new RuleMapWeightRandomLoadBalance(pluginAdapter); - } - - @Override - public Server choose(Object key) { - boolean isTriggered = false; - - WeightFilterEntity strategyWeightFilterEntity = strategyMapWeightRandomLoadBalance.getT(); - if (strategyWeightFilterEntity != null && strategyWeightFilterEntity.hasWeight()) { - isTriggered = true; - - List eligibleServers = getPredicate().getEligibleServers(getLoadBalancer().getAllServers(), key); - - try { - return strategyMapWeightRandomLoadBalance.choose(eligibleServers, strategyWeightFilterEntity); - } catch (Exception e) { - LOG.error("Exception causes for strategy weight-random-loadbalance, used default loadbalance", e); - - return super.choose(key); - } - } - - if (!isTriggered) { - WeightFilterEntity weightFilterEntity = ruleMapWeightRandomLoadBalance.getT(); - if (weightFilterEntity != null && weightFilterEntity.hasWeight()) { - List eligibleServers = getPredicate().getEligibleServers(getLoadBalancer().getAllServers(), key); - - try { - return ruleMapWeightRandomLoadBalance.choose(eligibleServers, weightFilterEntity); - } catch (Exception e) { - LOG.error("Exception causes for rule weight-random-loadbalance, used default loadbalance", e); - - return super.choose(key); - } - } - } - - return super.choose(key); - } -} \ No newline at end of file diff --git a/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/decorator/ZoneAvoidanceRuleDecorator.java b/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/decorator/ZoneAvoidanceRuleDecorator.java deleted file mode 100644 index bbd48cec15..0000000000 --- a/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/decorator/ZoneAvoidanceRuleDecorator.java +++ /dev/null @@ -1,84 +0,0 @@ -package com.nepxion.discovery.plugin.framework.decorator; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import java.util.List; - -import javax.annotation.PostConstruct; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.ApplicationContext; - -import com.nepxion.discovery.common.entity.WeightFilterEntity; -import com.nepxion.discovery.plugin.framework.adapter.PluginAdapter; -import com.nepxion.discovery.plugin.framework.context.PluginContextHolder; -import com.nepxion.discovery.plugin.framework.loadbalance.weight.RuleMapWeightRandomLoadBalance; -import com.nepxion.discovery.plugin.framework.loadbalance.weight.StrategyMapWeightRandomLoadBalance; -import com.netflix.loadbalancer.Server; -import com.netflix.loadbalancer.ZoneAvoidanceRule; - -public class ZoneAvoidanceRuleDecorator extends ZoneAvoidanceRule { - private static final Logger LOG = LoggerFactory.getLogger(ZoneAvoidanceRuleDecorator.class); - - @Autowired - private ApplicationContext applicationContext; - - @Autowired - private PluginAdapter pluginAdapter; - - private StrategyMapWeightRandomLoadBalance strategyMapWeightRandomLoadBalance; - private RuleMapWeightRandomLoadBalance ruleMapWeightRandomLoadBalance; - - @PostConstruct - private void initialize() { - PluginContextHolder pluginContextHolder = applicationContext.getBean(PluginContextHolder.class); - strategyMapWeightRandomLoadBalance = new StrategyMapWeightRandomLoadBalance(pluginAdapter, pluginContextHolder); - ruleMapWeightRandomLoadBalance = new RuleMapWeightRandomLoadBalance(pluginAdapter); - } - - @Override - public Server choose(Object key) { - boolean isTriggered = false; - - WeightFilterEntity strategyWeightFilterEntity = strategyMapWeightRandomLoadBalance.getT(); - if (strategyWeightFilterEntity != null && strategyWeightFilterEntity.hasWeight()) { - isTriggered = true; - - List eligibleServers = getPredicate().getEligibleServers(getLoadBalancer().getAllServers(), key); - - try { - return strategyMapWeightRandomLoadBalance.choose(eligibleServers, strategyWeightFilterEntity); - } catch (Exception e) { - LOG.error("Exception causes for strategy weight-random-loadbalance, used default loadbalance", e); - - return super.choose(key); - } - } - - if (!isTriggered) { - WeightFilterEntity weightFilterEntity = ruleMapWeightRandomLoadBalance.getT(); - if (weightFilterEntity != null && weightFilterEntity.hasWeight()) { - List eligibleServers = getPredicate().getEligibleServers(getLoadBalancer().getAllServers(), key); - - try { - return ruleMapWeightRandomLoadBalance.choose(eligibleServers, weightFilterEntity); - } catch (Exception e) { - LOG.error("Exception causes for rule weight-random-loadbalance, used default loadbalance", e); - - return super.choose(key); - } - } - } - - return super.choose(key); - } -} \ No newline at end of file diff --git a/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/event/CustomizationEvent.java b/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/event/CustomizationEvent.java deleted file mode 100644 index 1df9d59576..0000000000 --- a/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/event/CustomizationEvent.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.nepxion.discovery.plugin.framework.event; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import java.io.Serializable; - -import com.nepxion.discovery.common.entity.CustomizationEntity; - -public class CustomizationEvent implements Serializable { - private static final long serialVersionUID = 7843872188960155327L; - - private CustomizationEntity customizationEntity; - - public CustomizationEvent(CustomizationEntity customizationEntity) { - this.customizationEntity = customizationEntity; - } - - public CustomizationEntity getCustomizationEntity() { - return customizationEntity; - } -} \ No newline at end of file diff --git a/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/event/PluginSubscriber.java b/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/event/PluginSubscriber.java deleted file mode 100644 index e556879945..0000000000 --- a/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/event/PluginSubscriber.java +++ /dev/null @@ -1,180 +0,0 @@ -package com.nepxion.discovery.plugin.framework.event; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; - -import com.google.common.eventbus.Subscribe; -import com.nepxion.discovery.common.entity.RuleEntity; -import com.nepxion.discovery.common.exception.DiscoveryException; -import com.nepxion.discovery.plugin.framework.adapter.PluginAdapter; -import com.nepxion.discovery.plugin.framework.config.PluginConfigParser; -import com.nepxion.discovery.plugin.framework.context.PluginContextAware; -import com.nepxion.discovery.plugin.framework.listener.loadbalance.LoadBalanceListenerExecutor; -import com.nepxion.eventbus.annotation.EventBus; -import com.netflix.loadbalancer.ZoneAwareLoadBalancer; - -@EventBus -public class PluginSubscriber { - private static final Logger LOG = LoggerFactory.getLogger(PluginSubscriber.class); - - @Autowired - private PluginContextAware pluginContextAware; - - @Autowired - private PluginAdapter pluginAdapter; - - @Autowired - private PluginConfigParser pluninConfigParser; - - @Autowired - private PluginEventWapper pluginEventWapper; - - @Autowired - private LoadBalanceListenerExecutor loadBalanceListenerExecutor; - - @Subscribe - public void onRuleUpdated(RuleUpdatedEvent ruleUpdatedEvent) { - Boolean discoveryControlEnabled = pluginContextAware.isDiscoveryControlEnabled(); - if (!discoveryControlEnabled) { - LOG.info("Discovery control is disabled, ignore to subscribe"); - - return; - } - - LOG.info("Rule updating has been triggered"); - - if (ruleUpdatedEvent == null) { - throw new DiscoveryException("RuleUpdatedEvent can't be null"); - } - - String rule = ruleUpdatedEvent.getRule(); - try { - RuleEntity ruleEntity = pluninConfigParser.parse(rule); - pluginAdapter.setDynamicRule(ruleEntity); - - pluginEventWapper.fireCustomization(); - } catch (Exception e) { - LOG.error("Parse rule xml failed", e); - - throw e; - } - - refreshLoadBalancer(); - } - - @Subscribe - public void onRuleCleared(RuleClearedEvent ruleClearedEvent) { - Boolean discoveryControlEnabled = pluginContextAware.isDiscoveryControlEnabled(); - if (!discoveryControlEnabled) { - LOG.info("Discovery control is disabled, ignore to subscribe"); - - return; - } - - LOG.info("Rule clearing has been triggered"); - - if (ruleClearedEvent == null) { - throw new DiscoveryException("RuleClearedEvent can't be null"); - } - - pluginAdapter.clearDynamicRule(); - - pluginEventWapper.fireCustomization(); - - refreshLoadBalancer(); - } - - @Subscribe - public void onVersionUpdated(VersionUpdatedEvent versionUpdatedEvent) { - Boolean discoveryControlEnabled = pluginContextAware.isDiscoveryControlEnabled(); - if (!discoveryControlEnabled) { - LOG.info("Discovery control is disabled, ignore to subscribe"); - - return; - } - - LOG.info("Version updating has been triggered"); - - if (versionUpdatedEvent == null) { - throw new DiscoveryException("VersionUpdatedEvent can't be null"); - } - - String dynamicVersion = versionUpdatedEvent.getDynamicVersion(); - String localVersion = versionUpdatedEvent.getLocalVersion(); - - if (StringUtils.isEmpty(localVersion)) { - pluginAdapter.setDynamicVersion(dynamicVersion); - - refreshLoadBalancer(); - - LOG.info("Version has been updated, new version is {}", dynamicVersion); - } else { - if (StringUtils.equals(pluginAdapter.getLocalVersion(), localVersion)) { - pluginAdapter.setDynamicVersion(dynamicVersion); - - refreshLoadBalancer(); - - LOG.info("Version has been updated, new version is {}", dynamicVersion); - } else { - throw new DiscoveryException("Version updating will be ignored, because input localVersion=" + localVersion + ", current localVersion=" + pluginAdapter.getLocalVersion()); - } - } - } - - @Subscribe - public void onVersionCleared(VersionClearedEvent versionClearedEvent) { - Boolean discoveryControlEnabled = pluginContextAware.isDiscoveryControlEnabled(); - if (!discoveryControlEnabled) { - LOG.info("Discovery control is disabled, ignore to subscribe"); - - return; - } - - LOG.info("Version clearing has been triggered"); - - if (versionClearedEvent == null) { - throw new DiscoveryException("VersionClearedEvent can't be null"); - } - - String localVersion = versionClearedEvent.getLocalVersion(); - - if (StringUtils.isEmpty(localVersion)) { - pluginAdapter.clearDynamicVersion(); - - refreshLoadBalancer(); - - LOG.info("Version has been cleared"); - } else { - if (StringUtils.equals(pluginAdapter.getLocalVersion(), localVersion)) { - pluginAdapter.clearDynamicVersion(); - - refreshLoadBalancer(); - - LOG.info("Version has been cleared"); - } else { - throw new DiscoveryException("Version clearing will be ignored, because input localVersion=" + localVersion + ", current localVersion=" + pluginAdapter.getLocalVersion()); - } - } - } - - private void refreshLoadBalancer() { - ZoneAwareLoadBalancer loadBalancer = loadBalanceListenerExecutor.getLoadBalancer(); - if (loadBalancer == null) { - return; - } - - // 当规则或者版本更新后,强制刷新Ribbon缓存 - loadBalancer.updateListOfServers(); - } -} \ No newline at end of file diff --git a/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/event/RuleClearedEvent.java b/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/event/RuleClearedEvent.java deleted file mode 100644 index 0572e32740..0000000000 --- a/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/event/RuleClearedEvent.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.nepxion.discovery.plugin.framework.event; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import java.io.Serializable; - -public class RuleClearedEvent implements Serializable { - private static final long serialVersionUID = -4942710381954711909L; -} \ No newline at end of file diff --git a/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/event/RuleUpdatedEvent.java b/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/event/RuleUpdatedEvent.java deleted file mode 100644 index 251bb81fad..0000000000 --- a/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/event/RuleUpdatedEvent.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.nepxion.discovery.plugin.framework.event; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import java.io.Serializable; - -public class RuleUpdatedEvent implements Serializable { - private static final long serialVersionUID = 2315578803987663866L; - - private String rule; - - public RuleUpdatedEvent(String rule) { - this.rule = rule; - } - - public String getRule() { - return rule; - } -} \ No newline at end of file diff --git a/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/loadbalance/weight/AbstractArrayWeightRandomLoadBalance.java b/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/loadbalance/weight/AbstractArrayWeightRandomLoadBalance.java deleted file mode 100644 index 3944f29417..0000000000 --- a/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/loadbalance/weight/AbstractArrayWeightRandomLoadBalance.java +++ /dev/null @@ -1,65 +0,0 @@ -package com.nepxion.discovery.plugin.framework.loadbalance.weight; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import java.util.List; -import java.util.concurrent.ThreadLocalRandom; - -import org.apache.commons.collections4.CollectionUtils; - -import com.nepxion.discovery.plugin.framework.loadbalance.WeightRandomLoadBalance; -import com.netflix.loadbalancer.Server; - -public abstract class AbstractArrayWeightRandomLoadBalance implements WeightRandomLoadBalance { - @Override - public Server choose(List serverList, T t) { - if (CollectionUtils.isEmpty(serverList)) { - return null; - } - - int[] weights = new int[serverList.size()]; - for (int i = 0; i < serverList.size(); i++) { - Server server = serverList.get(i); - weights[i] = getWeight(server, t); - } - - int index = getIndex(weights); - - return serverList.get(index); - } - - private int getIndex(int[] weights) { - // 次序号/权重区间值 - int[][] weightHolder = new int[weights.length][2]; - // 总权重 - int totalWeight = 0; - // 赋值次序号和区间值累加的数组值,从小到大排列 - // 例如,对于权重分别为20,40, 60的三个服务,将形成[0, 20),[20, 60),[60, 120]三个区间 - for (int i = 0; i < weights.length; i++) { - if (weights[i] <= 0) { - continue; - } - - totalWeight += weights[i]; - weightHolder[i][0] = i; - weightHolder[i][1] = totalWeight; - } - - // 获取介于0(含)和n(不含)伪随机,均匀分布的int值 - int hitWeight = ThreadLocalRandom.current().nextInt(totalWeight) + 1; // [1, totalWeight) - for (int i = 0; i < weightHolder.length; i++) { - if (hitWeight <= weightHolder[i][1]) { - return weightHolder[i][0]; - } - } - - return weightHolder[0][0]; - } -} \ No newline at end of file diff --git a/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/loadbalance/weight/AbstractMapWeightRandomLoadBalance.java b/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/loadbalance/weight/AbstractMapWeightRandomLoadBalance.java deleted file mode 100644 index 62e0aa6eac..0000000000 --- a/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/loadbalance/weight/AbstractMapWeightRandomLoadBalance.java +++ /dev/null @@ -1,70 +0,0 @@ -package com.nepxion.discovery.plugin.framework.loadbalance.weight; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import java.util.ArrayList; -import java.util.List; -import java.util.SortedMap; -import java.util.TreeMap; - -import org.apache.commons.collections4.CollectionUtils; -import org.apache.commons.collections4.MapUtils; -import org.apache.commons.lang3.tuple.ImmutablePair; -import org.apache.commons.lang3.tuple.Pair; - -import com.nepxion.discovery.common.exception.DiscoveryException; -import com.nepxion.discovery.plugin.framework.loadbalance.WeightRandomLoadBalance; -import com.netflix.loadbalancer.Server; - -public abstract class AbstractMapWeightRandomLoadBalance implements WeightRandomLoadBalance { - @Override - public Server choose(List serverList, T t) { - if (CollectionUtils.isEmpty(serverList)) { - return null; - } - - List> weightPairList = new ArrayList>(); - for (Server server : serverList) { - int weight = getWeight(server, t); - weightPairList.add(new ImmutablePair(server, weight)); - } - - MapWeightRandom weightRandom = new MapWeightRandom(weightPairList); - - return weightRandom.random(); - } - - public class MapWeightRandom { - private TreeMap weightMap = new TreeMap(); - - public MapWeightRandom(List> pairlist) { - for (Pair pair : pairlist) { - double value = pair.getValue().doubleValue(); - if (value <= 0) { - continue; - } - - double lastWeight = weightMap.size() == 0 ? 0 : weightMap.lastKey().doubleValue(); - weightMap.put(value + lastWeight, pair.getKey()); - } - } - - public K random() { - if (MapUtils.isEmpty(weightMap)) { - throw new DiscoveryException("No weight value is configed"); - } - - double randomWeight = weightMap.lastKey() * Math.random(); - SortedMap tailMap = weightMap.tailMap(randomWeight, false); - - return weightMap.get(tailMap.firstKey()); - } - } -} \ No newline at end of file diff --git a/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/loadbalance/weight/RuleWeightRandomLoadBalanceAdapter.java b/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/loadbalance/weight/RuleWeightRandomLoadBalanceAdapter.java deleted file mode 100644 index cc2a56b811..0000000000 --- a/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/loadbalance/weight/RuleWeightRandomLoadBalanceAdapter.java +++ /dev/null @@ -1,87 +0,0 @@ -package com.nepxion.discovery.plugin.framework.loadbalance.weight; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import java.util.List; -import java.util.Map; - -import com.nepxion.discovery.common.entity.DiscoveryEntity; -import com.nepxion.discovery.common.entity.RegionWeightEntity; -import com.nepxion.discovery.common.entity.RuleEntity; -import com.nepxion.discovery.common.entity.VersionWeightEntity; -import com.nepxion.discovery.common.entity.WeightEntity; -import com.nepxion.discovery.common.entity.WeightEntityWrapper; -import com.nepxion.discovery.common.entity.WeightFilterEntity; -import com.nepxion.discovery.plugin.framework.adapter.PluginAdapter; -import com.netflix.loadbalancer.Server; - -public class RuleWeightRandomLoadBalanceAdapter extends AbstractWeightRandomLoadBalanceAdapter { - public RuleWeightRandomLoadBalanceAdapter(PluginAdapter pluginAdapter) { - super(pluginAdapter); - } - - @Override - public WeightFilterEntity getT() { - RuleEntity ruleEntity = pluginAdapter.getRule(); - if (ruleEntity == null) { - return null; - } - - DiscoveryEntity discoveryEntity = ruleEntity.getDiscoveryEntity(); - if (discoveryEntity == null) { - return null; - } - - WeightFilterEntity weightFilterEntity = discoveryEntity.getWeightFilterEntity(); - - return weightFilterEntity; - } - - @Override - public int getWeight(Server server, WeightFilterEntity weightFilterEntity) { - Map> versionWeightEntityMap = weightFilterEntity.getVersionWeightEntityMap(); - List versionWeightEntityList = weightFilterEntity.getVersionWeightEntityList(); - VersionWeightEntity versionWeightEntity = weightFilterEntity.getVersionWeightEntity(); - - Map> regionWeightEntityMap = weightFilterEntity.getRegionWeightEntityMap(); - List regionWeightEntityList = weightFilterEntity.getRegionWeightEntityList(); - RegionWeightEntity regionWeightEntity = weightFilterEntity.getRegionWeightEntity(); - - String providerServiceId = pluginAdapter.getServerServiceId(server); - String providerVersion = pluginAdapter.getServerVersion(server); - String providerRegion = pluginAdapter.getServerRegion(server); - - String serviceId = pluginAdapter.getServiceId(); - int weight = WeightEntityWrapper.getWeight(serviceId, providerServiceId, providerVersion, versionWeightEntityMap); - if (weight < 0) { - weight = WeightEntityWrapper.getWeight(providerServiceId, providerVersion, versionWeightEntityList); - } - if (weight < 0) { - weight = WeightEntityWrapper.getWeight(providerVersion, versionWeightEntity); - } - - if (weight < 0) { - weight = WeightEntityWrapper.getWeight(serviceId, providerServiceId, providerRegion, regionWeightEntityMap); - } - if (weight < 0) { - weight = WeightEntityWrapper.getWeight(providerServiceId, providerRegion, regionWeightEntityList); - } - if (weight < 0) { - weight = WeightEntityWrapper.getWeight(providerRegion, regionWeightEntity); - } - - // 所有的权重配置都没找到,则按权重值为0来处理 - if (weight < 0) { - weight = 0; - } - - return weight; - } -} \ No newline at end of file diff --git a/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/loadbalance/weight/StrategyWeightRandomLoadBalanceAdapter.java b/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/loadbalance/weight/StrategyWeightRandomLoadBalanceAdapter.java deleted file mode 100644 index 356c43a50f..0000000000 --- a/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/loadbalance/weight/StrategyWeightRandomLoadBalanceAdapter.java +++ /dev/null @@ -1,97 +0,0 @@ -package com.nepxion.discovery.plugin.framework.loadbalance.weight; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import java.util.List; - -import org.apache.commons.lang3.StringUtils; - -import com.nepxion.discovery.common.constant.DiscoveryConstant; -import com.nepxion.discovery.common.entity.RegionWeightEntity; -import com.nepxion.discovery.common.entity.VersionWeightEntity; -import com.nepxion.discovery.common.entity.WeightEntity; -import com.nepxion.discovery.common.entity.WeightEntityWrapper; -import com.nepxion.discovery.common.entity.WeightFilterEntity; -import com.nepxion.discovery.plugin.framework.adapter.PluginAdapter; -import com.nepxion.discovery.plugin.framework.context.PluginContextHolder; -import com.netflix.loadbalancer.Server; - -public class StrategyWeightRandomLoadBalanceAdapter extends AbstractWeightRandomLoadBalanceAdapter { - public StrategyWeightRandomLoadBalanceAdapter(PluginAdapter pluginAdapter, PluginContextHolder pluginContextHolder) { - super(pluginAdapter, pluginContextHolder); - } - - @Override - public WeightFilterEntity getT() { - WeightFilterEntity weightFilterEntity = new WeightFilterEntity(); - - String versionWeightValue = pluginContextHolder.getContext(DiscoveryConstant.N_D_VERSION_WEIGHT); - if (StringUtils.isNotEmpty(versionWeightValue)) { - try { - List weightEntityList = WeightEntityWrapper.parseWeightEntityList(versionWeightValue); - weightFilterEntity.setVersionWeightEntityList(weightEntityList); - } catch (Exception e) { - VersionWeightEntity weightEntity = new VersionWeightEntity(); - - WeightEntityWrapper.parseWeightEntity(weightEntity, versionWeightValue); - - weightFilterEntity.setVersionWeightEntity(weightEntity); - } - } - - String regionWeightValue = pluginContextHolder.getContext(DiscoveryConstant.N_D_REGION_WEIGHT); - if (StringUtils.isNotEmpty(regionWeightValue)) { - try { - List weightEntityList = WeightEntityWrapper.parseWeightEntityList(regionWeightValue); - weightFilterEntity.setRegionWeightEntityList(weightEntityList); - } catch (Exception e) { - RegionWeightEntity weightEntity = new RegionWeightEntity(); - - WeightEntityWrapper.parseWeightEntity(weightEntity, regionWeightValue); - - weightFilterEntity.setRegionWeightEntity(weightEntity); - } - } - - return weightFilterEntity; - } - - @Override - public int getWeight(Server server, WeightFilterEntity weightFilterEntity) { - List versionWeightEntityList = weightFilterEntity.getVersionWeightEntityList(); - VersionWeightEntity versionWeightEntity = weightFilterEntity.getVersionWeightEntity(); - - List regionWeightEntityList = weightFilterEntity.getRegionWeightEntityList(); - RegionWeightEntity regionWeightEntity = weightFilterEntity.getRegionWeightEntity(); - - String providerServiceId = pluginAdapter.getServerServiceId(server); - String providerVersion = pluginAdapter.getServerVersion(server); - String providerRegion = pluginAdapter.getServerRegion(server); - - int weight = WeightEntityWrapper.getWeight(providerServiceId, providerVersion, versionWeightEntityList); - if (weight < 0) { - weight = WeightEntityWrapper.getWeight(providerVersion, versionWeightEntity); - } - - if (weight < 0) { - weight = WeightEntityWrapper.getWeight(providerServiceId, providerRegion, regionWeightEntityList); - } - if (weight < 0) { - weight = WeightEntityWrapper.getWeight(providerRegion, regionWeightEntity); - } - - // 所有的权重配置都没找到,则按权重值为0来处理 - if (weight < 0) { - weight = 0; - } - - return weight; - } -} \ No newline at end of file diff --git a/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/time/SystemClock.java b/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/time/SystemClock.java deleted file mode 100644 index a052072c81..0000000000 --- a/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/time/SystemClock.java +++ /dev/null @@ -1,63 +0,0 @@ -package com.nepxion.discovery.plugin.framework.time; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ThreadFactory; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicLong; - -// System.currentTimeMillis()是比较重的调用,调用时候要进行内核态/用户态切换,应该让真正在忙着的那些线程尽量少切换 -// SystemClock的时间精度不那么高,所以不能用在要求时间非常精准的场景 -public class SystemClock { - private static final String THREAD_NAME = "system-clock-daemon-thread"; - private static final SystemClock SYSTEM_CLOCK = new SystemClock(1); - - private final long precision; - private final AtomicLong now; - - public SystemClock(long precision) { - this.precision = precision; - - now = new AtomicLong(System.currentTimeMillis()); - scheduleClockUpdating(); - } - - private void scheduleClockUpdating() { - ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() { - @Override - public Thread newThread(Runnable runnable) { - Thread thread = new Thread(runnable, THREAD_NAME); - thread.setDaemon(true); - - return thread; - } - }); - scheduler.scheduleAtFixedRate(new Runnable() { - @Override - public void run() { - now.set(System.currentTimeMillis()); - } - }, precision, precision, TimeUnit.MILLISECONDS); - } - - public long now() { - return now.get(); - } - - public long precision() { - return precision; - } - - public static SystemClock instance() { - return SYSTEM_CLOCK; - } -} \ No newline at end of file diff --git a/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/util/MetadataUtil.java b/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/util/MetadataUtil.java deleted file mode 100644 index 8193ca1996..0000000000 --- a/discovery-plugin-framework/src/main/java/com/nepxion/discovery/plugin/framework/util/MetadataUtil.java +++ /dev/null @@ -1,60 +0,0 @@ -package com.nepxion.discovery.plugin.framework.util; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.Set; - -import com.nepxion.discovery.common.constant.DiscoveryConstant; - -public class MetadataUtil { - public static void filter(Map metadata) { - Properties properties = System.getProperties(); - Set propertyNames = properties.stringPropertyNames(); - for (String propertyName : propertyNames) { - if (propertyName.startsWith(DiscoveryConstant.EXT + ".")) { - String key = propertyName.substring((DiscoveryConstant.EXT + ".").length()); - String value = properties.get(propertyName).toString(); - metadata.put(key, value); - } - } - } - - public static void filter(List metadata) { - Properties properties = System.getProperties(); - Set propertyNames = properties.stringPropertyNames(); - for (String propertyName : propertyNames) { - if (propertyName.startsWith(DiscoveryConstant.EXT + ".")) { - String key = propertyName.substring((DiscoveryConstant.EXT + ".").length()); - String value = properties.get(propertyName).toString(); - - int index = getIndex(metadata, key); - if (index > -1) { - metadata.set(index, key + "=" + value); - } else { - metadata.add(key + "=" + value); - } - } - } - } - - private static int getIndex(List metadata, String key) { - for (int i = 0; i < metadata.size(); i++) { - String result = metadata.get(i); - if (result.startsWith(key + "=")) { - return i; - } - } - - return -1; - } -} \ No newline at end of file diff --git a/discovery-plugin-framework/src/test/java/com/nepxion/discovery/plugin/framework/loadbalance/ArrayWeightRandomLoadBalanceTest.java b/discovery-plugin-framework/src/test/java/com/nepxion/discovery/plugin/framework/loadbalance/ArrayWeightRandomLoadBalanceTest.java deleted file mode 100644 index f13ad814e8..0000000000 --- a/discovery-plugin-framework/src/test/java/com/nepxion/discovery/plugin/framework/loadbalance/ArrayWeightRandomLoadBalanceTest.java +++ /dev/null @@ -1,127 +0,0 @@ -package com.nepxion.discovery.plugin.framework.loadbalance; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import java.text.DecimalFormat; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ThreadLocalRandom; - -import org.apache.commons.collections4.CollectionUtils; - -public class ArrayWeightRandomLoadBalanceTest { - public static void main(String[] args) { - test(1000000); - } - - public static void test(int totolCount) { - long t = System.currentTimeMillis(); - - List serverList = new ArrayList(); - serverList.add("1.0"); - serverList.add("2.0"); - serverList.add("3.0"); - serverList.add("1.0"); - serverList.add("2.0"); - serverList.add("3.0"); - serverList.add("4.0"); - serverList.add("4.0"); - serverList.add("5.0"); - serverList.add("5.0"); - - Map weightMap = new HashMap(); - weightMap.put("1.0", 10); - weightMap.put("2.0", 50); - weightMap.put("3.0", 20); - weightMap.put("4.0", 5); - weightMap.put("5.0", 15); - - int v1Count = 0; - int v2Count = 0; - int v3Count = 0; - int v4Count = 0; - int v5Count = 0; - for (int i = 0; i < totolCount; i++) { - String server = choose(serverList, weightMap); - if (server.startsWith("1.0")) { - v1Count++; - } - if (server.startsWith("2.0")) { - v2Count++; - } - if (server.startsWith("3.0")) { - v3Count++; - } - if (server.startsWith("4.0")) { - v4Count++; - } - if (server.startsWith("5.0")) { - v5Count++; - } - } - - System.out.println("------------------------------"); - System.out.println(totolCount + "次循环,数组方式随机权重准确度和性能:"); - DecimalFormat format = new DecimalFormat("0.0000"); - System.out.println("1.0版本服务随机权重=" + format.format((double) v1Count * 100 / totolCount) + "%"); - System.out.println("2.0版本服务随机权重=" + format.format((double) v2Count * 100 / totolCount) + "%"); - System.out.println("3.0版本服务随机权重=" + format.format((double) v3Count * 100 / totolCount) + "%"); - System.out.println("4.0版本服务随机权重=" + format.format((double) v4Count * 100 / totolCount) + "%"); - System.out.println("5.0版本服务随机权重=" + format.format((double) v5Count * 100 / totolCount) + "%"); - System.out.println("耗时时间:" + (System.currentTimeMillis() - t)); - System.out.println("------------------------------"); - } - - public static String choose(List serverList, Map weightMap) { - if (CollectionUtils.isEmpty(serverList)) { - return null; - } - - int[] weights = new int[serverList.size()]; - for (int i = 0; i < serverList.size(); i++) { - String server = serverList.get(i); - weights[i] = weightMap.get(server); - } - - int index = getIndex(weights); - - return serverList.get(index); - } - - private static int getIndex(int[] weights) { - // 次序号/权重区间值 - int[][] weightHolder = new int[weights.length][2]; - // 总权重 - int totalWeight = 0; - // 赋值次序号和区间值累加的数组值,从小到大排列 - // 例如,对于权重分别为20,40, 60的三个服务,将形成[0, 20),[20, 60),[60, 120]三个区间 - for (int i = 0; i < weights.length; i++) { - if (weights[i] <= 0) { - continue; - } - - totalWeight += weights[i]; - weightHolder[i][0] = i; - weightHolder[i][1] = totalWeight; - } - - // 获取介于0(含)和n(不含)伪随机,均匀分布的int值 - int hitWeight = ThreadLocalRandom.current().nextInt(totalWeight) + 1; // [1, totalWeight) - for (int i = 0; i < weightHolder.length; i++) { - if (hitWeight <= weightHolder[i][1]) { - return weightHolder[i][0]; - } - } - - return weightHolder[0][0]; - } -} \ No newline at end of file diff --git a/discovery-plugin-framework/src/test/java/com/nepxion/discovery/plugin/framework/loadbalance/MapWeightRandomLoadBalanceTest.java b/discovery-plugin-framework/src/test/java/com/nepxion/discovery/plugin/framework/loadbalance/MapWeightRandomLoadBalanceTest.java deleted file mode 100644 index 97cd27d67b..0000000000 --- a/discovery-plugin-framework/src/test/java/com/nepxion/discovery/plugin/framework/loadbalance/MapWeightRandomLoadBalanceTest.java +++ /dev/null @@ -1,107 +0,0 @@ -package com.nepxion.discovery.plugin.framework.loadbalance; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import java.text.DecimalFormat; -import java.util.ArrayList; -import java.util.List; -import java.util.SortedMap; -import java.util.TreeMap; - -import org.apache.commons.collections4.MapUtils; -import org.apache.commons.lang3.tuple.ImmutablePair; -import org.apache.commons.lang3.tuple.Pair; - -import com.nepxion.discovery.common.exception.DiscoveryException; - -public class MapWeightRandomLoadBalanceTest { - public static void main(String[] args) { - test(1000000); - } - - public static void test(int totolCount) { - long t = System.currentTimeMillis(); - - List> list = new ArrayList>(); - list.add(new ImmutablePair("1.0", 10D)); - list.add(new ImmutablePair("2.0", 50D)); - list.add(new ImmutablePair("3.0", 20D)); - list.add(new ImmutablePair("1.0", 10D)); - list.add(new ImmutablePair("2.0", 50D)); - list.add(new ImmutablePair("3.0", 20D)); - list.add(new ImmutablePair("4.0", 5D)); - list.add(new ImmutablePair("4.0", 5D)); - list.add(new ImmutablePair("5.0", 15D)); - list.add(new ImmutablePair("5.0", 15D)); - - int v1Count = 0; - int v2Count = 0; - int v3Count = 0; - int v4Count = 0; - int v5Count = 0; - for (int i = 0; i < totolCount; i++) { - MapWeightRandom weightRandom = new MapWeightRandom(list); - String server = weightRandom.random(); - if (server.startsWith("1.0")) { - v1Count++; - } - if (server.startsWith("2.0")) { - v2Count++; - } - if (server.startsWith("3.0")) { - v3Count++; - } - if (server.startsWith("4.0")) { - v4Count++; - } - if (server.startsWith("5.0")) { - v5Count++; - } - } - - System.out.println("------------------------------"); - System.out.println(totolCount + "次循环,散列方式随机权重准确度和性能:"); - DecimalFormat format = new DecimalFormat("0.0000"); - System.out.println("1.0版本服务随机权重=" + format.format((double) v1Count * 100 / totolCount) + "%"); - System.out.println("2.0版本服务随机权重=" + format.format((double) v2Count * 100 / totolCount) + "%"); - System.out.println("3.0版本服务随机权重=" + format.format((double) v3Count * 100 / totolCount) + "%"); - System.out.println("4.0版本服务随机权重=" + format.format((double) v4Count * 100 / totolCount) + "%"); - System.out.println("5.0版本服务随机权重=" + format.format((double) v5Count * 100 / totolCount) + "%"); - System.out.println("耗时时间:" + (System.currentTimeMillis() - t)); - System.out.println("------------------------------"); - } - - public static class MapWeightRandom { - private TreeMap weightMap = new TreeMap(); - - public MapWeightRandom(List> pairlist) { - for (Pair pair : pairlist) { - double value = pair.getValue().doubleValue(); - if (value <= 0) { - continue; - } - - double lastWeight = weightMap.size() == 0 ? 0 : weightMap.lastKey().doubleValue(); - weightMap.put(value + lastWeight, pair.getKey()); - } - } - - public K random() { - if (MapUtils.isEmpty(weightMap)) { - throw new DiscoveryException("No weight value is configed"); - } - - double randomWeight = weightMap.lastKey() * Math.random(); - SortedMap tailMap = weightMap.tailMap(randomWeight, false); - - return weightMap.get(tailMap.firstKey()); - } - } -} \ No newline at end of file diff --git a/discovery-plugin-register-center/discovery-plugin-register-center-starter-consul/pom.xml b/discovery-plugin-register-center/discovery-plugin-register-center-starter-consul/pom.xml new file mode 100644 index 0000000000..5ce88fea79 --- /dev/null +++ b/discovery-plugin-register-center/discovery-plugin-register-center-starter-consul/pom.xml @@ -0,0 +1,28 @@ + + + discovery-plugin-register-center-starter-consul + Nepxion Discovery Plugin Register Center Starter Consul + jar + 4.0.0 + Nepxion Discovery is a solution for Spring Cloud with blue green, gray, weight, limitation, circuit breaker, degrade, isolation, monitor, tracing, dye, failover, async agent + http://www.nepxion.com + + + com.nepxion + discovery-plugin-register-center + 6.23.0 + + + + + ${project.groupId} + discovery-plugin-register-center-starter + + + + org.springframework.cloud + spring-cloud-starter-consul-discovery + + + \ No newline at end of file diff --git a/discovery-plugin-register-center/discovery-plugin-register-center-starter-consul/src/main/java/com/nepxion/discovery/plugin/registercenter/consul/adapter/ConsulAdapter.java b/discovery-plugin-register-center/discovery-plugin-register-center-starter-consul/src/main/java/com/nepxion/discovery/plugin/registercenter/consul/adapter/ConsulAdapter.java new file mode 100644 index 0000000000..58ef751f53 --- /dev/null +++ b/discovery-plugin-register-center/discovery-plugin-register-center-starter-consul/src/main/java/com/nepxion/discovery/plugin/registercenter/consul/adapter/ConsulAdapter.java @@ -0,0 +1,32 @@ +package com.nepxion.discovery.plugin.registercenter.consul.adapter; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.Map; + +import org.springframework.cloud.consul.discovery.ConsulServer; + +import com.nepxion.discovery.plugin.framework.adapter.AbstractPluginAdapter; +import com.netflix.loadbalancer.Server; + +public class ConsulAdapter extends AbstractPluginAdapter { + @Override + public Map getServerMetadata(Server server) { + if (server instanceof ConsulServer) { + ConsulServer consulServer = (ConsulServer) server; + + return consulServer.getMetadata(); + } + + return emptyMetadata; + + // throw new DiscoveryException("Server instance isn't the type of ConsulServer"); + } +} \ No newline at end of file diff --git a/discovery-plugin-register-center/discovery-plugin-register-center-starter-consul/src/main/java/com/nepxion/discovery/plugin/registercenter/consul/configuration/ConsulAutoConfiguration.java b/discovery-plugin-register-center/discovery-plugin-register-center-starter-consul/src/main/java/com/nepxion/discovery/plugin/registercenter/consul/configuration/ConsulAutoConfiguration.java new file mode 100644 index 0000000000..80760a9914 --- /dev/null +++ b/discovery-plugin-register-center/discovery-plugin-register-center-starter-consul/src/main/java/com/nepxion/discovery/plugin/registercenter/consul/configuration/ConsulAutoConfiguration.java @@ -0,0 +1,52 @@ +package com.nepxion.discovery.plugin.registercenter.consul.configuration; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.springframework.cloud.netflix.ribbon.RibbonClients; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import com.nepxion.banner.BannerConstant; +import com.nepxion.banner.Description; +import com.nepxion.banner.LogoBanner; +import com.nepxion.banner.NepxionBanner; +import com.nepxion.discovery.common.entity.DiscoveryType; +import com.nepxion.discovery.plugin.framework.adapter.PluginAdapter; +import com.nepxion.discovery.plugin.framework.configuration.PluginLoadBalanceConfiguration; +import com.nepxion.discovery.plugin.registercenter.consul.adapter.ConsulAdapter; +import com.taobao.text.Color; + +@Configuration +@RibbonClients(defaultConfiguration = { PluginLoadBalanceConfiguration.class, ConsulLoadBalanceConfiguration.class }) +public class ConsulAutoConfiguration { + static { + /*String bannerShown = System.getProperty(BannerConstant.BANNER_SHOWN, "true"); + if (Boolean.valueOf(bannerShown)) { + System.out.println(""); + System.out.println("╔═══╗ ╔╗"); + System.out.println("║╔═╗║ ║║"); + System.out.println("║║ ╚╬══╦═╗╔══╦╗╔╣║"); + System.out.println("║║ ╔╣╔╗║╔╗╣══╣║║║║"); + System.out.println("║╚═╝║╚╝║║║╠══║╚╝║╚╗"); + System.out.println("╚═══╩══╩╝╚╩══╩══╩═╝"); + System.out.println(ConsulConstant.DISCOVERY_PLUGIN + " Discovery"); + System.out.println(""); + }*/ + + LogoBanner logoBanner = new LogoBanner(ConsulAutoConfiguration.class, "/com/nepxion/consul/resource/logo.txt", "Welcome to Nepxion", 6, 5, new Color[] { Color.red, Color.green, Color.cyan, Color.blue, Color.yellow, Color.magenta }, true); + + NepxionBanner.show(logoBanner, new Description("Discovery:", DiscoveryType.CONSUL.toString(), 0, 1), new Description(BannerConstant.GITHUB + ":", BannerConstant.NEPXION_GITHUB + "/Discovery", 0, 1)); + } + + @Bean + public PluginAdapter pluginAdapter() { + return new ConsulAdapter(); + } +} \ No newline at end of file diff --git a/discovery-plugin-framework-consul/src/main/java/com/nepxion/discovery/plugin/framework/configuration/ConsulLoadBalanceConfiguration.java b/discovery-plugin-register-center/discovery-plugin-register-center-starter-consul/src/main/java/com/nepxion/discovery/plugin/registercenter/consul/configuration/ConsulLoadBalanceConfiguration.java similarity index 82% rename from discovery-plugin-framework-consul/src/main/java/com/nepxion/discovery/plugin/framework/configuration/ConsulLoadBalanceConfiguration.java rename to discovery-plugin-register-center/discovery-plugin-register-center-starter-consul/src/main/java/com/nepxion/discovery/plugin/registercenter/consul/configuration/ConsulLoadBalanceConfiguration.java index d80c829c87..914962bd44 100644 --- a/discovery-plugin-framework-consul/src/main/java/com/nepxion/discovery/plugin/framework/configuration/ConsulLoadBalanceConfiguration.java +++ b/discovery-plugin-register-center/discovery-plugin-register-center-starter-consul/src/main/java/com/nepxion/discovery/plugin/registercenter/consul/configuration/ConsulLoadBalanceConfiguration.java @@ -1,4 +1,4 @@ -package com.nepxion.discovery.plugin.framework.configuration; +package com.nepxion.discovery.plugin.registercenter.consul.configuration; /** *

Title: Nepxion Discovery

@@ -15,11 +15,10 @@ import org.springframework.cloud.consul.discovery.ConsulRibbonClientConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.core.env.ConfigurableEnvironment; import com.ecwid.consul.v1.ConsulClient; -import com.nepxion.discovery.plugin.framework.decorator.ConsulServerListDecorator; import com.nepxion.discovery.plugin.framework.listener.loadbalance.LoadBalanceListenerExecutor; +import com.nepxion.discovery.plugin.registercenter.consul.decorator.ConsulServerListDecorator; import com.netflix.client.config.IClientConfig; import com.netflix.loadbalancer.ServerList; @@ -29,9 +28,6 @@ public class ConsulLoadBalanceConfiguration { @Autowired private ConsulClient client; - @Autowired - private ConfigurableEnvironment environment; - @Autowired private LoadBalanceListenerExecutor loadBalanceListenerExecutor; @@ -39,7 +35,6 @@ public class ConsulLoadBalanceConfiguration { public ServerList ribbonServerList(IClientConfig config, ConsulDiscoveryProperties properties) { ConsulServerListDecorator serverList = new ConsulServerListDecorator(client, properties); serverList.initWithNiwsConfig(config); - serverList.setEnvironment(environment); serverList.setLoadBalanceListenerExecutor(loadBalanceListenerExecutor); return serverList; diff --git a/discovery-plugin-register-center/discovery-plugin-register-center-starter-consul/src/main/java/com/nepxion/discovery/plugin/registercenter/consul/constant/ConsulConstant.java b/discovery-plugin-register-center/discovery-plugin-register-center-starter-consul/src/main/java/com/nepxion/discovery/plugin/registercenter/consul/constant/ConsulConstant.java new file mode 100644 index 0000000000..c5f16b81c2 --- /dev/null +++ b/discovery-plugin-register-center/discovery-plugin-register-center-starter-consul/src/main/java/com/nepxion/discovery/plugin/registercenter/consul/constant/ConsulConstant.java @@ -0,0 +1,14 @@ +package com.nepxion.discovery.plugin.registercenter.consul.constant; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +public class ConsulConstant { + +} \ No newline at end of file diff --git a/discovery-plugin-register-center/discovery-plugin-register-center-starter-consul/src/main/java/com/nepxion/discovery/plugin/registercenter/consul/context/ConsulApplicationContextInitializer.java b/discovery-plugin-register-center/discovery-plugin-register-center-starter-consul/src/main/java/com/nepxion/discovery/plugin/registercenter/consul/context/ConsulApplicationContextInitializer.java new file mode 100644 index 0000000000..d72412adef --- /dev/null +++ b/discovery-plugin-register-center/discovery-plugin-register-center-starter-consul/src/main/java/com/nepxion/discovery/plugin/registercenter/consul/context/ConsulApplicationContextInitializer.java @@ -0,0 +1,118 @@ +package com.nepxion.discovery.plugin.registercenter.consul.context; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.List; +import java.util.Map; + +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.BeansException; +import org.springframework.boot.SpringBootVersion; +import org.springframework.cloud.consul.discovery.ConsulDiscoveryProperties; +import org.springframework.cloud.consul.serviceregistry.ConsulServiceRegistry; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.core.env.ConfigurableEnvironment; + +import com.nepxion.discovery.common.constant.DiscoveryConstant; +import com.nepxion.discovery.common.constant.DiscoveryMetaDataConstant; +import com.nepxion.discovery.common.context.DiscoveryMetaDataPreInstallation; +import com.nepxion.discovery.common.entity.DiscoveryType; +import com.nepxion.discovery.plugin.framework.adapter.ApplicationInfoAdapter; +import com.nepxion.discovery.plugin.framework.context.PluginApplicationContextInitializer; +import com.nepxion.discovery.plugin.framework.context.PluginContextAware; +import com.nepxion.discovery.plugin.framework.util.MetadataUtil; +import com.nepxion.discovery.plugin.registercenter.consul.decorator.ConsulServiceRegistryDecorator; + +public class ConsulApplicationContextInitializer extends PluginApplicationContextInitializer { + @Override + protected Object afterInitialization(ConfigurableApplicationContext applicationContext, Object bean, String beanName) throws BeansException { + if (bean instanceof ConsulServiceRegistry) { + ConsulServiceRegistry consulServiceRegistry = (ConsulServiceRegistry) bean; + + return new ConsulServiceRegistryDecorator(consulServiceRegistry, applicationContext); + } else if (bean instanceof ConsulDiscoveryProperties) { + ConfigurableEnvironment environment = applicationContext.getEnvironment(); + + ConsulDiscoveryProperties consulDiscoveryProperties = (ConsulDiscoveryProperties) bean; + consulDiscoveryProperties.setPreferIpAddress(true); + + List metadata = consulDiscoveryProperties.getTags(); + + String groupKey = PluginContextAware.getGroupKey(environment); + /*if (!MetadataUtil.containsKey(metadata, groupKey)) { + metadata.add(groupKey + "=" + DiscoveryConstant.DEFAULT); + } + if (!MetadataUtil.containsKey(metadata, DiscoveryConstant.VERSION)) { + metadata.add(DiscoveryConstant.VERSION + "=" + DiscoveryConstant.DEFAULT); + } + if (!MetadataUtil.containsKey(metadata, DiscoveryConstant.REGION)) { + metadata.add(DiscoveryConstant.REGION + "=" + DiscoveryConstant.DEFAULT); + } + if (!MetadataUtil.containsKey(metadata, DiscoveryConstant.ENVIRONMENT)) { + metadata.add(DiscoveryConstant.ENVIRONMENT + "=" + DiscoveryConstant.DEFAULT); + } + if (!MetadataUtil.containsKey(metadata, DiscoveryConstant.ZONE)) { + metadata.add(DiscoveryConstant.ZONE + "=" + DiscoveryConstant.DEFAULT); + } + if (!MetadataUtil.containsKey(metadata, DiscoveryConstant.ACTIVE)) { + metadata.add(DiscoveryConstant.ACTIVE + "=" + "false"); + }*/ + String prefixGroup = getPrefixGroup(applicationContext); + if (StringUtils.isNotEmpty(prefixGroup)) { + metadata.set(MetadataUtil.getIndex(metadata, groupKey), groupKey + "=" + prefixGroup); + } + String gitVersion = getGitVersion(applicationContext); + if (StringUtils.isNotEmpty(gitVersion)) { + metadata.set(MetadataUtil.getIndex(metadata, DiscoveryConstant.VERSION), DiscoveryConstant.VERSION + "=" + gitVersion); + } + + metadata.add(DiscoveryMetaDataConstant.SPRING_BOOT_VERSION + "=" + SpringBootVersion.getVersion()); + metadata.add(DiscoveryMetaDataConstant.SPRING_APPLICATION_NAME + "=" + PluginContextAware.getApplicationName(environment)); + metadata.add(DiscoveryMetaDataConstant.SPRING_APPLICATION_TYPE + "=" + PluginContextAware.getApplicationType(environment)); + String applicationGatewayType = PluginContextAware.getApplicationGatewayType(environment); + if (StringUtils.isNotEmpty(applicationGatewayType)) { + metadata.add(DiscoveryMetaDataConstant.SPRING_APPLICATION_GATEWAY_TYPE + "=" + applicationGatewayType); + } + metadata.add(DiscoveryMetaDataConstant.SPRING_APPLICATION_PROTOCOL + "=" + PluginContextAware.getApplicationProtocol(environment)); + metadata.add(DiscoveryMetaDataConstant.SPRING_APPLICATION_UUID + "=" + PluginContextAware.getApplicationUUId(environment)); + metadata.add(DiscoveryMetaDataConstant.SPRING_APPLICATION_DISCOVERY_PLUGIN + "=" + DiscoveryType.CONSUL); + metadata.add(DiscoveryMetaDataConstant.SPRING_APPLICATION_DISCOVERY_VERSION + "=" + DiscoveryConstant.DISCOVERY_VERSION); + String agentVersion = System.getProperty(DiscoveryConstant.SPRING_APPLICATION_DISCOVERY_AGENT_VERSION); + if (StringUtils.isNotEmpty(agentVersion)) { + metadata.add(DiscoveryMetaDataConstant.SPRING_APPLICATION_DISCOVERY_AGENT_VERSION + "=" + agentVersion); + } + metadata.add(DiscoveryMetaDataConstant.SPRING_APPLICATION_GROUP_KEY + "=" + groupKey); + metadata.add(DiscoveryMetaDataConstant.SPRING_APPLICATION_CONTEXT_PATH + "=" + PluginContextAware.getContextPath(environment)); + + try { + ApplicationInfoAdapter applicationInfoAdapter = applicationContext.getBean(ApplicationInfoAdapter.class); + if (applicationInfoAdapter != null) { + metadata.add(DiscoveryMetaDataConstant.SPRING_APPLICATION_APP_ID + "=" + applicationInfoAdapter.getAppId()); + } + } catch (Exception e) { + + } + + for (Map.Entry entry : DiscoveryMetaDataPreInstallation.getMetadata().entrySet()) { + String key = entry.getKey(); + String value = entry.getValue(); + if (StringUtils.isNotEmpty(value)) { + metadata.add(key + "=" + value); + } + } + + MetadataUtil.filter(metadata, environment); + + return bean; + } else { + return bean; + } + } +} \ No newline at end of file diff --git a/discovery-plugin-register-center/discovery-plugin-register-center-starter-consul/src/main/java/com/nepxion/discovery/plugin/registercenter/consul/decorator/ConsulServerListDecorator.java b/discovery-plugin-register-center/discovery-plugin-register-center-starter-consul/src/main/java/com/nepxion/discovery/plugin/registercenter/consul/decorator/ConsulServerListDecorator.java new file mode 100644 index 0000000000..5aa5071e93 --- /dev/null +++ b/discovery-plugin-register-center/discovery-plugin-register-center-starter-consul/src/main/java/com/nepxion/discovery/plugin/registercenter/consul/decorator/ConsulServerListDecorator.java @@ -0,0 +1,55 @@ +package com.nepxion.discovery.plugin.registercenter.consul.decorator; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.List; + +import org.springframework.cloud.consul.discovery.ConsulDiscoveryProperties; +import org.springframework.cloud.consul.discovery.ConsulServer; +import org.springframework.cloud.consul.discovery.ConsulServerList; + +import com.ecwid.consul.v1.ConsulClient; +import com.nepxion.discovery.plugin.framework.listener.loadbalance.LoadBalanceListenerExecutor; + +public class ConsulServerListDecorator extends ConsulServerList { + private LoadBalanceListenerExecutor loadBalanceListenerExecutor; + + public ConsulServerListDecorator(ConsulClient client, ConsulDiscoveryProperties properties) { + super(client, properties); + } + + @Override + public List getInitialListOfServers() { + List servers = super.getInitialListOfServers(); + + filter(servers); + + return servers; + } + + @Override + public List getUpdatedListOfServers() { + List servers = super.getUpdatedListOfServers(); + + filter(servers); + + return servers; + } + + private void filter(List servers) { + String serviceId = getServiceId(); + + loadBalanceListenerExecutor.onGetServers(serviceId, servers); + } + + public void setLoadBalanceListenerExecutor(LoadBalanceListenerExecutor loadBalanceListenerExecutor) { + this.loadBalanceListenerExecutor = loadBalanceListenerExecutor; + } +} \ No newline at end of file diff --git a/discovery-plugin-register-center/discovery-plugin-register-center-starter-consul/src/main/java/com/nepxion/discovery/plugin/registercenter/consul/decorator/ConsulServiceRegistryDecorator.java b/discovery-plugin-register-center/discovery-plugin-register-center-starter-consul/src/main/java/com/nepxion/discovery/plugin/registercenter/consul/decorator/ConsulServiceRegistryDecorator.java new file mode 100644 index 0000000000..1f46b1d790 --- /dev/null +++ b/discovery-plugin-register-center/discovery-plugin-register-center-starter-consul/src/main/java/com/nepxion/discovery/plugin/registercenter/consul/decorator/ConsulServiceRegistryDecorator.java @@ -0,0 +1,84 @@ +package com.nepxion.discovery.plugin.registercenter.consul.decorator; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.springframework.beans.BeansException; +import org.springframework.cloud.consul.serviceregistry.ConsulRegistration; +import org.springframework.cloud.consul.serviceregistry.ConsulServiceRegistry; +import org.springframework.context.ConfigurableApplicationContext; + +import com.nepxion.discovery.plugin.framework.listener.register.RegisterListenerExecutor; + +public class ConsulServiceRegistryDecorator extends ConsulServiceRegistry { + // private static final Logger LOG = LoggerFactory.getLogger(ConsulServiceRegistryDecorator.class); + + private ConsulServiceRegistry serviceRegistry; + private ConfigurableApplicationContext applicationContext; + + public ConsulServiceRegistryDecorator(ConsulServiceRegistry serviceRegistry, ConfigurableApplicationContext applicationContext) { + super(null, null, null, null); + + this.serviceRegistry = serviceRegistry; + this.applicationContext = applicationContext; + } + + @Override + public void register(ConsulRegistration registration) { + try { + RegisterListenerExecutor registerListenerExecutor = applicationContext.getBean(RegisterListenerExecutor.class); + registerListenerExecutor.onRegister(registration); + } catch (BeansException e) { + // LOG.warn("Get bean for RegisterListenerExecutor failed, ignore to executor listener"); + } + + serviceRegistry.register(registration); + } + + @Override + public void deregister(ConsulRegistration registration) { + try { + RegisterListenerExecutor registerListenerExecutor = applicationContext.getBean(RegisterListenerExecutor.class); + registerListenerExecutor.onDeregister(registration); + } catch (BeansException e) { + // LOG.warn("Get bean for RegisterListenerExecutor failed, ignore to executor listener"); + } + + serviceRegistry.deregister(registration); + } + + @Override + public void setStatus(ConsulRegistration registration, String status) { + try { + RegisterListenerExecutor registerListenerExecutor = applicationContext.getBean(RegisterListenerExecutor.class); + registerListenerExecutor.onSetStatus(registration, status); + } catch (BeansException e) { + // LOG.warn("Get bean for RegisterListenerExecutor failed, ignore to executor listener"); + } + + serviceRegistry.setStatus(registration, status); + } + + @Override + public Object getStatus(ConsulRegistration registration) { + return serviceRegistry.getStatus(registration); + } + + @Override + public void close() { + try { + RegisterListenerExecutor registerListenerExecutor = applicationContext.getBean(RegisterListenerExecutor.class); + registerListenerExecutor.onClose(); + } catch (BeansException e) { + // LOG.warn("Get bean for RegisterListenerExecutor failed, ignore to executor listener"); + } + + serviceRegistry.close(); + } +} \ No newline at end of file diff --git a/discovery-plugin-register-center/discovery-plugin-register-center-starter-consul/src/main/resources/META-INF/spring.factories b/discovery-plugin-register-center/discovery-plugin-register-center-starter-consul/src/main/resources/META-INF/spring.factories new file mode 100644 index 0000000000..1e26edc37a --- /dev/null +++ b/discovery-plugin-register-center/discovery-plugin-register-center-starter-consul/src/main/resources/META-INF/spring.factories @@ -0,0 +1,5 @@ +org.springframework.context.ApplicationContextInitializer=\ +com.nepxion.discovery.plugin.registercenter.consul.context.ConsulApplicationContextInitializer + +org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ +com.nepxion.discovery.plugin.registercenter.consul.configuration.ConsulAutoConfiguration \ No newline at end of file diff --git a/discovery-plugin-register-center/discovery-plugin-register-center-starter-eureka/pom.xml b/discovery-plugin-register-center/discovery-plugin-register-center-starter-eureka/pom.xml new file mode 100644 index 0000000000..58aa69d489 --- /dev/null +++ b/discovery-plugin-register-center/discovery-plugin-register-center-starter-eureka/pom.xml @@ -0,0 +1,28 @@ + + + discovery-plugin-register-center-starter-eureka + Nepxion Discovery Plugin Register Center Starter Eureka + jar + 4.0.0 + Nepxion Discovery is a solution for Spring Cloud with blue green, gray, weight, limitation, circuit breaker, degrade, isolation, monitor, tracing, dye, failover, async agent + http://www.nepxion.com + + + com.nepxion + discovery-plugin-register-center + 6.23.0 + + + + + ${project.groupId} + discovery-plugin-register-center-starter + + + + org.springframework.cloud + spring-cloud-starter-netflix-eureka-client + + + \ No newline at end of file diff --git a/discovery-plugin-register-center/discovery-plugin-register-center-starter-eureka/src/main/java/com/nepxion/discovery/plugin/registercenter/eureka/adapter/EurekaAdapter.java b/discovery-plugin-register-center/discovery-plugin-register-center-starter-eureka/src/main/java/com/nepxion/discovery/plugin/registercenter/eureka/adapter/EurekaAdapter.java new file mode 100644 index 0000000000..75194ed276 --- /dev/null +++ b/discovery-plugin-register-center/discovery-plugin-register-center-starter-eureka/src/main/java/com/nepxion/discovery/plugin/registercenter/eureka/adapter/EurekaAdapter.java @@ -0,0 +1,31 @@ +package com.nepxion.discovery.plugin.registercenter.eureka.adapter; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.Map; + +import com.nepxion.discovery.plugin.framework.adapter.AbstractPluginAdapter; +import com.netflix.loadbalancer.Server; +import com.netflix.niws.loadbalancer.DiscoveryEnabledServer; + +public class EurekaAdapter extends AbstractPluginAdapter { + @Override + public Map getServerMetadata(Server server) { + if (server instanceof DiscoveryEnabledServer) { + DiscoveryEnabledServer discoveryEnabledServer = (DiscoveryEnabledServer) server; + + return discoveryEnabledServer.getInstanceInfo().getMetadata(); + } + + return emptyMetadata; + + // throw new DiscoveryException("Server instance isn't the type of DiscoveryEnabledServer"); + } +} \ No newline at end of file diff --git a/discovery-plugin-framework-eureka/src/main/java/com/nepxion/discovery/plugin/framework/configuration/EurekaAutoConfiguration.java b/discovery-plugin-register-center/discovery-plugin-register-center-starter-eureka/src/main/java/com/nepxion/discovery/plugin/registercenter/eureka/configuration/EurekaAutoConfiguration.java similarity index 85% rename from discovery-plugin-framework-eureka/src/main/java/com/nepxion/discovery/plugin/framework/configuration/EurekaAutoConfiguration.java rename to discovery-plugin-register-center/discovery-plugin-register-center-starter-eureka/src/main/java/com/nepxion/discovery/plugin/registercenter/eureka/configuration/EurekaAutoConfiguration.java index 71e9f7a6e5..be76ab2b2d 100644 --- a/discovery-plugin-framework-eureka/src/main/java/com/nepxion/discovery/plugin/framework/configuration/EurekaAutoConfiguration.java +++ b/discovery-plugin-register-center/discovery-plugin-register-center-starter-eureka/src/main/java/com/nepxion/discovery/plugin/registercenter/eureka/configuration/EurekaAutoConfiguration.java @@ -1,4 +1,4 @@ -package com.nepxion.discovery.plugin.framework.configuration; +package com.nepxion.discovery.plugin.registercenter.eureka.configuration; /** *

Title: Nepxion Discovery

@@ -17,9 +17,10 @@ import com.nepxion.banner.Description; import com.nepxion.banner.LogoBanner; import com.nepxion.banner.NepxionBanner; -import com.nepxion.discovery.plugin.framework.adapter.EurekaAdapter; +import com.nepxion.discovery.common.entity.DiscoveryType; import com.nepxion.discovery.plugin.framework.adapter.PluginAdapter; -import com.nepxion.discovery.plugin.framework.constant.EurekaConstant; +import com.nepxion.discovery.plugin.framework.configuration.PluginLoadBalanceConfiguration; +import com.nepxion.discovery.plugin.registercenter.eureka.adapter.EurekaAdapter; import com.taobao.text.Color; @Configuration @@ -41,7 +42,7 @@ public class EurekaAutoConfiguration { LogoBanner logoBanner = new LogoBanner(EurekaAutoConfiguration.class, "/com/nepxion/eureka/resource/logo.txt", "Welcome to Nepxion", 6, 5, new Color[] { Color.red, Color.green, Color.cyan, Color.blue, Color.yellow, Color.magenta }, true); - NepxionBanner.show(logoBanner, new Description("Discovery:", EurekaConstant.DISCOVERY_PLUGIN, 0, 1), new Description(BannerConstant.GITHUB + ":", BannerConstant.NEPXION_GITHUB + "/Discovery", 0, 1)); + NepxionBanner.show(logoBanner, new Description("Discovery:", DiscoveryType.EUREKA.toString(), 0, 1), new Description(BannerConstant.GITHUB + ":", BannerConstant.NEPXION_GITHUB + "/Discovery", 0, 1)); } @Bean diff --git a/discovery-plugin-framework-eureka/src/main/java/com/nepxion/discovery/plugin/framework/configuration/EurekaLoadBalanceConfiguration.java b/discovery-plugin-register-center/discovery-plugin-register-center-starter-eureka/src/main/java/com/nepxion/discovery/plugin/registercenter/eureka/configuration/EurekaLoadBalanceConfiguration.java similarity index 87% rename from discovery-plugin-framework-eureka/src/main/java/com/nepxion/discovery/plugin/framework/configuration/EurekaLoadBalanceConfiguration.java rename to discovery-plugin-register-center/discovery-plugin-register-center-starter-eureka/src/main/java/com/nepxion/discovery/plugin/registercenter/eureka/configuration/EurekaLoadBalanceConfiguration.java index ce8e681324..96173faa27 100644 --- a/discovery-plugin-framework-eureka/src/main/java/com/nepxion/discovery/plugin/framework/configuration/EurekaLoadBalanceConfiguration.java +++ b/discovery-plugin-register-center/discovery-plugin-register-center-starter-eureka/src/main/java/com/nepxion/discovery/plugin/registercenter/eureka/configuration/EurekaLoadBalanceConfiguration.java @@ -1,4 +1,4 @@ -package com.nepxion.discovery.plugin.framework.configuration; +package com.nepxion.discovery.plugin.registercenter.eureka.configuration; /** *

Title: Nepxion Discovery

@@ -19,10 +19,9 @@ import org.springframework.cloud.netflix.ribbon.eureka.EurekaRibbonClientConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.core.env.ConfigurableEnvironment; -import com.nepxion.discovery.plugin.framework.decorator.EurekaServerListDecorator; import com.nepxion.discovery.plugin.framework.listener.loadbalance.LoadBalanceListenerExecutor; +import com.nepxion.discovery.plugin.registercenter.eureka.decorator.EurekaServerListDecorator; import com.netflix.client.config.IClientConfig; import com.netflix.discovery.EurekaClient; import com.netflix.loadbalancer.ServerList; @@ -40,9 +39,6 @@ public class EurekaLoadBalanceConfiguration { @Autowired private PropertiesFactory propertiesFactory; - @Autowired - private ConfigurableEnvironment environment; - @Autowired private LoadBalanceListenerExecutor loadBalanceListenerExecutor; @@ -55,7 +51,6 @@ public ServerList ribbonServerList(IClientConfig config, ProviderTitle: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +public class EurekaConstant { + +} \ No newline at end of file diff --git a/discovery-plugin-register-center/discovery-plugin-register-center-starter-eureka/src/main/java/com/nepxion/discovery/plugin/registercenter/eureka/context/EurekaApplicationContextInitializer.java b/discovery-plugin-register-center/discovery-plugin-register-center-starter-eureka/src/main/java/com/nepxion/discovery/plugin/registercenter/eureka/context/EurekaApplicationContextInitializer.java new file mode 100644 index 0000000000..76c1a38b95 --- /dev/null +++ b/discovery-plugin-register-center/discovery-plugin-register-center-starter-eureka/src/main/java/com/nepxion/discovery/plugin/registercenter/eureka/context/EurekaApplicationContextInitializer.java @@ -0,0 +1,117 @@ +package com.nepxion.discovery.plugin.registercenter.eureka.context; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.Map; + +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.BeansException; +import org.springframework.boot.SpringBootVersion; +import org.springframework.cloud.netflix.eureka.EurekaInstanceConfigBean; +import org.springframework.cloud.netflix.eureka.serviceregistry.EurekaServiceRegistry; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.core.env.ConfigurableEnvironment; + +import com.nepxion.discovery.common.constant.DiscoveryConstant; +import com.nepxion.discovery.common.constant.DiscoveryMetaDataConstant; +import com.nepxion.discovery.common.context.DiscoveryMetaDataPreInstallation; +import com.nepxion.discovery.common.entity.DiscoveryType; +import com.nepxion.discovery.plugin.framework.adapter.ApplicationInfoAdapter; +import com.nepxion.discovery.plugin.framework.context.PluginApplicationContextInitializer; +import com.nepxion.discovery.plugin.framework.context.PluginContextAware; +import com.nepxion.discovery.plugin.framework.util.MetadataUtil; +import com.nepxion.discovery.plugin.registercenter.eureka.decorator.EurekaServiceRegistryDecorator; + +public class EurekaApplicationContextInitializer extends PluginApplicationContextInitializer { + @Override + protected Object afterInitialization(ConfigurableApplicationContext applicationContext, Object bean, String beanName) throws BeansException { + if (bean instanceof EurekaServiceRegistry) { + EurekaServiceRegistry eurekaServiceRegistry = (EurekaServiceRegistry) bean; + + return new EurekaServiceRegistryDecorator(eurekaServiceRegistry, applicationContext); + } else if (bean instanceof EurekaInstanceConfigBean) { + ConfigurableEnvironment environment = applicationContext.getEnvironment(); + + EurekaInstanceConfigBean eurekaInstanceConfig = (EurekaInstanceConfigBean) bean; + eurekaInstanceConfig.setPreferIpAddress(true); + + Map metadata = eurekaInstanceConfig.getMetadataMap(); + + String groupKey = PluginContextAware.getGroupKey(environment); + /*if (!metadata.containsKey(groupKey)) { + metadata.put(groupKey, DiscoveryConstant.DEFAULT); + } + if (!metadata.containsKey(DiscoveryConstant.VERSION)) { + metadata.put(DiscoveryConstant.VERSION, DiscoveryConstant.DEFAULT); + } + if (!metadata.containsKey(DiscoveryConstant.REGION)) { + metadata.put(DiscoveryConstant.REGION, DiscoveryConstant.DEFAULT); + } + if (!metadata.containsKey(DiscoveryConstant.ENVIRONMENT)) { + metadata.put(DiscoveryConstant.ENVIRONMENT, DiscoveryConstant.DEFAULT); + } + if (!metadata.containsKey(DiscoveryConstant.ZONE)) { + metadata.put(DiscoveryConstant.ZONE, DiscoveryConstant.DEFAULT); + } + if (!metadata.containsKey(DiscoveryConstant.ACTIVE)) { + metadata.put(DiscoveryConstant.ACTIVE, "false"); + }*/ + String prefixGroup = getPrefixGroup(applicationContext); + if (StringUtils.isNotEmpty(prefixGroup)) { + metadata.put(groupKey, prefixGroup); + } + String gitVersion = getGitVersion(applicationContext); + if (StringUtils.isNotEmpty(gitVersion)) { + metadata.put(DiscoveryConstant.VERSION, gitVersion); + } + + metadata.put(DiscoveryMetaDataConstant.SPRING_BOOT_VERSION, SpringBootVersion.getVersion()); + metadata.put(DiscoveryMetaDataConstant.SPRING_APPLICATION_NAME, PluginContextAware.getApplicationName(environment)); + metadata.put(DiscoveryMetaDataConstant.SPRING_APPLICATION_TYPE, PluginContextAware.getApplicationType(environment)); + String applicationGatewayType = PluginContextAware.getApplicationGatewayType(environment); + if (StringUtils.isNotEmpty(applicationGatewayType)) { + metadata.put(DiscoveryMetaDataConstant.SPRING_APPLICATION_GATEWAY_TYPE, applicationGatewayType); + } + metadata.put(DiscoveryMetaDataConstant.SPRING_APPLICATION_PROTOCOL, PluginContextAware.getApplicationProtocol(environment)); + metadata.put(DiscoveryMetaDataConstant.SPRING_APPLICATION_UUID, PluginContextAware.getApplicationUUId(environment)); + metadata.put(DiscoveryMetaDataConstant.SPRING_APPLICATION_DISCOVERY_PLUGIN, DiscoveryType.EUREKA.toString()); + metadata.put(DiscoveryMetaDataConstant.SPRING_APPLICATION_DISCOVERY_VERSION, DiscoveryConstant.DISCOVERY_VERSION); + String agentVersion = System.getProperty(DiscoveryConstant.SPRING_APPLICATION_DISCOVERY_AGENT_VERSION); + if (StringUtils.isNotEmpty(agentVersion)) { + metadata.put(DiscoveryMetaDataConstant.SPRING_APPLICATION_DISCOVERY_AGENT_VERSION, agentVersion); + } + metadata.put(DiscoveryMetaDataConstant.SPRING_APPLICATION_GROUP_KEY, groupKey); + metadata.put(DiscoveryMetaDataConstant.SPRING_APPLICATION_CONTEXT_PATH, PluginContextAware.getContextPath(environment)); + + try { + ApplicationInfoAdapter applicationInfoAdapter = applicationContext.getBean(ApplicationInfoAdapter.class); + if (applicationInfoAdapter != null) { + metadata.put(DiscoveryMetaDataConstant.SPRING_APPLICATION_APP_ID, applicationInfoAdapter.getAppId()); + } + } catch (Exception e) { + + } + + for (Map.Entry entry : DiscoveryMetaDataPreInstallation.getMetadata().entrySet()) { + String key = entry.getKey(); + String value = entry.getValue(); + if (StringUtils.isNotEmpty(value)) { + metadata.put(key, value); + } + } + + MetadataUtil.filter(metadata, environment); + + return bean; + } else { + return bean; + } + } +} \ No newline at end of file diff --git a/discovery-plugin-register-center/discovery-plugin-register-center-starter-eureka/src/main/java/com/nepxion/discovery/plugin/registercenter/eureka/decorator/EurekaServerListDecorator.java b/discovery-plugin-register-center/discovery-plugin-register-center-starter-eureka/src/main/java/com/nepxion/discovery/plugin/registercenter/eureka/decorator/EurekaServerListDecorator.java new file mode 100644 index 0000000000..6faf0fe6b0 --- /dev/null +++ b/discovery-plugin-register-center/discovery-plugin-register-center-starter-eureka/src/main/java/com/nepxion/discovery/plugin/registercenter/eureka/decorator/EurekaServerListDecorator.java @@ -0,0 +1,59 @@ +package com.nepxion.discovery.plugin.registercenter.eureka.decorator; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.List; + +import org.springframework.cloud.netflix.ribbon.eureka.DomainExtractingServerList; + +import com.nepxion.discovery.plugin.framework.listener.loadbalance.LoadBalanceListenerExecutor; +import com.netflix.client.config.IClientConfig; +import com.netflix.loadbalancer.ServerList; +import com.netflix.niws.loadbalancer.DiscoveryEnabledServer; + +public class EurekaServerListDecorator extends DomainExtractingServerList { + private LoadBalanceListenerExecutor loadBalanceListenerExecutor; + + private String serviceId; + + public EurekaServerListDecorator(ServerList list, IClientConfig clientConfig, boolean approximateZoneFromHostname) { + super(list, clientConfig, approximateZoneFromHostname); + } + + @Override + public List getInitialListOfServers() { + List servers = super.getInitialListOfServers(); + + filter(servers); + + return servers; + } + + @Override + public List getUpdatedListOfServers() { + List servers = super.getUpdatedListOfServers(); + + filter(servers); + + return servers; + } + + private void filter(List servers) { + loadBalanceListenerExecutor.onGetServers(serviceId, servers); + } + + public void setLoadBalanceListenerExecutor(LoadBalanceListenerExecutor loadBalanceListenerExecutor) { + this.loadBalanceListenerExecutor = loadBalanceListenerExecutor; + } + + public void setServiceId(String serviceId) { + this.serviceId = serviceId; + } +} \ No newline at end of file diff --git a/discovery-plugin-register-center/discovery-plugin-register-center-starter-eureka/src/main/java/com/nepxion/discovery/plugin/registercenter/eureka/decorator/EurekaServiceRegistryDecorator.java b/discovery-plugin-register-center/discovery-plugin-register-center-starter-eureka/src/main/java/com/nepxion/discovery/plugin/registercenter/eureka/decorator/EurekaServiceRegistryDecorator.java new file mode 100644 index 0000000000..122631788c --- /dev/null +++ b/discovery-plugin-register-center/discovery-plugin-register-center-starter-eureka/src/main/java/com/nepxion/discovery/plugin/registercenter/eureka/decorator/EurekaServiceRegistryDecorator.java @@ -0,0 +1,82 @@ +package com.nepxion.discovery.plugin.registercenter.eureka.decorator; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.springframework.beans.BeansException; +import org.springframework.cloud.netflix.eureka.serviceregistry.EurekaRegistration; +import org.springframework.cloud.netflix.eureka.serviceregistry.EurekaServiceRegistry; +import org.springframework.context.ConfigurableApplicationContext; + +import com.nepxion.discovery.plugin.framework.listener.register.RegisterListenerExecutor; + +public class EurekaServiceRegistryDecorator extends EurekaServiceRegistry { + // private static final Logger LOG = LoggerFactory.getLogger(EurekaServiceRegistryDecorator.class); + + private EurekaServiceRegistry serviceRegistry; + private ConfigurableApplicationContext applicationContext; + + public EurekaServiceRegistryDecorator(EurekaServiceRegistry serviceRegistry, ConfigurableApplicationContext applicationContext) { + this.serviceRegistry = serviceRegistry; + this.applicationContext = applicationContext; + } + + @Override + public void register(EurekaRegistration registration) { + try { + RegisterListenerExecutor registerListenerExecutor = applicationContext.getBean(RegisterListenerExecutor.class); + registerListenerExecutor.onRegister(registration); + } catch (BeansException e) { + // LOG.warn("Get bean for RegisterListenerExecutor failed, ignore to executor listener"); + } + + serviceRegistry.register(registration); + } + + @Override + public void deregister(EurekaRegistration registration) { + try { + RegisterListenerExecutor registerListenerExecutor = applicationContext.getBean(RegisterListenerExecutor.class); + registerListenerExecutor.onDeregister(registration); + } catch (BeansException e) { + // LOG.warn("Get bean for RegisterListenerExecutor failed, ignore to executor listener"); + } + + serviceRegistry.deregister(registration); + } + + @Override + public void setStatus(EurekaRegistration registration, String status) { + try { + RegisterListenerExecutor registerListenerExecutor = applicationContext.getBean(RegisterListenerExecutor.class); + registerListenerExecutor.onSetStatus(registration, status); + } catch (BeansException e) { + // LOG.warn("Get bean for RegisterListenerExecutor failed, ignore to executor listener"); + } + + serviceRegistry.setStatus(registration, status); + } + + @Override + public Object getStatus(EurekaRegistration registration) { + return serviceRegistry.getStatus(registration); + } + + @Override + public void close() { + try { + RegisterListenerExecutor registerListenerExecutor = applicationContext.getBean(RegisterListenerExecutor.class); + registerListenerExecutor.onClose(); + } catch (BeansException e) { + // LOG.warn("Get bean for RegisterListenerExecutor failed, ignore to executor listener"); + } + + serviceRegistry.close(); + } +} \ No newline at end of file diff --git a/discovery-plugin-register-center/discovery-plugin-register-center-starter-eureka/src/main/resources/META-INF/spring.factories b/discovery-plugin-register-center/discovery-plugin-register-center-starter-eureka/src/main/resources/META-INF/spring.factories new file mode 100644 index 0000000000..4640569a43 --- /dev/null +++ b/discovery-plugin-register-center/discovery-plugin-register-center-starter-eureka/src/main/resources/META-INF/spring.factories @@ -0,0 +1,5 @@ +org.springframework.context.ApplicationContextInitializer=\ +com.nepxion.discovery.plugin.registercenter.eureka.context.EurekaApplicationContextInitializer + +org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ +com.nepxion.discovery.plugin.registercenter.eureka.configuration.EurekaAutoConfiguration \ No newline at end of file diff --git a/discovery-plugin-register-center/discovery-plugin-register-center-starter-nacos/pom.xml b/discovery-plugin-register-center/discovery-plugin-register-center-starter-nacos/pom.xml new file mode 100644 index 0000000000..40e41c3c7a --- /dev/null +++ b/discovery-plugin-register-center/discovery-plugin-register-center-starter-nacos/pom.xml @@ -0,0 +1,28 @@ + + + discovery-plugin-register-center-starter-nacos + Nepxion Discovery Plugin Register Center Starter Nacos + jar + 4.0.0 + Nepxion Discovery is a solution for Spring Cloud with blue green, gray, weight, limitation, circuit breaker, degrade, isolation, monitor, tracing, dye, failover, async agent + http://www.nepxion.com + + + com.nepxion + discovery-plugin-register-center + 6.23.0 + + + + + ${project.groupId} + discovery-plugin-register-center-starter + + + + com.alibaba.cloud + spring-cloud-starter-alibaba-nacos-discovery + + + \ No newline at end of file diff --git a/discovery-plugin-register-center/discovery-plugin-register-center-starter-nacos/src/main/java/com/nepxion/discovery/plugin/registercenter/nacos/adapter/NacosAdapter.java b/discovery-plugin-register-center/discovery-plugin-register-center-starter-nacos/src/main/java/com/nepxion/discovery/plugin/registercenter/nacos/adapter/NacosAdapter.java new file mode 100644 index 0000000000..f33be34d8e --- /dev/null +++ b/discovery-plugin-register-center/discovery-plugin-register-center-starter-nacos/src/main/java/com/nepxion/discovery/plugin/registercenter/nacos/adapter/NacosAdapter.java @@ -0,0 +1,71 @@ +package com.nepxion.discovery.plugin.registercenter.nacos.adapter; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.Map; + +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.cloud.client.ServiceInstance; + +import com.alibaba.cloud.nacos.ribbon.NacosServer; +import com.nepxion.discovery.plugin.framework.adapter.AbstractPluginAdapter; +import com.nepxion.discovery.plugin.registercenter.nacos.constant.NacosConstant; +import com.netflix.loadbalancer.Server; + +public class NacosAdapter extends AbstractPluginAdapter { + @Value("${" + NacosConstant.SPRING_APPLICATION_NACOS_SERVICE_ID_FILTER_ENABLED + ":true}") + protected Boolean nacosServiceIdFilterEnabled; + + public static final String SEPARATE = "@@"; + + @Override + public Map getServerMetadata(Server server) { + if (server instanceof NacosServer) { + NacosServer nacosServer = (NacosServer) server; + + return nacosServer.getMetadata(); + } + + return emptyMetadata; + + // throw new DiscoveryException("Server instance isn't the type of NacosServer"); + } + + @Override + public String getServiceId() { + String serviceId = super.getServiceId(); + + return filterServiceId(serviceId); + } + + @Override + public String getServerServiceId(Server server) { + String serverServiceId = super.getServerServiceId(server); + + return filterServiceId(serverServiceId); + } + + @Override + public String getInstanceServiceId(ServiceInstance instance) { + String instanceServiceId = super.getInstanceServiceId(instance); + + return filterServiceId(instanceServiceId); + } + + // 由于Nacos注册中心会自动把服务名处理成GROUP@@SERVICE_ID的格式,导致根据服务名去获取元数据的时候会找不到,通过如下方式过滤掉GROUP前缀 + private String filterServiceId(String serviceId) { + if (nacosServiceIdFilterEnabled && StringUtils.contains(serviceId, SEPARATE)) { + serviceId = serviceId.substring(serviceId.indexOf(SEPARATE) + SEPARATE.length(), serviceId.length()); + } + + return serviceId; + } +} \ No newline at end of file diff --git a/discovery-plugin-register-center/discovery-plugin-register-center-starter-nacos/src/main/java/com/nepxion/discovery/plugin/registercenter/nacos/configuration/NacosAutoConfiguration.java b/discovery-plugin-register-center/discovery-plugin-register-center-starter-nacos/src/main/java/com/nepxion/discovery/plugin/registercenter/nacos/configuration/NacosAutoConfiguration.java new file mode 100644 index 0000000000..a49c543f5c --- /dev/null +++ b/discovery-plugin-register-center/discovery-plugin-register-center-starter-nacos/src/main/java/com/nepxion/discovery/plugin/registercenter/nacos/configuration/NacosAutoConfiguration.java @@ -0,0 +1,52 @@ +package com.nepxion.discovery.plugin.registercenter.nacos.configuration; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.springframework.cloud.netflix.ribbon.RibbonClients; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import com.nepxion.banner.BannerConstant; +import com.nepxion.banner.Description; +import com.nepxion.banner.LogoBanner; +import com.nepxion.banner.NepxionBanner; +import com.nepxion.discovery.common.entity.DiscoveryType; +import com.nepxion.discovery.plugin.framework.adapter.PluginAdapter; +import com.nepxion.discovery.plugin.framework.configuration.PluginLoadBalanceConfiguration; +import com.nepxion.discovery.plugin.registercenter.nacos.adapter.NacosAdapter; +import com.taobao.text.Color; + +@Configuration +@RibbonClients(defaultConfiguration = { PluginLoadBalanceConfiguration.class, NacosLoadBalanceConfiguration.class }) +public class NacosAutoConfiguration { + static { + /*String bannerShown = System.getProperty(BannerConstant.BANNER_SHOWN, "true"); + if (Boolean.valueOf(bannerShown)) { + System.out.println(""); + System.out.println("╔═╗ ╔╗"); + System.out.println("║║╚╗║║"); + System.out.println("║╔╗╚╝╠══╦══╦══╦══╗"); + System.out.println("║║╚╗║║╔╗║╔═╣╔╗║══╣"); + System.out.println("║║ ║║║╔╗║╚═╣╚╝╠══║"); + System.out.println("╚╝ ╚═╩╝╚╩══╩══╩══╝"); + System.out.println(NacosConstant.DISCOVERY_PLUGIN + " Discovery"); + System.out.println(""); + }*/ + + LogoBanner logoBanner = new LogoBanner(NacosAutoConfiguration.class, "/com/nepxion/nacos/resource/logo.txt", "Welcome to Nepxion", 5, 5, new Color[] { Color.red, Color.green, Color.cyan, Color.blue, Color.yellow }, true); + + NepxionBanner.show(logoBanner, new Description("Discovery:", DiscoveryType.NACOS.toString(), 0, 1), new Description(BannerConstant.GITHUB + ":", BannerConstant.NEPXION_GITHUB + "/Discovery", 0, 1)); + } + + @Bean + public PluginAdapter pluginAdapter() { + return new NacosAdapter(); + } +} \ No newline at end of file diff --git a/discovery-plugin-register-center/discovery-plugin-register-center-starter-nacos/src/main/java/com/nepxion/discovery/plugin/registercenter/nacos/configuration/NacosLoadBalanceConfiguration.java b/discovery-plugin-register-center/discovery-plugin-register-center-starter-nacos/src/main/java/com/nepxion/discovery/plugin/registercenter/nacos/configuration/NacosLoadBalanceConfiguration.java new file mode 100644 index 0000000000..6e2144d33a --- /dev/null +++ b/discovery-plugin-register-center/discovery-plugin-register-center-starter-nacos/src/main/java/com/nepxion/discovery/plugin/registercenter/nacos/configuration/NacosLoadBalanceConfiguration.java @@ -0,0 +1,38 @@ +package com.nepxion.discovery.plugin.registercenter.nacos.configuration; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.AutoConfigureAfter; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import com.alibaba.cloud.nacos.NacosDiscoveryProperties; +import com.alibaba.cloud.nacos.ribbon.NacosRibbonClientConfiguration; +import com.nepxion.discovery.plugin.framework.listener.loadbalance.LoadBalanceListenerExecutor; +import com.nepxion.discovery.plugin.registercenter.nacos.decorator.NacosServerListDecorator; +import com.netflix.client.config.IClientConfig; +import com.netflix.loadbalancer.ServerList; + +@Configuration +@AutoConfigureAfter(NacosRibbonClientConfiguration.class) +public class NacosLoadBalanceConfiguration { + @Autowired + private LoadBalanceListenerExecutor loadBalanceListenerExecutor; + + @Bean + public ServerList ribbonServerList(IClientConfig config, NacosDiscoveryProperties nacosDiscoveryProperties) { + NacosServerListDecorator serverList = new NacosServerListDecorator(nacosDiscoveryProperties); + serverList.initWithNiwsConfig(config); + serverList.setLoadBalanceListenerExecutor(loadBalanceListenerExecutor); + + return serverList; + } +} \ No newline at end of file diff --git a/discovery-plugin-register-center/discovery-plugin-register-center-starter-nacos/src/main/java/com/nepxion/discovery/plugin/registercenter/nacos/constant/NacosConstant.java b/discovery-plugin-register-center/discovery-plugin-register-center-starter-nacos/src/main/java/com/nepxion/discovery/plugin/registercenter/nacos/constant/NacosConstant.java new file mode 100644 index 0000000000..3139dbebd9 --- /dev/null +++ b/discovery-plugin-register-center/discovery-plugin-register-center-starter-nacos/src/main/java/com/nepxion/discovery/plugin/registercenter/nacos/constant/NacosConstant.java @@ -0,0 +1,14 @@ +package com.nepxion.discovery.plugin.registercenter.nacos.constant; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +public class NacosConstant { + public static final String SPRING_APPLICATION_NACOS_SERVICE_ID_FILTER_ENABLED = "spring.application.nacos.service.id.filter.enabled"; +} \ No newline at end of file diff --git a/discovery-plugin-register-center/discovery-plugin-register-center-starter-nacos/src/main/java/com/nepxion/discovery/plugin/registercenter/nacos/context/NacosApplicationContextInitializer.java b/discovery-plugin-register-center/discovery-plugin-register-center-starter-nacos/src/main/java/com/nepxion/discovery/plugin/registercenter/nacos/context/NacosApplicationContextInitializer.java new file mode 100644 index 0000000000..89768ef0bf --- /dev/null +++ b/discovery-plugin-register-center/discovery-plugin-register-center-starter-nacos/src/main/java/com/nepxion/discovery/plugin/registercenter/nacos/context/NacosApplicationContextInitializer.java @@ -0,0 +1,120 @@ +package com.nepxion.discovery.plugin.registercenter.nacos.context; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.Map; + +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.BeansException; +import org.springframework.boot.SpringBootVersion; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.core.env.ConfigurableEnvironment; + +import com.alibaba.cloud.nacos.NacosDiscoveryProperties; +import com.alibaba.cloud.nacos.NacosServiceManager; +import com.alibaba.cloud.nacos.registry.NacosServiceRegistry; +import com.nepxion.discovery.common.constant.DiscoveryConstant; +import com.nepxion.discovery.common.constant.DiscoveryMetaDataConstant; +import com.nepxion.discovery.common.context.DiscoveryMetaDataPreInstallation; +import com.nepxion.discovery.common.entity.DiscoveryType; +import com.nepxion.discovery.plugin.framework.adapter.ApplicationInfoAdapter; +import com.nepxion.discovery.plugin.framework.context.PluginApplicationContextInitializer; +import com.nepxion.discovery.plugin.framework.context.PluginContextAware; +import com.nepxion.discovery.plugin.framework.util.MetadataUtil; +import com.nepxion.discovery.plugin.registercenter.nacos.decorator.NacosServiceRegistryDecorator; + +public class NacosApplicationContextInitializer extends PluginApplicationContextInitializer { + @Override + protected Object afterInitialization(ConfigurableApplicationContext applicationContext, Object bean, String beanName) throws BeansException { + if (bean instanceof NacosServiceRegistry) { + NacosServiceRegistry nacosServiceRegistry = (NacosServiceRegistry) bean; + + NacosServiceManager nacosServiceManager = applicationContext.getBean(NacosServiceManager.class); + NacosDiscoveryProperties nacosDiscoveryProperties = applicationContext.getBean(NacosDiscoveryProperties.class); + + return new NacosServiceRegistryDecorator(nacosServiceManager, nacosDiscoveryProperties, nacosServiceRegistry, applicationContext); + } else if (bean instanceof NacosDiscoveryProperties) { + ConfigurableEnvironment environment = applicationContext.getEnvironment(); + + NacosDiscoveryProperties nacosDiscoveryProperties = (NacosDiscoveryProperties) bean; + + Map metadata = nacosDiscoveryProperties.getMetadata(); + + String groupKey = PluginContextAware.getGroupKey(environment); + /*if (!metadata.containsKey(groupKey)) { + metadata.put(groupKey, DiscoveryConstant.DEFAULT); + } + if (!metadata.containsKey(DiscoveryConstant.VERSION)) { + metadata.put(DiscoveryConstant.VERSION, DiscoveryConstant.DEFAULT); + } + if (!metadata.containsKey(DiscoveryConstant.REGION)) { + metadata.put(DiscoveryConstant.REGION, DiscoveryConstant.DEFAULT); + } + if (!metadata.containsKey(DiscoveryConstant.ENVIRONMENT)) { + metadata.put(DiscoveryConstant.ENVIRONMENT, DiscoveryConstant.DEFAULT); + } + if (!metadata.containsKey(DiscoveryConstant.ZONE)) { + metadata.put(DiscoveryConstant.ZONE, DiscoveryConstant.DEFAULT); + } + if (!metadata.containsKey(DiscoveryConstant.ACTIVE)) { + metadata.put(DiscoveryConstant.ACTIVE, "false"); + }*/ + String prefixGroup = getPrefixGroup(applicationContext); + if (StringUtils.isNotEmpty(prefixGroup)) { + metadata.put(groupKey, prefixGroup); + } + String gitVersion = getGitVersion(applicationContext); + if (StringUtils.isNotEmpty(gitVersion)) { + metadata.put(DiscoveryConstant.VERSION, gitVersion); + } + + metadata.put(DiscoveryMetaDataConstant.SPRING_BOOT_VERSION, SpringBootVersion.getVersion()); + metadata.put(DiscoveryMetaDataConstant.SPRING_APPLICATION_NAME, PluginContextAware.getApplicationName(environment)); + metadata.put(DiscoveryMetaDataConstant.SPRING_APPLICATION_TYPE, PluginContextAware.getApplicationType(environment)); + String applicationGatewayType = PluginContextAware.getApplicationGatewayType(environment); + if (StringUtils.isNotEmpty(applicationGatewayType)) { + metadata.put(DiscoveryMetaDataConstant.SPRING_APPLICATION_GATEWAY_TYPE, applicationGatewayType); + } + metadata.put(DiscoveryMetaDataConstant.SPRING_APPLICATION_PROTOCOL, PluginContextAware.getApplicationProtocol(environment)); + metadata.put(DiscoveryMetaDataConstant.SPRING_APPLICATION_UUID, PluginContextAware.getApplicationUUId(environment)); + metadata.put(DiscoveryMetaDataConstant.SPRING_APPLICATION_DISCOVERY_PLUGIN, DiscoveryType.NACOS.toString()); + metadata.put(DiscoveryMetaDataConstant.SPRING_APPLICATION_DISCOVERY_VERSION, DiscoveryConstant.DISCOVERY_VERSION); + String agentVersion = System.getProperty(DiscoveryConstant.SPRING_APPLICATION_DISCOVERY_AGENT_VERSION); + if (StringUtils.isNotEmpty(agentVersion)) { + metadata.put(DiscoveryMetaDataConstant.SPRING_APPLICATION_DISCOVERY_AGENT_VERSION, agentVersion); + } + metadata.put(DiscoveryMetaDataConstant.SPRING_APPLICATION_GROUP_KEY, groupKey); + metadata.put(DiscoveryMetaDataConstant.SPRING_APPLICATION_CONTEXT_PATH, PluginContextAware.getContextPath(environment)); + + try { + ApplicationInfoAdapter applicationInfoAdapter = applicationContext.getBean(ApplicationInfoAdapter.class); + if (applicationInfoAdapter != null) { + metadata.put(DiscoveryMetaDataConstant.SPRING_APPLICATION_APP_ID, applicationInfoAdapter.getAppId()); + } + } catch (Exception e) { + + } + + for (Map.Entry entry : DiscoveryMetaDataPreInstallation.getMetadata().entrySet()) { + String key = entry.getKey(); + String value = entry.getValue(); + if (StringUtils.isNotEmpty(value)) { + metadata.put(key, value); + } + } + + MetadataUtil.filter(metadata, environment); + + return bean; + } else { + return bean; + } + } +} \ No newline at end of file diff --git a/discovery-plugin-register-center/discovery-plugin-register-center-starter-nacos/src/main/java/com/nepxion/discovery/plugin/registercenter/nacos/decorator/NacosServerListDecorator.java b/discovery-plugin-register-center/discovery-plugin-register-center-starter-nacos/src/main/java/com/nepxion/discovery/plugin/registercenter/nacos/decorator/NacosServerListDecorator.java new file mode 100644 index 0000000000..d01361be99 --- /dev/null +++ b/discovery-plugin-register-center/discovery-plugin-register-center-starter-nacos/src/main/java/com/nepxion/discovery/plugin/registercenter/nacos/decorator/NacosServerListDecorator.java @@ -0,0 +1,53 @@ +package com.nepxion.discovery.plugin.registercenter.nacos.decorator; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.List; + +import com.alibaba.cloud.nacos.NacosDiscoveryProperties; +import com.alibaba.cloud.nacos.ribbon.NacosServer; +import com.alibaba.cloud.nacos.ribbon.NacosServerList; +import com.nepxion.discovery.plugin.framework.listener.loadbalance.LoadBalanceListenerExecutor; + +public class NacosServerListDecorator extends NacosServerList { + private LoadBalanceListenerExecutor loadBalanceListenerExecutor; + + public NacosServerListDecorator(NacosDiscoveryProperties nacosDiscoveryProperties) { + super(nacosDiscoveryProperties); + } + + @Override + public List getInitialListOfServers() { + List servers = super.getInitialListOfServers(); + + filter(servers); + + return servers; + } + + @Override + public List getUpdatedListOfServers() { + List servers = super.getUpdatedListOfServers(); + + filter(servers); + + return servers; + } + + private void filter(List servers) { + String serviceId = getServiceId(); + + loadBalanceListenerExecutor.onGetServers(serviceId, servers); + } + + public void setLoadBalanceListenerExecutor(LoadBalanceListenerExecutor loadBalanceListenerExecutor) { + this.loadBalanceListenerExecutor = loadBalanceListenerExecutor; + } +} \ No newline at end of file diff --git a/discovery-plugin-register-center/discovery-plugin-register-center-starter-nacos/src/main/java/com/nepxion/discovery/plugin/registercenter/nacos/decorator/NacosServiceRegistryDecorator.java b/discovery-plugin-register-center/discovery-plugin-register-center-starter-nacos/src/main/java/com/nepxion/discovery/plugin/registercenter/nacos/decorator/NacosServiceRegistryDecorator.java new file mode 100644 index 0000000000..8e8fb73c60 --- /dev/null +++ b/discovery-plugin-register-center/discovery-plugin-register-center-starter-nacos/src/main/java/com/nepxion/discovery/plugin/registercenter/nacos/decorator/NacosServiceRegistryDecorator.java @@ -0,0 +1,86 @@ +package com.nepxion.discovery.plugin.registercenter.nacos.decorator; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.springframework.beans.BeansException; +import org.springframework.cloud.client.serviceregistry.Registration; +import org.springframework.context.ConfigurableApplicationContext; + +import com.alibaba.cloud.nacos.NacosDiscoveryProperties; +import com.alibaba.cloud.nacos.NacosServiceManager; +import com.alibaba.cloud.nacos.registry.NacosServiceRegistry; +import com.nepxion.discovery.plugin.framework.listener.register.RegisterListenerExecutor; + +public class NacosServiceRegistryDecorator extends NacosServiceRegistry { + // private static final Logger LOG = LoggerFactory.getLogger(NacosServiceRegistryDecorator.class); + + private NacosServiceRegistry serviceRegistry; + private ConfigurableApplicationContext applicationContext; + + public NacosServiceRegistryDecorator(NacosServiceManager nacosServiceManager, NacosDiscoveryProperties nacosDiscoveryProperties, NacosServiceRegistry serviceRegistry, ConfigurableApplicationContext applicationContext) { + super(nacosServiceManager, nacosDiscoveryProperties); + + this.serviceRegistry = serviceRegistry; + this.applicationContext = applicationContext; + } + + @Override + public void register(Registration registration) { + try { + RegisterListenerExecutor registerListenerExecutor = applicationContext.getBean(RegisterListenerExecutor.class); + registerListenerExecutor.onRegister(registration); + } catch (BeansException e) { + // LOG.warn("Get bean for RegisterListenerExecutor failed, ignore to executor listener"); + } + + serviceRegistry.register(registration); + } + + @Override + public void deregister(Registration registration) { + try { + RegisterListenerExecutor registerListenerExecutor = applicationContext.getBean(RegisterListenerExecutor.class); + registerListenerExecutor.onDeregister(registration); + } catch (BeansException e) { + // LOG.warn("Get bean for RegisterListenerExecutor failed, ignore to executor listener"); + } + + serviceRegistry.deregister(registration); + } + + @Override + public void setStatus(Registration registration, String status) { + try { + RegisterListenerExecutor registerListenerExecutor = applicationContext.getBean(RegisterListenerExecutor.class); + registerListenerExecutor.onSetStatus(registration, status); + } catch (BeansException e) { + // LOG.warn("Get bean for RegisterListenerExecutor failed, ignore to executor listener"); + } + + serviceRegistry.setStatus(registration, status); + } + + @Override + public Object getStatus(Registration registration) { + return serviceRegistry.getStatus(registration); + } + + @Override + public void close() { + try { + RegisterListenerExecutor registerListenerExecutor = applicationContext.getBean(RegisterListenerExecutor.class); + registerListenerExecutor.onClose(); + } catch (BeansException e) { + // LOG.warn("Get bean for RegisterListenerExecutor failed, ignore to executor listener"); + } + + serviceRegistry.close(); + } +} \ No newline at end of file diff --git a/discovery-plugin-register-center/discovery-plugin-register-center-starter-nacos/src/main/resources/META-INF/additional-spring-configuration-metadata.json b/discovery-plugin-register-center/discovery-plugin-register-center-starter-nacos/src/main/resources/META-INF/additional-spring-configuration-metadata.json new file mode 100644 index 0000000000..cb1f23024e --- /dev/null +++ b/discovery-plugin-register-center/discovery-plugin-register-center-starter-nacos/src/main/resources/META-INF/additional-spring-configuration-metadata.json @@ -0,0 +1,10 @@ +{ + "properties": [ + { + "name": "spring.application.nacos.service.id.filter.enabled", + "type": "java.lang.Boolean", + "defaultValue": true, + "description": "Whether nacos service id filter is enabled." + } + ] +} \ No newline at end of file diff --git a/discovery-plugin-register-center/discovery-plugin-register-center-starter-nacos/src/main/resources/META-INF/spring.factories b/discovery-plugin-register-center/discovery-plugin-register-center-starter-nacos/src/main/resources/META-INF/spring.factories new file mode 100644 index 0000000000..565caed6ae --- /dev/null +++ b/discovery-plugin-register-center/discovery-plugin-register-center-starter-nacos/src/main/resources/META-INF/spring.factories @@ -0,0 +1,5 @@ +org.springframework.context.ApplicationContextInitializer=\ +com.nepxion.discovery.plugin.registercenter.nacos.context.NacosApplicationContextInitializer + +org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ +com.nepxion.discovery.plugin.registercenter.nacos.configuration.NacosAutoConfiguration \ No newline at end of file diff --git a/discovery-plugin-register-center/discovery-plugin-register-center-starter-zookeeper/pom.xml b/discovery-plugin-register-center/discovery-plugin-register-center-starter-zookeeper/pom.xml new file mode 100644 index 0000000000..73d16da7d7 --- /dev/null +++ b/discovery-plugin-register-center/discovery-plugin-register-center-starter-zookeeper/pom.xml @@ -0,0 +1,28 @@ + + + discovery-plugin-register-center-starter-zookeeper + Nepxion Discovery Plugin Register Center Starter Zookeeper + jar + 4.0.0 + Nepxion Discovery is a solution for Spring Cloud with blue green, gray, weight, limitation, circuit breaker, degrade, isolation, monitor, tracing, dye, failover, async agent + http://www.nepxion.com + + + com.nepxion + discovery-plugin-register-center + 6.23.0 + + + + + ${project.groupId} + discovery-plugin-register-center-starter + + + + org.springframework.cloud + spring-cloud-starter-zookeeper-discovery + + + \ No newline at end of file diff --git a/discovery-plugin-register-center/discovery-plugin-register-center-starter-zookeeper/src/main/java/com/nepxion/discovery/plugin/registercenter/zookeeper/adapter/ZookeeperAdapter.java b/discovery-plugin-register-center/discovery-plugin-register-center-starter-zookeeper/src/main/java/com/nepxion/discovery/plugin/registercenter/zookeeper/adapter/ZookeeperAdapter.java new file mode 100644 index 0000000000..646496b5eb --- /dev/null +++ b/discovery-plugin-register-center/discovery-plugin-register-center-starter-zookeeper/src/main/java/com/nepxion/discovery/plugin/registercenter/zookeeper/adapter/ZookeeperAdapter.java @@ -0,0 +1,50 @@ +package com.nepxion.discovery.plugin.registercenter.zookeeper.adapter; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.Map; + +import javax.annotation.PostConstruct; + +import org.springframework.cloud.zookeeper.discovery.ZookeeperServer; +import org.springframework.cloud.zookeeper.serviceregistry.ZookeeperRegistration; + +import com.nepxion.discovery.common.exception.DiscoveryException; +import com.nepxion.discovery.plugin.framework.adapter.AbstractPluginAdapter; +import com.netflix.loadbalancer.Server; + +public class ZookeeperAdapter extends AbstractPluginAdapter { + // Zookeeper比较特殊,getServiceInstance是Lazy Initialize模式 + @PostConstruct + public void initialize() { + if (registration instanceof ZookeeperRegistration) { + ZookeeperRegistration zookeeperRegistration = (ZookeeperRegistration) registration; + + zookeeperRegistration.getServiceInstance(); + + return; + } + + throw new DiscoveryException("Registration isn't the type of ZookeeperRegistration"); + } + + @Override + public Map getServerMetadata(Server server) { + if (server instanceof ZookeeperServer) { + ZookeeperServer zookeeperServer = (ZookeeperServer) server; + + return zookeeperServer.getInstance().getPayload().getMetadata(); + } + + return emptyMetadata; + + // throw new DiscoveryException("Server instance isn't the type of ZookeeperServer"); + } +} \ No newline at end of file diff --git a/discovery-plugin-register-center/discovery-plugin-register-center-starter-zookeeper/src/main/java/com/nepxion/discovery/plugin/registercenter/zookeeper/configuration/ZookeeperAutoConfiguration.java b/discovery-plugin-register-center/discovery-plugin-register-center-starter-zookeeper/src/main/java/com/nepxion/discovery/plugin/registercenter/zookeeper/configuration/ZookeeperAutoConfiguration.java new file mode 100644 index 0000000000..c426c1d875 --- /dev/null +++ b/discovery-plugin-register-center/discovery-plugin-register-center-starter-zookeeper/src/main/java/com/nepxion/discovery/plugin/registercenter/zookeeper/configuration/ZookeeperAutoConfiguration.java @@ -0,0 +1,54 @@ +package com.nepxion.discovery.plugin.registercenter.zookeeper.configuration; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.springframework.cloud.netflix.ribbon.RibbonClients; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import com.nepxion.banner.BannerConstant; +import com.nepxion.banner.Description; +import com.nepxion.banner.LogoBanner; +import com.nepxion.banner.NepxionBanner; +import com.nepxion.discovery.common.entity.DiscoveryType; +import com.nepxion.discovery.plugin.framework.adapter.PluginAdapter; +import com.nepxion.discovery.plugin.framework.configuration.PluginLoadBalanceConfiguration; +import com.nepxion.discovery.plugin.registercenter.zookeeper.adapter.ZookeeperAdapter; +import com.taobao.text.Color; + +@Configuration +@RibbonClients(defaultConfiguration = { PluginLoadBalanceConfiguration.class, ZookeeperLoadBalanceConfiguration.class }) +public class ZookeeperAutoConfiguration { + static { + /*String bannerShown = System.getProperty(BannerConstant.BANNER_SHOWN, "true"); + if (Boolean.valueOf(bannerShown)) { + System.out.println(""); + System.out.println("╔════╗ ╔╗"); + System.out.println("╚══╗═║ ║║"); + System.out.println(" ╔╝╔╬══╦══╣║╔╦══╦══╦══╦══╦═╗"); + System.out.println(" ╔╝╔╝║╔╗║╔╗║╚╝╣║═╣║═╣╔╗║║═╣╔╝"); + System.out.println("╔╝═╚═╣╚╝║╚╝║╔╗╣║═╣║═╣╚╝║║═╣║"); + System.out.println("╚════╩══╩══╩╝╚╩══╩══╣╔═╩══╩╝"); + System.out.println(" ║║"); + System.out.println(" ╚╝"); + System.out.println(ZookeeperConstant.DISCOVERY_PLUGIN + " Discovery"); + System.out.println(""); + }*/ + + LogoBanner logoBanner = new LogoBanner(ZookeeperAutoConfiguration.class, "/com/nepxion/zookeeper/resource/logo.txt", "Welcome to Nepxion", 9, 5, new Color[] { Color.red, Color.green, Color.cyan, Color.blue, Color.yellow, Color.magenta, Color.red, Color.green, Color.cyan }, true); + + NepxionBanner.show(logoBanner, new Description("Discovery:", DiscoveryType.ZOOKEEPER.toString(), 0, 1), new Description(BannerConstant.GITHUB + ":", BannerConstant.NEPXION_GITHUB + "/Discovery", 0, 1)); + } + + @Bean + public PluginAdapter pluginAdapter() { + return new ZookeeperAdapter(); + } +} \ No newline at end of file diff --git a/discovery-plugin-framework-zookeeper/src/main/java/com/nepxion/discovery/plugin/framework/configuration/ZookeeperLoadBalanceConfiguration.java b/discovery-plugin-register-center/discovery-plugin-register-center-starter-zookeeper/src/main/java/com/nepxion/discovery/plugin/registercenter/zookeeper/configuration/ZookeeperLoadBalanceConfiguration.java similarity index 86% rename from discovery-plugin-framework-zookeeper/src/main/java/com/nepxion/discovery/plugin/framework/configuration/ZookeeperLoadBalanceConfiguration.java rename to discovery-plugin-register-center/discovery-plugin-register-center-starter-zookeeper/src/main/java/com/nepxion/discovery/plugin/registercenter/zookeeper/configuration/ZookeeperLoadBalanceConfiguration.java index 925fbeaa91..02832b1fdb 100644 --- a/discovery-plugin-framework-zookeeper/src/main/java/com/nepxion/discovery/plugin/framework/configuration/ZookeeperLoadBalanceConfiguration.java +++ b/discovery-plugin-register-center/discovery-plugin-register-center-starter-zookeeper/src/main/java/com/nepxion/discovery/plugin/registercenter/zookeeper/configuration/ZookeeperLoadBalanceConfiguration.java @@ -1,4 +1,4 @@ -package com.nepxion.discovery.plugin.framework.configuration; +package com.nepxion.discovery.plugin.registercenter.zookeeper.configuration; /** *

Title: Nepxion Discovery

@@ -19,19 +19,15 @@ import org.springframework.cloud.zookeeper.discovery.dependency.ZookeeperDependencies; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.core.env.ConfigurableEnvironment; -import com.nepxion.discovery.plugin.framework.decorator.ZookeeperServerListDecorator; import com.nepxion.discovery.plugin.framework.listener.loadbalance.LoadBalanceListenerExecutor; +import com.nepxion.discovery.plugin.registercenter.zookeeper.decorator.ZookeeperServerListDecorator; import com.netflix.client.config.IClientConfig; import com.netflix.loadbalancer.ServerList; @Configuration @AutoConfigureAfter(ZookeeperRibbonClientConfiguration.class) public class ZookeeperLoadBalanceConfiguration { - @Autowired - private ConfigurableEnvironment environment; - @Autowired private LoadBalanceListenerExecutor loadBalanceListenerExecutor; @@ -40,7 +36,6 @@ public class ZookeeperLoadBalanceConfiguration { public ServerList ribbonServerListFromDependencies(IClientConfig config, ZookeeperDependencies zookeeperDependencies, ServiceDiscovery serviceDiscovery) { ZookeeperServerListDecorator serverList = new ZookeeperServerListDecorator(serviceDiscovery); serverList.initFromDependencies(config, zookeeperDependencies); - serverList.setEnvironment(environment); serverList.setLoadBalanceListenerExecutor(loadBalanceListenerExecutor); serverList.setServiceId(config.getClientName()); @@ -52,7 +47,6 @@ public ServerList ribbonServerListFromDependencies(IClientConfig config, Zook public ServerList ribbonServerList(IClientConfig config, ServiceDiscovery serviceDiscovery) { ZookeeperServerListDecorator serverList = new ZookeeperServerListDecorator(serviceDiscovery); serverList.initWithNiwsConfig(config); - serverList.setEnvironment(environment); serverList.setLoadBalanceListenerExecutor(loadBalanceListenerExecutor); serverList.setServiceId(config.getClientName()); diff --git a/discovery-plugin-register-center/discovery-plugin-register-center-starter-zookeeper/src/main/java/com/nepxion/discovery/plugin/registercenter/zookeeper/constant/ZookeeperConstant.java b/discovery-plugin-register-center/discovery-plugin-register-center-starter-zookeeper/src/main/java/com/nepxion/discovery/plugin/registercenter/zookeeper/constant/ZookeeperConstant.java new file mode 100644 index 0000000000..8ee95f9518 --- /dev/null +++ b/discovery-plugin-register-center/discovery-plugin-register-center-starter-zookeeper/src/main/java/com/nepxion/discovery/plugin/registercenter/zookeeper/constant/ZookeeperConstant.java @@ -0,0 +1,14 @@ +package com.nepxion.discovery.plugin.registercenter.zookeeper.constant; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +public class ZookeeperConstant { + public static final String ZOOKEEPER_METADATA = "spring.cloud.zookeeper.discovery.metadata"; +} \ No newline at end of file diff --git a/discovery-plugin-register-center/discovery-plugin-register-center-starter-zookeeper/src/main/java/com/nepxion/discovery/plugin/registercenter/zookeeper/context/ZookeeperApplicationContextInitializer.java b/discovery-plugin-register-center/discovery-plugin-register-center-starter-zookeeper/src/main/java/com/nepxion/discovery/plugin/registercenter/zookeeper/context/ZookeeperApplicationContextInitializer.java new file mode 100644 index 0000000000..8a626fb47c --- /dev/null +++ b/discovery-plugin-register-center/discovery-plugin-register-center-starter-zookeeper/src/main/java/com/nepxion/discovery/plugin/registercenter/zookeeper/context/ZookeeperApplicationContextInitializer.java @@ -0,0 +1,117 @@ +package com.nepxion.discovery.plugin.registercenter.zookeeper.context; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.Map; + +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.BeansException; +import org.springframework.boot.SpringBootVersion; +import org.springframework.cloud.zookeeper.discovery.ZookeeperDiscoveryProperties; +import org.springframework.cloud.zookeeper.serviceregistry.ZookeeperServiceRegistry; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.core.env.ConfigurableEnvironment; + +import com.nepxion.discovery.common.constant.DiscoveryConstant; +import com.nepxion.discovery.common.constant.DiscoveryMetaDataConstant; +import com.nepxion.discovery.common.context.DiscoveryMetaDataPreInstallation; +import com.nepxion.discovery.common.entity.DiscoveryType; +import com.nepxion.discovery.plugin.framework.adapter.ApplicationInfoAdapter; +import com.nepxion.discovery.plugin.framework.context.PluginApplicationContextInitializer; +import com.nepxion.discovery.plugin.framework.context.PluginContextAware; +import com.nepxion.discovery.plugin.framework.util.MetadataUtil; +import com.nepxion.discovery.plugin.registercenter.zookeeper.decorator.ZookeeperServiceRegistryDecorator; + +public class ZookeeperApplicationContextInitializer extends PluginApplicationContextInitializer { + @Override + protected Object afterInitialization(ConfigurableApplicationContext applicationContext, Object bean, String beanName) throws BeansException { + if (bean instanceof ZookeeperServiceRegistry) { + ZookeeperServiceRegistry zookeeperServiceRegistry = (ZookeeperServiceRegistry) bean; + + return new ZookeeperServiceRegistryDecorator(zookeeperServiceRegistry, applicationContext); + } else if (bean instanceof ZookeeperDiscoveryProperties) { + ConfigurableEnvironment environment = applicationContext.getEnvironment(); + + ZookeeperDiscoveryProperties zookeeperDiscoveryProperties = (ZookeeperDiscoveryProperties) bean; + zookeeperDiscoveryProperties.setPreferIpAddress(true); + + Map metadata = zookeeperDiscoveryProperties.getMetadata(); + + String groupKey = PluginContextAware.getGroupKey(environment); + /*if (!metadata.containsKey(groupKey)) { + metadata.put(groupKey, DiscoveryConstant.DEFAULT); + } + if (!metadata.containsKey(DiscoveryConstant.VERSION)) { + metadata.put(DiscoveryConstant.VERSION, DiscoveryConstant.DEFAULT); + } + if (!metadata.containsKey(DiscoveryConstant.REGION)) { + metadata.put(DiscoveryConstant.REGION, DiscoveryConstant.DEFAULT); + } + if (!metadata.containsKey(DiscoveryConstant.ENVIRONMENT)) { + metadata.put(DiscoveryConstant.ENVIRONMENT, DiscoveryConstant.DEFAULT); + } + if (!metadata.containsKey(DiscoveryConstant.ZONE)) { + metadata.put(DiscoveryConstant.ZONE, DiscoveryConstant.DEFAULT); + } + if (!metadata.containsKey(DiscoveryConstant.ACTIVE)) { + metadata.put(DiscoveryConstant.ACTIVE, "false"); + }*/ + String prefixGroup = getPrefixGroup(applicationContext); + if (StringUtils.isNotEmpty(prefixGroup)) { + metadata.put(groupKey, prefixGroup); + } + String gitVersion = getGitVersion(applicationContext); + if (StringUtils.isNotEmpty(gitVersion)) { + metadata.put(DiscoveryConstant.VERSION, gitVersion); + } + + metadata.put(DiscoveryMetaDataConstant.SPRING_BOOT_VERSION, SpringBootVersion.getVersion()); + metadata.put(DiscoveryMetaDataConstant.SPRING_APPLICATION_NAME, PluginContextAware.getApplicationName(environment)); + metadata.put(DiscoveryMetaDataConstant.SPRING_APPLICATION_TYPE, PluginContextAware.getApplicationType(environment)); + String applicationGatewayType = PluginContextAware.getApplicationGatewayType(environment); + if (StringUtils.isNotEmpty(applicationGatewayType)) { + metadata.put(DiscoveryMetaDataConstant.SPRING_APPLICATION_GATEWAY_TYPE, applicationGatewayType); + } + metadata.put(DiscoveryMetaDataConstant.SPRING_APPLICATION_PROTOCOL, PluginContextAware.getApplicationProtocol(environment)); + metadata.put(DiscoveryMetaDataConstant.SPRING_APPLICATION_UUID, PluginContextAware.getApplicationUUId(environment)); + metadata.put(DiscoveryMetaDataConstant.SPRING_APPLICATION_DISCOVERY_PLUGIN, DiscoveryType.ZOOKEEPER.toString()); + metadata.put(DiscoveryMetaDataConstant.SPRING_APPLICATION_DISCOVERY_VERSION, DiscoveryConstant.DISCOVERY_VERSION); + String agentVersion = System.getProperty(DiscoveryConstant.SPRING_APPLICATION_DISCOVERY_AGENT_VERSION); + if (StringUtils.isNotEmpty(agentVersion)) { + metadata.put(DiscoveryMetaDataConstant.SPRING_APPLICATION_DISCOVERY_AGENT_VERSION, agentVersion); + } + metadata.put(DiscoveryMetaDataConstant.SPRING_APPLICATION_GROUP_KEY, groupKey); + metadata.put(DiscoveryMetaDataConstant.SPRING_APPLICATION_CONTEXT_PATH, PluginContextAware.getContextPath(environment)); + + try { + ApplicationInfoAdapter applicationInfoAdapter = applicationContext.getBean(ApplicationInfoAdapter.class); + if (applicationInfoAdapter != null) { + metadata.put(DiscoveryMetaDataConstant.SPRING_APPLICATION_APP_ID, applicationInfoAdapter.getAppId()); + } + } catch (Exception e) { + + } + + for (Map.Entry entry : DiscoveryMetaDataPreInstallation.getMetadata().entrySet()) { + String key = entry.getKey(); + String value = entry.getValue(); + if (StringUtils.isNotEmpty(value)) { + metadata.put(key, value); + } + } + + MetadataUtil.filter(metadata, environment); + + return bean; + } else { + return bean; + } + } +} \ No newline at end of file diff --git a/discovery-plugin-register-center/discovery-plugin-register-center-starter-zookeeper/src/main/java/com/nepxion/discovery/plugin/registercenter/zookeeper/decorator/ZookeeperServerListDecorator.java b/discovery-plugin-register-center/discovery-plugin-register-center-starter-zookeeper/src/main/java/com/nepxion/discovery/plugin/registercenter/zookeeper/decorator/ZookeeperServerListDecorator.java new file mode 100644 index 0000000000..051bdb0ed3 --- /dev/null +++ b/discovery-plugin-register-center/discovery-plugin-register-center-starter-zookeeper/src/main/java/com/nepxion/discovery/plugin/registercenter/zookeeper/decorator/ZookeeperServerListDecorator.java @@ -0,0 +1,59 @@ +package com.nepxion.discovery.plugin.registercenter.zookeeper.decorator; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.List; + +import org.apache.curator.x.discovery.ServiceDiscovery; +import org.springframework.cloud.zookeeper.discovery.ZookeeperInstance; +import org.springframework.cloud.zookeeper.discovery.ZookeeperServer; +import org.springframework.cloud.zookeeper.discovery.ZookeeperServerList; + +import com.nepxion.discovery.plugin.framework.listener.loadbalance.LoadBalanceListenerExecutor; + +public class ZookeeperServerListDecorator extends ZookeeperServerList { + private LoadBalanceListenerExecutor loadBalanceListenerExecutor; + + private String serviceId; + + public ZookeeperServerListDecorator(ServiceDiscovery serviceDiscovery) { + super(serviceDiscovery); + } + + @Override + public List getInitialListOfServers() { + List servers = super.getInitialListOfServers(); + + filter(servers); + + return servers; + } + + @Override + public List getUpdatedListOfServers() { + List servers = super.getUpdatedListOfServers(); + + filter(servers); + + return servers; + } + + private void filter(List servers) { + loadBalanceListenerExecutor.onGetServers(serviceId, servers); + } + + public void setLoadBalanceListenerExecutor(LoadBalanceListenerExecutor loadBalanceListenerExecutor) { + this.loadBalanceListenerExecutor = loadBalanceListenerExecutor; + } + + public void setServiceId(String serviceId) { + this.serviceId = serviceId; + } +} \ No newline at end of file diff --git a/discovery-plugin-register-center/discovery-plugin-register-center-starter-zookeeper/src/main/java/com/nepxion/discovery/plugin/registercenter/zookeeper/decorator/ZookeeperServiceRegistryDecorator.java b/discovery-plugin-register-center/discovery-plugin-register-center-starter-zookeeper/src/main/java/com/nepxion/discovery/plugin/registercenter/zookeeper/decorator/ZookeeperServiceRegistryDecorator.java new file mode 100644 index 0000000000..f2acd6d845 --- /dev/null +++ b/discovery-plugin-register-center/discovery-plugin-register-center-starter-zookeeper/src/main/java/com/nepxion/discovery/plugin/registercenter/zookeeper/decorator/ZookeeperServiceRegistryDecorator.java @@ -0,0 +1,89 @@ +package com.nepxion.discovery.plugin.registercenter.zookeeper.decorator; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.springframework.beans.BeansException; +import org.springframework.cloud.zookeeper.serviceregistry.ZookeeperRegistration; +import org.springframework.cloud.zookeeper.serviceregistry.ZookeeperServiceRegistry; +import org.springframework.context.ConfigurableApplicationContext; + +import com.nepxion.discovery.plugin.framework.listener.register.RegisterListenerExecutor; + +public class ZookeeperServiceRegistryDecorator extends ZookeeperServiceRegistry { + // private static final Logger LOG = LoggerFactory.getLogger(ZookeeperServiceRegistryDecorator.class); + + private ZookeeperServiceRegistry serviceRegistry; + private ConfigurableApplicationContext applicationContext; + + public ZookeeperServiceRegistryDecorator(ZookeeperServiceRegistry serviceRegistry, ConfigurableApplicationContext applicationContext) { + super(null); + + this.serviceRegistry = serviceRegistry; + this.applicationContext = applicationContext; + } + + @Override + public void register(ZookeeperRegistration registration) { + try { + RegisterListenerExecutor registerListenerExecutor = applicationContext.getBean(RegisterListenerExecutor.class); + registerListenerExecutor.onRegister(registration); + } catch (BeansException e) { + // LOG.warn("Get bean for RegisterListenerExecutor failed, ignore to executor listener"); + } + + serviceRegistry.register(registration); + } + + @Override + public void deregister(ZookeeperRegistration registration) { + try { + RegisterListenerExecutor registerListenerExecutor = applicationContext.getBean(RegisterListenerExecutor.class); + registerListenerExecutor.onDeregister(registration); + } catch (BeansException e) { + // LOG.warn("Get bean for RegisterListenerExecutor failed, ignore to executor listener"); + } + + serviceRegistry.deregister(registration); + } + + @Override + public void setStatus(ZookeeperRegistration registration, String status) { + try { + RegisterListenerExecutor registerListenerExecutor = applicationContext.getBean(RegisterListenerExecutor.class); + registerListenerExecutor.onSetStatus(registration, status); + } catch (BeansException e) { + // LOG.warn("Get bean for RegisterListenerExecutor failed, ignore to executor listener"); + } + + serviceRegistry.setStatus(registration, status); + } + + @Override + public Object getStatus(ZookeeperRegistration registration) { + return serviceRegistry.getStatus(registration); + } + + @Override + public void close() { + try { + RegisterListenerExecutor registerListenerExecutor = applicationContext.getBean(RegisterListenerExecutor.class); + registerListenerExecutor.onClose(); + } catch (BeansException e) { + // LOG.warn("Get bean for RegisterListenerExecutor failed, ignore to executor listener"); + } + + serviceRegistry.close(); + } + + @Override + public void afterSingletonsInstantiated() { + serviceRegistry.afterSingletonsInstantiated(); + } +} \ No newline at end of file diff --git a/discovery-plugin-register-center/discovery-plugin-register-center-starter-zookeeper/src/main/resources/META-INF/spring.factories b/discovery-plugin-register-center/discovery-plugin-register-center-starter-zookeeper/src/main/resources/META-INF/spring.factories new file mode 100644 index 0000000000..9e701d2871 --- /dev/null +++ b/discovery-plugin-register-center/discovery-plugin-register-center-starter-zookeeper/src/main/resources/META-INF/spring.factories @@ -0,0 +1,5 @@ +org.springframework.context.ApplicationContextInitializer=\ +com.nepxion.discovery.plugin.registercenter.zookeeper.context.ZookeeperApplicationContextInitializer + +org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ +com.nepxion.discovery.plugin.registercenter.zookeeper.configuration.ZookeeperAutoConfiguration \ No newline at end of file diff --git a/discovery-plugin-register-center/discovery-plugin-register-center-starter/pom.xml b/discovery-plugin-register-center/discovery-plugin-register-center-starter/pom.xml new file mode 100644 index 0000000000..696b46acac --- /dev/null +++ b/discovery-plugin-register-center/discovery-plugin-register-center-starter/pom.xml @@ -0,0 +1,28 @@ + + + discovery-plugin-register-center-starter + Nepxion Discovery Plugin Register Center Starter + jar + 4.0.0 + Nepxion Discovery is a solution for Spring Cloud with blue green, gray, weight, limitation, circuit breaker, degrade, isolation, monitor, tracing, dye, failover, async agent + http://www.nepxion.com + + + com.nepxion + discovery-plugin-register-center + 6.23.0 + + + + + ${project.groupId} + discovery-plugin-framework-starter + + + + ${project.groupId} + discovery-plugin-config-center-starter + + + \ No newline at end of file diff --git a/discovery-plugin-register-center/pom.xml b/discovery-plugin-register-center/pom.xml new file mode 100644 index 0000000000..84ecf4571f --- /dev/null +++ b/discovery-plugin-register-center/pom.xml @@ -0,0 +1,24 @@ + + + discovery-plugin-register-center + Nepxion Discovery Plugin Register Center + pom + 4.0.0 + Nepxion Discovery is a solution for Spring Cloud with blue green, gray, weight, limitation, circuit breaker, degrade, isolation, monitor, tracing, dye, failover, async agent + http://www.nepxion.com + + + com.nepxion + discovery + 6.23.0 + + + + discovery-plugin-register-center-starter + discovery-plugin-register-center-starter-eureka + discovery-plugin-register-center-starter-consul + discovery-plugin-register-center-starter-zookeeper + discovery-plugin-register-center-starter-nacos + + \ No newline at end of file diff --git a/discovery-plugin-starter-consul/pom.xml b/discovery-plugin-starter-consul/pom.xml deleted file mode 100644 index 056c9a49c4..0000000000 --- a/discovery-plugin-starter-consul/pom.xml +++ /dev/null @@ -1,33 +0,0 @@ - - - discovery-plugin-starter-consul - Nepxion Discovery Plugin Starter Consul - jar - 4.0.0 - Nepxion Discovery is an enhancement for Spring Cloud Discovery - http://www.nepxion.com - - - com.nepxion - discovery - 5.2.0-SNAPSHOT - - - - - ${project.groupId} - discovery-plugin-config-center - - - - ${project.groupId} - discovery-plugin-admin-center - - - - ${project.groupId} - discovery-plugin-framework-consul - - - \ No newline at end of file diff --git a/discovery-plugin-starter-consul/src/main/resources/META-INF/spring.factories b/discovery-plugin-starter-consul/src/main/resources/META-INF/spring.factories deleted file mode 100644 index 85306b06cd..0000000000 --- a/discovery-plugin-starter-consul/src/main/resources/META-INF/spring.factories +++ /dev/null @@ -1,8 +0,0 @@ -org.springframework.context.ApplicationContextInitializer=\ -com.nepxion.discovery.plugin.framework.context.ConsulApplicationContextInitializer - -org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ -com.nepxion.discovery.plugin.framework.configuration.PluginAutoConfiguration,\ -com.nepxion.discovery.plugin.framework.configuration.ConsulAutoConfiguration,\ -com.nepxion.discovery.plugin.configcenter.configuration.ConfigAutoConfiguration,\ -com.nepxion.discovery.plugin.admincenter.configuration.AdminAutoConfiguration \ No newline at end of file diff --git a/discovery-plugin-starter-eureka/pom.xml b/discovery-plugin-starter-eureka/pom.xml deleted file mode 100644 index 1c717429b3..0000000000 --- a/discovery-plugin-starter-eureka/pom.xml +++ /dev/null @@ -1,33 +0,0 @@ - - - discovery-plugin-starter-eureka - Nepxion Discovery Plugin Starter Eureka - jar - 4.0.0 - Nepxion Discovery is an enhancement for Spring Cloud Discovery - http://www.nepxion.com - - - com.nepxion - discovery - 5.2.0-SNAPSHOT - - - - - ${project.groupId} - discovery-plugin-config-center - - - - ${project.groupId} - discovery-plugin-admin-center - - - - ${project.groupId} - discovery-plugin-framework-eureka - - - \ No newline at end of file diff --git a/discovery-plugin-starter-eureka/src/main/resources/META-INF/spring.factories b/discovery-plugin-starter-eureka/src/main/resources/META-INF/spring.factories deleted file mode 100644 index ed789b2850..0000000000 --- a/discovery-plugin-starter-eureka/src/main/resources/META-INF/spring.factories +++ /dev/null @@ -1,8 +0,0 @@ -org.springframework.context.ApplicationContextInitializer=\ -com.nepxion.discovery.plugin.framework.context.EurekaApplicationContextInitializer - -org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ -com.nepxion.discovery.plugin.framework.configuration.PluginAutoConfiguration,\ -com.nepxion.discovery.plugin.framework.configuration.EurekaAutoConfiguration,\ -com.nepxion.discovery.plugin.configcenter.configuration.ConfigAutoConfiguration,\ -com.nepxion.discovery.plugin.admincenter.configuration.AdminAutoConfiguration \ No newline at end of file diff --git a/discovery-plugin-starter-nacos/pom.xml b/discovery-plugin-starter-nacos/pom.xml deleted file mode 100644 index d96e1379a0..0000000000 --- a/discovery-plugin-starter-nacos/pom.xml +++ /dev/null @@ -1,33 +0,0 @@ - - - discovery-plugin-starter-nacos - Nepxion Discovery Plugin Starter Nacos - jar - 4.0.0 - Nepxion Discovery is an enhancement for Spring Cloud Discovery - http://www.nepxion.com - - - com.nepxion - discovery - 5.2.0-SNAPSHOT - - - - - ${project.groupId} - discovery-plugin-config-center - - - - ${project.groupId} - discovery-plugin-admin-center - - - - ${project.groupId} - discovery-plugin-framework-nacos - - - \ No newline at end of file diff --git a/discovery-plugin-starter-nacos/src/main/resources/META-INF/spring.factories b/discovery-plugin-starter-nacos/src/main/resources/META-INF/spring.factories deleted file mode 100644 index 9d23042454..0000000000 --- a/discovery-plugin-starter-nacos/src/main/resources/META-INF/spring.factories +++ /dev/null @@ -1,8 +0,0 @@ -org.springframework.context.ApplicationContextInitializer=\ -com.nepxion.discovery.plugin.framework.context.NacosApplicationContextInitializer - -org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ -com.nepxion.discovery.plugin.framework.configuration.PluginAutoConfiguration,\ -com.nepxion.discovery.plugin.framework.configuration.NacosAutoConfiguration,\ -com.nepxion.discovery.plugin.configcenter.configuration.ConfigAutoConfiguration,\ -com.nepxion.discovery.plugin.admincenter.configuration.AdminAutoConfiguration \ No newline at end of file diff --git a/discovery-plugin-starter-zookeeper/pom.xml b/discovery-plugin-starter-zookeeper/pom.xml deleted file mode 100644 index 7c2afb137d..0000000000 --- a/discovery-plugin-starter-zookeeper/pom.xml +++ /dev/null @@ -1,33 +0,0 @@ - - - discovery-plugin-starter-zookeeper - Nepxion Discovery Plugin Starter Zookeeper - jar - 4.0.0 - Nepxion Discovery is an enhancement for Spring Cloud Discovery - http://www.nepxion.com - - - com.nepxion - discovery - 5.2.0-SNAPSHOT - - - - - ${project.groupId} - discovery-plugin-config-center - - - - ${project.groupId} - discovery-plugin-admin-center - - - - ${project.groupId} - discovery-plugin-framework-zookeeper - - - \ No newline at end of file diff --git a/discovery-plugin-starter-zookeeper/src/main/resources/META-INF/spring.factories b/discovery-plugin-starter-zookeeper/src/main/resources/META-INF/spring.factories deleted file mode 100644 index e6f734383b..0000000000 --- a/discovery-plugin-starter-zookeeper/src/main/resources/META-INF/spring.factories +++ /dev/null @@ -1,8 +0,0 @@ -org.springframework.context.ApplicationContextInitializer=\ -com.nepxion.discovery.plugin.framework.context.ZookeeperApplicationContextInitializer - -org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ -com.nepxion.discovery.plugin.framework.configuration.PluginAutoConfiguration,\ -com.nepxion.discovery.plugin.framework.configuration.ZookeeperAutoConfiguration,\ -com.nepxion.discovery.plugin.configcenter.configuration.ConfigAutoConfiguration,\ -com.nepxion.discovery.plugin.admincenter.configuration.AdminAutoConfiguration \ No newline at end of file diff --git a/discovery-plugin-strategy-starter-gateway/pom.xml b/discovery-plugin-strategy-starter-gateway/pom.xml deleted file mode 100644 index 9a019a636c..0000000000 --- a/discovery-plugin-strategy-starter-gateway/pom.xml +++ /dev/null @@ -1,28 +0,0 @@ - - - discovery-plugin-strategy-starter-gateway - Nepxion Discovery Plugin Strategy Starter Gateway - jar - 4.0.0 - Nepxion Discovery is an enhancement for Spring Cloud Discovery - http://www.nepxion.com - - - com.nepxion - discovery - 5.2.0-SNAPSHOT - - - - - ${project.groupId} - discovery-plugin-strategy - - - - org.springframework.cloud - spring-cloud-starter-gateway - - - \ No newline at end of file diff --git a/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/configuration/GatewayStrategyAutoConfiguration.java b/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/configuration/GatewayStrategyAutoConfiguration.java deleted file mode 100644 index 4e1d5ccff7..0000000000 --- a/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/configuration/GatewayStrategyAutoConfiguration.java +++ /dev/null @@ -1,56 +0,0 @@ -package com.nepxion.discovery.plugin.strategy.gateway.configuration; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import org.springframework.boot.autoconfigure.AutoConfigureBefore; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.cloud.netflix.ribbon.RibbonClientConfiguration; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -import com.nepxion.discovery.plugin.strategy.adapter.DefaultDiscoveryEnabledAdapter; -import com.nepxion.discovery.plugin.strategy.adapter.DiscoveryEnabledAdapter; -import com.nepxion.discovery.plugin.strategy.constant.StrategyConstant; -import com.nepxion.discovery.plugin.strategy.gateway.constant.GatewayStrategyConstant; -import com.nepxion.discovery.plugin.strategy.gateway.filter.DefaultGatewayStrategyRouteFilter; -import com.nepxion.discovery.plugin.strategy.gateway.filter.GatewayStrategyFilter; -import com.nepxion.discovery.plugin.strategy.gateway.filter.GatewayStrategyRouteFilter; -import com.nepxion.discovery.plugin.strategy.gateway.wrapper.DefaultCallableWrapper; -import com.nepxion.discovery.plugin.strategy.wrapper.CallableWrapper; - -@Configuration -@AutoConfigureBefore(RibbonClientConfiguration.class) -@ConditionalOnProperty(value = StrategyConstant.SPRING_APPLICATION_STRATEGY_CONTROL_ENABLED, matchIfMissing = true) -public class GatewayStrategyAutoConfiguration { - @Bean - public GatewayStrategyFilter gatewayStrategyFilter() { - return new GatewayStrategyFilter(); - } - - @Bean - @ConditionalOnMissingBean - @ConditionalOnProperty(value = GatewayStrategyConstant.SPRING_APPLICATION_STRATEGY_GATEWAY_ROUTE_FILTER_ENABLED, matchIfMissing = true) - public GatewayStrategyRouteFilter gatewayStrategyRouteFilter() { - return new DefaultGatewayStrategyRouteFilter(); - } - - @Bean - @ConditionalOnMissingBean - public DiscoveryEnabledAdapter discoveryEnabledAdapter() { - return new DefaultDiscoveryEnabledAdapter(); - } - - @Bean - @ConditionalOnProperty(value = StrategyConstant.SPRING_APPLICATION_STRATEGY_HYSTRIX_THREADLOCAL_SUPPORTED, matchIfMissing = false) - public CallableWrapper callableWrapper() { - return new DefaultCallableWrapper(); - } -} \ No newline at end of file diff --git a/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/constant/GatewayStrategyConstant.java b/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/constant/GatewayStrategyConstant.java deleted file mode 100644 index 25cf613496..0000000000 --- a/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/constant/GatewayStrategyConstant.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.nepxion.discovery.plugin.strategy.gateway.constant; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -public class GatewayStrategyConstant { - public static final String SPRING_APPLICATION_STRATEGY_GATEWAY_ROUTE_FILTER_ENABLED = "spring.application.strategy.gateway.route.filter.enabled"; - public static final String SPRING_APPLICATION_STRATEGY_GATEWAY_ROUTE_FILTER_ORDER = "spring.application.strategy.gateway.route.filter.order"; - public static final String SPRING_APPLICATION_STRATEGY_GATEWAY_HEADER_PRIORITY = "spring.application.strategy.gateway.header.priority"; - public static final int SPRING_APPLICATION_STRATEGY_GATEWAY_ROUTE_FILTER_ORDER_VALUE = 9000; -} \ No newline at end of file diff --git a/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/context/GatewayStrategyApplicationContextInitializer.java b/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/context/GatewayStrategyApplicationContextInitializer.java deleted file mode 100644 index 43f2b64d9c..0000000000 --- a/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/context/GatewayStrategyApplicationContextInitializer.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.nepxion.discovery.plugin.strategy.gateway.context; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import org.springframework.context.ApplicationContextInitializer; -import org.springframework.context.ConfigurableApplicationContext; - -import com.nepxion.discovery.common.constant.DiscoveryConstant; - -public class GatewayStrategyApplicationContextInitializer implements ApplicationContextInitializer { - @Override - public void initialize(ConfigurableApplicationContext applicationContext) { - System.setProperty(DiscoveryConstant.SPRING_APPLICATION_TYPE, DiscoveryConstant.GATEWAY_TYPE); - } -} \ No newline at end of file diff --git a/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/context/GatewayStrategyContextHolder.java b/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/context/GatewayStrategyContextHolder.java deleted file mode 100644 index 9bca034f02..0000000000 --- a/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/context/GatewayStrategyContextHolder.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.nepxion.discovery.plugin.strategy.gateway.context; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.web.server.ServerWebExchange; - -import com.nepxion.discovery.plugin.strategy.context.AbstractStrategyContextHolder; - -public class GatewayStrategyContextHolder extends AbstractStrategyContextHolder { - private static final Logger LOG = LoggerFactory.getLogger(GatewayStrategyContextHolder.class); - - public ServerWebExchange getExchange() { - return GatewayStrategyContext.getCurrentContext().getExchange(); - } - - @Override - public String getHeader(String name) { - ServerWebExchange exchange = getExchange(); - if (exchange == null) { - LOG.warn("The ServerWebExchange object is null"); - - return null; - } - - return exchange.getRequest().getHeaders().getFirst(name); - } -} \ No newline at end of file diff --git a/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/filter/AbstractGatewayStrategyRouteFilter.java b/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/filter/AbstractGatewayStrategyRouteFilter.java deleted file mode 100644 index 89a4084dcd..0000000000 --- a/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/filter/AbstractGatewayStrategyRouteFilter.java +++ /dev/null @@ -1,121 +0,0 @@ -package com.nepxion.discovery.plugin.strategy.gateway.filter; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import reactor.core.publisher.Mono; - -import org.apache.commons.lang3.StringUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.cloud.gateway.filter.GatewayFilterChain; -import org.springframework.cloud.gateway.filter.GlobalFilter; -import org.springframework.core.Ordered; -import org.springframework.core.env.ConfigurableEnvironment; -import org.springframework.http.server.reactive.ServerHttpRequest; -import org.springframework.web.server.ServerWebExchange; - -import com.nepxion.discovery.common.constant.DiscoveryConstant; -import com.nepxion.discovery.plugin.framework.adapter.PluginAdapter; -import com.nepxion.discovery.plugin.strategy.constant.StrategyConstant; -import com.nepxion.discovery.plugin.strategy.context.StrategyContextHolder; -import com.nepxion.discovery.plugin.strategy.gateway.constant.GatewayStrategyConstant; - -public abstract class AbstractGatewayStrategyRouteFilter implements GlobalFilter, Ordered, GatewayStrategyRouteFilter { - @Autowired - private ConfigurableEnvironment environment; - - @Autowired - protected PluginAdapter pluginAdapter; - - @Autowired - protected StrategyContextHolder strategyContextHolder; - - @Override - public int getOrder() { - return environment.getProperty(GatewayStrategyConstant.SPRING_APPLICATION_STRATEGY_GATEWAY_ROUTE_FILTER_ORDER, Integer.class, GatewayStrategyConstant.SPRING_APPLICATION_STRATEGY_GATEWAY_ROUTE_FILTER_ORDER_VALUE); - } - - @Override - public Mono filter(ServerWebExchange exchange, GatewayFilterChain chain) { - Boolean interceptLogPrint = environment.getProperty(StrategyConstant.SPRING_APPLICATION_STRATEGY_INTERCEPT_LOG_PRINT, Boolean.class, Boolean.FALSE); - - if (interceptLogPrint) { - System.out.println("--------- Input Route Header Information ---------"); - printRouteHeader(); - System.out.println("--------------------------------------------------"); - } - - String routeVersion = getRouteVersion(); - String routeRegion = getRouteRegion(); - String routeAddress = getRouteAddress(); - String routeVersionWeight = getRouteVersionWeight(); - String routeRegionWeight = getRouteRegionWeight(); - - // 通过过滤器设置路由Header头部信息,并全链路传递到服务端 - // 如果外界也传了相同的Header,例如,从Postman传递过来的Header,当下面的变量为true,以网关设置为优先,否则以外界传值为优先 - Boolean gatewayHeaderPriority = environment.getProperty(GatewayStrategyConstant.SPRING_APPLICATION_STRATEGY_GATEWAY_HEADER_PRIORITY, Boolean.class, Boolean.TRUE); - - // 通过过滤器设置路由Header头部信息,并全链路传递到服务端 - ServerHttpRequest.Builder requestBuilder = exchange.getRequest().mutate(); - if (StringUtils.isNotEmpty(routeVersion)) { - GatewayStrategyFilterResolver.setHeader(requestBuilder, DiscoveryConstant.N_D_VERSION, routeVersion, gatewayHeaderPriority); - } - if (StringUtils.isNotEmpty(routeRegion)) { - GatewayStrategyFilterResolver.setHeader(requestBuilder, DiscoveryConstant.N_D_REGION, routeRegion, gatewayHeaderPriority); - } - if (StringUtils.isNotEmpty(routeAddress)) { - GatewayStrategyFilterResolver.setHeader(requestBuilder, DiscoveryConstant.N_D_ADDRESS, routeAddress, gatewayHeaderPriority); - } - if (StringUtils.isNotEmpty(routeVersionWeight)) { - GatewayStrategyFilterResolver.setHeader(requestBuilder, DiscoveryConstant.N_D_VERSION_WEIGHT, routeVersionWeight, gatewayHeaderPriority); - } - if (StringUtils.isNotEmpty(routeRegionWeight)) { - GatewayStrategyFilterResolver.setHeader(requestBuilder, DiscoveryConstant.N_D_REGION_WEIGHT, routeRegionWeight, gatewayHeaderPriority); - } - - // 开启此项,将启动提供端的服务隔离机制,则传递到服务的是网关自身ServiceType, ServiceId, ServiceHost, Group - // 如果不隔离,为了调用链完整,最好外界自身传递ServiceType, ServiceId, ServiceHost, Group - Boolean providerIsolationEnabled = environment.getProperty(StrategyConstant.SPRING_APPLICATION_STRATEGY_PROVIDER_ISOLATION_ENABLED, Boolean.class, Boolean.FALSE); - - GatewayStrategyFilterResolver.setHeader(requestBuilder, DiscoveryConstant.N_D_SERVICE_TYPE, pluginAdapter.getServiceType(), providerIsolationEnabled ? providerIsolationEnabled : gatewayHeaderPriority); - GatewayStrategyFilterResolver.setHeader(requestBuilder, DiscoveryConstant.N_D_SERVICE_ID, pluginAdapter.getServiceId(), providerIsolationEnabled ? providerIsolationEnabled : gatewayHeaderPriority); - GatewayStrategyFilterResolver.setHeader(requestBuilder, DiscoveryConstant.N_D_SERVICE_ADDRESS, pluginAdapter.getHost() + ":" + pluginAdapter.getPort(), providerIsolationEnabled ? providerIsolationEnabled : gatewayHeaderPriority); - GatewayStrategyFilterResolver.setHeader(requestBuilder, DiscoveryConstant.N_D_SERVICE_GROUP, pluginAdapter.getGroup(), providerIsolationEnabled ? providerIsolationEnabled : gatewayHeaderPriority); - GatewayStrategyFilterResolver.setHeader(requestBuilder, DiscoveryConstant.N_D_SERVICE_VERSION, pluginAdapter.getVersion(), providerIsolationEnabled ? providerIsolationEnabled : gatewayHeaderPriority); - GatewayStrategyFilterResolver.setHeader(requestBuilder, DiscoveryConstant.N_D_SERVICE_REGION, pluginAdapter.getRegion(), providerIsolationEnabled ? providerIsolationEnabled : gatewayHeaderPriority); - - if (interceptLogPrint) { - System.out.println("--------- Output Route Header Information --------"); - printRouteHeader(); - System.out.println("--------------------------------------------------"); - } - - ServerHttpRequest newRequest = requestBuilder.build(); - ServerWebExchange newExchange = exchange.mutate().request(newRequest).build(); - - return chain.filter(newExchange); - } - - private void printRouteHeader() { - System.out.println(DiscoveryConstant.N_D_SERVICE_TYPE + "=" + strategyContextHolder.getHeader(DiscoveryConstant.N_D_SERVICE_TYPE)); - System.out.println(DiscoveryConstant.N_D_SERVICE_ID + "=" + strategyContextHolder.getHeader(DiscoveryConstant.N_D_SERVICE_ID)); - System.out.println(DiscoveryConstant.N_D_SERVICE_ADDRESS + "=" + strategyContextHolder.getHeader(DiscoveryConstant.N_D_SERVICE_ADDRESS)); - System.out.println(DiscoveryConstant.N_D_SERVICE_GROUP + "=" + strategyContextHolder.getHeader(DiscoveryConstant.N_D_SERVICE_GROUP)); - System.out.println(DiscoveryConstant.N_D_SERVICE_VERSION + "=" + strategyContextHolder.getHeader(DiscoveryConstant.N_D_SERVICE_VERSION)); - System.out.println(DiscoveryConstant.N_D_SERVICE_REGION + "=" + strategyContextHolder.getHeader(DiscoveryConstant.N_D_SERVICE_REGION)); - } - - public PluginAdapter getPluginAdapter() { - return pluginAdapter; - } - - public StrategyContextHolder getStrategyContextHolder() { - return strategyContextHolder; - } -} \ No newline at end of file diff --git a/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/filter/CustomizationGatewayStrategyRouteFilter.java b/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/filter/CustomizationGatewayStrategyRouteFilter.java deleted file mode 100644 index 7cd1831508..0000000000 --- a/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/filter/CustomizationGatewayStrategyRouteFilter.java +++ /dev/null @@ -1,152 +0,0 @@ -package com.nepxion.discovery.plugin.strategy.gateway.filter; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import java.util.List; -import java.util.Map; - -import org.apache.commons.lang3.StringUtils; - -import com.nepxion.discovery.common.entity.RuleEntity; -import com.nepxion.discovery.common.entity.StrategyConditionEntity; -import com.nepxion.discovery.common.entity.StrategyCustomizationEntity; -import com.nepxion.discovery.common.entity.StrategyRouteEntity; -import com.nepxion.discovery.common.entity.StrategyType; - -public class CustomizationGatewayStrategyRouteFilter extends DefaultGatewayStrategyRouteFilter { - // 从远程配置中心或者本地配置文件获取版本路由配置。如果是远程配置中心,则值会动态改变 - @Override - public String getRouteVersion() { - StrategyConditionEntity strategyConditionEntity = getTriggeredStrategyConditionEntity(); - if (strategyConditionEntity != null) { - String versionId = strategyConditionEntity.getVersionId(); - StrategyRouteEntity strategyRouteEntity = getTriggeredStrategyRouteEntity(versionId, StrategyType.VERSION); - if (strategyRouteEntity != null) { - return strategyRouteEntity.getValue(); - } - } - - return super.getRouteVersion(); - } - - // 从远程配置中心或者本地配置文件获取区域路由配置。如果是远程配置中心,则值会动态改变 - @Override - public String getRouteRegion() { - StrategyConditionEntity strategyConditionEntity = getTriggeredStrategyConditionEntity(); - if (strategyConditionEntity != null) { - String regionId = strategyConditionEntity.getRegionId(); - StrategyRouteEntity strategyRouteEntity = getTriggeredStrategyRouteEntity(regionId, StrategyType.REGION); - if (strategyRouteEntity != null) { - return strategyRouteEntity.getValue(); - } - } - - return super.getRouteRegion(); - } - - // 从远程配置中心或者本地配置文件获取IP地址和端口路由配置。如果是远程配置中心,则值会动态改变 - @Override - public String getRouteAddress() { - StrategyConditionEntity strategyConditionEntity = getTriggeredStrategyConditionEntity(); - if (strategyConditionEntity != null) { - String addressId = strategyConditionEntity.getAddressId(); - StrategyRouteEntity strategyRouteEntity = getTriggeredStrategyRouteEntity(addressId, StrategyType.ADDRESS); - if (strategyRouteEntity != null) { - return strategyRouteEntity.getValue(); - } - } - - return super.getRouteAddress(); - } - - // 从远程配置中心或者本地配置文件获取版本权重配置。如果是远程配置中心,则值会动态改变 - @Override - public String getRouteVersionWeight() { - StrategyConditionEntity strategyConditionEntity = getTriggeredStrategyConditionEntity(); - if (strategyConditionEntity != null) { - String versionWeightId = strategyConditionEntity.getVersionWeightId(); - StrategyRouteEntity strategyRouteEntity = getTriggeredStrategyRouteEntity(versionWeightId, StrategyType.VERSION_WEIGHT); - if (strategyRouteEntity != null) { - return strategyRouteEntity.getValue(); - } - } - - return super.getRouteVersionWeight(); - } - - // 从远程配置中心或者本地配置文件获取区域权重配置。如果是远程配置中心,则值会动态改变 - @Override - public String getRouteRegionWeight() { - StrategyConditionEntity strategyConditionEntity = getTriggeredStrategyConditionEntity(); - if (strategyConditionEntity != null) { - String regionWeightId = strategyConditionEntity.getRegionWeightId(); - StrategyRouteEntity strategyRouteEntity = getTriggeredStrategyRouteEntity(regionWeightId, StrategyType.REGION_WEIGHT); - if (strategyRouteEntity != null) { - return strategyRouteEntity.getValue(); - } - } - - return super.getRouteRegionWeight(); - } - - private StrategyRouteEntity getTriggeredStrategyRouteEntity(String id, StrategyType type) { - if (StringUtils.isEmpty(id)) { - return null; - } - - RuleEntity ruleEntity = pluginAdapter.getRule(); - if (ruleEntity != null) { - StrategyCustomizationEntity strategyCustomizationEntity = ruleEntity.getStrategyCustomizationEntity(); - if (strategyCustomizationEntity != null) { - List strategyRouteEntityList = strategyCustomizationEntity.getStrategyRouteEntityList(); - for (StrategyRouteEntity strategyRouteEntity : strategyRouteEntityList) { - if (StringUtils.equals(strategyRouteEntity.getId(), id) && strategyRouteEntity.getType() == type) { - return strategyRouteEntity; - } - } - } - } - - return null; - } - - private StrategyConditionEntity getTriggeredStrategyConditionEntity() { - RuleEntity ruleEntity = pluginAdapter.getRule(); - if (ruleEntity != null) { - StrategyCustomizationEntity strategyCustomizationEntity = ruleEntity.getStrategyCustomizationEntity(); - if (strategyCustomizationEntity != null) { - List strategyConditionEntityList = strategyCustomizationEntity.getStrategyConditionEntityList(); - for (StrategyConditionEntity strategyConditionEntity : strategyConditionEntityList) { - boolean isTriggered = isTriggered(strategyConditionEntity); - if (isTriggered) { - return strategyConditionEntity; - } - } - } - } - - return null; - } - - private boolean isTriggered(StrategyConditionEntity strategyConditionEntity) { - Map headerMap = strategyConditionEntity.getHeaderMap(); - for (Map.Entry entry : headerMap.entrySet()) { - String headerName = entry.getKey(); - String headerValue = entry.getValue(); - - String value = strategyContextHolder.getHeader(headerName); - if (!StringUtils.equals(headerValue, value)) { - return false; - } - } - - return true; - } -} \ No newline at end of file diff --git a/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/filter/DefaultGatewayStrategyRouteFilter.java b/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/filter/DefaultGatewayStrategyRouteFilter.java deleted file mode 100644 index d374597b71..0000000000 --- a/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/filter/DefaultGatewayStrategyRouteFilter.java +++ /dev/null @@ -1,85 +0,0 @@ -package com.nepxion.discovery.plugin.strategy.gateway.filter; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import com.nepxion.discovery.common.entity.RuleEntity; -import com.nepxion.discovery.common.entity.StrategyEntity; - -public class DefaultGatewayStrategyRouteFilter extends AbstractGatewayStrategyRouteFilter { - // 从远程配置中心或者本地配置文件获取版本路由配置。如果是远程配置中心,则值会动态改变 - @Override - public String getRouteVersion() { - RuleEntity ruleEntity = pluginAdapter.getRule(); - if (ruleEntity != null) { - StrategyEntity strategyEntity = ruleEntity.getStrategyEntity(); - if (strategyEntity != null) { - return strategyEntity.getVersionValue(); - } - } - - return null; - } - - // 从远程配置中心或者本地配置文件获取区域路由配置。如果是远程配置中心,则值会动态改变 - @Override - public String getRouteRegion() { - RuleEntity ruleEntity = pluginAdapter.getRule(); - if (ruleEntity != null) { - StrategyEntity strategyEntity = ruleEntity.getStrategyEntity(); - if (strategyEntity != null) { - return strategyEntity.getRegionValue(); - } - } - - return null; - } - - // 从远程配置中心或者本地配置文件获取IP地址和端口路由配置。如果是远程配置中心,则值会动态改变 - @Override - public String getRouteAddress() { - RuleEntity ruleEntity = pluginAdapter.getRule(); - if (ruleEntity != null) { - StrategyEntity strategyEntity = ruleEntity.getStrategyEntity(); - if (strategyEntity != null) { - return strategyEntity.getAddressValue(); - } - } - - return null; - } - - // 从远程配置中心或者本地配置文件获取版本权重配置。如果是远程配置中心,则值会动态改变 - @Override - public String getRouteVersionWeight() { - RuleEntity ruleEntity = pluginAdapter.getRule(); - if (ruleEntity != null) { - StrategyEntity strategyEntity = ruleEntity.getStrategyEntity(); - if (strategyEntity != null) { - return strategyEntity.getVersionWeightValue(); - } - } - - return null; - } - - // 从远程配置中心或者本地配置文件获取区域权重配置。如果是远程配置中心,则值会动态改变 - @Override - public String getRouteRegionWeight() { - RuleEntity ruleEntity = pluginAdapter.getRule(); - if (ruleEntity != null) { - StrategyEntity strategyEntity = ruleEntity.getStrategyEntity(); - if (strategyEntity != null) { - return strategyEntity.getRegionWeightValue(); - } - } - - return null; - } -} \ No newline at end of file diff --git a/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/filter/GatewayStrategyFilter.java b/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/filter/GatewayStrategyFilter.java deleted file mode 100644 index 8ada5963cb..0000000000 --- a/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/filter/GatewayStrategyFilter.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.nepxion.discovery.plugin.strategy.gateway.filter; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import reactor.core.publisher.Mono; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.cloud.gateway.filter.GatewayFilterChain; -import org.springframework.cloud.gateway.filter.GlobalFilter; -import org.springframework.core.Ordered; -import org.springframework.core.env.ConfigurableEnvironment; -import org.springframework.web.server.ServerWebExchange; - -import com.nepxion.discovery.plugin.strategy.gateway.constant.GatewayStrategyConstant; -import com.nepxion.discovery.plugin.strategy.gateway.context.GatewayStrategyContext; - -public class GatewayStrategyFilter implements GlobalFilter, Ordered { - private static final Logger LOG = LoggerFactory.getLogger(GatewayStrategyFilter.class); - - @Autowired - private ConfigurableEnvironment environment; - - @Override - public int getOrder() { - return environment.getProperty(GatewayStrategyConstant.SPRING_APPLICATION_STRATEGY_GATEWAY_ROUTE_FILTER_ORDER, Integer.class, GatewayStrategyConstant.SPRING_APPLICATION_STRATEGY_GATEWAY_ROUTE_FILTER_ORDER_VALUE) - 1; - } - - @Override - public Mono filter(ServerWebExchange exchange, GatewayFilterChain chain) { - LOG.debug("Gateway strategy context is set with {}", exchange); - - GatewayStrategyContext.getCurrentContext().setExchange(exchange); - - return chain.filter(exchange); - } -} \ No newline at end of file diff --git a/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/filter/GatewayStrategyFilterResolver.java b/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/filter/GatewayStrategyFilterResolver.java deleted file mode 100644 index fb68345c12..0000000000 --- a/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/filter/GatewayStrategyFilterResolver.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.nepxion.discovery.plugin.strategy.gateway.filter; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import org.apache.commons.lang3.StringUtils; -import org.springframework.http.server.reactive.ServerHttpRequest; - -public class GatewayStrategyFilterResolver { - public static void setHeader(ServerHttpRequest.Builder requestBuilder, String headerName, String headerValue, Boolean gatewayHeaderPriority) { - if (StringUtils.isEmpty(headerValue)) { - return; - } - - if (gatewayHeaderPriority) { - // 需要把外界的Header清除 - requestBuilder.headers(headers -> headers.remove(headerName)); - } - // 不管外界是否传递了Header,网关侧都加入Header - // 当外界没传递了Header,由网关侧Header来替代 - // 当外界传递了Header,虽然网关侧也添加了Header,但传递到调用链的还是第一个Header。参考exchange.getRequest().getHeaders().getFirst(name) - requestBuilder.header(headerName, headerValue); - } -} \ No newline at end of file diff --git a/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/filter/GatewayStrategyRouteFilter.java b/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/filter/GatewayStrategyRouteFilter.java deleted file mode 100644 index dfa36cd88f..0000000000 --- a/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/filter/GatewayStrategyRouteFilter.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.nepxion.discovery.plugin.strategy.gateway.filter; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -public interface GatewayStrategyRouteFilter { - String getRouteVersion(); - - String getRouteRegion(); - - String getRouteAddress(); - - String getRouteVersionWeight(); - - String getRouteRegionWeight(); -} \ No newline at end of file diff --git a/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/wrapper/DefaultCallableWrapper.java b/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/wrapper/DefaultCallableWrapper.java deleted file mode 100644 index 4f78617252..0000000000 --- a/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/wrapper/DefaultCallableWrapper.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.nepxion.discovery.plugin.strategy.gateway.wrapper; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @author Hao Huang - * @version 1.0 - */ - -import java.util.concurrent.Callable; - -import org.springframework.web.server.ServerWebExchange; - -import com.nepxion.discovery.plugin.strategy.gateway.context.GatewayStrategyContext; -import com.nepxion.discovery.plugin.strategy.wrapper.CallableWrapper; - -public class DefaultCallableWrapper implements CallableWrapper { - @Override - public Callable wrapCallable(Callable delegate) { - ServerWebExchange exchange = GatewayStrategyContext.getCurrentContext().getExchange(); - - return new Callable() { - @Override - public T call() throws Exception { - try { - GatewayStrategyContext.getCurrentContext().setExchange(exchange); - - return delegate.call(); - } finally { - GatewayStrategyContext.clearCurrentContext(); - } - } - }; - } -} \ No newline at end of file diff --git a/discovery-plugin-strategy-starter-gateway/src/main/resources/META-INF/spring.factories b/discovery-plugin-strategy-starter-gateway/src/main/resources/META-INF/spring.factories deleted file mode 100644 index c920ff10ba..0000000000 --- a/discovery-plugin-strategy-starter-gateway/src/main/resources/META-INF/spring.factories +++ /dev/null @@ -1,7 +0,0 @@ -org.springframework.context.ApplicationContextInitializer=\ -com.nepxion.discovery.plugin.strategy.gateway.context.GatewayStrategyApplicationContextInitializer - -org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ -com.nepxion.discovery.plugin.strategy.configuration.StrategyAutoConfiguration,\ -com.nepxion.discovery.plugin.strategy.gateway.configuration.GatewayStrategyAutoConfiguration,\ -com.nepxion.discovery.plugin.strategy.gateway.configuration.GatewayStrategyContextAutoConfiguration \ No newline at end of file diff --git a/discovery-plugin-strategy-starter-hystrix/pom.xml b/discovery-plugin-strategy-starter-hystrix/pom.xml deleted file mode 100644 index 2517971a4a..0000000000 --- a/discovery-plugin-strategy-starter-hystrix/pom.xml +++ /dev/null @@ -1,28 +0,0 @@ - - - discovery-plugin-strategy-starter-hystrix - Nepxion Discovery Plugin Strategy Starter Hystrix - jar - 4.0.0 - Nepxion Discovery is an enhancement for Spring Cloud Discovery - http://www.nepxion.com - - - com.nepxion - discovery - 5.2.0-SNAPSHOT - - - - - ${project.groupId} - discovery-plugin-strategy - - - - org.springframework.cloud - spring-cloud-starter-netflix-hystrix - - - \ No newline at end of file diff --git a/discovery-plugin-strategy-starter-hystrix/src/main/java/com/nepxion/discovery/plugin/strategy/hystrix/configuration/HystrixStrategyAutoConfiguration.java b/discovery-plugin-strategy-starter-hystrix/src/main/java/com/nepxion/discovery/plugin/strategy/hystrix/configuration/HystrixStrategyAutoConfiguration.java deleted file mode 100644 index 391a88db7d..0000000000 --- a/discovery-plugin-strategy-starter-hystrix/src/main/java/com/nepxion/discovery/plugin/strategy/hystrix/configuration/HystrixStrategyAutoConfiguration.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.nepxion.discovery.plugin.strategy.hystrix.configuration; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @author Hao Huang - * @version 1.0 - */ - -import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -import com.nepxion.discovery.plugin.strategy.constant.StrategyConstant; -import com.nepxion.discovery.plugin.strategy.hystrix.context.HystrixContextConcurrencyStrategy; -import com.netflix.hystrix.Hystrix; - -@Configuration -@ConditionalOnClass(Hystrix.class) -@ConditionalOnProperty(value = StrategyConstant.SPRING_APPLICATION_STRATEGY_HYSTRIX_THREADLOCAL_SUPPORTED, matchIfMissing = false) -public class HystrixStrategyAutoConfiguration { - @Bean - public HystrixContextConcurrencyStrategy hystrixContextConcurrencyStrategy() { - return new HystrixContextConcurrencyStrategy(); - } -} \ No newline at end of file diff --git a/discovery-plugin-strategy-starter-service/pom.xml b/discovery-plugin-strategy-starter-service/pom.xml deleted file mode 100644 index d104321e15..0000000000 --- a/discovery-plugin-strategy-starter-service/pom.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - discovery-plugin-strategy-starter-service - Nepxion Discovery Plugin Strategy Starter Service - jar - 4.0.0 - Nepxion Discovery is an enhancement for Spring Cloud Discovery - http://www.nepxion.com - - - com.nepxion - discovery - 5.2.0-SNAPSHOT - - - - - ${project.groupId} - discovery-plugin-strategy - - - - ${project.groupId} - matrix-aop-starter - - - - org.springframework.cloud - spring-cloud-starter-openfeign - - - - org.springframework.boot - spring-boot-starter-web - - - \ No newline at end of file diff --git a/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/aop/AbstractStrategyInterceptor.java b/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/aop/AbstractStrategyInterceptor.java deleted file mode 100644 index 605133a2a1..0000000000 --- a/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/aop/AbstractStrategyInterceptor.java +++ /dev/null @@ -1,106 +0,0 @@ -package com.nepxion.discovery.plugin.strategy.service.aop; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import java.util.ArrayList; -import java.util.Enumeration; -import java.util.List; - -import javax.servlet.http.HttpServletRequest; - -import org.apache.commons.lang3.StringUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.core.env.ConfigurableEnvironment; -import org.springframework.web.context.request.ServletRequestAttributes; - -import com.nepxion.discovery.common.constant.DiscoveryConstant; -import com.nepxion.discovery.common.util.StringUtil; -import com.nepxion.discovery.plugin.framework.adapter.PluginAdapter; -import com.nepxion.discovery.plugin.strategy.constant.StrategyConstant; -import com.nepxion.discovery.plugin.strategy.service.context.ServiceStrategyContextHolder; - -public abstract class AbstractStrategyInterceptor { - @Autowired - protected ConfigurableEnvironment environment; - - @Autowired - protected PluginAdapter pluginAdapter; - - @Autowired - protected ServiceStrategyContextHolder serviceStrategyContextHolder; - - protected List requestHeaderList = new ArrayList(); - - public AbstractStrategyInterceptor(String requestHeaders) { - if (StringUtils.isNotEmpty(requestHeaders)) { - requestHeaderList.addAll(StringUtil.splitToList(requestHeaders.toLowerCase(), DiscoveryConstant.SEPARATE)); - } - /*if (!requestHeaderList.contains(DiscoveryConstant.N_D_VERSION)) { - requestHeaderList.add(DiscoveryConstant.N_D_VERSION); - } - if (!requestHeaderList.contains(DiscoveryConstant.N_D_REGION)) { - requestHeaderList.add(DiscoveryConstant.N_D_REGION); - } - if (!requestHeaderList.contains(DiscoveryConstant.N_D_ADDRESS)) { - requestHeaderList.add(DiscoveryConstant.N_D_ADDRESS); - } - if (!requestHeaderList.contains(DiscoveryConstant.N_D_VERSION_WEIGHT)) { - requestHeaderList.add(DiscoveryConstant.N_D_VERSION_WEIGHT); - } - if (!requestHeaderList.contains(DiscoveryConstant.N_D_REGION_WEIGHT)) { - requestHeaderList.add(DiscoveryConstant.N_D_REGION_WEIGHT); - }*/ - } - - protected void printInputRouteHeader() { - Boolean interceptLogPrint = environment.getProperty(StrategyConstant.SPRING_APPLICATION_STRATEGY_INTERCEPT_LOG_PRINT, Boolean.class, Boolean.FALSE); - if (!interceptLogPrint) { - return; - } - - ServletRequestAttributes attributes = serviceStrategyContextHolder.getRestAttributes(); - if (attributes == null) { - return; - } - - HttpServletRequest previousRequest = attributes.getRequest(); - Enumeration headerNames = previousRequest.getHeaderNames(); - if (headerNames == null) { - return; - } - - System.out.println("--------- Input Route Header Information ---------"); - while (headerNames.hasMoreElements()) { - String headerName = headerNames.nextElement(); - boolean isHeaderContains = isHeaderContains(headerName.toLowerCase()); - if (isHeaderContains) { - String headerValue = previousRequest.getHeader(headerName); - - System.out.println(headerName + "=" + headerValue); - } - } - System.out.println("--------------------------------------------------"); - } - - protected boolean isHeaderContains(String headerName) { - return headerName.startsWith(DiscoveryConstant.N_D_PREFIX) || requestHeaderList.contains(headerName); - } - - protected boolean isHeaderContainsExcludeInner(String headerName) { - return isHeaderContains(headerName) && - !StringUtils.equals(headerName, DiscoveryConstant.N_D_SERVICE_TYPE) && - !StringUtils.equals(headerName, DiscoveryConstant.N_D_SERVICE_ID) && - !StringUtils.equals(headerName, DiscoveryConstant.N_D_SERVICE_ADDRESS) && - !StringUtils.equals(headerName, DiscoveryConstant.N_D_SERVICE_GROUP) && - !StringUtils.equals(headerName, DiscoveryConstant.N_D_SERVICE_VERSION) && - !StringUtils.equals(headerName, DiscoveryConstant.N_D_SERVICE_REGION); - // return isHeaderContains(headerName) && !headerName.startsWith(DiscoveryConstant.N_D_SERVICE_PREFIX); - } -} \ No newline at end of file diff --git a/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/aop/FeignStrategyInterceptor.java b/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/aop/FeignStrategyInterceptor.java deleted file mode 100644 index 6ead10645e..0000000000 --- a/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/aop/FeignStrategyInterceptor.java +++ /dev/null @@ -1,99 +0,0 @@ -package com.nepxion.discovery.plugin.strategy.service.aop; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import feign.RequestInterceptor; -import feign.RequestTemplate; - -import java.util.Collection; -import java.util.Enumeration; -import java.util.Map; - -import javax.servlet.http.HttpServletRequest; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.web.context.request.ServletRequestAttributes; - -import com.nepxion.discovery.common.constant.DiscoveryConstant; -import com.nepxion.discovery.plugin.strategy.constant.StrategyConstant; - -public class FeignStrategyInterceptor extends AbstractStrategyInterceptor implements RequestInterceptor { - private static final Logger LOG = LoggerFactory.getLogger(FeignStrategyInterceptor.class); - - public FeignStrategyInterceptor(String requestHeaders) { - super(requestHeaders); - - LOG.info("----------- Feign Intercept Information ----------"); - LOG.info("Feign desires to intercept customer headers are {}", requestHeaderList); - LOG.info("--------------------------------------------------"); - } - - @Override - public void apply(RequestTemplate requestTemplate) { - printInputRouteHeader(); - - applyInnerHeader(requestTemplate); - applyOuterHeader(requestTemplate); - - printOutputRouteHeader(requestTemplate); - } - - private void applyInnerHeader(RequestTemplate requestTemplate) { - requestTemplate.header(DiscoveryConstant.N_D_SERVICE_TYPE, pluginAdapter.getServiceType()); - requestTemplate.header(DiscoveryConstant.N_D_SERVICE_ID, pluginAdapter.getServiceId()); - requestTemplate.header(DiscoveryConstant.N_D_SERVICE_ADDRESS, pluginAdapter.getHost() + ":" + pluginAdapter.getPort()); - requestTemplate.header(DiscoveryConstant.N_D_SERVICE_GROUP, pluginAdapter.getGroup()); - requestTemplate.header(DiscoveryConstant.N_D_SERVICE_VERSION, pluginAdapter.getVersion()); - requestTemplate.header(DiscoveryConstant.N_D_SERVICE_REGION, pluginAdapter.getRegion()); - } - - private void applyOuterHeader(RequestTemplate requestTemplate) { - ServletRequestAttributes attributes = serviceStrategyContextHolder.getRestAttributes(); - if (attributes == null) { - return; - } - - HttpServletRequest previousRequest = attributes.getRequest(); - Enumeration headerNames = previousRequest.getHeaderNames(); - if (headerNames == null) { - return; - } - - while (headerNames.hasMoreElements()) { - String headerName = headerNames.nextElement(); - String headerValue = previousRequest.getHeader(headerName); - boolean isHeaderContains = isHeaderContainsExcludeInner(headerName.toLowerCase()); - if (isHeaderContains) { - requestTemplate.header(headerName, headerValue); - } - } - } - - private void printOutputRouteHeader(RequestTemplate requestTemplate) { - Boolean interceptLogPrint = environment.getProperty(StrategyConstant.SPRING_APPLICATION_STRATEGY_INTERCEPT_LOG_PRINT, Boolean.class, Boolean.FALSE); - if (!interceptLogPrint) { - return; - } - - System.out.println("--------- Output Route Header Information --------"); - Map> headers = requestTemplate.headers(); - for (Map.Entry> entry : headers.entrySet()) { - String headerName = entry.getKey(); - boolean isHeaderContains = isHeaderContains(headerName.toLowerCase()); - if (isHeaderContains) { - Collection headerValue = entry.getValue(); - - System.out.println(headerName + "=" + headerValue); - } - } - System.out.println("--------------------------------------------------"); - } -} \ No newline at end of file diff --git a/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/aop/RestTemplateStrategyInterceptor.java b/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/aop/RestTemplateStrategyInterceptor.java deleted file mode 100644 index 930fc6d8db..0000000000 --- a/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/aop/RestTemplateStrategyInterceptor.java +++ /dev/null @@ -1,109 +0,0 @@ -package com.nepxion.discovery.plugin.strategy.service.aop; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import java.io.IOException; -import java.util.Enumeration; -import java.util.Iterator; -import java.util.List; -import java.util.Map.Entry; - -import javax.servlet.http.HttpServletRequest; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpRequest; -import org.springframework.http.client.ClientHttpRequestExecution; -import org.springframework.http.client.ClientHttpRequestInterceptor; -import org.springframework.http.client.ClientHttpResponse; -import org.springframework.web.context.request.ServletRequestAttributes; - -import com.nepxion.discovery.common.constant.DiscoveryConstant; -import com.nepxion.discovery.plugin.strategy.constant.StrategyConstant; - -public class RestTemplateStrategyInterceptor extends AbstractStrategyInterceptor implements ClientHttpRequestInterceptor { - private static final Logger LOG = LoggerFactory.getLogger(RestTemplateStrategyInterceptor.class); - - public RestTemplateStrategyInterceptor(String requestHeaders) { - super(requestHeaders); - - LOG.info("------- RestTemplate Intercept Information -------"); - LOG.info("RestTemplate desires to intercept customer headers are {}", requestHeaderList); - LOG.info("--------------------------------------------------"); - } - - @Override - public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { - printInputRouteHeader(); - - applyInnerHeader(request); - applyOuterHeader(request); - - printOutputRouteHeader(request); - - return execution.execute(request, body); - } - - private void applyInnerHeader(HttpRequest request) { - HttpHeaders headers = request.getHeaders(); - headers.add(DiscoveryConstant.N_D_SERVICE_TYPE, pluginAdapter.getServiceType()); - headers.add(DiscoveryConstant.N_D_SERVICE_ID, pluginAdapter.getServiceId()); - headers.add(DiscoveryConstant.N_D_SERVICE_ADDRESS, pluginAdapter.getHost() + ":" + pluginAdapter.getPort()); - headers.add(DiscoveryConstant.N_D_SERVICE_GROUP, pluginAdapter.getGroup()); - headers.add(DiscoveryConstant.N_D_SERVICE_VERSION, pluginAdapter.getVersion()); - headers.add(DiscoveryConstant.N_D_SERVICE_REGION, pluginAdapter.getRegion()); - } - - private void applyOuterHeader(HttpRequest request) { - ServletRequestAttributes attributes = serviceStrategyContextHolder.getRestAttributes(); - if (attributes == null) { - return; - } - - HttpServletRequest previousRequest = attributes.getRequest(); - Enumeration headerNames = previousRequest.getHeaderNames(); - if (headerNames == null) { - return; - } - - HttpHeaders headers = request.getHeaders(); - while (headerNames.hasMoreElements()) { - String headerName = headerNames.nextElement(); - String headerValue = previousRequest.getHeader(headerName); - boolean isHeaderContains = isHeaderContainsExcludeInner(headerName.toLowerCase()); - if (isHeaderContains) { - headers.add(headerName, headerValue); - } - } - } - - private void printOutputRouteHeader(HttpRequest request) { - Boolean interceptLogPrint = environment.getProperty(StrategyConstant.SPRING_APPLICATION_STRATEGY_INTERCEPT_LOG_PRINT, Boolean.class, Boolean.FALSE); - if (!interceptLogPrint) { - return; - } - - System.out.println("--------- Output Route Header Information --------"); - HttpHeaders headers = request.getHeaders(); - for (Iterator>> iterator = headers.entrySet().iterator(); iterator.hasNext();) { - Entry> header = iterator.next(); - String headerName = header.getKey(); - boolean isHeaderContains = isHeaderContains(headerName.toLowerCase()); - if (isHeaderContains) { - List headerValue = header.getValue(); - - System.out.println(headerName + "=" + headerValue); - } - } - - System.out.println("--------------------------------------------------"); - } -} \ No newline at end of file diff --git a/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/aop/RpcStrategyAutoScanProxy.java b/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/aop/RpcStrategyAutoScanProxy.java deleted file mode 100644 index 35aa416ff9..0000000000 --- a/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/aop/RpcStrategyAutoScanProxy.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.nepxion.discovery.plugin.strategy.service.aop; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import java.lang.annotation.Annotation; - -import org.springframework.web.bind.annotation.RestController; - -import com.nepxion.matrix.proxy.aop.DefaultAutoScanProxy; -import com.nepxion.matrix.proxy.mode.ProxyMode; -import com.nepxion.matrix.proxy.mode.ScanMode; - -public class RpcStrategyAutoScanProxy extends DefaultAutoScanProxy { - private static final long serialVersionUID = 8436914718400274011L; - - private String[] commonInterceptorNames; - - @SuppressWarnings("rawtypes") - private Class[] methodAnnotations; - - public RpcStrategyAutoScanProxy(String scanPackages) { - super(scanPackages, ProxyMode.BY_CLASS_ANNOTATION_ONLY, ScanMode.FOR_CLASS_ANNOTATION_ONLY); - } - - @Override - protected String[] getCommonInterceptorNames() { - if (commonInterceptorNames == null) { - commonInterceptorNames = new String[] { "rpcStrategyInterceptor" }; - } - - return commonInterceptorNames; - } - - @SuppressWarnings("unchecked") - @Override - protected Class[] getClassAnnotations() { - if (methodAnnotations == null) { - methodAnnotations = new Class[] { RestController.class }; - } - - return methodAnnotations; - } -} \ No newline at end of file diff --git a/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/aop/RpcStrategyInterceptor.java b/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/aop/RpcStrategyInterceptor.java deleted file mode 100644 index 34be245f5a..0000000000 --- a/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/aop/RpcStrategyInterceptor.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.nepxion.discovery.plugin.strategy.service.aop; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import java.util.LinkedHashMap; -import java.util.Map; - -import org.aopalliance.intercept.MethodInvocation; -import org.apache.commons.lang3.ArrayUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.nepxion.discovery.plugin.strategy.service.constant.ServiceStrategyConstant; -import com.nepxion.discovery.plugin.strategy.service.context.RpcStrategyContext; -import com.nepxion.matrix.proxy.aop.AbstractInterceptor; - -public class RpcStrategyInterceptor extends AbstractInterceptor { - private static final Logger LOG = LoggerFactory.getLogger(RpcStrategyInterceptor.class); - - @Override - public Object invoke(MethodInvocation invocation) throws Throwable { - Class proxiedClass = getProxiedClass(invocation); - String methodName = getMethodName(invocation); - String[] methodParameterNames = getMethodParameterNames(invocation); - Object[] arguments = getArguments(invocation); - - Map parameterMap = new LinkedHashMap(); - if (ArrayUtils.isNotEmpty(arguments)) { - for (int i = 0; i < arguments.length; i++) { - String parameterName = null; - if (ArrayUtils.isNotEmpty(methodParameterNames)) { - parameterName = methodParameterNames[i]; - } else { - parameterName = String.valueOf(i); - } - Object argument = arguments[i]; - - parameterMap.put(parameterName, argument); - } - } - - RpcStrategyContext context = RpcStrategyContext.getCurrentContext(); - context.add(ServiceStrategyConstant.CLASS, proxiedClass); - context.add(ServiceStrategyConstant.METHOD, methodName); - context.add(ServiceStrategyConstant.PARAMETER_MAP, parameterMap); - - LOG.debug("Rpc strategy context is set with {}", context); - - try { - return invocation.proceed(); - } finally { - RpcStrategyContext.clearCurrentContext(); - - LOG.debug("Rpc strategy context is cleared"); - } - } -} \ No newline at end of file diff --git a/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/configuration/ServiceStrategyAutoConfiguration.java b/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/configuration/ServiceStrategyAutoConfiguration.java deleted file mode 100644 index c3d2e2040d..0000000000 --- a/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/configuration/ServiceStrategyAutoConfiguration.java +++ /dev/null @@ -1,133 +0,0 @@ -package com.nepxion.discovery.plugin.strategy.service.configuration; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import org.apache.commons.lang3.StringUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.AutoConfigureBefore; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.cloud.netflix.ribbon.RibbonClientConfiguration; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.core.env.ConfigurableEnvironment; - -import com.nepxion.discovery.common.exception.DiscoveryException; -import com.nepxion.discovery.plugin.strategy.adapter.DefaultDiscoveryEnabledAdapter; -import com.nepxion.discovery.plugin.strategy.adapter.DiscoveryEnabledAdapter; -import com.nepxion.discovery.plugin.strategy.constant.StrategyConstant; -import com.nepxion.discovery.plugin.strategy.service.aop.FeignStrategyInterceptor; -import com.nepxion.discovery.plugin.strategy.service.aop.RestTemplateStrategyInterceptor; -import com.nepxion.discovery.plugin.strategy.service.aop.RpcStrategyAutoScanProxy; -import com.nepxion.discovery.plugin.strategy.service.aop.RpcStrategyInterceptor; -import com.nepxion.discovery.plugin.strategy.service.constant.ServiceStrategyConstant; -import com.nepxion.discovery.plugin.strategy.service.isolation.ProviderIsolationStrategyAutoScanProxy; -import com.nepxion.discovery.plugin.strategy.service.isolation.ProviderIsolationStrategyInterceptor; -import com.nepxion.discovery.plugin.strategy.service.wrapper.DefaultCallableWrapper; -import com.nepxion.discovery.plugin.strategy.wrapper.CallableWrapper; - -@Configuration -@AutoConfigureBefore(RibbonClientConfiguration.class) -@ConditionalOnProperty(value = StrategyConstant.SPRING_APPLICATION_STRATEGY_CONTROL_ENABLED, matchIfMissing = true) -public class ServiceStrategyAutoConfiguration { - @Autowired - private ConfigurableEnvironment environment; - - @Bean - @ConditionalOnProperty(value = ServiceStrategyConstant.SPRING_APPLICATION_STRATEGY_RPC_INTERCEPT_ENABLED, matchIfMissing = false) - public RpcStrategyAutoScanProxy rpcStrategyAutoScanProxy() { - String scanPackages = environment.getProperty(ServiceStrategyConstant.SPRING_APPLICATION_STRATEGY_SCAN_PACKAGES); - if (StringUtils.isEmpty(scanPackages)) { - throw new DiscoveryException(ServiceStrategyConstant.SPRING_APPLICATION_STRATEGY_SCAN_PACKAGES + "'s value can't be empty"); - } - - if (ServiceStrategyConstant.EXCLUSION_SCAN_PACKAGES.contains(scanPackages)) { - throw new DiscoveryException("It can't scan packages for '" + ServiceStrategyConstant.EXCLUSION_SCAN_PACKAGES + "', please check '" + ServiceStrategyConstant.SPRING_APPLICATION_STRATEGY_SCAN_PACKAGES + "'"); - } - - return new RpcStrategyAutoScanProxy(scanPackages); - } - - @Bean - @ConditionalOnProperty(value = ServiceStrategyConstant.SPRING_APPLICATION_STRATEGY_RPC_INTERCEPT_ENABLED, matchIfMissing = false) - public RpcStrategyInterceptor rpcStrategyInterceptor() { - String scanPackages = environment.getProperty(ServiceStrategyConstant.SPRING_APPLICATION_STRATEGY_SCAN_PACKAGES); - if (StringUtils.isEmpty(scanPackages)) { - throw new DiscoveryException(ServiceStrategyConstant.SPRING_APPLICATION_STRATEGY_SCAN_PACKAGES + "'s value can't be empty"); - } - - if (ServiceStrategyConstant.EXCLUSION_SCAN_PACKAGES.contains(scanPackages)) { - throw new DiscoveryException("It can't scan packages for '" + ServiceStrategyConstant.EXCLUSION_SCAN_PACKAGES + "', please check '" + ServiceStrategyConstant.SPRING_APPLICATION_STRATEGY_SCAN_PACKAGES + "'"); - } - - return new RpcStrategyInterceptor(); - } - - @Bean - @ConditionalOnProperty(value = ServiceStrategyConstant.SPRING_APPLICATION_STRATEGY_REST_INTERCEPT_ENABLED, matchIfMissing = true) - public FeignStrategyInterceptor feignStrategyInterceptor() { - String requestHeaders = environment.getProperty(ServiceStrategyConstant.SPRING_APPLICATION_STRATEGY_REQUEST_HEADERS); - - return new FeignStrategyInterceptor(requestHeaders); - } - - @Bean - @ConditionalOnProperty(value = ServiceStrategyConstant.SPRING_APPLICATION_STRATEGY_REST_INTERCEPT_ENABLED, matchIfMissing = true) - public RestTemplateStrategyInterceptor restTemplateStrategyInterceptor() { - String requestHeaders = environment.getProperty(ServiceStrategyConstant.SPRING_APPLICATION_STRATEGY_REQUEST_HEADERS); - - return new RestTemplateStrategyInterceptor(requestHeaders); - } - - @Bean - @ConditionalOnMissingBean - @ConditionalOnProperty(value = ServiceStrategyConstant.SPRING_APPLICATION_STRATEGY_REST_INTERCEPT_ENABLED, matchIfMissing = true) - public DiscoveryEnabledAdapter discoveryEnabledAdapter() { - return new DefaultDiscoveryEnabledAdapter(); - } - - @Bean - @ConditionalOnMissingBean - @ConditionalOnProperty(value = StrategyConstant.SPRING_APPLICATION_STRATEGY_PROVIDER_ISOLATION_ENABLED, matchIfMissing = false) - public ProviderIsolationStrategyAutoScanProxy providerIsolationStrategyAutoScanProxy() { - String scanPackages = environment.getProperty(ServiceStrategyConstant.SPRING_APPLICATION_STRATEGY_SCAN_PACKAGES); - if (StringUtils.isEmpty(scanPackages)) { - throw new DiscoveryException(ServiceStrategyConstant.SPRING_APPLICATION_STRATEGY_SCAN_PACKAGES + "'s value can't be empty"); - } - - if (ServiceStrategyConstant.EXCLUSION_SCAN_PACKAGES.contains(scanPackages)) { - throw new DiscoveryException("It can't scan packages for '" + ServiceStrategyConstant.EXCLUSION_SCAN_PACKAGES + "', please check '" + ServiceStrategyConstant.SPRING_APPLICATION_STRATEGY_SCAN_PACKAGES + "'"); - } - - return new ProviderIsolationStrategyAutoScanProxy(scanPackages); - } - - @Bean - @ConditionalOnMissingBean - @ConditionalOnProperty(value = StrategyConstant.SPRING_APPLICATION_STRATEGY_PROVIDER_ISOLATION_ENABLED, matchIfMissing = false) - public ProviderIsolationStrategyInterceptor providerIsolationStrategyInterceptor() { - String scanPackages = environment.getProperty(ServiceStrategyConstant.SPRING_APPLICATION_STRATEGY_SCAN_PACKAGES); - if (StringUtils.isEmpty(scanPackages)) { - throw new DiscoveryException(ServiceStrategyConstant.SPRING_APPLICATION_STRATEGY_SCAN_PACKAGES + "'s value can't be empty"); - } - - if (ServiceStrategyConstant.EXCLUSION_SCAN_PACKAGES.contains(scanPackages)) { - throw new DiscoveryException("It can't scan packages for '" + ServiceStrategyConstant.EXCLUSION_SCAN_PACKAGES + "', please check '" + ServiceStrategyConstant.SPRING_APPLICATION_STRATEGY_SCAN_PACKAGES + "'"); - } - - return new ProviderIsolationStrategyInterceptor(); - } - - @Bean - @ConditionalOnProperty(value = StrategyConstant.SPRING_APPLICATION_STRATEGY_HYSTRIX_THREADLOCAL_SUPPORTED, matchIfMissing = false) - public CallableWrapper callableWrapper() { - return new DefaultCallableWrapper(); - } -} \ No newline at end of file diff --git a/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/constant/ServiceStrategyConstant.java b/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/constant/ServiceStrategyConstant.java deleted file mode 100644 index 3a6b70a6ca..0000000000 --- a/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/constant/ServiceStrategyConstant.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.nepxion.discovery.plugin.strategy.service.constant; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -public class ServiceStrategyConstant { - public static final String SPRING_APPLICATION_STRATEGY_RPC_INTERCEPT_ENABLED = "spring.application.strategy.rpc.intercept.enabled"; - public static final String SPRING_APPLICATION_STRATEGY_SCAN_PACKAGES = "spring.application.strategy.scan.packages"; - public static final String SPRING_APPLICATION_STRATEGY_REST_INTERCEPT_ENABLED = "spring.application.strategy.rest.intercept.enabled"; - public static final String SPRING_APPLICATION_STRATEGY_REQUEST_HEADERS = "spring.application.strategy.request.headers"; - public static final String CLASS = "class"; - public static final String METHOD = "method"; - public static final String PARAMETER_MAP = "parameterMap"; - - public static final String EXCLUSION_SCAN_PACKAGES = "com.nepxion.discovery.plugin.admincenter.endpoint"; -} \ No newline at end of file diff --git a/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/context/ServiceStrategyApplicationContextInitializer.java b/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/context/ServiceStrategyApplicationContextInitializer.java deleted file mode 100644 index 79cd7e561f..0000000000 --- a/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/context/ServiceStrategyApplicationContextInitializer.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.nepxion.discovery.plugin.strategy.service.context; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import org.springframework.context.ApplicationContextInitializer; -import org.springframework.context.ConfigurableApplicationContext; - -import com.nepxion.discovery.common.constant.DiscoveryConstant; - -public class ServiceStrategyApplicationContextInitializer implements ApplicationContextInitializer { - @Override - public void initialize(ConfigurableApplicationContext applicationContext) { - System.setProperty(DiscoveryConstant.SPRING_APPLICATION_TYPE, DiscoveryConstant.SERVICE_TYPE); - } -} \ No newline at end of file diff --git a/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/context/ServiceStrategyContextHolder.java b/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/context/ServiceStrategyContextHolder.java deleted file mode 100644 index 738261e7ef..0000000000 --- a/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/context/ServiceStrategyContextHolder.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.nepxion.discovery.plugin.strategy.service.context; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @author Fan Yang - * @version 1.0 - */ - -import java.util.Map; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.web.context.request.RequestAttributes; -import org.springframework.web.context.request.RequestContextHolder; -import org.springframework.web.context.request.ServletRequestAttributes; - -import com.nepxion.discovery.plugin.strategy.context.AbstractStrategyContextHolder; - -public class ServiceStrategyContextHolder extends AbstractStrategyContextHolder { - private static final Logger LOG = LoggerFactory.getLogger(ServiceStrategyContextHolder.class); - - public ServletRequestAttributes getRestAttributes() { - RequestAttributes requestAttributes = RestStrategyContext.getCurrentContext().getRequestAttributes(); - if (requestAttributes == null) { - requestAttributes = RequestContextHolder.getRequestAttributes(); - } - - return (ServletRequestAttributes) requestAttributes; - } - - public Map getRpcAttributes() { - return RpcStrategyContext.getCurrentContext().getAttributes(); - } - - @Override - public String getHeader(String name) { - ServletRequestAttributes attributes = getRestAttributes(); - if (attributes == null) { - LOG.warn("The ServletRequestAttributes object is null"); - - return null; - } - - return attributes.getRequest().getHeader(name); - } -} \ No newline at end of file diff --git a/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/isolation/ProviderIsolationStrategyAutoScanProxy.java b/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/isolation/ProviderIsolationStrategyAutoScanProxy.java deleted file mode 100644 index 590b5aa98d..0000000000 --- a/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/isolation/ProviderIsolationStrategyAutoScanProxy.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.nepxion.discovery.plugin.strategy.service.isolation; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import java.lang.annotation.Annotation; - -import org.springframework.web.bind.annotation.RestController; - -import com.nepxion.matrix.proxy.aop.DefaultAutoScanProxy; -import com.nepxion.matrix.proxy.mode.ProxyMode; -import com.nepxion.matrix.proxy.mode.ScanMode; - -public class ProviderIsolationStrategyAutoScanProxy extends DefaultAutoScanProxy { - private static final long serialVersionUID = 6147822053647878553L; - - private String[] commonInterceptorNames; - - @SuppressWarnings("rawtypes") - private Class[] methodAnnotations; - - public ProviderIsolationStrategyAutoScanProxy(String scanPackages) { - super(scanPackages, ProxyMode.BY_CLASS_ANNOTATION_ONLY, ScanMode.FOR_CLASS_ANNOTATION_ONLY); - } - - @Override - protected String[] getCommonInterceptorNames() { - if (commonInterceptorNames == null) { - commonInterceptorNames = new String[] { "providerIsolationStrategyInterceptor" }; - } - - return commonInterceptorNames; - } - - @SuppressWarnings("unchecked") - @Override - protected Class[] getClassAnnotations() { - if (methodAnnotations == null) { - methodAnnotations = new Class[] { RestController.class }; - } - - return methodAnnotations; - } -} \ No newline at end of file diff --git a/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/isolation/ProviderIsolationStrategyInterceptor.java b/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/isolation/ProviderIsolationStrategyInterceptor.java deleted file mode 100644 index 7a9188e8ff..0000000000 --- a/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/isolation/ProviderIsolationStrategyInterceptor.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.nepxion.discovery.plugin.strategy.service.isolation; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import org.aopalliance.intercept.MethodInvocation; -import org.apache.commons.lang3.StringUtils; -import org.springframework.beans.factory.annotation.Autowired; - -import com.nepxion.discovery.common.constant.DiscoveryConstant; -import com.nepxion.discovery.common.exception.DiscoveryException; -import com.nepxion.discovery.plugin.framework.adapter.PluginAdapter; -import com.nepxion.discovery.plugin.strategy.context.StrategyContextHolder; -import com.nepxion.matrix.proxy.aop.AbstractInterceptor; - -public class ProviderIsolationStrategyInterceptor extends AbstractInterceptor { - @Autowired - protected StrategyContextHolder strategyContextHolder; - - @Autowired - private PluginAdapter pluginAdapter; - - @Override - public Object invoke(MethodInvocation invocation) throws Throwable { - String groupHeader = strategyContextHolder.getHeader(DiscoveryConstant.N_D_SERVICE_GROUP); - String group = pluginAdapter.getGroup(); - String serviceId = pluginAdapter.getServiceId(); - if (!StringUtils.equals(groupHeader, group)) { - throw new DiscoveryException("Reject to invoke because of isolation with different service group for serviceId=" + serviceId); - } - - return invocation.proceed(); - } -} \ No newline at end of file diff --git a/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/wrapper/DefaultCallableWrapper.java b/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/wrapper/DefaultCallableWrapper.java deleted file mode 100644 index 79ca71b90f..0000000000 --- a/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/wrapper/DefaultCallableWrapper.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.nepxion.discovery.plugin.strategy.service.wrapper; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @author Hao Huang - * @version 1.0 - */ - -import java.util.concurrent.Callable; - -import org.springframework.web.context.request.RequestAttributes; -import org.springframework.web.context.request.RequestContextHolder; - -import com.nepxion.discovery.plugin.strategy.service.context.RestStrategyContext; -import com.nepxion.discovery.plugin.strategy.wrapper.CallableWrapper; - -public class DefaultCallableWrapper implements CallableWrapper { - @Override - public Callable wrapCallable(Callable delegate) { - RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes(); - - return new Callable() { - @Override - public T call() throws Exception { - try { - RestStrategyContext.getCurrentContext().setRequestAttributes(requestAttributes); - - return delegate.call(); - } finally { - RestStrategyContext.clearCurrentContext(); - } - } - }; - } -} \ No newline at end of file diff --git a/discovery-plugin-strategy-starter-service/src/main/resources/META-INF/spring.factories b/discovery-plugin-strategy-starter-service/src/main/resources/META-INF/spring.factories deleted file mode 100644 index 45be1550b7..0000000000 --- a/discovery-plugin-strategy-starter-service/src/main/resources/META-INF/spring.factories +++ /dev/null @@ -1,7 +0,0 @@ -org.springframework.context.ApplicationContextInitializer=\ -com.nepxion.discovery.plugin.strategy.service.context.ServiceStrategyApplicationContextInitializer - -org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ -com.nepxion.discovery.plugin.strategy.configuration.StrategyAutoConfiguration,\ -com.nepxion.discovery.plugin.strategy.service.configuration.ServiceStrategyAutoConfiguration,\ -com.nepxion.discovery.plugin.strategy.service.configuration.ServiceStrategyContextAutoConfiguration \ No newline at end of file diff --git a/discovery-plugin-strategy-starter-zuul/pom.xml b/discovery-plugin-strategy-starter-zuul/pom.xml deleted file mode 100644 index bbb7230b97..0000000000 --- a/discovery-plugin-strategy-starter-zuul/pom.xml +++ /dev/null @@ -1,28 +0,0 @@ - - - discovery-plugin-strategy-starter-zuul - Nepxion Discovery Plugin Strategy Starter Zuul - jar - 4.0.0 - Nepxion Discovery is an enhancement for Spring Cloud Discovery - http://www.nepxion.com - - - com.nepxion - discovery - 5.2.0-SNAPSHOT - - - - - ${project.groupId} - discovery-plugin-strategy - - - - org.springframework.cloud - spring-cloud-starter-netflix-zuul - - - \ No newline at end of file diff --git a/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/configuration/ZuulStrategyAutoConfiguration.java b/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/configuration/ZuulStrategyAutoConfiguration.java deleted file mode 100644 index c321e38b6b..0000000000 --- a/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/configuration/ZuulStrategyAutoConfiguration.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.nepxion.discovery.plugin.strategy.zuul.configuration; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import org.springframework.boot.autoconfigure.AutoConfigureBefore; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.cloud.netflix.ribbon.RibbonClientConfiguration; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -import com.nepxion.discovery.plugin.strategy.adapter.DefaultDiscoveryEnabledAdapter; -import com.nepxion.discovery.plugin.strategy.adapter.DiscoveryEnabledAdapter; -import com.nepxion.discovery.plugin.strategy.constant.StrategyConstant; -import com.nepxion.discovery.plugin.strategy.wrapper.CallableWrapper; -import com.nepxion.discovery.plugin.strategy.zuul.constant.ZuulStrategyConstant; -import com.nepxion.discovery.plugin.strategy.zuul.filter.DefaultZuulStrategyRouteFilter; -import com.nepxion.discovery.plugin.strategy.zuul.filter.ZuulStrategyRouteFilter; -import com.nepxion.discovery.plugin.strategy.zuul.wrapper.DefaultCallableWrapper; - -@Configuration -@AutoConfigureBefore(RibbonClientConfiguration.class) -@ConditionalOnProperty(value = StrategyConstant.SPRING_APPLICATION_STRATEGY_CONTROL_ENABLED, matchIfMissing = true) -public class ZuulStrategyAutoConfiguration { - @Bean - @ConditionalOnMissingBean - @ConditionalOnProperty(value = ZuulStrategyConstant.SPRING_APPLICATION_STRATEGY_ZUUL_ROUTE_FILTER_ENABLED, matchIfMissing = true) - public ZuulStrategyRouteFilter zuulStrategyRouteFilter() { - return new DefaultZuulStrategyRouteFilter(); - } - - @Bean - @ConditionalOnMissingBean - public DiscoveryEnabledAdapter discoveryEnabledAdapter() { - return new DefaultDiscoveryEnabledAdapter(); - } - - @Bean - @ConditionalOnProperty(value = StrategyConstant.SPRING_APPLICATION_STRATEGY_HYSTRIX_THREADLOCAL_SUPPORTED, matchIfMissing = false) - public CallableWrapper callableWrapper() { - return new DefaultCallableWrapper(); - } -} \ No newline at end of file diff --git a/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/constant/ZuulStrategyConstant.java b/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/constant/ZuulStrategyConstant.java deleted file mode 100644 index 2d18d8e1d2..0000000000 --- a/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/constant/ZuulStrategyConstant.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.nepxion.discovery.plugin.strategy.zuul.constant; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -public class ZuulStrategyConstant { - public static final String SPRING_APPLICATION_STRATEGY_ZUUL_ROUTE_FILTER_ENABLED = "spring.application.strategy.zuul.route.filter.enabled"; - public static final String SPRING_APPLICATION_STRATEGY_ZUUL_ROUTE_FILTER_ORDER = "spring.application.strategy.zuul.route.filter.order"; - public static final String SPRING_APPLICATION_STRATEGY_ZUUL_HEADER_PRIORITY = "spring.application.strategy.zuul.header.priority"; - public static final int SPRING_APPLICATION_STRATEGY_ZUUL_ROUTE_FILTER_ORDER_VALUE = 0; -} \ No newline at end of file diff --git a/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/context/ZuulStrategyApplicationContextInitializer.java b/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/context/ZuulStrategyApplicationContextInitializer.java deleted file mode 100644 index fb9ea2d578..0000000000 --- a/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/context/ZuulStrategyApplicationContextInitializer.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.nepxion.discovery.plugin.strategy.zuul.context; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import org.springframework.context.ApplicationContextInitializer; -import org.springframework.context.ConfigurableApplicationContext; - -import com.nepxion.discovery.common.constant.DiscoveryConstant; - -public class ZuulStrategyApplicationContextInitializer implements ApplicationContextInitializer { - @Override - public void initialize(ConfigurableApplicationContext applicationContext) { - System.setProperty(DiscoveryConstant.SPRING_APPLICATION_TYPE, DiscoveryConstant.GATEWAY_TYPE); - } -} \ No newline at end of file diff --git a/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/context/ZuulStrategyContextHolder.java b/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/context/ZuulStrategyContextHolder.java deleted file mode 100644 index e5715c3013..0000000000 --- a/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/context/ZuulStrategyContextHolder.java +++ /dev/null @@ -1,85 +0,0 @@ -package com.nepxion.discovery.plugin.strategy.zuul.context; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @author Fan Yang - * @version 1.0 - */ - -import java.util.Map; - -import javax.servlet.http.HttpServletRequest; - -import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.core.env.ConfigurableEnvironment; - -import com.nepxion.discovery.plugin.strategy.constant.StrategyConstant; -import com.nepxion.discovery.plugin.strategy.context.AbstractStrategyContextHolder; -import com.nepxion.discovery.plugin.strategy.zuul.constant.ZuulStrategyConstant; -import com.netflix.zuul.context.RequestContext; - -public class ZuulStrategyContextHolder extends AbstractStrategyContextHolder { - private static final Logger LOG = LoggerFactory.getLogger(ZuulStrategyContextHolder.class); - - @Autowired - private ConfigurableEnvironment environment; - - public HttpServletRequest getRequest() { - HttpServletRequest request = ZuulStrategyContext.getCurrentContext().getRequest(); - if (request == null) { - request = RequestContext.getCurrentContext().getRequest(); - } - - return request; - } - - public Map getZuulRequestHeaders() { - Map headers = ZuulStrategyContext.getCurrentContext().getHeaders(); - if (headers == null) { - headers = RequestContext.getCurrentContext().getZuulRequestHeaders(); - } - - return headers; - } - - @Override - public String getHeader(String name) { - HttpServletRequest request = getRequest(); - if (request == null) { - LOG.warn("The HttpServletRequest object is null"); - - return null; - } - - // 如果外界也传了相同的Header,例如,从Postman传递过来的Header,当下面的变量为true,以网关设置为优先,否则以外界传值为优先 - Boolean zuulHeaderPriority = environment.getProperty(ZuulStrategyConstant.SPRING_APPLICATION_STRATEGY_ZUUL_HEADER_PRIORITY, Boolean.class, Boolean.TRUE); - Boolean providerIsolationEnabled = environment.getProperty(StrategyConstant.SPRING_APPLICATION_STRATEGY_PROVIDER_ISOLATION_ENABLED, Boolean.class, Boolean.FALSE); - - if (providerIsolationEnabled ? providerIsolationEnabled : zuulHeaderPriority) { - // 来自于Zuul Filter的Header - String header = getZuulRequestHeaders().get(name); - if (StringUtils.isEmpty(header)) { - // 来自于外界的Header - header = request.getHeader(name); - } - - return header; - } else { - // 来自于外界的Header - String header = request.getHeader(name); - if (StringUtils.isEmpty(header)) { - // 来自于Zuul Filter的Header - header = getZuulRequestHeaders().get(name); - } - - return header; - } - } -} \ No newline at end of file diff --git a/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/filter/AbstractZuulStrategyRouteFilter.java b/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/filter/AbstractZuulStrategyRouteFilter.java deleted file mode 100644 index b990b06ae0..0000000000 --- a/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/filter/AbstractZuulStrategyRouteFilter.java +++ /dev/null @@ -1,121 +0,0 @@ -package com.nepxion.discovery.plugin.strategy.zuul.filter; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import org.apache.commons.lang3.StringUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.core.env.ConfigurableEnvironment; - -import com.nepxion.discovery.common.constant.DiscoveryConstant; -import com.nepxion.discovery.plugin.framework.adapter.PluginAdapter; -import com.nepxion.discovery.plugin.strategy.constant.StrategyConstant; -import com.nepxion.discovery.plugin.strategy.context.StrategyContextHolder; -import com.nepxion.discovery.plugin.strategy.zuul.constant.ZuulStrategyConstant; -import com.netflix.zuul.ZuulFilter; - -public abstract class AbstractZuulStrategyRouteFilter extends ZuulFilter implements ZuulStrategyRouteFilter { - @Autowired - private ConfigurableEnvironment environment; - - @Autowired - protected PluginAdapter pluginAdapter; - - @Autowired - protected StrategyContextHolder strategyContextHolder; - - @Override - public String filterType() { - return "pre"; - } - - @Override - public int filterOrder() { - return environment.getProperty(ZuulStrategyConstant.SPRING_APPLICATION_STRATEGY_ZUUL_ROUTE_FILTER_ORDER, Integer.class, ZuulStrategyConstant.SPRING_APPLICATION_STRATEGY_ZUUL_ROUTE_FILTER_ORDER_VALUE); - } - - @Override - public boolean shouldFilter() { - return true; - } - - @Override - public Object run() { - Boolean interceptLogPrint = environment.getProperty(StrategyConstant.SPRING_APPLICATION_STRATEGY_INTERCEPT_LOG_PRINT, Boolean.class, Boolean.FALSE); - - if (interceptLogPrint) { - System.out.println("--------- Input Route Header Information ---------"); - printRouteHeader(); - System.out.println("--------------------------------------------------"); - } - - String routeVersion = getRouteVersion(); - String routeRegion = getRouteRegion(); - String routeAddress = getRouteAddress(); - String routeVersionWeight = getRouteVersionWeight(); - String routeRegionWeight = getRouteRegionWeight(); - - // 通过过滤器设置路由Header头部信息,并全链路传递到服务端 - // 如果外界也传了相同的Header,例如,从Postman传递过来的Header,当下面的变量为true,以网关设置为优先,否则以外界传值为优先 - Boolean zuulHeaderPriority = environment.getProperty(ZuulStrategyConstant.SPRING_APPLICATION_STRATEGY_ZUUL_HEADER_PRIORITY, Boolean.class, Boolean.TRUE); - - // 通过过滤器设置路由Header头部信息,并全链路传递到服务端 - if (StringUtils.isNotEmpty(routeVersion)) { - ZuulStrategyFilterResolver.setHeader(DiscoveryConstant.N_D_VERSION, routeVersion, zuulHeaderPriority); - } - if (StringUtils.isNotEmpty(routeRegion)) { - ZuulStrategyFilterResolver.setHeader(DiscoveryConstant.N_D_REGION, routeRegion, zuulHeaderPriority); - } - if (StringUtils.isNotEmpty(routeAddress)) { - ZuulStrategyFilterResolver.setHeader(DiscoveryConstant.N_D_ADDRESS, routeAddress, zuulHeaderPriority); - } - if (StringUtils.isNotEmpty(routeVersionWeight)) { - ZuulStrategyFilterResolver.setHeader(DiscoveryConstant.N_D_VERSION_WEIGHT, routeVersionWeight, zuulHeaderPriority); - } - if (StringUtils.isNotEmpty(routeRegionWeight)) { - ZuulStrategyFilterResolver.setHeader(DiscoveryConstant.N_D_REGION_WEIGHT, routeRegionWeight, zuulHeaderPriority); - } - - // 开启此项,将启动提供端的服务隔离机制,则传递到服务的是网关自身ServiceType, ServiceId, ServiceHost, Group - // 如果不隔离,为了调用链完整,最好外界自身传递ServiceType, ServiceId, ServiceHost, Group - Boolean providerIsolationEnabled = environment.getProperty(StrategyConstant.SPRING_APPLICATION_STRATEGY_PROVIDER_ISOLATION_ENABLED, Boolean.class, Boolean.FALSE); - - ZuulStrategyFilterResolver.setHeader(DiscoveryConstant.N_D_SERVICE_TYPE, pluginAdapter.getServiceType(), providerIsolationEnabled ? providerIsolationEnabled : zuulHeaderPriority); - ZuulStrategyFilterResolver.setHeader(DiscoveryConstant.N_D_SERVICE_ID, pluginAdapter.getServiceId(), providerIsolationEnabled ? providerIsolationEnabled : zuulHeaderPriority); - ZuulStrategyFilterResolver.setHeader(DiscoveryConstant.N_D_SERVICE_ADDRESS, pluginAdapter.getHost() + ":" + pluginAdapter.getPort(), providerIsolationEnabled ? providerIsolationEnabled : zuulHeaderPriority); - ZuulStrategyFilterResolver.setHeader(DiscoveryConstant.N_D_SERVICE_GROUP, pluginAdapter.getGroup(), providerIsolationEnabled ? providerIsolationEnabled : zuulHeaderPriority); - ZuulStrategyFilterResolver.setHeader(DiscoveryConstant.N_D_SERVICE_VERSION, pluginAdapter.getVersion(), providerIsolationEnabled ? providerIsolationEnabled : zuulHeaderPriority); - ZuulStrategyFilterResolver.setHeader(DiscoveryConstant.N_D_SERVICE_REGION, pluginAdapter.getRegion(), providerIsolationEnabled ? providerIsolationEnabled : zuulHeaderPriority); - - if (interceptLogPrint) { - System.out.println("--------- Output Route Header Information --------"); - printRouteHeader(); - System.out.println("--------------------------------------------------"); - } - - return null; - } - - private void printRouteHeader() { - System.out.println(DiscoveryConstant.N_D_SERVICE_TYPE + "=" + strategyContextHolder.getHeader(DiscoveryConstant.N_D_SERVICE_TYPE)); - System.out.println(DiscoveryConstant.N_D_SERVICE_ID + "=" + strategyContextHolder.getHeader(DiscoveryConstant.N_D_SERVICE_ID)); - System.out.println(DiscoveryConstant.N_D_SERVICE_ADDRESS + "=" + strategyContextHolder.getHeader(DiscoveryConstant.N_D_SERVICE_ADDRESS)); - System.out.println(DiscoveryConstant.N_D_SERVICE_GROUP + "=" + strategyContextHolder.getHeader(DiscoveryConstant.N_D_SERVICE_GROUP)); - System.out.println(DiscoveryConstant.N_D_SERVICE_VERSION + "=" + strategyContextHolder.getHeader(DiscoveryConstant.N_D_SERVICE_VERSION)); - System.out.println(DiscoveryConstant.N_D_SERVICE_REGION + "=" + strategyContextHolder.getHeader(DiscoveryConstant.N_D_SERVICE_REGION)); - } - - public PluginAdapter getPluginAdapter() { - return pluginAdapter; - } - - public StrategyContextHolder getStrategyContextHolder() { - return strategyContextHolder; - } -} \ No newline at end of file diff --git a/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/filter/CustomizationZuulStrategyRouteFilter.java b/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/filter/CustomizationZuulStrategyRouteFilter.java deleted file mode 100644 index 9c4b7b1013..0000000000 --- a/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/filter/CustomizationZuulStrategyRouteFilter.java +++ /dev/null @@ -1,152 +0,0 @@ -package com.nepxion.discovery.plugin.strategy.zuul.filter; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import java.util.List; -import java.util.Map; - -import org.apache.commons.lang3.StringUtils; - -import com.nepxion.discovery.common.entity.RuleEntity; -import com.nepxion.discovery.common.entity.StrategyConditionEntity; -import com.nepxion.discovery.common.entity.StrategyCustomizationEntity; -import com.nepxion.discovery.common.entity.StrategyRouteEntity; -import com.nepxion.discovery.common.entity.StrategyType; - -public class CustomizationZuulStrategyRouteFilter extends DefaultZuulStrategyRouteFilter { - // 从远程配置中心或者本地配置文件获取版本路由配置。如果是远程配置中心,则值会动态改变 - @Override - public String getRouteVersion() { - StrategyConditionEntity strategyConditionEntity = getTriggeredStrategyConditionEntity(); - if (strategyConditionEntity != null) { - String versionId = strategyConditionEntity.getVersionId(); - StrategyRouteEntity strategyRouteEntity = getTriggeredStrategyRouteEntity(versionId, StrategyType.VERSION); - if (strategyRouteEntity != null) { - return strategyRouteEntity.getValue(); - } - } - - return super.getRouteVersion(); - } - - // 从远程配置中心或者本地配置文件获取区域路由配置。如果是远程配置中心,则值会动态改变 - @Override - public String getRouteRegion() { - StrategyConditionEntity strategyConditionEntity = getTriggeredStrategyConditionEntity(); - if (strategyConditionEntity != null) { - String regionId = strategyConditionEntity.getRegionId(); - StrategyRouteEntity strategyRouteEntity = getTriggeredStrategyRouteEntity(regionId, StrategyType.REGION); - if (strategyRouteEntity != null) { - return strategyRouteEntity.getValue(); - } - } - - return super.getRouteRegion(); - } - - // 从远程配置中心或者本地配置文件获取IP地址和端口路由配置。如果是远程配置中心,则值会动态改变 - @Override - public String getRouteAddress() { - StrategyConditionEntity strategyConditionEntity = getTriggeredStrategyConditionEntity(); - if (strategyConditionEntity != null) { - String addressId = strategyConditionEntity.getAddressId(); - StrategyRouteEntity strategyRouteEntity = getTriggeredStrategyRouteEntity(addressId, StrategyType.ADDRESS); - if (strategyRouteEntity != null) { - return strategyRouteEntity.getValue(); - } - } - - return super.getRouteAddress(); - } - - // 从远程配置中心或者本地配置文件获取版本权重配置。如果是远程配置中心,则值会动态改变 - @Override - public String getRouteVersionWeight() { - StrategyConditionEntity strategyConditionEntity = getTriggeredStrategyConditionEntity(); - if (strategyConditionEntity != null) { - String versionWeightId = strategyConditionEntity.getVersionWeightId(); - StrategyRouteEntity strategyRouteEntity = getTriggeredStrategyRouteEntity(versionWeightId, StrategyType.VERSION_WEIGHT); - if (strategyRouteEntity != null) { - return strategyRouteEntity.getValue(); - } - } - - return super.getRouteVersionWeight(); - } - - // 从远程配置中心或者本地配置文件获取区域权重配置。如果是远程配置中心,则值会动态改变 - @Override - public String getRouteRegionWeight() { - StrategyConditionEntity strategyConditionEntity = getTriggeredStrategyConditionEntity(); - if (strategyConditionEntity != null) { - String regionWeightId = strategyConditionEntity.getRegionWeightId(); - StrategyRouteEntity strategyRouteEntity = getTriggeredStrategyRouteEntity(regionWeightId, StrategyType.REGION_WEIGHT); - if (strategyRouteEntity != null) { - return strategyRouteEntity.getValue(); - } - } - - return super.getRouteRegionWeight(); - } - - private StrategyRouteEntity getTriggeredStrategyRouteEntity(String id, StrategyType type) { - if (StringUtils.isEmpty(id)) { - return null; - } - - RuleEntity ruleEntity = pluginAdapter.getRule(); - if (ruleEntity != null) { - StrategyCustomizationEntity strategyCustomizationEntity = ruleEntity.getStrategyCustomizationEntity(); - if (strategyCustomizationEntity != null) { - List strategyRouteEntityList = strategyCustomizationEntity.getStrategyRouteEntityList(); - for (StrategyRouteEntity strategyRouteEntity : strategyRouteEntityList) { - if (StringUtils.equals(strategyRouteEntity.getId(), id) && strategyRouteEntity.getType() == type) { - return strategyRouteEntity; - } - } - } - } - - return null; - } - - private StrategyConditionEntity getTriggeredStrategyConditionEntity() { - RuleEntity ruleEntity = pluginAdapter.getRule(); - if (ruleEntity != null) { - StrategyCustomizationEntity strategyCustomizationEntity = ruleEntity.getStrategyCustomizationEntity(); - if (strategyCustomizationEntity != null) { - List strategyConditionEntityList = strategyCustomizationEntity.getStrategyConditionEntityList(); - for (StrategyConditionEntity strategyConditionEntity : strategyConditionEntityList) { - boolean isTriggered = isTriggered(strategyConditionEntity); - if (isTriggered) { - return strategyConditionEntity; - } - } - } - } - - return null; - } - - private boolean isTriggered(StrategyConditionEntity strategyConditionEntity) { - Map headerMap = strategyConditionEntity.getHeaderMap(); - for (Map.Entry entry : headerMap.entrySet()) { - String headerName = entry.getKey(); - String headerValue = entry.getValue(); - - String value = strategyContextHolder.getHeader(headerName); - if (!StringUtils.equals(headerValue, value)) { - return false; - } - } - - return true; - } -} \ No newline at end of file diff --git a/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/filter/DefaultZuulStrategyRouteFilter.java b/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/filter/DefaultZuulStrategyRouteFilter.java deleted file mode 100644 index 8f820fc9f2..0000000000 --- a/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/filter/DefaultZuulStrategyRouteFilter.java +++ /dev/null @@ -1,85 +0,0 @@ -package com.nepxion.discovery.plugin.strategy.zuul.filter; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import com.nepxion.discovery.common.entity.RuleEntity; -import com.nepxion.discovery.common.entity.StrategyEntity; - -public class DefaultZuulStrategyRouteFilter extends AbstractZuulStrategyRouteFilter { - // 从远程配置中心或者本地配置文件获取版本路由配置。如果是远程配置中心,则值会动态改变 - @Override - public String getRouteVersion() { - RuleEntity ruleEntity = pluginAdapter.getRule(); - if (ruleEntity != null) { - StrategyEntity strategyEntity = ruleEntity.getStrategyEntity(); - if (strategyEntity != null) { - return strategyEntity.getVersionValue(); - } - } - - return null; - } - - // 从远程配置中心或者本地配置文件获取区域路由配置。如果是远程配置中心,则值会动态改变 - @Override - public String getRouteRegion() { - RuleEntity ruleEntity = pluginAdapter.getRule(); - if (ruleEntity != null) { - StrategyEntity strategyEntity = ruleEntity.getStrategyEntity(); - if (strategyEntity != null) { - return strategyEntity.getRegionValue(); - } - } - - return null; - } - - // 从远程配置中心或者本地配置文件获取IP地址和端口路由配置。如果是远程配置中心,则值会动态改变 - @Override - public String getRouteAddress() { - RuleEntity ruleEntity = pluginAdapter.getRule(); - if (ruleEntity != null) { - StrategyEntity strategyEntity = ruleEntity.getStrategyEntity(); - if (strategyEntity != null) { - return strategyEntity.getAddressValue(); - } - } - - return null; - } - - // 从远程配置中心或者本地配置文件获取版本权重配置。如果是远程配置中心,则值会动态改变 - @Override - public String getRouteVersionWeight() { - RuleEntity ruleEntity = pluginAdapter.getRule(); - if (ruleEntity != null) { - StrategyEntity strategyEntity = ruleEntity.getStrategyEntity(); - if (strategyEntity != null) { - return strategyEntity.getVersionWeightValue(); - } - } - - return null; - } - - // 从远程配置中心或者本地配置文件获取区域权重配置。如果是远程配置中心,则值会动态改变 - @Override - public String getRouteRegionWeight() { - RuleEntity ruleEntity = pluginAdapter.getRule(); - if (ruleEntity != null) { - StrategyEntity strategyEntity = ruleEntity.getStrategyEntity(); - if (strategyEntity != null) { - return strategyEntity.getRegionWeightValue(); - } - } - - return null; - } -} \ No newline at end of file diff --git a/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/filter/ZuulStrategyFilterResolver.java b/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/filter/ZuulStrategyFilterResolver.java deleted file mode 100644 index 0a138a94f9..0000000000 --- a/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/filter/ZuulStrategyFilterResolver.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.nepxion.discovery.plugin.strategy.zuul.filter; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import org.apache.commons.lang3.StringUtils; - -import com.netflix.zuul.context.RequestContext; - -public class ZuulStrategyFilterResolver { - public static void setHeader(String headerName, String headerValue, Boolean zuulHeaderPriority) { - if (StringUtils.isEmpty(headerValue)) { - return; - } - - RequestContext context = RequestContext.getCurrentContext(); - - if (zuulHeaderPriority) { - // 通过Zuul Filter的Header直接把外界的Header替换掉,并传递 - context.addZuulRequestHeader(headerName, headerValue); - } else { - // 在外界的Header不存在的前提下,通过Zuul Filter的Header传递 - String header = context.getRequest().getHeader(headerName); - if (StringUtils.isEmpty(header)) { - context.addZuulRequestHeader(headerName, headerValue); - } - } - } -} \ No newline at end of file diff --git a/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/filter/ZuulStrategyRouteFilter.java b/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/filter/ZuulStrategyRouteFilter.java deleted file mode 100644 index be8c462283..0000000000 --- a/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/filter/ZuulStrategyRouteFilter.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.nepxion.discovery.plugin.strategy.zuul.filter; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -public interface ZuulStrategyRouteFilter { - String getRouteVersion(); - - String getRouteRegion(); - - String getRouteAddress(); - - String getRouteVersionWeight(); - - String getRouteRegionWeight(); -} \ No newline at end of file diff --git a/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/wrapper/DefaultCallableWrapper.java b/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/wrapper/DefaultCallableWrapper.java deleted file mode 100644 index ffb5de096a..0000000000 --- a/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/wrapper/DefaultCallableWrapper.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.nepxion.discovery.plugin.strategy.zuul.wrapper; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @author Hao Huang - * @version 1.0 - */ - -import java.util.Map; -import java.util.concurrent.Callable; - -import javax.servlet.http.HttpServletRequest; - -import com.nepxion.discovery.plugin.strategy.wrapper.CallableWrapper; -import com.nepxion.discovery.plugin.strategy.zuul.context.ZuulStrategyContext; -import com.netflix.zuul.context.RequestContext; - -public class DefaultCallableWrapper implements CallableWrapper { - @Override - public Callable wrapCallable(Callable delegate) { - HttpServletRequest request = RequestContext.getCurrentContext().getRequest(); - Map headers = RequestContext.getCurrentContext().getZuulRequestHeaders(); - - return new Callable() { - @Override - public T call() throws Exception { - try { - ZuulStrategyContext.getCurrentContext().setRequest(request); - ZuulStrategyContext.getCurrentContext().setHeaders(headers); - - return delegate.call(); - } finally { - ZuulStrategyContext.clearCurrentContext(); - } - } - }; - } -} \ No newline at end of file diff --git a/discovery-plugin-strategy-starter-zuul/src/main/resources/META-INF/spring.factories b/discovery-plugin-strategy-starter-zuul/src/main/resources/META-INF/spring.factories deleted file mode 100644 index 16445fbdc6..0000000000 --- a/discovery-plugin-strategy-starter-zuul/src/main/resources/META-INF/spring.factories +++ /dev/null @@ -1,7 +0,0 @@ -org.springframework.context.ApplicationContextInitializer=\ -com.nepxion.discovery.plugin.strategy.zuul.context.ZuulStrategyApplicationContextInitializer - -org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ -com.nepxion.discovery.plugin.strategy.configuration.StrategyAutoConfiguration,\ -com.nepxion.discovery.plugin.strategy.zuul.configuration.ZuulStrategyAutoConfiguration,\ -com.nepxion.discovery.plugin.strategy.zuul.configuration.ZuulStrategyContextAutoConfiguration \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/pom.xml b/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/pom.xml new file mode 100644 index 0000000000..475bfd4838 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/pom.xml @@ -0,0 +1,71 @@ + + + discovery-plugin-strategy-starter-gateway + Nepxion Discovery Plugin Strategy Starter Gateway + jar + 4.0.0 + Nepxion Discovery is a solution for Spring Cloud with blue green, gray, weight, limitation, circuit breaker, degrade, isolation, monitor, tracing, dye, failover, async agent + http://www.nepxion.com + + + com.nepxion + discovery-plugin-strategy + 6.23.0 + + + + + ${project.groupId} + discovery-plugin-strategy-starter + + + + ${project.groupId} + discovery-common-nacos + provided + + + + ${project.groupId} + discovery-common-apollo + provided + + + + ${project.groupId} + discovery-common-redis + provided + + + + ${project.groupId} + discovery-common-zookeeper + provided + + + + ${project.groupId} + discovery-common-consul + provided + + + + ${project.groupId} + discovery-common-etcd + provided + + + + org.springframework.cloud + spring-cloud-starter-gateway + + + + org.apache.skywalking + apm-agent-core + ${skywalking.version} + provided + + + \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/configuration/GatewayStrategyAutoConfiguration.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/configuration/GatewayStrategyAutoConfiguration.java new file mode 100644 index 0000000000..c1d8f952e6 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/configuration/GatewayStrategyAutoConfiguration.java @@ -0,0 +1,167 @@ +package com.nepxion.discovery.plugin.strategy.gateway.configuration; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @author Ning Zhang + * @version 1.0 + */ + +import org.apache.skywalking.apm.agent.core.context.TracingContext; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.AutoConfigureBefore; +import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.cloud.netflix.ribbon.RibbonClientConfiguration; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.env.ConfigurableEnvironment; + +import com.nepxion.discovery.common.apollo.proccessor.ApolloProcessor; +import com.nepxion.discovery.common.consul.proccessor.ConsulProcessor; +import com.nepxion.discovery.common.etcd.proccessor.EtcdProcessor; +import com.nepxion.discovery.common.nacos.proccessor.NacosProcessor; +import com.nepxion.discovery.common.redis.proccessor.RedisProcessor; +import com.nepxion.discovery.common.zookeeper.proccessor.ZookeeperProcessor; +import com.nepxion.discovery.plugin.strategy.constant.StrategyConstant; +import com.nepxion.discovery.plugin.strategy.gateway.constant.GatewayStrategyConstant; +import com.nepxion.discovery.plugin.strategy.gateway.context.GatewayStrategyContextListener; +import com.nepxion.discovery.plugin.strategy.gateway.filter.DefaultGatewayStrategyClearFilter; +import com.nepxion.discovery.plugin.strategy.gateway.filter.DefaultGatewayStrategyRouteFilter; +import com.nepxion.discovery.plugin.strategy.gateway.filter.GatewayStrategyClearFilter; +import com.nepxion.discovery.plugin.strategy.gateway.filter.GatewayStrategyRouteFilter; +import com.nepxion.discovery.plugin.strategy.gateway.filter.SkyWalkingGatewayStrategyFilter; +import com.nepxion.discovery.plugin.strategy.gateway.monitor.DefaultGatewayStrategyMonitor; +import com.nepxion.discovery.plugin.strategy.gateway.monitor.GatewayStrategyMonitor; +import com.nepxion.discovery.plugin.strategy.gateway.processor.GatewayStrategyRouteApolloProcessor; +import com.nepxion.discovery.plugin.strategy.gateway.processor.GatewayStrategyRouteConsulProcessor; +import com.nepxion.discovery.plugin.strategy.gateway.processor.GatewayStrategyRouteEtcdProcessor; +import com.nepxion.discovery.plugin.strategy.gateway.processor.GatewayStrategyRouteNacosProcessor; +import com.nepxion.discovery.plugin.strategy.gateway.processor.GatewayStrategyRouteRedisProcessor; +import com.nepxion.discovery.plugin.strategy.gateway.processor.GatewayStrategyRouteZookeeperProcessor; +import com.nepxion.discovery.plugin.strategy.gateway.route.DefaultGatewayStrategyRoute; +import com.nepxion.discovery.plugin.strategy.gateway.route.GatewayStrategyRoute; +import com.nepxion.discovery.plugin.strategy.gateway.wrapper.DefaultGatewayStrategyCallableWrapper; +import com.nepxion.discovery.plugin.strategy.gateway.wrapper.GatewayStrategyCallableWrapper; + +@Configuration +@AutoConfigureBefore(RibbonClientConfiguration.class) +public class GatewayStrategyAutoConfiguration { + @Bean + @ConditionalOnMissingBean + public GatewayStrategyRouteFilter gatewayStrategyRouteFilter() { + return new DefaultGatewayStrategyRouteFilter(); + } + + @Bean + @ConditionalOnMissingBean + public GatewayStrategyClearFilter gatewayStrategyClearFilter() { + return new DefaultGatewayStrategyClearFilter(); + } + + @Bean + @ConditionalOnMissingBean + @ConditionalOnProperty(value = StrategyConstant.SPRING_APPLICATION_STRATEGY_MONITOR_ENABLED, matchIfMissing = false) + public GatewayStrategyMonitor gatewayStrategyMonitor() { + return new DefaultGatewayStrategyMonitor(); + } + + @Bean + @ConditionalOnMissingBean + public GatewayStrategyRoute gatewayStrategyRoute() { + return new DefaultGatewayStrategyRoute(); + } + + @Bean + @ConditionalOnMissingBean + @ConditionalOnProperty(value = StrategyConstant.SPRING_APPLICATION_STRATEGY_HYSTRIX_THREADLOCAL_SUPPORTED, matchIfMissing = false) + public GatewayStrategyCallableWrapper gatewayStrategyCallableWrapper() { + return new DefaultGatewayStrategyCallableWrapper(); + } + + @Bean + public GatewayStrategyContextListener gatewayStrategyContextListener() { + return new GatewayStrategyContextListener(); + } + + @ConditionalOnClass(NacosProcessor.class) + @ConditionalOnProperty(value = GatewayStrategyConstant.SPRING_APPLICATION_STRATEGY_GATEWAY_DYNAMIC_ROUTE_ENABLED, matchIfMissing = false) + protected static class GatewayRouteNacosConfiguration { + @Bean + @ConditionalOnProperty(value = "spring.cloud.gateway.discovery.locator.enabled", havingValue = "false", matchIfMissing = true) + public NacosProcessor gatewayStrategyRouteNacosProcessor() { + return new GatewayStrategyRouteNacosProcessor(); + } + } + + @ConditionalOnClass(ApolloProcessor.class) + @ConditionalOnProperty(value = GatewayStrategyConstant.SPRING_APPLICATION_STRATEGY_GATEWAY_DYNAMIC_ROUTE_ENABLED, matchIfMissing = false) + protected static class GatewayRouteApolloConfiguration { + @Bean + @ConditionalOnProperty(value = "spring.cloud.gateway.discovery.locator.enabled", havingValue = "false", matchIfMissing = true) + public ApolloProcessor gatewayStrategyRouteApolloProcessor() { + return new GatewayStrategyRouteApolloProcessor(); + } + } + + @ConditionalOnClass(RedisProcessor.class) + @ConditionalOnProperty(value = GatewayStrategyConstant.SPRING_APPLICATION_STRATEGY_GATEWAY_DYNAMIC_ROUTE_ENABLED, matchIfMissing = false) + protected static class GatewayRouteRedisConfiguration { + @Bean + @ConditionalOnProperty(value = "spring.cloud.gateway.discovery.locator.enabled", havingValue = "false", matchIfMissing = true) + public RedisProcessor gatewayStrategyRouteRedisProcessor() { + return new GatewayStrategyRouteRedisProcessor(); + } + } + + @ConditionalOnClass(ZookeeperProcessor.class) + @ConditionalOnProperty(value = GatewayStrategyConstant.SPRING_APPLICATION_STRATEGY_GATEWAY_DYNAMIC_ROUTE_ENABLED, matchIfMissing = false) + protected static class GatewayRouteZookeeperConfiguration { + @Bean + @ConditionalOnProperty(value = "spring.cloud.gateway.discovery.locator.enabled", havingValue = "false", matchIfMissing = true) + public ZookeeperProcessor gatewayStrategyRouteZookeeperProcessor() { + return new GatewayStrategyRouteZookeeperProcessor(); + } + } + + @ConditionalOnClass(ConsulProcessor.class) + @ConditionalOnProperty(value = GatewayStrategyConstant.SPRING_APPLICATION_STRATEGY_GATEWAY_DYNAMIC_ROUTE_ENABLED, matchIfMissing = false) + protected static class GatewayRouteConsulConfiguration { + @Bean + @ConditionalOnProperty(value = "spring.cloud.gateway.discovery.locator.enabled", havingValue = "false", matchIfMissing = true) + public ConsulProcessor gatewayStrategyRouteConsulProcessor() { + return new GatewayStrategyRouteConsulProcessor(); + } + } + + @ConditionalOnClass(EtcdProcessor.class) + @ConditionalOnProperty(value = GatewayStrategyConstant.SPRING_APPLICATION_STRATEGY_GATEWAY_DYNAMIC_ROUTE_ENABLED, matchIfMissing = false) + protected static class GatewayRouteEtcdConfiguration { + @Bean + @ConditionalOnProperty(value = "spring.cloud.gateway.discovery.locator.enabled", havingValue = "false", matchIfMissing = true) + public EtcdProcessor gatewayStrategyRouteEtcdProcessor() { + return new GatewayStrategyRouteEtcdProcessor(); + } + } + + @ConditionalOnClass(TracingContext.class) + protected static class SkywalkingStrategyConfiguration { + @Autowired + private ConfigurableEnvironment environment; + + @Bean + @ConditionalOnProperty(value = StrategyConstant.SPRING_APPLICATION_STRATEGY_MONITOR_ENABLED, matchIfMissing = false) + public SkyWalkingGatewayStrategyFilter skyWalkingGatewayStrategyFilter() { + Boolean skywalkingTraceIdEnabled = environment.getProperty(GatewayStrategyConstant.SPRING_APPLICATION_STRATEGY_GATEWAY_SKYWALKING_TRACEID_ENABLED, Boolean.class, Boolean.TRUE); + if (skywalkingTraceIdEnabled) { + return new SkyWalkingGatewayStrategyFilter(); + } + + return null; + } + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/configuration/GatewayStrategyContextAutoConfiguration.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/configuration/GatewayStrategyContextAutoConfiguration.java similarity index 88% rename from discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/configuration/GatewayStrategyContextAutoConfiguration.java rename to discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/configuration/GatewayStrategyContextAutoConfiguration.java index 2cd6d74b39..b68a7195be 100644 --- a/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/configuration/GatewayStrategyContextAutoConfiguration.java +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/configuration/GatewayStrategyContextAutoConfiguration.java @@ -10,6 +10,7 @@ */ import org.springframework.boot.autoconfigure.AutoConfigureBefore; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.cloud.netflix.ribbon.RibbonClientConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -20,6 +21,7 @@ @AutoConfigureBefore(RibbonClientConfiguration.class) public class GatewayStrategyContextAutoConfiguration { @Bean + @ConditionalOnMissingBean public GatewayStrategyContextHolder gatewayStrategyContextHolder() { return new GatewayStrategyContextHolder(); } diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/constant/GatewayStrategyConstant.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/constant/GatewayStrategyConstant.java new file mode 100644 index 0000000000..82e81080f3 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/constant/GatewayStrategyConstant.java @@ -0,0 +1,20 @@ +package com.nepxion.discovery.plugin.strategy.gateway.constant; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +public class GatewayStrategyConstant { + public static final String SPRING_APPLICATION_STRATEGY_GATEWAY_ROUTE_FILTER_ORDER = "spring.application.strategy.gateway.route.filter.order"; + public static final String SPRING_APPLICATION_STRATEGY_GATEWAY_HEADER_PRIORITY = "spring.application.strategy.gateway.header.priority"; + public static final String SPRING_APPLICATION_STRATEGY_GATEWAY_ORIGINAL_HEADER_IGNORED = "spring.application.strategy.gateway.original.header.ignored"; + public static final String SPRING_APPLICATION_STRATEGY_GATEWAY_CORE_HEADER_TRANSMISSION_ENABLED = "spring.application.strategy.gateway.core.header.transmission.enabled"; + public static final String SPRING_APPLICATION_STRATEGY_GATEWAY_DYNAMIC_ROUTE_ENABLED = "spring.application.strategy.gateway.dynamic.route.enabled"; + public static final String SPRING_APPLICATION_STRATEGY_GATEWAY_SKYWALKING_TRACEID_ENABLED = "spring.application.strategy.gateway.skywalking.traceid.enabled"; + public static final int SPRING_APPLICATION_STRATEGY_GATEWAY_ROUTE_FILTER_ORDER_VALUE = 9000; +} \ No newline at end of file diff --git a/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/context/GatewayStrategyContext.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/context/GatewayStrategyContext.java similarity index 100% rename from discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/context/GatewayStrategyContext.java rename to discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/context/GatewayStrategyContext.java diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/context/GatewayStrategyContextHolder.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/context/GatewayStrategyContextHolder.java new file mode 100644 index 0000000000..cdf2f9121e --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/context/GatewayStrategyContextHolder.java @@ -0,0 +1,105 @@ +package com.nepxion.discovery.plugin.strategy.gateway.context; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.net.URI; +import java.util.Collections; +import java.util.Enumeration; +import java.util.Set; + +import org.springframework.http.HttpCookie; +import org.springframework.http.server.reactive.ServerHttpRequest; +import org.springframework.web.server.ServerWebExchange; + +import com.nepxion.discovery.plugin.strategy.context.AbstractStrategyContextHolder; + +public class GatewayStrategyContextHolder extends AbstractStrategyContextHolder { + public ServerWebExchange getExchange() { + return GatewayStrategyContext.getCurrentContext().getExchange(); + } + + public ServerHttpRequest getServerHttpRequest() { + ServerWebExchange exchange = getExchange(); + if (exchange == null) { + // LOG.warn("The ServerWebExchange object is lost for thread switched, or it is got before context filter probably"); + + return null; + } + + ServerHttpRequest request = exchange.getRequest(); + if (request == null) { + // LOG.warn("The ServerHttpRequest object is lost for thread switched, or it is got before context filter probably"); + + return null; + } + + return request; + } + + @Override + public Enumeration getHeaderNames() { + ServerHttpRequest request = getServerHttpRequest(); + if (request == null) { + return null; + } + + Set headerNameSet = request.getHeaders().keySet(); + + return Collections.enumeration(headerNameSet); + } + + @Override + public String getHeader(String name) { + ServerHttpRequest request = getServerHttpRequest(); + if (request == null) { + return null; + } + + return request.getHeaders().getFirst(name); + } + + @Override + public String getParameter(String name) { + ServerHttpRequest request = getServerHttpRequest(); + if (request == null) { + return null; + } + + return request.getQueryParams().getFirst(name); + } + + public HttpCookie getHttpCookie(String name) { + ServerHttpRequest request = getServerHttpRequest(); + if (request == null) { + return null; + } + + return request.getCookies().getFirst(name); + } + + @Override + public String getCookie(String name) { + HttpCookie cookie = getHttpCookie(name); + if (cookie != null) { + return cookie.getValue(); + } + + return null; + } + + public URI getURI() { + ServerHttpRequest request = getServerHttpRequest(); + if (request == null) { + return null; + } + + return request.getURI(); + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/context/GatewayStrategyContextListener.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/context/GatewayStrategyContextListener.java new file mode 100644 index 0000000000..badf951aa3 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/context/GatewayStrategyContextListener.java @@ -0,0 +1,26 @@ +package com.nepxion.discovery.plugin.strategy.gateway.context; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.context.ApplicationListener; +import org.springframework.context.event.ContextRefreshedEvent; + +public class GatewayStrategyContextListener implements ApplicationListener { + private static final Logger LOG = LoggerFactory.getLogger(GatewayStrategyContextListener.class); + + @Override + public void onApplicationEvent(ContextRefreshedEvent event) { + // 异步调用下,第一次启动在某些情况下可能存在丢失上下文的问题 + LOG.info("Initialize Gateway Strategy Context after Application started..."); + GatewayStrategyContext.getCurrentContext(); + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/context/GatewayStrategyEnvironmentPostProcessor.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/context/GatewayStrategyEnvironmentPostProcessor.java new file mode 100644 index 0000000000..66c8c80a07 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/context/GatewayStrategyEnvironmentPostProcessor.java @@ -0,0 +1,35 @@ +package com.nepxion.discovery.plugin.strategy.gateway.context; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.env.EnvironmentPostProcessor; +import org.springframework.core.Ordered; +import org.springframework.core.env.ConfigurableEnvironment; + +import com.nepxion.discovery.common.constant.DiscoveryConstant; +import com.nepxion.discovery.common.entity.GatewayType; +import com.nepxion.discovery.common.entity.ServiceType; +import com.nepxion.discovery.common.util.EnvironmentUtil; + +public class GatewayStrategyEnvironmentPostProcessor implements EnvironmentPostProcessor, Ordered { + @Override + public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { + if (EnvironmentUtil.isStandardEnvironment(environment)) { + System.setProperty(DiscoveryConstant.SPRING_APPLICATION_TYPE, ServiceType.GATEWAY.toString()); + System.setProperty(DiscoveryConstant.SPRING_APPLICATION_GATEWAY_TYPE, GatewayType.SPRING_CLOUD_GATEWAY.toString()); + } + } + + @Override + public int getOrder() { + return Ordered.HIGHEST_PRECEDENCE; + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/event/GatewayStrategyRouteAddedEvent.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/event/GatewayStrategyRouteAddedEvent.java new file mode 100644 index 0000000000..e3cbb9f9ae --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/event/GatewayStrategyRouteAddedEvent.java @@ -0,0 +1,28 @@ +package com.nepxion.discovery.plugin.strategy.gateway.event; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.io.Serializable; + +import com.nepxion.discovery.common.entity.GatewayStrategyRouteEntity; + +public class GatewayStrategyRouteAddedEvent implements Serializable { + private static final long serialVersionUID = -5614788825646267155L; + + private GatewayStrategyRouteEntity gatewayStrategyRouteEntity; + + public GatewayStrategyRouteAddedEvent(GatewayStrategyRouteEntity gatewayStrategyRouteEntity) { + this.gatewayStrategyRouteEntity = gatewayStrategyRouteEntity; + } + + public GatewayStrategyRouteEntity getGatewayStrategyRouteEntity() { + return gatewayStrategyRouteEntity; + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/event/GatewayStrategyRouteDeletedEvent.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/event/GatewayStrategyRouteDeletedEvent.java new file mode 100644 index 0000000000..80a6b2212b --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/event/GatewayStrategyRouteDeletedEvent.java @@ -0,0 +1,26 @@ +package com.nepxion.discovery.plugin.strategy.gateway.event; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.io.Serializable; + +public class GatewayStrategyRouteDeletedEvent implements Serializable { + private static final long serialVersionUID = 9073567694566348300L; + + private String routeId; + + public GatewayStrategyRouteDeletedEvent(String routeId) { + this.routeId = routeId; + } + + public String getRouteId() { + return routeId; + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/event/GatewayStrategyRouteModifiedEvent.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/event/GatewayStrategyRouteModifiedEvent.java new file mode 100644 index 0000000000..a76bfce5a8 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/event/GatewayStrategyRouteModifiedEvent.java @@ -0,0 +1,28 @@ +package com.nepxion.discovery.plugin.strategy.gateway.event; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.io.Serializable; + +import com.nepxion.discovery.common.entity.GatewayStrategyRouteEntity; + +public class GatewayStrategyRouteModifiedEvent implements Serializable { + private static final long serialVersionUID = -64955673371333231L; + + private GatewayStrategyRouteEntity gatewayStrategyRouteEntity; + + public GatewayStrategyRouteModifiedEvent(GatewayStrategyRouteEntity gatewayStrategyRouteEntity) { + this.gatewayStrategyRouteEntity = gatewayStrategyRouteEntity; + } + + public GatewayStrategyRouteEntity getGatewayStrategyRouteEntity() { + return gatewayStrategyRouteEntity; + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/event/GatewayStrategyRouteUpdatedAllEvent.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/event/GatewayStrategyRouteUpdatedAllEvent.java new file mode 100644 index 0000000000..77b62e29e4 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/event/GatewayStrategyRouteUpdatedAllEvent.java @@ -0,0 +1,29 @@ +package com.nepxion.discovery.plugin.strategy.gateway.event; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.io.Serializable; +import java.util.List; + +import com.nepxion.discovery.common.entity.GatewayStrategyRouteEntity; + +public class GatewayStrategyRouteUpdatedAllEvent implements Serializable { + private static final long serialVersionUID = -153096630379952734L; + + private List gatewayStrategyRouteEntityList; + + public GatewayStrategyRouteUpdatedAllEvent(List gatewayStrategyRouteEntityList) { + this.gatewayStrategyRouteEntityList = gatewayStrategyRouteEntityList; + } + + public List getGatewayStrategyRouteEntityList() { + return gatewayStrategyRouteEntityList; + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/filter/AbstractGatewayStrategyRouteFilter.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/filter/AbstractGatewayStrategyRouteFilter.java new file mode 100644 index 0000000000..2ddaadbf57 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/filter/AbstractGatewayStrategyRouteFilter.java @@ -0,0 +1,272 @@ +package com.nepxion.discovery.plugin.strategy.gateway.filter; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import reactor.core.publisher.Mono; + +import java.util.Map; + +import org.apache.commons.collections4.MapUtils; +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.cloud.gateway.filter.GatewayFilterChain; +import org.springframework.http.server.reactive.ServerHttpRequest; +import org.springframework.web.server.ServerWebExchange; + +import com.nepxion.discovery.common.constant.DiscoveryConstant; +import com.nepxion.discovery.plugin.framework.adapter.PluginAdapter; +import com.nepxion.discovery.plugin.strategy.gateway.constant.GatewayStrategyConstant; +import com.nepxion.discovery.plugin.strategy.gateway.context.GatewayStrategyContext; +import com.nepxion.discovery.plugin.strategy.gateway.monitor.GatewayStrategyMonitor; +import com.nepxion.discovery.plugin.strategy.wrapper.StrategyWrapper; + +public abstract class AbstractGatewayStrategyRouteFilter implements GatewayStrategyRouteFilter { + @Autowired + protected PluginAdapter pluginAdapter; + + @Autowired + protected StrategyWrapper strategyWrapper; + + @Autowired(required = false) + protected GatewayStrategyMonitor gatewayStrategyMonitor; + + // 如果外界也传了相同的Header,例如,从Postman传递过来的Header,当下面的变量为true,以网关设置为优先,否则以外界传值为优先 + @Value("${" + GatewayStrategyConstant.SPRING_APPLICATION_STRATEGY_GATEWAY_HEADER_PRIORITY + ":true}") + protected Boolean gatewayHeaderPriority; + + // 当以网关设置为优先的时候,网关未配置Header,而外界配置了Header,仍旧忽略外界的Header + @Value("${" + GatewayStrategyConstant.SPRING_APPLICATION_STRATEGY_GATEWAY_ORIGINAL_HEADER_IGNORED + ":true}") + protected Boolean gatewayOriginalHeaderIgnored; + + // Gateway上核心策略Header是否传递。当全局订阅启动时,可以关闭核心策略Header传递,这样可以节省传递数据的大小,一定程度上可以提升性能 + // 核心策略Header指n-d-开头的Header(不包括n-d-env,因为环境路由隔离,必须传递该Header),不包括n-d-service开头的Header + @Value("${" + GatewayStrategyConstant.SPRING_APPLICATION_STRATEGY_GATEWAY_CORE_HEADER_TRANSMISSION_ENABLED + ":true}") + protected Boolean gatewayCoreHeaderTransmissionEnabled; + + @Value("${" + GatewayStrategyConstant.SPRING_APPLICATION_STRATEGY_GATEWAY_ROUTE_FILTER_ORDER + ":" + GatewayStrategyConstant.SPRING_APPLICATION_STRATEGY_GATEWAY_ROUTE_FILTER_ORDER_VALUE + "}") + protected Integer filterOrder; + + @Override + public int getOrder() { + return filterOrder; + } + + @Override + public Mono filter(ServerWebExchange exchange, GatewayFilterChain chain) { + // 把ServerWebExchange放入ThreadLocal中 + GatewayStrategyContext.getCurrentContext().setExchange(exchange); + + // 通过过滤器设置路由Header头部信息,并全链路传递到服务端 + ServerHttpRequest request = exchange.getRequest(); + ServerHttpRequest.Builder requestBuilder = request.mutate(); + + // 处理内部Header的转发 + applyInnerHeader(request, requestBuilder); + + // 处理外部Header的转发 + applyOuterHeader(request, requestBuilder); + + // 调用链监控 + if (gatewayStrategyMonitor != null) { + gatewayStrategyMonitor.monitor(exchange); + } + + // 拦截侦测请求 + String path = request.getPath().toString(); + if (path.contains(DiscoveryConstant.INSPECTOR_ENDPOINT_URL)) { + GatewayStrategyFilterResolver.setHeader(request, requestBuilder, DiscoveryConstant.INSPECTOR_ENDPOINT_HEADER, pluginAdapter.getPluginInfo(null), true); + } + + ServerHttpRequest newRequest = requestBuilder.build(); + ServerWebExchange newExchange = exchange.mutate().request(newRequest).build(); + + // 把新的ServerWebExchange放入ThreadLocal中 + GatewayStrategyContext.getCurrentContext().setExchange(newExchange); + + return chain.filter(newExchange); + } + + // 处理内部Header的转发,即把本地服务的相关属性封装成Header转发到下游服务去 + private void applyInnerHeader(ServerHttpRequest request, ServerHttpRequest.Builder requestBuilder) { + // 设置本地组名到Header中,并全链路传递 + // 对于服务A -> 网关 -> 服务B调用链 + // 域网关下(gatewayHeaderPriority=true),只传递网关自身的group,不传递上游服务A的group,起到基于组的网关端服务调用隔离 + // 非域网关下(gatewayHeaderPriority=false),优先传递上游服务A的group,基于组的网关端服务调用隔离不生效,但可以实现基于相关参数的熔断限流等功能 + GatewayStrategyFilterResolver.setHeader(request, requestBuilder, DiscoveryConstant.N_D_SERVICE_GROUP, pluginAdapter.getGroup(), gatewayHeaderPriority); + + // 网关只负责传递上游服务A的相关参数(例如:serviceId),不传递自身的参数,实现基于相关参数的熔断限流等功能。即gatewayHeaderPriority为false + GatewayStrategyFilterResolver.setHeader(request, requestBuilder, DiscoveryConstant.N_D_SERVICE_TYPE, pluginAdapter.getServiceType(), false); + String serviceAppId = pluginAdapter.getServiceAppId(); + if (StringUtils.isNotEmpty(serviceAppId)) { + GatewayStrategyFilterResolver.setHeader(request, requestBuilder, DiscoveryConstant.N_D_SERVICE_APP_ID, serviceAppId, false); + } + GatewayStrategyFilterResolver.setHeader(request, requestBuilder, DiscoveryConstant.N_D_SERVICE_ID, pluginAdapter.getServiceId(), false); + GatewayStrategyFilterResolver.setHeader(request, requestBuilder, DiscoveryConstant.N_D_SERVICE_ADDRESS, pluginAdapter.getHost() + ":" + pluginAdapter.getPort(), false); + String version = pluginAdapter.getVersion(); + if (StringUtils.isNotEmpty(version) && !StringUtils.equals(version, DiscoveryConstant.DEFAULT)) { + GatewayStrategyFilterResolver.setHeader(request, requestBuilder, DiscoveryConstant.N_D_SERVICE_VERSION, version, false); + } + String region = pluginAdapter.getRegion(); + if (StringUtils.isNotEmpty(region) && !StringUtils.equals(region, DiscoveryConstant.DEFAULT)) { + GatewayStrategyFilterResolver.setHeader(request, requestBuilder, DiscoveryConstant.N_D_SERVICE_REGION, region, false); + } + String environment = pluginAdapter.getEnvironment(); + if (StringUtils.isNotEmpty(environment) && !StringUtils.equals(environment, DiscoveryConstant.DEFAULT)) { + GatewayStrategyFilterResolver.setHeader(request, requestBuilder, DiscoveryConstant.N_D_SERVICE_ENVIRONMENT, environment, false); + } + String zone = pluginAdapter.getZone(); + if (StringUtils.isNotEmpty(zone) && !StringUtils.equals(zone, DiscoveryConstant.DEFAULT)) { + GatewayStrategyFilterResolver.setHeader(request, requestBuilder, DiscoveryConstant.N_D_SERVICE_ZONE, zone, false); + } + } + + // 处理外部Header的转发,即外部服务传递过来的Header,中继转发到下游服务去 + private void applyOuterHeader(ServerHttpRequest request, ServerHttpRequest.Builder requestBuilder) { + String routeEnvironment = getRouteEnvironment(); + if (StringUtils.isNotEmpty(routeEnvironment)) { + GatewayStrategyFilterResolver.setHeader(request, requestBuilder, DiscoveryConstant.N_D_ENVIRONMENT, routeEnvironment, false); + } + + // 外置Header预先塞入 + Map externalHeaderMap = getExternalHeaderMap(); + if (MapUtils.isNotEmpty(externalHeaderMap)) { + for (Map.Entry entry : externalHeaderMap.entrySet()) { + String key = entry.getKey(); + String value = entry.getValue(); + + GatewayStrategyFilterResolver.setHeader(request, requestBuilder, key, value, gatewayHeaderPriority); + } + } + + if (gatewayCoreHeaderTransmissionEnabled) { + // 内置Header预先塞入 + Map internalHeaderMap = strategyWrapper.getHeaderMap(); + if (MapUtils.isNotEmpty(internalHeaderMap)) { + for (Map.Entry entry : internalHeaderMap.entrySet()) { + String key = entry.getKey(); + String value = entry.getValue(); + + GatewayStrategyFilterResolver.setHeader(request, requestBuilder, key, value, gatewayHeaderPriority); + } + } + + String routeVersion = getRouteVersion(); + String routeRegion = getRouteRegion(); + String routeAddress = getRouteAddress(); + String routeVersionWeight = getRouteVersionWeight(); + String routeRegionWeight = getRouteRegionWeight(); + String routeVersionPrefer = getRouteVersionPrefer(); + String routeVersionFailover = getRouteVersionFailover(); + String routeRegionTransfer = getRouteRegionTransfer(); + String routeRegionFailover = getRouteRegionFailover(); + String routeEnvironmentFailover = getRouteEnvironmentFailover(); + String routeZoneFailover = getRouteZoneFailover(); + String routeAddressFailover = getRouteAddressFailover(); + String routeIdBlacklist = getRouteIdBlacklist(); + String routeAddressBlacklist = getRouteAddressBlacklist(); + + if (StringUtils.isNotEmpty(routeVersion)) { + GatewayStrategyFilterResolver.setHeader(request, requestBuilder, DiscoveryConstant.N_D_VERSION, routeVersion, gatewayHeaderPriority); + } else { + GatewayStrategyFilterResolver.ignoreHeader(requestBuilder, DiscoveryConstant.N_D_VERSION, gatewayHeaderPriority, gatewayOriginalHeaderIgnored); + } + if (StringUtils.isNotEmpty(routeRegion)) { + GatewayStrategyFilterResolver.setHeader(request, requestBuilder, DiscoveryConstant.N_D_REGION, routeRegion, gatewayHeaderPriority); + } else { + GatewayStrategyFilterResolver.ignoreHeader(requestBuilder, DiscoveryConstant.N_D_REGION, gatewayHeaderPriority, gatewayOriginalHeaderIgnored); + } + if (StringUtils.isNotEmpty(routeAddress)) { + GatewayStrategyFilterResolver.setHeader(request, requestBuilder, DiscoveryConstant.N_D_ADDRESS, routeAddress, gatewayHeaderPriority); + } else { + GatewayStrategyFilterResolver.ignoreHeader(requestBuilder, DiscoveryConstant.N_D_ADDRESS, gatewayHeaderPriority, gatewayOriginalHeaderIgnored); + } + if (StringUtils.isNotEmpty(routeVersionWeight)) { + GatewayStrategyFilterResolver.setHeader(request, requestBuilder, DiscoveryConstant.N_D_VERSION_WEIGHT, routeVersionWeight, gatewayHeaderPriority); + } else { + GatewayStrategyFilterResolver.ignoreHeader(requestBuilder, DiscoveryConstant.N_D_VERSION_WEIGHT, gatewayHeaderPriority, gatewayOriginalHeaderIgnored); + } + if (StringUtils.isNotEmpty(routeRegionWeight)) { + GatewayStrategyFilterResolver.setHeader(request, requestBuilder, DiscoveryConstant.N_D_REGION_WEIGHT, routeRegionWeight, gatewayHeaderPriority); + } else { + GatewayStrategyFilterResolver.ignoreHeader(requestBuilder, DiscoveryConstant.N_D_REGION_WEIGHT, gatewayHeaderPriority, gatewayOriginalHeaderIgnored); + } + if (StringUtils.isNotEmpty(routeVersionPrefer)) { + GatewayStrategyFilterResolver.setHeader(request, requestBuilder, DiscoveryConstant.N_D_VERSION_PREFER, routeVersionPrefer, gatewayHeaderPriority); + } else { + GatewayStrategyFilterResolver.ignoreHeader(requestBuilder, DiscoveryConstant.N_D_VERSION_PREFER, gatewayHeaderPriority, gatewayOriginalHeaderIgnored); + } + if (StringUtils.isNotEmpty(routeVersionFailover)) { + GatewayStrategyFilterResolver.setHeader(request, requestBuilder, DiscoveryConstant.N_D_VERSION_FAILOVER, routeVersionFailover, gatewayHeaderPriority); + } else { + GatewayStrategyFilterResolver.ignoreHeader(requestBuilder, DiscoveryConstant.N_D_VERSION_FAILOVER, gatewayHeaderPriority, gatewayOriginalHeaderIgnored); + } + if (StringUtils.isNotEmpty(routeRegionTransfer)) { + GatewayStrategyFilterResolver.setHeader(request, requestBuilder, DiscoveryConstant.N_D_REGION_TRANSFER, routeRegionTransfer, gatewayHeaderPriority); + } else { + GatewayStrategyFilterResolver.ignoreHeader(requestBuilder, DiscoveryConstant.N_D_REGION_TRANSFER, gatewayHeaderPriority, gatewayOriginalHeaderIgnored); + } + if (StringUtils.isNotEmpty(routeRegionFailover)) { + GatewayStrategyFilterResolver.setHeader(request, requestBuilder, DiscoveryConstant.N_D_REGION_FAILOVER, routeRegionFailover, gatewayHeaderPriority); + } else { + GatewayStrategyFilterResolver.ignoreHeader(requestBuilder, DiscoveryConstant.N_D_REGION_FAILOVER, gatewayHeaderPriority, gatewayOriginalHeaderIgnored); + } + if (StringUtils.isNotEmpty(routeEnvironmentFailover)) { + GatewayStrategyFilterResolver.setHeader(request, requestBuilder, DiscoveryConstant.N_D_ENVIRONMENT_FAILOVER, routeEnvironmentFailover, gatewayHeaderPriority); + } else { + GatewayStrategyFilterResolver.ignoreHeader(requestBuilder, DiscoveryConstant.N_D_ENVIRONMENT_FAILOVER, gatewayHeaderPriority, gatewayOriginalHeaderIgnored); + } + if (StringUtils.isNotEmpty(routeZoneFailover)) { + GatewayStrategyFilterResolver.setHeader(request, requestBuilder, DiscoveryConstant.N_D_ZONE_FAILOVER, routeZoneFailover, gatewayHeaderPriority); + } else { + GatewayStrategyFilterResolver.ignoreHeader(requestBuilder, DiscoveryConstant.N_D_ZONE_FAILOVER, gatewayHeaderPriority, gatewayOriginalHeaderIgnored); + } + if (StringUtils.isNotEmpty(routeAddressFailover)) { + GatewayStrategyFilterResolver.setHeader(request, requestBuilder, DiscoveryConstant.N_D_ADDRESS_FAILOVER, routeAddressFailover, gatewayHeaderPriority); + } else { + GatewayStrategyFilterResolver.ignoreHeader(requestBuilder, DiscoveryConstant.N_D_ADDRESS_FAILOVER, gatewayHeaderPriority, gatewayOriginalHeaderIgnored); + } + if (StringUtils.isNotEmpty(routeIdBlacklist)) { + GatewayStrategyFilterResolver.setHeader(request, requestBuilder, DiscoveryConstant.N_D_ID_BLACKLIST, routeIdBlacklist, gatewayHeaderPriority); + } else { + GatewayStrategyFilterResolver.ignoreHeader(requestBuilder, DiscoveryConstant.N_D_ID_BLACKLIST, gatewayHeaderPriority, gatewayOriginalHeaderIgnored); + } + if (StringUtils.isNotEmpty(routeAddressBlacklist)) { + GatewayStrategyFilterResolver.setHeader(request, requestBuilder, DiscoveryConstant.N_D_ADDRESS_BLACKLIST, routeAddressBlacklist, gatewayHeaderPriority); + } else { + GatewayStrategyFilterResolver.ignoreHeader(requestBuilder, DiscoveryConstant.N_D_ADDRESS_BLACKLIST, gatewayHeaderPriority, gatewayOriginalHeaderIgnored); + } + } else { + // 当核心Header传值开关关闭的时候,执行忽略Header设置的相关逻辑 + GatewayStrategyFilterResolver.ignoreHeader(requestBuilder, DiscoveryConstant.N_D_VERSION); + GatewayStrategyFilterResolver.ignoreHeader(requestBuilder, DiscoveryConstant.N_D_REGION); + GatewayStrategyFilterResolver.ignoreHeader(requestBuilder, DiscoveryConstant.N_D_ADDRESS); + GatewayStrategyFilterResolver.ignoreHeader(requestBuilder, DiscoveryConstant.N_D_VERSION_WEIGHT); + GatewayStrategyFilterResolver.ignoreHeader(requestBuilder, DiscoveryConstant.N_D_REGION_WEIGHT); + GatewayStrategyFilterResolver.ignoreHeader(requestBuilder, DiscoveryConstant.N_D_VERSION_PREFER); + GatewayStrategyFilterResolver.ignoreHeader(requestBuilder, DiscoveryConstant.N_D_VERSION_FAILOVER); + GatewayStrategyFilterResolver.ignoreHeader(requestBuilder, DiscoveryConstant.N_D_REGION_TRANSFER); + GatewayStrategyFilterResolver.ignoreHeader(requestBuilder, DiscoveryConstant.N_D_REGION_FAILOVER); + GatewayStrategyFilterResolver.ignoreHeader(requestBuilder, DiscoveryConstant.N_D_ENVIRONMENT_FAILOVER); + GatewayStrategyFilterResolver.ignoreHeader(requestBuilder, DiscoveryConstant.N_D_ZONE_FAILOVER); + GatewayStrategyFilterResolver.ignoreHeader(requestBuilder, DiscoveryConstant.N_D_ADDRESS_FAILOVER); + GatewayStrategyFilterResolver.ignoreHeader(requestBuilder, DiscoveryConstant.N_D_ID_BLACKLIST); + GatewayStrategyFilterResolver.ignoreHeader(requestBuilder, DiscoveryConstant.N_D_ADDRESS_BLACKLIST); + } + } + + public Map getExternalHeaderMap() { + return null; + } + + public PluginAdapter getPluginAdapter() { + return pluginAdapter; + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/filter/DefaultGatewayStrategyClearFilter.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/filter/DefaultGatewayStrategyClearFilter.java new file mode 100644 index 0000000000..23d9be1698 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/filter/DefaultGatewayStrategyClearFilter.java @@ -0,0 +1,42 @@ +package com.nepxion.discovery.plugin.strategy.gateway.filter; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import reactor.core.publisher.Mono; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cloud.gateway.filter.GatewayFilterChain; +import org.springframework.core.Ordered; +import org.springframework.web.server.ServerWebExchange; + +import com.nepxion.discovery.plugin.strategy.gateway.context.GatewayStrategyContext; +import com.nepxion.discovery.plugin.strategy.gateway.monitor.GatewayStrategyMonitor; + +public class DefaultGatewayStrategyClearFilter implements GatewayStrategyClearFilter { + @Autowired(required = false) + protected GatewayStrategyMonitor gatewayStrategyMonitor; + + @Override + public int getOrder() { + return Ordered.LOWEST_PRECEDENCE - 1; + } + + @Override + public Mono filter(ServerWebExchange exchange, GatewayFilterChain chain) { + GatewayStrategyContext.clearCurrentContext(); + + // 调用链释放 + if (gatewayStrategyMonitor != null) { + gatewayStrategyMonitor.release(exchange); + } + + return chain.filter(exchange); + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/filter/DefaultGatewayStrategyRouteFilter.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/filter/DefaultGatewayStrategyRouteFilter.java new file mode 100644 index 0000000000..0d93a261e0 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/filter/DefaultGatewayStrategyRouteFilter.java @@ -0,0 +1,99 @@ +package com.nepxion.discovery.plugin.strategy.gateway.filter; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.springframework.beans.factory.annotation.Autowired; + +import com.nepxion.discovery.plugin.strategy.context.StrategyContextHolder; + +// 负载均衡前执行路由过滤 +public class DefaultGatewayStrategyRouteFilter extends AbstractGatewayStrategyRouteFilter { + @Autowired + protected StrategyContextHolder strategyContextHolder; + + @Override + public String getRouteVersion() { + return strategyContextHolder.getRouteVersion(); + } + + @Override + public String getRouteRegion() { + return strategyContextHolder.getRouteRegion(); + } + + @Override + public String getRouteEnvironment() { + return strategyContextHolder.getRouteEnvironment(); + } + + @Override + public String getRouteAddress() { + return strategyContextHolder.getRouteAddress(); + } + + @Override + public String getRouteVersionWeight() { + return strategyContextHolder.getRouteVersionWeight(); + } + + @Override + public String getRouteRegionWeight() { + return strategyContextHolder.getRouteRegionWeight(); + } + + @Override + public String getRouteVersionPrefer() { + return strategyContextHolder.getRouteVersionPrefer(); + } + + @Override + public String getRouteVersionFailover() { + return strategyContextHolder.getRouteVersionFailover(); + } + + @Override + public String getRouteRegionTransfer() { + return strategyContextHolder.getRouteRegionTransfer(); + } + + @Override + public String getRouteRegionFailover() { + return strategyContextHolder.getRouteRegionFailover(); + } + + @Override + public String getRouteEnvironmentFailover() { + return strategyContextHolder.getRouteEnvironmentFailover(); + } + + @Override + public String getRouteZoneFailover() { + return strategyContextHolder.getRouteZoneFailover(); + } + + @Override + public String getRouteAddressFailover() { + return strategyContextHolder.getRouteAddressFailover(); + } + + @Override + public String getRouteIdBlacklist() { + return strategyContextHolder.getRouteIdBlacklist(); + } + + @Override + public String getRouteAddressBlacklist() { + return strategyContextHolder.getRouteAddressBlacklist(); + } + + public StrategyContextHolder getStrategyContextHolder() { + return strategyContextHolder; + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/filter/GatewayStrategyClearFilter.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/filter/GatewayStrategyClearFilter.java new file mode 100644 index 0000000000..e186973b75 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/filter/GatewayStrategyClearFilter.java @@ -0,0 +1,14 @@ +package com.nepxion.discovery.plugin.strategy.gateway.filter; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +public interface GatewayStrategyClearFilter extends GatewayStrategyFilter { + +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/filter/GatewayStrategyFilter.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/filter/GatewayStrategyFilter.java new file mode 100644 index 0000000000..d481e4953c --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/filter/GatewayStrategyFilter.java @@ -0,0 +1,17 @@ +package com.nepxion.discovery.plugin.strategy.gateway.filter; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.springframework.cloud.gateway.filter.GlobalFilter; +import org.springframework.core.Ordered; + +public interface GatewayStrategyFilter extends GlobalFilter, Ordered { + +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/filter/GatewayStrategyFilterResolver.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/filter/GatewayStrategyFilterResolver.java new file mode 100644 index 0000000000..340ac6f51c --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/filter/GatewayStrategyFilterResolver.java @@ -0,0 +1,46 @@ +package com.nepxion.discovery.plugin.strategy.gateway.filter; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.apache.commons.lang3.StringUtils; +import org.springframework.http.server.reactive.ServerHttpRequest; + +public class GatewayStrategyFilterResolver { + public static void setHeader(ServerHttpRequest request, ServerHttpRequest.Builder requestBuilder, String headerName, String headerValue, Boolean gatewayHeaderPriority) { + if (StringUtils.isEmpty(headerValue)) { + return; + } + + if (gatewayHeaderPriority) { + // 需要把外界的Header清除 + requestBuilder.headers(headers -> headers.remove(headerName)); + + // 需要把内置的Header加入 + requestBuilder.headers(headers -> headers.add(headerName, headerValue)); + } else { + // 非网关优先条件下,判断外界请求是否含有Header + // 如果含有,则不加入内置的Header + if (!request.getHeaders().containsKey(headerName)) { + requestBuilder.headers(headers -> headers.add(headerName, headerValue)); + } + } + } + + public static void ignoreHeader(ServerHttpRequest.Builder requestBuilder, String headerName, Boolean gatewayHeaderPriority, Boolean gatewayOriginalHeaderIgnored) { + if (gatewayHeaderPriority && gatewayOriginalHeaderIgnored) { + ignoreHeader(requestBuilder, headerName); + } + } + + public static void ignoreHeader(ServerHttpRequest.Builder requestBuilder, String headerName) { + // 需要把外界的Header清除 + requestBuilder.headers(headers -> headers.remove(headerName)); + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/filter/GatewayStrategyRouteFilter.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/filter/GatewayStrategyRouteFilter.java new file mode 100644 index 0000000000..cc83315c7d --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/filter/GatewayStrategyRouteFilter.java @@ -0,0 +1,16 @@ +package com.nepxion.discovery.plugin.strategy.gateway.filter; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import com.nepxion.discovery.plugin.strategy.filter.StrategyRouteFilter; + +public interface GatewayStrategyRouteFilter extends GatewayStrategyFilter, StrategyRouteFilter { + +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/filter/SkyWalkingGatewayStrategyFilter.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/filter/SkyWalkingGatewayStrategyFilter.java new file mode 100644 index 0000000000..5d3ea00d96 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/filter/SkyWalkingGatewayStrategyFilter.java @@ -0,0 +1,70 @@ +package com.nepxion.discovery.plugin.strategy.gateway.filter; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import reactor.core.publisher.Mono; + +import org.apache.skywalking.apm.agent.core.context.TracingContext; +import org.apache.skywalking.apm.agent.core.context.trace.AbstractTracingSpan; +import org.apache.skywalking.apm.agent.core.context.trace.EntrySpan; +import org.springframework.cloud.gateway.filter.GatewayFilterChain; +import org.springframework.core.Ordered; +import org.springframework.web.server.ServerWebExchange; + +import com.nepxion.discovery.common.constant.DiscoveryConstant; +import com.nepxion.discovery.common.util.ReflectionUtil; +import com.nepxion.discovery.plugin.strategy.monitor.StrategySpan; +import com.nepxion.discovery.plugin.strategy.monitor.StrategyTracerContext; + +public class SkyWalkingGatewayStrategyFilter implements GatewayStrategyFilter { + public static final String SKYWALING_SPAN = "SKYWALING_SPAN"; + public static final String OWNER = "owner"; + + @Override + public int getOrder() { + return Ordered.HIGHEST_PRECEDENCE; + } + + @Override + public Mono filter(ServerWebExchange exchange, GatewayFilterChain chain) { + String traceId = null; + + try { + EntrySpan entrySpan = exchange.getAttribute(SKYWALING_SPAN); + + traceId = getTraceId(entrySpan); + } catch (Exception e) { + + } + + StrategySpan strategySpan = new StrategySpan(); + strategySpan.setTraceId(traceId != null ? traceId : DiscoveryConstant.IGNORED); + strategySpan.setSpanId(DiscoveryConstant.IGNORED); + + StrategyTracerContext.getCurrentContext().setSpan(strategySpan); + + return chain.filter(exchange); + } + + private String getTraceId(AbstractTracingSpan tracingSpan) throws Exception { + if (tracingSpan == null) { + return null; + } + + Object owner = ReflectionUtil.getValue(AbstractTracingSpan.class, tracingSpan, OWNER); + if (owner instanceof TracingContext) { + TracingContext tracingContext = (TracingContext) owner; + + return tracingContext.getReadablePrimaryTraceId(); + } + + return null; + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/monitor/DefaultGatewayStrategyMonitor.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/monitor/DefaultGatewayStrategyMonitor.java new file mode 100644 index 0000000000..bbae2fa792 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/monitor/DefaultGatewayStrategyMonitor.java @@ -0,0 +1,35 @@ +package com.nepxion.discovery.plugin.strategy.gateway.monitor; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.springframework.web.server.ServerWebExchange; + +import com.nepxion.discovery.plugin.strategy.monitor.StrategyMonitor; + +public class DefaultGatewayStrategyMonitor extends StrategyMonitor implements GatewayStrategyMonitor { + @Override + public void monitor(ServerWebExchange exchange) { + spanBuild(); + + loggerOutput(); + loggerDebug(); + + alarm(null); + + spanOutput(null); + } + + @Override + public void release(ServerWebExchange exchange) { + loggerClear(); + + spanFinish(); + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/monitor/GatewayStrategyMonitor.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/monitor/GatewayStrategyMonitor.java new file mode 100644 index 0000000000..938ca9b80c --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/monitor/GatewayStrategyMonitor.java @@ -0,0 +1,18 @@ +package com.nepxion.discovery.plugin.strategy.gateway.monitor; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.springframework.web.server.ServerWebExchange; + +public interface GatewayStrategyMonitor { + void monitor(ServerWebExchange exchange); + + void release(ServerWebExchange exchange); +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/processor/GatewayStrategyRouteApolloProcessor.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/processor/GatewayStrategyRouteApolloProcessor.java new file mode 100644 index 0000000000..f9373cd012 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/processor/GatewayStrategyRouteApolloProcessor.java @@ -0,0 +1,45 @@ +package com.nepxion.discovery.plugin.strategy.gateway.processor; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.springframework.beans.factory.annotation.Autowired; + +import com.nepxion.discovery.common.apollo.proccessor.ApolloProcessor; +import com.nepxion.discovery.common.constant.DiscoveryConstant; +import com.nepxion.discovery.plugin.framework.adapter.PluginAdapter; +import com.nepxion.discovery.plugin.strategy.gateway.route.GatewayStrategyRoute; + +public class GatewayStrategyRouteApolloProcessor extends ApolloProcessor { + @Autowired + private PluginAdapter pluginAdapter; + + @Autowired + private GatewayStrategyRoute gatewayStrategyRoute; + + @Override + public String getGroup() { + return pluginAdapter.getGroup(); + } + + @Override + public String getDataId() { + return pluginAdapter.getServiceId() + "-" + DiscoveryConstant.DYNAMIC_ROUTE_KEY; + } + + @Override + public String getDescription() { + return DiscoveryConstant.SPRING_CLOUD_GATEWAY_DYNAMIC_ROUTE_DESCRIPTION; + } + + @Override + public void callbackConfig(String config) { + gatewayStrategyRoute.updateAll(config); + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/processor/GatewayStrategyRouteConsulProcessor.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/processor/GatewayStrategyRouteConsulProcessor.java new file mode 100644 index 0000000000..0c846a7098 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/processor/GatewayStrategyRouteConsulProcessor.java @@ -0,0 +1,45 @@ +package com.nepxion.discovery.plugin.strategy.gateway.processor; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.springframework.beans.factory.annotation.Autowired; + +import com.nepxion.discovery.common.constant.DiscoveryConstant; +import com.nepxion.discovery.common.consul.proccessor.ConsulProcessor; +import com.nepxion.discovery.plugin.framework.adapter.PluginAdapter; +import com.nepxion.discovery.plugin.strategy.gateway.route.GatewayStrategyRoute; + +public class GatewayStrategyRouteConsulProcessor extends ConsulProcessor { + @Autowired + private PluginAdapter pluginAdapter; + + @Autowired + private GatewayStrategyRoute gatewayStrategyRoute; + + @Override + public String getGroup() { + return pluginAdapter.getGroup(); + } + + @Override + public String getDataId() { + return pluginAdapter.getServiceId() + "-" + DiscoveryConstant.DYNAMIC_ROUTE_KEY; + } + + @Override + public String getDescription() { + return DiscoveryConstant.SPRING_CLOUD_GATEWAY_DYNAMIC_ROUTE_DESCRIPTION; + } + + @Override + public void callbackConfig(String config) { + gatewayStrategyRoute.updateAll(config); + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/processor/GatewayStrategyRouteEtcdProcessor.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/processor/GatewayStrategyRouteEtcdProcessor.java new file mode 100644 index 0000000000..ac03148b4f --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/processor/GatewayStrategyRouteEtcdProcessor.java @@ -0,0 +1,45 @@ +package com.nepxion.discovery.plugin.strategy.gateway.processor; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.springframework.beans.factory.annotation.Autowired; + +import com.nepxion.discovery.common.constant.DiscoveryConstant; +import com.nepxion.discovery.common.etcd.proccessor.EtcdProcessor; +import com.nepxion.discovery.plugin.framework.adapter.PluginAdapter; +import com.nepxion.discovery.plugin.strategy.gateway.route.GatewayStrategyRoute; + +public class GatewayStrategyRouteEtcdProcessor extends EtcdProcessor { + @Autowired + private PluginAdapter pluginAdapter; + + @Autowired + private GatewayStrategyRoute gatewayStrategyRoute; + + @Override + public String getGroup() { + return pluginAdapter.getGroup(); + } + + @Override + public String getDataId() { + return pluginAdapter.getServiceId() + "-" + DiscoveryConstant.DYNAMIC_ROUTE_KEY; + } + + @Override + public String getDescription() { + return DiscoveryConstant.SPRING_CLOUD_GATEWAY_DYNAMIC_ROUTE_DESCRIPTION; + } + + @Override + public void callbackConfig(String config) { + gatewayStrategyRoute.updateAll(config); + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/processor/GatewayStrategyRouteNacosProcessor.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/processor/GatewayStrategyRouteNacosProcessor.java new file mode 100644 index 0000000000..2bed6cc87c --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/processor/GatewayStrategyRouteNacosProcessor.java @@ -0,0 +1,45 @@ +package com.nepxion.discovery.plugin.strategy.gateway.processor; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.springframework.beans.factory.annotation.Autowired; + +import com.nepxion.discovery.common.constant.DiscoveryConstant; +import com.nepxion.discovery.common.nacos.proccessor.NacosProcessor; +import com.nepxion.discovery.plugin.framework.adapter.PluginAdapter; +import com.nepxion.discovery.plugin.strategy.gateway.route.GatewayStrategyRoute; + +public class GatewayStrategyRouteNacosProcessor extends NacosProcessor { + @Autowired + private PluginAdapter pluginAdapter; + + @Autowired + private GatewayStrategyRoute gatewayStrategyRoute; + + @Override + public String getGroup() { + return pluginAdapter.getGroup(); + } + + @Override + public String getDataId() { + return pluginAdapter.getServiceId() + "-" + DiscoveryConstant.DYNAMIC_ROUTE_KEY; + } + + @Override + public String getDescription() { + return DiscoveryConstant.SPRING_CLOUD_GATEWAY_DYNAMIC_ROUTE_DESCRIPTION; + } + + @Override + public void callbackConfig(String config) { + gatewayStrategyRoute.updateAll(config); + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/processor/GatewayStrategyRouteRedisProcessor.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/processor/GatewayStrategyRouteRedisProcessor.java new file mode 100644 index 0000000000..9d1d786057 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/processor/GatewayStrategyRouteRedisProcessor.java @@ -0,0 +1,45 @@ +package com.nepxion.discovery.plugin.strategy.gateway.processor; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.springframework.beans.factory.annotation.Autowired; + +import com.nepxion.discovery.common.constant.DiscoveryConstant; +import com.nepxion.discovery.common.redis.proccessor.RedisProcessor; +import com.nepxion.discovery.plugin.framework.adapter.PluginAdapter; +import com.nepxion.discovery.plugin.strategy.gateway.route.GatewayStrategyRoute; + +public class GatewayStrategyRouteRedisProcessor extends RedisProcessor { + @Autowired + private PluginAdapter pluginAdapter; + + @Autowired + private GatewayStrategyRoute gatewayStrategyRoute; + + @Override + public String getGroup() { + return pluginAdapter.getGroup(); + } + + @Override + public String getDataId() { + return pluginAdapter.getServiceId() + "-" + DiscoveryConstant.DYNAMIC_ROUTE_KEY; + } + + @Override + public String getDescription() { + return DiscoveryConstant.SPRING_CLOUD_GATEWAY_DYNAMIC_ROUTE_DESCRIPTION; + } + + @Override + public void callbackConfig(String config) { + gatewayStrategyRoute.updateAll(config); + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/processor/GatewayStrategyRouteZookeeperProcessor.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/processor/GatewayStrategyRouteZookeeperProcessor.java new file mode 100644 index 0000000000..d71c67fda9 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/processor/GatewayStrategyRouteZookeeperProcessor.java @@ -0,0 +1,45 @@ +package com.nepxion.discovery.plugin.strategy.gateway.processor; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.springframework.beans.factory.annotation.Autowired; + +import com.nepxion.discovery.common.constant.DiscoveryConstant; +import com.nepxion.discovery.common.zookeeper.proccessor.ZookeeperProcessor; +import com.nepxion.discovery.plugin.framework.adapter.PluginAdapter; +import com.nepxion.discovery.plugin.strategy.gateway.route.GatewayStrategyRoute; + +public class GatewayStrategyRouteZookeeperProcessor extends ZookeeperProcessor { + @Autowired + private PluginAdapter pluginAdapter; + + @Autowired + private GatewayStrategyRoute gatewayStrategyRoute; + + @Override + public String getGroup() { + return pluginAdapter.getGroup(); + } + + @Override + public String getDataId() { + return pluginAdapter.getServiceId() + "-" + DiscoveryConstant.DYNAMIC_ROUTE_KEY; + } + + @Override + public String getDescription() { + return DiscoveryConstant.SPRING_CLOUD_GATEWAY_DYNAMIC_ROUTE_DESCRIPTION; + } + + @Override + public void callbackConfig(String config) { + gatewayStrategyRoute.updateAll(config); + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/route/AbstractGatewayStrategyRoute.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/route/AbstractGatewayStrategyRoute.java new file mode 100644 index 0000000000..f8a0071608 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/route/AbstractGatewayStrategyRoute.java @@ -0,0 +1,479 @@ +package com.nepxion.discovery.plugin.strategy.gateway.route; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Ning Zhang + * @author Haojun Ren + * @version 1.0 + */ + +import reactor.core.Disposable; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +import java.net.URI; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeSet; +import java.util.concurrent.ExecutorService; +import java.util.function.Function; +import java.util.function.Predicate; +import java.util.stream.Collectors; + +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cloud.gateway.config.GatewayProperties; +import org.springframework.cloud.gateway.event.RefreshRoutesEvent; +import org.springframework.cloud.gateway.filter.FilterDefinition; +import org.springframework.cloud.gateway.handler.predicate.PredicateDefinition; +import org.springframework.cloud.gateway.route.RouteDefinition; +import org.springframework.cloud.gateway.route.RouteDefinitionLocator; +import org.springframework.cloud.gateway.route.RouteDefinitionWriter; +import org.springframework.cloud.gateway.support.NotFoundException; +import org.springframework.context.ApplicationEventPublisher; +import org.springframework.context.ApplicationEventPublisherAware; +import org.springframework.web.util.UriComponentsBuilder; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.nepxion.discovery.common.constant.DiscoveryConstant; +import com.nepxion.discovery.common.entity.GatewayStrategyRouteEntity; +import com.nepxion.discovery.common.exception.DiscoveryException; +import com.nepxion.discovery.common.future.DiscoveryFutureCallback; +import com.nepxion.discovery.common.future.DiscoveryFutureResolver; +import com.nepxion.discovery.common.thread.DiscoveryThreadPoolFactory; +import com.nepxion.discovery.common.util.JsonUtil; +import com.nepxion.discovery.plugin.framework.event.PluginPublisher; +import com.nepxion.discovery.plugin.strategy.gateway.event.GatewayStrategyRouteAddedEvent; +import com.nepxion.discovery.plugin.strategy.gateway.event.GatewayStrategyRouteDeletedEvent; +import com.nepxion.discovery.plugin.strategy.gateway.event.GatewayStrategyRouteModifiedEvent; +import com.nepxion.discovery.plugin.strategy.gateway.event.GatewayStrategyRouteUpdatedAllEvent; + +public abstract class AbstractGatewayStrategyRoute implements GatewayStrategyRoute, ApplicationEventPublisherAware { + private static final Logger LOG = LoggerFactory.getLogger(AbstractGatewayStrategyRoute.class); + + private ExecutorService executorService = DiscoveryThreadPoolFactory.getExecutorService("gateway-route"); + + @Autowired + private RouteDefinitionLocator routeDefinitionLocator; + + @Autowired + private RouteDefinitionWriter routeDefinitionWriter; + + @Autowired + private GatewayProperties gatewayProperties; + + @Autowired + private PluginPublisher pluginPublisher; + + private ApplicationEventPublisher applicationEventPublisher; + + @Override + public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) { + this.applicationEventPublisher = applicationEventPublisher; + } + + @Override + public synchronized void add(GatewayStrategyRouteEntity gatewayStrategyRouteEntity) { + if (gatewayStrategyRouteEntity == null) { + throw new DiscoveryException("Gateway dynamic route is null"); + } + + Map routeDefinitionMap = locateRoutes(); + String routeId = gatewayStrategyRouteEntity.getId(); + if (routeDefinitionMap.containsKey(routeId)) { + throw new DiscoveryException("Gateway dynamic route for routeId=[" + routeId + "] is duplicated"); + } + + RouteDefinition routeDefinition = convertRoute(gatewayStrategyRouteEntity); + addRoute(routeDefinition); + + LOG.info("Added Gateway dynamic route={}", routeDefinition); + + applicationEventPublisher.publishEvent(new RefreshRoutesEvent(this)); + + pluginPublisher.asyncPublish(new GatewayStrategyRouteAddedEvent(gatewayStrategyRouteEntity)); + } + + @Override + public synchronized void modify(GatewayStrategyRouteEntity gatewayStrategyRouteEntity) { + if (gatewayStrategyRouteEntity == null) { + throw new DiscoveryException("Gateway dynamic route is null"); + } + + Map routeDefinitionMap = locateRoutes(); + String routeId = gatewayStrategyRouteEntity.getId(); + + if (!routeDefinitionMap.containsKey(routeId)) { + throw new DiscoveryException("Gateway dynamic route for routeId=[" + routeId + "] isn't found"); + } + + RouteDefinition routeDefinition = convertRoute(gatewayStrategyRouteEntity); + modifyRoute(routeDefinition); + + LOG.info("Modified Gateway dynamic route={}", routeDefinition); + + applicationEventPublisher.publishEvent(new RefreshRoutesEvent(this)); + + pluginPublisher.asyncPublish(new GatewayStrategyRouteModifiedEvent(gatewayStrategyRouteEntity)); + } + + @Override + public synchronized void delete(String routeId) { + if (StringUtils.isEmpty(routeId)) { + throw new DiscoveryException("RouteId is empty"); + } + + Map routeDefinitionMap = locateRoutes(); + RouteDefinition routeDefinition = routeDefinitionMap.get(routeId); + if (routeDefinition == null) { + throw new DiscoveryException("Gateway dynamic route for routeId=[" + routeId + "] isn't found"); + } + + deleteRoute(routeDefinition); + + LOG.info("Deleted Gateway dynamic route for routeId={}", routeId); + + applicationEventPublisher.publishEvent(new RefreshRoutesEvent(this)); + + pluginPublisher.asyncPublish(new GatewayStrategyRouteDeletedEvent(routeId)); + } + + @Override + public synchronized void updateAll(List gatewayStrategyRouteEntityList) { + if (gatewayStrategyRouteEntityList == null) { + throw new DiscoveryException("Gateway dynamic routes are null"); + } + + boolean isIdDuplicated = isIdDuplicated(gatewayStrategyRouteEntityList); + if (isIdDuplicated) { + throw new DiscoveryException("Gateway dynamic routes have duplicated routeIds"); + } + + Map dynamicRouteDefinitionMap = gatewayStrategyRouteEntityList.stream().collect(Collectors.toMap(GatewayStrategyRouteEntity::getId, this::convertRoute)); + Map currentRouteDefinitionMap = locateRoutes(); + + List addRouteDefinitionList = new ArrayList(dynamicRouteDefinitionMap.size()); + List modifyRouteDefinitionList = new ArrayList(dynamicRouteDefinitionMap.size()); + List deleteRouteDefinitionList = new ArrayList(dynamicRouteDefinitionMap.size()); + + for (Map.Entry entry : dynamicRouteDefinitionMap.entrySet()) { + String routeId = entry.getKey(); + RouteDefinition routeDefinition = entry.getValue(); + if (!currentRouteDefinitionMap.containsKey(routeId)) { + addRouteDefinitionList.add(routeDefinition); + } + } + + for (Map.Entry entry : dynamicRouteDefinitionMap.entrySet()) { + String routeId = entry.getKey(); + RouteDefinition routeDefinition = entry.getValue(); + if (currentRouteDefinitionMap.containsKey(routeId)) { + RouteDefinition currentRouteDefinition = currentRouteDefinitionMap.get(routeId); + if (!currentRouteDefinition.equals(routeDefinition)) { + modifyRouteDefinitionList.add(routeDefinition); + } + } + } + + for (Map.Entry entry : currentRouteDefinitionMap.entrySet()) { + String routeId = entry.getKey(); + RouteDefinition routeDefinition = entry.getValue(); + if (!dynamicRouteDefinitionMap.containsKey(routeId)) { + deleteRouteDefinitionList.add(routeDefinition); + } + } + + for (RouteDefinition routeDefinition : addRouteDefinitionList) { + addRoute(routeDefinition); + } + + for (RouteDefinition routeDefinition : modifyRouteDefinitionList) { + modifyRoute(routeDefinition); + } + + for (RouteDefinition routeDefinition : deleteRouteDefinitionList) { + deleteRoute(routeDefinition); + } + + LOG.info("--- Gateway Dynamic Routes Update Information ----"); + LOG.info("Total count={}", gatewayStrategyRouteEntityList.size()); + LOG.info("Added count={}", addRouteDefinitionList.size()); + LOG.info("Modified count={}", modifyRouteDefinitionList.size()); + LOG.info("Deleted count={}", deleteRouteDefinitionList.size()); + LOG.info("--------------------------------------------------"); + + if (addRouteDefinitionList.isEmpty() && modifyRouteDefinitionList.isEmpty() && deleteRouteDefinitionList.isEmpty()) { + return; + } + + applicationEventPublisher.publishEvent(new RefreshRoutesEvent(this)); + + pluginPublisher.asyncPublish(new GatewayStrategyRouteUpdatedAllEvent(gatewayStrategyRouteEntityList)); + } + + @Override + public synchronized void updateAll(String gatewayStrategyRouteConfig) { + if (StringUtils.isBlank(gatewayStrategyRouteConfig)) { + gatewayStrategyRouteConfig = DiscoveryConstant.EMPTY_JSON_RULE_MULTIPLE; + } + + List gatewayStrategyRouteEntityList = JsonUtil.fromJson(gatewayStrategyRouteConfig, new TypeReference>() { + }); + + updateAll(gatewayStrategyRouteEntityList); + } + + @Override + public GatewayStrategyRouteEntity view(String routeId) { + if (StringUtils.isEmpty(routeId)) { + throw new DiscoveryException("RouteId is empty"); + } + + RouteDefinition routeDefinition = locateRoutes().get(routeId); + if (routeDefinition == null) { + throw new DiscoveryException("Gateway dynamic route for routeId=[" + routeId + "] isn't found"); + } + + return convertRoute(routeDefinition); + } + + @Override + public List viewAll() { + List gatewayStrategyRouteEntityList = new ArrayList(); + + Map routeDefinitionMap = locateRoutes(); + for (Map.Entry entry : routeDefinitionMap.entrySet()) { + RouteDefinition routeDefinition = entry.getValue(); + GatewayStrategyRouteEntity gatewayStrategyRouteEntity = convertRoute(routeDefinition); + gatewayStrategyRouteEntityList.add(gatewayStrategyRouteEntity); + } + + return gatewayStrategyRouteEntityList; + } + + public Map locateRoutes() { + /* + Map routeDefinitionMap = new HashMap(); + Flux routeDefinitions = routeDefinitionLocator.getRouteDefinitions(); + Disposable disposable = null; + try { + disposable = routeDefinitions.subscribe(routeDefinition -> routeDefinitionMap.put(routeDefinition.getId(), routeDefinition)); + try { + Thread.sleep(100); + } catch (InterruptedException e) { + } + } finally { + if (disposable != null) { + disposable.dispose(); + } + } + + return routeDefinitionMap; + */ + + Flux routeDefinitions = routeDefinitionLocator.getRouteDefinitions(); + try { + return DiscoveryFutureResolver.call(executorService, new DiscoveryFutureCallback>() { + @Override + public Map callback() { + List routeDefinitionList = routeDefinitions.collectList().block(); + + return routeDefinitionList.stream().collect(Collectors.toMap(RouteDefinition::getId, RouteDefinition -> RouteDefinition)); + } + }); + } catch (Exception e) { + return new HashMap(); + } + } + + private boolean isIdDuplicated(List gatewayStrategyRouteEntityList) { + Set gatewayStrategyRouteEntitySet = new TreeSet(new Comparator() { + public int compare(GatewayStrategyRouteEntity gatewayStrategyRouteEntity1, GatewayStrategyRouteEntity gatewayStrategyRouteEntity2) { + return gatewayStrategyRouteEntity1.getId().compareTo(gatewayStrategyRouteEntity2.getId()); + } + }); + gatewayStrategyRouteEntitySet.addAll(gatewayStrategyRouteEntityList); + + return gatewayStrategyRouteEntitySet.size() < gatewayStrategyRouteEntityList.size(); + } + + public RouteDefinition convertRoute(GatewayStrategyRouteEntity gatewayStrategyRouteEntity) { + RouteDefinition routeDefinition = new RouteDefinition(); + routeDefinition.setId(gatewayStrategyRouteEntity.getId()); + routeDefinition.setUri(convertURI(gatewayStrategyRouteEntity.getUri())); + + List predicateList = gatewayStrategyRouteEntity.getPredicates(); + List userPredicates = gatewayStrategyRouteEntity.getUserPredicates(); + List predicateDefinitionList = new ArrayList(predicateList.size() + userPredicates.size()); + for (String predicate : predicateList) { + predicateDefinitionList.add(new PredicateDefinition(predicate)); + } + for (GatewayStrategyRouteEntity.Predicate predicate : userPredicates) { + PredicateDefinition predicateDefinition = new PredicateDefinition(); + predicateDefinition.setName(predicate.getName()); + predicateDefinition.setArgs(predicate.getArgs()); + predicateDefinitionList.add(predicateDefinition); + } + routeDefinition.setPredicates(predicateDefinitionList); + + List filterList = gatewayStrategyRouteEntity.getFilters(); + List userFilters = gatewayStrategyRouteEntity.getUserFilters(); + List filterDefinitionList = new ArrayList(filterList.size() + userFilters.size()); + for (String filter : filterList) { + filterDefinitionList.add(new FilterDefinition(filter)); + } + for (GatewayStrategyRouteEntity.Filter filter : userFilters) { + FilterDefinition filterDefinition = new FilterDefinition(); + filterDefinition.setName(filter.getName()); + filterDefinition.setArgs(filter.getArgs()); + filterDefinitionList.add(filterDefinition); + } + routeDefinition.setFilters(filterDefinitionList); + + routeDefinition.setOrder(gatewayStrategyRouteEntity.getOrder()); + // Metadata isn't supported in Finchley and Greenwich + try { + routeDefinition.setMetadata(gatewayStrategyRouteEntity.getMetadata()); + } catch (Throwable e) { + + } + + return routeDefinition; + } + + public GatewayStrategyRouteEntity convertRoute(RouteDefinition routeDefinition) { + GatewayStrategyRouteEntity gatewayStrategyRouteEntity = new GatewayStrategyRouteEntity(); + gatewayStrategyRouteEntity.setId(routeDefinition.getId()); + gatewayStrategyRouteEntity.setUri(routeDefinition.getUri().toString()); + gatewayStrategyRouteEntity.setOrder(routeDefinition.getOrder()); + // Metadata isn't supported in Finchley and Greenwich + try { + gatewayStrategyRouteEntity.setMetadata(routeDefinition.getMetadata()); + } catch (Throwable e) { + + } + convertPredicates(routeDefinition.getPredicates(), gatewayStrategyRouteEntity.getPredicates(), gatewayStrategyRouteEntity.getUserPredicates()); + convertFilters(routeDefinition.getFilters(), gatewayStrategyRouteEntity.getFilters(), gatewayStrategyRouteEntity.getUserFilters()); + + return gatewayStrategyRouteEntity; + } + + public void convertPredicates(List predicateDefinitionList, List predicateList, List userPredicateList) { + for (PredicateDefinition predicateDefinition : predicateDefinitionList) { + String name = predicateDefinition.getName(); + Map args = predicateDefinition.getArgs(); + boolean internal = isInternal(args); + if (internal) { + predicateList.add(String.format("%s=%s", name, StringUtils.join(args.values(), ","))); + } else { + GatewayStrategyRouteEntity.Predicate predicate = new GatewayStrategyRouteEntity.Predicate(); + predicate.setName(predicateDefinition.getName()); + predicate.setArgs(predicateDefinition.getArgs()); + + userPredicateList.add(predicate); + } + } + } + + public void convertFilters(List filterDefinitionList, List filterList, List userFilterList) { + for (FilterDefinition filterDefinition : filterDefinitionList) { + String name = filterDefinition.getName(); + Map args = filterDefinition.getArgs(); + boolean internal = isInternal(args); + if (internal) { + filterList.add(String.format("%s=%s", name, StringUtils.join(args.values(), ","))); + } else { + GatewayStrategyRouteEntity.Filter filter = new GatewayStrategyRouteEntity.Filter(); + filter.setName(filterDefinition.getName()); + filter.setArgs(filterDefinition.getArgs()); + + userFilterList.add(filter); + } + } + } + + public boolean isInternal(Map args) { + for (Map.Entry entry : args.entrySet()) { + String key = entry.getKey(); + // 如果key包含_genkey_,表示为网关内置配置,例如,Path,RewritePath的key都会以_genkey_来命名 + if (key.contains("_genkey_")) { + return true; + } + } + + return false; + } + + public URI convertURI(String value) { + URI uri; + if (value.toLowerCase().startsWith("http") || value.toLowerCase().startsWith("https")) { + uri = UriComponentsBuilder.fromHttpUrl(value).build().toUri(); + } else { + uri = URI.create(value); + } + + return uri; + } + + public void addRoute(RouteDefinition routeDefinition) { + Disposable disposable = null; + try { + disposable = routeDefinitionWriter.save(Mono.just(routeDefinition)).subscribe(); + } finally { + if (disposable != null) { + disposable.dispose(); + } + } + } + + public void modifyRoute(RouteDefinition routeDefinition) { + deleteRoute(routeDefinition); + addRoute(routeDefinition); + } + + public void deleteRoute(RouteDefinition routeDefinition) { + Disposable disposable = null; + try { + disposable = routeDefinitionWriter + .delete(Mono.just(routeDefinition.getId())) + .onErrorResume(new Function>() { + @Override + public Mono apply(Throwable throwable) { + if (throwable instanceof NotFoundException) { + gatewayProperties.getRoutes().removeIf(new Predicate() { + @Override + public boolean test(RouteDefinition routeCandidate) { + return routeCandidate.getId().equals(routeDefinition.getId()); + } + }); + + return Mono.empty(); + } + + return Mono.error(throwable); + } + }).subscribe(); + } finally { + if (disposable != null) { + disposable.dispose(); + } + } + } + + public void clearRoutes() { + Map routeDefinitionMap = locateRoutes(); + for (Map.Entry entry : routeDefinitionMap.entrySet()) { + RouteDefinition routeDefinition = entry.getValue(); + deleteRoute(routeDefinition); + } + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/route/DefaultGatewayStrategyRoute.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/route/DefaultGatewayStrategyRoute.java new file mode 100644 index 0000000000..480c33fc27 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/route/DefaultGatewayStrategyRoute.java @@ -0,0 +1,14 @@ +package com.nepxion.discovery.plugin.strategy.gateway.route; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Ning Zhang + * @version 1.0 + */ + +public class DefaultGatewayStrategyRoute extends AbstractGatewayStrategyRoute { + +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/route/GatewayStrategyRoute.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/route/GatewayStrategyRoute.java new file mode 100644 index 0000000000..2368233d18 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/route/GatewayStrategyRoute.java @@ -0,0 +1,30 @@ +package com.nepxion.discovery.plugin.strategy.gateway.route; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Ning Zhang + * @version 1.0 + */ + +import java.util.List; + +import com.nepxion.discovery.common.entity.GatewayStrategyRouteEntity; + +public interface GatewayStrategyRoute { + void add(GatewayStrategyRouteEntity gatewayStrategyRouteEntity); + + void modify(GatewayStrategyRouteEntity gatewayStrategyRouteEntity); + + void delete(String routeId); + + void updateAll(List gatewayStrategyRouteEntityList); + + void updateAll(String gatewayStrategyRouteConfig); + + GatewayStrategyRouteEntity view(String routeId); + + List viewAll(); +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/wrapper/DefaultGatewayStrategyCallableWrapper.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/wrapper/DefaultGatewayStrategyCallableWrapper.java new file mode 100644 index 0000000000..0df3b4287d --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/wrapper/DefaultGatewayStrategyCallableWrapper.java @@ -0,0 +1,44 @@ +package com.nepxion.discovery.plugin.strategy.gateway.wrapper; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @author Hao Huang + * @version 1.0 + */ + +import java.util.concurrent.Callable; + +import org.springframework.web.server.ServerWebExchange; + +import com.nepxion.discovery.plugin.strategy.gateway.context.GatewayStrategyContext; +import com.nepxion.discovery.plugin.strategy.monitor.StrategyTracerContext; + +public class DefaultGatewayStrategyCallableWrapper implements GatewayStrategyCallableWrapper { + @Override + public Callable wrapCallable(Callable callable) { + ServerWebExchange exchange = GatewayStrategyContext.getCurrentContext().getExchange(); + + Object span = StrategyTracerContext.getCurrentContext().getSpan(); + + return new Callable() { + @Override + public T call() throws Exception { + try { + GatewayStrategyContext.getCurrentContext().setExchange(exchange); + + StrategyTracerContext.getCurrentContext().setSpan(span); + + return callable.call(); + } finally { + GatewayStrategyContext.clearCurrentContext(); + + StrategyTracerContext.clearCurrentContext(); + } + } + }; + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/wrapper/GatewayStrategyCallableWrapper.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/wrapper/GatewayStrategyCallableWrapper.java new file mode 100644 index 0000000000..61b3ef9868 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/wrapper/GatewayStrategyCallableWrapper.java @@ -0,0 +1,17 @@ +package com.nepxion.discovery.plugin.strategy.gateway.wrapper; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @author Hao Huang + * @version 1.0 + */ + +import com.nepxion.discovery.plugin.strategy.wrapper.StrategyCallableWrapper; + +public interface GatewayStrategyCallableWrapper extends StrategyCallableWrapper { + +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/resources/META-INF/additional-spring-configuration-metadata.json b/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/resources/META-INF/additional-spring-configuration-metadata.json new file mode 100644 index 0000000000..9623a6b6bb --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/resources/META-INF/additional-spring-configuration-metadata.json @@ -0,0 +1,40 @@ +{ + "properties": [ + { + "name": "spring.application.strategy.gateway.route.filter.order", + "type": "java.lang.Integer", + "defaultValue": 9000, + "description": "Strategy gateway route filter order." + }, + { + "name": "spring.application.strategy.gateway.header.priority", + "type": "java.lang.Boolean", + "defaultValue": true, + "description": "Whether strategy gateway header priority is enabled." + }, + { + "name": "spring.application.strategy.gateway.original.header.ignored", + "type": "java.lang.Boolean", + "defaultValue": true, + "description": "Whether strategy gateway original header ignored is enabled." + }, + { + "name": "spring.application.strategy.gateway.core.header.transmission.enabled", + "type": "java.lang.Boolean", + "defaultValue": true, + "description": "Whether strategy gateway core header transmission is enabled." + }, + { + "name": "spring.application.strategy.gateway.dynamic.route.enabled", + "type": "java.lang.Boolean", + "defaultValue": false, + "description": "Whether strategy gateway dynamic route is enabled." + }, + { + "name": "spring.application.strategy.gateway.skywalking.traceid.enabled", + "type": "java.lang.Boolean", + "defaultValue": true, + "description": "Whether strategy gateway skywalking traceid is enabled." + } + ] +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/resources/META-INF/spring.factories b/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/resources/META-INF/spring.factories new file mode 100644 index 0000000000..d7e89de224 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/resources/META-INF/spring.factories @@ -0,0 +1,6 @@ +org.springframework.boot.env.EnvironmentPostProcessor=\ +com.nepxion.discovery.plugin.strategy.gateway.context.GatewayStrategyEnvironmentPostProcessor + +org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ +com.nepxion.discovery.plugin.strategy.gateway.configuration.GatewayStrategyAutoConfiguration,\ +com.nepxion.discovery.plugin.strategy.gateway.configuration.GatewayStrategyContextAutoConfiguration \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-hystrix/pom.xml b/discovery-plugin-strategy/discovery-plugin-strategy-starter-hystrix/pom.xml new file mode 100644 index 0000000000..5c32788fee --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-hystrix/pom.xml @@ -0,0 +1,28 @@ + + + discovery-plugin-strategy-starter-hystrix + Nepxion Discovery Plugin Strategy Starter Hystrix + jar + 4.0.0 + Nepxion Discovery is a solution for Spring Cloud with blue green, gray, weight, limitation, circuit breaker, degrade, isolation, monitor, tracing, dye, failover, async agent + http://www.nepxion.com + + + com.nepxion + discovery-plugin-strategy + 6.23.0 + + + + + ${project.groupId} + discovery-plugin-strategy-starter + + + + org.springframework.cloud + spring-cloud-starter-netflix-hystrix + + + \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-hystrix/src/main/java/com/nepxion/discovery/plugin/strategy/hystrix/configuration/HystrixStrategyAutoConfiguration.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-hystrix/src/main/java/com/nepxion/discovery/plugin/strategy/hystrix/configuration/HystrixStrategyAutoConfiguration.java new file mode 100644 index 0000000000..cd3f8fff23 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-hystrix/src/main/java/com/nepxion/discovery/plugin/strategy/hystrix/configuration/HystrixStrategyAutoConfiguration.java @@ -0,0 +1,42 @@ +package com.nepxion.discovery.plugin.strategy.hystrix.configuration; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @author Hao Huang + * @version 1.0 + */ + +import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import com.nepxion.banner.BannerConstant; +import com.nepxion.banner.Description; +import com.nepxion.banner.LogoBanner; +import com.nepxion.banner.NepxionBanner; +import com.nepxion.discovery.common.entity.ProtectorType; +import com.nepxion.discovery.plugin.strategy.constant.StrategyConstant; +import com.nepxion.discovery.plugin.strategy.hystrix.context.HystrixContextConcurrencyStrategy; +import com.netflix.hystrix.Hystrix; +import com.taobao.text.Color; + +@Configuration +@ConditionalOnClass(Hystrix.class) +@ConditionalOnProperty(value = StrategyConstant.SPRING_APPLICATION_STRATEGY_HYSTRIX_THREADLOCAL_SUPPORTED, matchIfMissing = false) +public class HystrixStrategyAutoConfiguration { + static { + LogoBanner logoBanner = new LogoBanner(HystrixStrategyAutoConfiguration.class, "/com/nepxion/hystrix/resource/logo.txt", "Welcome to Nepxion", 7, 5, new Color[] { Color.red, Color.green, Color.cyan, Color.blue, Color.yellow, Color.magenta, Color.red }, true); + + NepxionBanner.show(logoBanner, new Description("Protector:", ProtectorType.HYSTRIX.toString(), 0, 1), new Description(BannerConstant.GITHUB + ":", BannerConstant.NEPXION_GITHUB + "/Discovery", 0, 1)); + } + + @Bean + public HystrixContextConcurrencyStrategy hystrixContextConcurrencyStrategy() { + return new HystrixContextConcurrencyStrategy(); + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-hystrix/src/main/java/com/nepxion/discovery/plugin/strategy/hystrix/constant/HystrixStrategyConstant.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-hystrix/src/main/java/com/nepxion/discovery/plugin/strategy/hystrix/constant/HystrixStrategyConstant.java new file mode 100644 index 0000000000..582e865822 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-hystrix/src/main/java/com/nepxion/discovery/plugin/strategy/hystrix/constant/HystrixStrategyConstant.java @@ -0,0 +1,14 @@ +package com.nepxion.discovery.plugin.strategy.hystrix.constant; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +public class HystrixStrategyConstant { + +} \ No newline at end of file diff --git a/discovery-plugin-strategy-starter-hystrix/src/main/java/com/nepxion/discovery/plugin/strategy/hystrix/context/HystrixContextConcurrencyStrategy.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-hystrix/src/main/java/com/nepxion/discovery/plugin/strategy/hystrix/context/HystrixContextConcurrencyStrategy.java similarity index 79% rename from discovery-plugin-strategy-starter-hystrix/src/main/java/com/nepxion/discovery/plugin/strategy/hystrix/context/HystrixContextConcurrencyStrategy.java rename to discovery-plugin-strategy/discovery-plugin-strategy-starter-hystrix/src/main/java/com/nepxion/discovery/plugin/strategy/hystrix/context/HystrixContextConcurrencyStrategy.java index c13ef60b45..6bc0b24974 100644 --- a/discovery-plugin-strategy-starter-hystrix/src/main/java/com/nepxion/discovery/plugin/strategy/hystrix/context/HystrixContextConcurrencyStrategy.java +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-hystrix/src/main/java/com/nepxion/discovery/plugin/strategy/hystrix/context/HystrixContextConcurrencyStrategy.java @@ -17,7 +17,7 @@ import org.springframework.beans.factory.annotation.Autowired; -import com.nepxion.discovery.plugin.strategy.wrapper.CallableWrapper; +import com.nepxion.discovery.plugin.strategy.wrapper.StrategyCallableWrapper; import com.netflix.hystrix.HystrixThreadPoolKey; import com.netflix.hystrix.HystrixThreadPoolProperties; import com.netflix.hystrix.strategy.HystrixPlugins; @@ -33,12 +33,13 @@ // 使用线程隔离模式时,无法获取ThreadLocal中信息,自定义并发策略解决 public class HystrixContextConcurrencyStrategy extends HystrixConcurrencyStrategy { @Autowired - private CallableWrapper wrapper; - private HystrixConcurrencyStrategy delegate; + private StrategyCallableWrapper strategyCallableWrapper; + + private HystrixConcurrencyStrategy hystrixConcurrencyStrategy; public HystrixContextConcurrencyStrategy() { // HystrixPlugins只能注册一次策略,保留原对象 - this.delegate = HystrixPlugins.getInstance().getConcurrencyStrategy(); + this.hystrixConcurrencyStrategy = HystrixPlugins.getInstance().getConcurrencyStrategy(); // Keeps references of existing Hystrix plugins. HystrixCommandExecutionHook commandExecutionHook = HystrixPlugins.getInstance().getCommandExecutionHook(); @@ -58,26 +59,28 @@ public HystrixContextConcurrencyStrategy() { @Override public BlockingQueue getBlockingQueue(int maxQueueSize) { - return delegate.getBlockingQueue(maxQueueSize); + return hystrixConcurrencyStrategy.getBlockingQueue(maxQueueSize); } @Override public HystrixRequestVariable getRequestVariable(HystrixRequestVariableLifecycle rv) { - return delegate.getRequestVariable(rv); + return hystrixConcurrencyStrategy.getRequestVariable(rv); } @Override public ThreadPoolExecutor getThreadPool(HystrixThreadPoolKey threadPoolKey, HystrixProperty corePoolSize, HystrixProperty maximumPoolSize, HystrixProperty keepAliveTime, TimeUnit unit, BlockingQueue workQueue) { - return delegate.getThreadPool(threadPoolKey, corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue); + return hystrixConcurrencyStrategy.getThreadPool(threadPoolKey, corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue); } @Override public ThreadPoolExecutor getThreadPool(HystrixThreadPoolKey threadPoolKey, HystrixThreadPoolProperties threadPoolProperties) { - return delegate.getThreadPool(threadPoolKey, threadPoolProperties); + return hystrixConcurrencyStrategy.getThreadPool(threadPoolKey, threadPoolProperties); } @Override public Callable wrapCallable(Callable callable) { - return wrapper.wrapCallable(callable); + Callable originCallable = hystrixConcurrencyStrategy.wrapCallable(callable); + + return strategyCallableWrapper.wrapCallable(originCallable); } } \ No newline at end of file diff --git a/discovery-plugin-strategy-starter-hystrix/src/main/resources/META-INF/spring.factories b/discovery-plugin-strategy/discovery-plugin-strategy-starter-hystrix/src/main/resources/META-INF/spring.factories similarity index 100% rename from discovery-plugin-strategy-starter-hystrix/src/main/resources/META-INF/spring.factories rename to discovery-plugin-strategy/discovery-plugin-strategy-starter-hystrix/src/main/resources/META-INF/spring.factories diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-opentelemetry/pom.xml b/discovery-plugin-strategy/discovery-plugin-strategy-starter-opentelemetry/pom.xml new file mode 100644 index 0000000000..b5a8999bce --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-opentelemetry/pom.xml @@ -0,0 +1,30 @@ + + + discovery-plugin-strategy-starter-opentelemetry + Nepxion Discovery Plugin Strategy Starter OpenTelemetry + jar + 4.0.0 + Nepxion Discovery is a solution for Spring Cloud with blue green, gray, weight, limitation, circuit breaker, degrade, isolation, monitor, tracing, dye, failover, async agent + http://www.nepxion.com + + + com.nepxion + discovery-plugin-strategy + 6.23.0 + + + + + ${project.groupId} + discovery-plugin-strategy-starter + + + + io.opentelemetry + opentelemetry-api + ${opentelemetry.version} + provided + + + \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-opentelemetry/src/main/java/com/nepxion/discovery/plugin/strategy/opentelemetry/configuration/OpenTelemetryStrategyAutoConfiguration.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-opentelemetry/src/main/java/com/nepxion/discovery/plugin/strategy/opentelemetry/configuration/OpenTelemetryStrategyAutoConfiguration.java new file mode 100644 index 0000000000..82494e8db4 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-opentelemetry/src/main/java/com/nepxion/discovery/plugin/strategy/opentelemetry/configuration/OpenTelemetryStrategyAutoConfiguration.java @@ -0,0 +1,41 @@ +package com.nepxion.discovery.plugin.strategy.opentelemetry.configuration; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import com.nepxion.banner.BannerConstant; +import com.nepxion.banner.Description; +import com.nepxion.banner.LogoBanner; +import com.nepxion.banner.NepxionBanner; +import com.nepxion.discovery.common.entity.TracingType; +import com.nepxion.discovery.plugin.strategy.constant.StrategyConstant; +import com.nepxion.discovery.plugin.strategy.monitor.StrategyTracer; +import com.nepxion.discovery.plugin.strategy.opentelemetry.monitor.OpenTelemetryStrategyTracer; +import com.taobao.text.Color; + +@Configuration +public class OpenTelemetryStrategyAutoConfiguration { + static { + LogoBanner logoBanner = new LogoBanner(OpenTelemetryStrategyAutoConfiguration.class, "/com/nepxion/opentelemetry/resource/logo.txt", "Welcome to Nepxion", 8, 5, new Color[] { Color.red, Color.green, Color.cyan, Color.blue, Color.yellow, Color.magenta, Color.red, Color.green }, true); + + NepxionBanner.show(logoBanner, new Description("Tracing:", TracingType.OPENTELEMETRY.toString(), 0, 1), new Description(BannerConstant.GITHUB + ":", BannerConstant.NEPXION_GITHUB + "/Discovery", 0, 1)); + } + + @Bean + @ConditionalOnMissingBean + @ConditionalOnProperty(value = StrategyConstant.SPRING_APPLICATION_STRATEGY_MONITOR_ENABLED, matchIfMissing = false) + public StrategyTracer strategyTracer() { + return new OpenTelemetryStrategyTracer(); + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-opentelemetry/src/main/java/com/nepxion/discovery/plugin/strategy/opentelemetry/constant/OpenTelemetryStrategyConstant.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-opentelemetry/src/main/java/com/nepxion/discovery/plugin/strategy/opentelemetry/constant/OpenTelemetryStrategyConstant.java new file mode 100644 index 0000000000..7afdf16177 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-opentelemetry/src/main/java/com/nepxion/discovery/plugin/strategy/opentelemetry/constant/OpenTelemetryStrategyConstant.java @@ -0,0 +1,14 @@ +package com.nepxion.discovery.plugin.strategy.opentelemetry.constant; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +public class OpenTelemetryStrategyConstant { + +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-opentelemetry/src/main/java/com/nepxion/discovery/plugin/strategy/opentelemetry/monitor/OpenTelemetryStrategyTracer.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-opentelemetry/src/main/java/com/nepxion/discovery/plugin/strategy/opentelemetry/monitor/OpenTelemetryStrategyTracer.java new file mode 100644 index 0000000000..fa66d403a0 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-opentelemetry/src/main/java/com/nepxion/discovery/plugin/strategy/opentelemetry/monitor/OpenTelemetryStrategyTracer.java @@ -0,0 +1,70 @@ +package com.nepxion.discovery.plugin.strategy.opentelemetry.monitor; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import io.opentelemetry.api.trace.Span; +import io.opentelemetry.api.trace.Tracer; + +import org.apache.commons.lang3.exception.ExceptionUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; + +import com.nepxion.discovery.common.constant.DiscoveryConstant; +import com.nepxion.discovery.plugin.strategy.constant.StrategyConstant; +import com.nepxion.discovery.plugin.strategy.monitor.AbstractStrategyTracer; + +public class OpenTelemetryStrategyTracer extends AbstractStrategyTracer { + @Value("${" + StrategyConstant.SPRING_APPLICATION_STRATEGY_TRACER_EXCEPTION_DETAIL_OUTPUT_ENABLED + ":false}") + protected Boolean tracerExceptionDetailOutputEnabled; + + @Autowired + private Tracer tracer; + + @Override + protected Span buildSpan() { + return tracer.spanBuilder(tracerSpanValue).startSpan(); + } + + @Override + protected void outputSpan(Span span, String key, String value) { + span.setAttribute(key, value); + } + + @Override + protected void errorSpan(Span span, Throwable e) { + span.setAttribute(DiscoveryConstant.EVENT, DiscoveryConstant.ERROR); + if (tracerExceptionDetailOutputEnabled) { + span.setAttribute(DiscoveryConstant.ERROR_OBJECT, ExceptionUtils.getStackTrace(e)); + } else { + span.recordException(e); + } + } + + @Override + protected void finishSpan(Span span) { + span.end(); + } + + // Never used probably + @Override + protected Span getActiveSpan() { + return null; + } + + @Override + protected String toTraceId(Span span) { + return span.getSpanContext().getTraceId(); + } + + @Override + protected String toSpanId(Span span) { + return span.getSpanContext().getSpanId(); + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-opentelemetry/src/main/resources/META-INF/spring.factories b/discovery-plugin-strategy/discovery-plugin-strategy-starter-opentelemetry/src/main/resources/META-INF/spring.factories new file mode 100644 index 0000000000..233b2f2ea7 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-opentelemetry/src/main/resources/META-INF/spring.factories @@ -0,0 +1,2 @@ +org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ +com.nepxion.discovery.plugin.strategy.opentelemetry.configuration.OpenTelemetryStrategyAutoConfiguration \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-opentracing/pom.xml b/discovery-plugin-strategy/discovery-plugin-strategy-starter-opentracing/pom.xml new file mode 100644 index 0000000000..8bd8ff4195 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-opentracing/pom.xml @@ -0,0 +1,30 @@ + + + discovery-plugin-strategy-starter-opentracing + Nepxion Discovery Plugin Strategy Starter OpenTracing + jar + 4.0.0 + Nepxion Discovery is a solution for Spring Cloud with blue green, gray, weight, limitation, circuit breaker, degrade, isolation, monitor, tracing, dye, failover, async agent + http://www.nepxion.com + + + com.nepxion + discovery-plugin-strategy + 6.23.0 + + + + + ${project.groupId} + discovery-plugin-strategy-starter + + + + io.opentracing + opentracing-api + ${opentracing.version} + provided + + + \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-opentracing/src/main/java/com/nepxion/discovery/plugin/strategy/opentracing/configuration/OpenTracingStrategyAutoConfiguration.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-opentracing/src/main/java/com/nepxion/discovery/plugin/strategy/opentracing/configuration/OpenTracingStrategyAutoConfiguration.java new file mode 100644 index 0000000000..c9abb0428a --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-opentracing/src/main/java/com/nepxion/discovery/plugin/strategy/opentracing/configuration/OpenTracingStrategyAutoConfiguration.java @@ -0,0 +1,41 @@ +package com.nepxion.discovery.plugin.strategy.opentracing.configuration; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import com.nepxion.banner.BannerConstant; +import com.nepxion.banner.Description; +import com.nepxion.banner.LogoBanner; +import com.nepxion.banner.NepxionBanner; +import com.nepxion.discovery.common.entity.TracingType; +import com.nepxion.discovery.plugin.strategy.constant.StrategyConstant; +import com.nepxion.discovery.plugin.strategy.monitor.StrategyTracer; +import com.nepxion.discovery.plugin.strategy.opentracing.monitor.OpenTracingStrategyTracer; +import com.taobao.text.Color; + +@Configuration +public class OpenTracingStrategyAutoConfiguration { + static { + LogoBanner logoBanner = new LogoBanner(OpenTracingStrategyAutoConfiguration.class, "/com/nepxion/opentracing/resource/logo.txt", "Welcome to Nepxion", 8, 5, new Color[] { Color.red, Color.green, Color.cyan, Color.blue, Color.yellow, Color.magenta, Color.red, Color.green }, true); + + NepxionBanner.show(logoBanner, new Description("Tracing:", TracingType.OPENTRACING.toString(), 0, 1), new Description(BannerConstant.GITHUB + ":", BannerConstant.NEPXION_GITHUB + "/Discovery", 0, 1)); + } + + @Bean + @ConditionalOnMissingBean + @ConditionalOnProperty(value = StrategyConstant.SPRING_APPLICATION_STRATEGY_MONITOR_ENABLED, matchIfMissing = false) + public StrategyTracer strategyTracer() { + return new OpenTracingStrategyTracer(); + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-opentracing/src/main/java/com/nepxion/discovery/plugin/strategy/opentracing/constant/OpenTracingStrategyConstant.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-opentracing/src/main/java/com/nepxion/discovery/plugin/strategy/opentracing/constant/OpenTracingStrategyConstant.java new file mode 100644 index 0000000000..a7af28b7f0 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-opentracing/src/main/java/com/nepxion/discovery/plugin/strategy/opentracing/constant/OpenTracingStrategyConstant.java @@ -0,0 +1,14 @@ +package com.nepxion.discovery.plugin.strategy.opentracing.constant; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +public class OpenTracingStrategyConstant { + +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-opentracing/src/main/java/com/nepxion/discovery/plugin/strategy/opentracing/monitor/OpenTracingStrategyTracer.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-opentracing/src/main/java/com/nepxion/discovery/plugin/strategy/opentracing/monitor/OpenTracingStrategyTracer.java new file mode 100644 index 0000000000..5699ca8728 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-opentracing/src/main/java/com/nepxion/discovery/plugin/strategy/opentracing/monitor/OpenTracingStrategyTracer.java @@ -0,0 +1,74 @@ +package com.nepxion.discovery.plugin.strategy.opentracing.monitor; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import io.opentracing.Span; +import io.opentracing.Tracer; + +import java.util.LinkedHashMap; +import java.util.Map; + +import org.apache.commons.lang3.exception.ExceptionUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; + +import com.nepxion.discovery.common.constant.DiscoveryConstant; +import com.nepxion.discovery.plugin.strategy.constant.StrategyConstant; +import com.nepxion.discovery.plugin.strategy.monitor.AbstractStrategyTracer; + +public class OpenTracingStrategyTracer extends AbstractStrategyTracer { + @Value("${" + StrategyConstant.SPRING_APPLICATION_STRATEGY_TRACER_EXCEPTION_DETAIL_OUTPUT_ENABLED + ":false}") + protected Boolean tracerExceptionDetailOutputEnabled; + + @Autowired + private Tracer tracer; + + @Override + protected Span buildSpan() { + return tracer.buildSpan(tracerSpanValue).start(); + } + + @Override + protected void outputSpan(Span span, String key, String value) { + span.setTag(key, value); + } + + @Override + protected void errorSpan(Span span, Throwable e) { + Map map = new LinkedHashMap(); + map.put(DiscoveryConstant.EVENT, DiscoveryConstant.ERROR); + if (tracerExceptionDetailOutputEnabled) { + map.put(DiscoveryConstant.ERROR_OBJECT, ExceptionUtils.getStackTrace(e)); + } else { + map.put(DiscoveryConstant.ERROR_OBJECT, e); + } + span.log(map); + } + + @Override + protected void finishSpan(Span span) { + span.finish(); + } + + @Override + protected Span getActiveSpan() { + return tracer.activeSpan(); + } + + @Override + protected String toTraceId(Span span) { + return span.context().toTraceId(); + } + + @Override + protected String toSpanId(Span span) { + return span.context().toSpanId(); + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-opentracing/src/main/resources/META-INF/spring.factories b/discovery-plugin-strategy/discovery-plugin-strategy-starter-opentracing/src/main/resources/META-INF/spring.factories new file mode 100644 index 0000000000..fcb54ce31e --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-opentracing/src/main/resources/META-INF/spring.factories @@ -0,0 +1,2 @@ +org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ +com.nepxion.discovery.plugin.strategy.opentracing.configuration.OpenTracingStrategyAutoConfiguration \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-datasource/pom.xml b/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-datasource/pom.xml new file mode 100644 index 0000000000..dcbe16f3ed --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-datasource/pom.xml @@ -0,0 +1,74 @@ + + + discovery-plugin-strategy-starter-sentinel-datasource + Nepxion Discovery Plugin Strategy Starter Sentinel DataSource + jar + 4.0.0 + Nepxion Discovery is a solution for Spring Cloud with blue green, gray, weight, limitation, circuit breaker, degrade, isolation, monitor, tracing, dye, failover, async agent + http://www.nepxion.com + + + com.nepxion + discovery-plugin-strategy + 6.23.0 + + + + + ${project.groupId} + discovery-plugin-framework-starter + + + + ${project.groupId} + discovery-common-nacos + provided + + + + ${project.groupId} + discovery-common-apollo + provided + + + + ${project.groupId} + discovery-common-redis + provided + + + + ${project.groupId} + discovery-common-zookeeper + provided + + + + ${project.groupId} + discovery-common-consul + provided + + + + ${project.groupId} + discovery-common-etcd + provided + + + + com.alibaba.csp + sentinel-core + + + + com.alibaba.csp + sentinel-parameter-flow-control + + + + com.alibaba.csp + sentinel-transport-simple-http + + + \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-datasource/src/main/java/com/nepxion/discovery/plugin/strategy/sentinel/datasource/configuration/SentinelStrategyDataSourceAutoConfiguration.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-datasource/src/main/java/com/nepxion/discovery/plugin/strategy/sentinel/datasource/configuration/SentinelStrategyDataSourceAutoConfiguration.java new file mode 100644 index 0000000000..b1f3dfd42b --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-datasource/src/main/java/com/nepxion/discovery/plugin/strategy/sentinel/datasource/configuration/SentinelStrategyDataSourceAutoConfiguration.java @@ -0,0 +1,251 @@ +package com.nepxion.discovery.plugin.strategy.sentinel.datasource.configuration; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Weihua Wang + * @author Haojun Ren + * @version 1.0 + */ + +import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import com.nepxion.banner.BannerConstant; +import com.nepxion.banner.Description; +import com.nepxion.banner.LogoBanner; +import com.nepxion.banner.NepxionBanner; +import com.nepxion.discovery.common.apollo.proccessor.ApolloProcessor; +import com.nepxion.discovery.common.consul.proccessor.ConsulProcessor; +import com.nepxion.discovery.common.entity.ProtectorType; +import com.nepxion.discovery.common.entity.SentinelRuleType; +import com.nepxion.discovery.common.etcd.proccessor.EtcdProcessor; +import com.nepxion.discovery.common.nacos.proccessor.NacosProcessor; +import com.nepxion.discovery.common.redis.proccessor.RedisProcessor; +import com.nepxion.discovery.common.zookeeper.proccessor.ZookeeperProcessor; +import com.nepxion.discovery.plugin.strategy.sentinel.datasource.constant.SentinelStrategyDataSourceConstant; +import com.nepxion.discovery.plugin.strategy.sentinel.datasource.loader.SentinelStrategyRuleLoader; +import com.nepxion.discovery.plugin.strategy.sentinel.datasource.parser.SentinelStrategyAuthorityRuleParser; +import com.nepxion.discovery.plugin.strategy.sentinel.datasource.parser.SentinelStrategyDegradeRuleParser; +import com.nepxion.discovery.plugin.strategy.sentinel.datasource.parser.SentinelStrategyFlowRuleParser; +import com.nepxion.discovery.plugin.strategy.sentinel.datasource.parser.SentinelStrategyParamFlowRuleParser; +import com.nepxion.discovery.plugin.strategy.sentinel.datasource.parser.SentinelStrategySystemRuleParser; +import com.nepxion.discovery.plugin.strategy.sentinel.datasource.processor.SentinelStrategyRuleApolloProcessor; +import com.nepxion.discovery.plugin.strategy.sentinel.datasource.processor.SentinelStrategyRuleConsulProcessor; +import com.nepxion.discovery.plugin.strategy.sentinel.datasource.processor.SentinelStrategyRuleEtcdProcessor; +import com.nepxion.discovery.plugin.strategy.sentinel.datasource.processor.SentinelStrategyRuleNacosProcessor; +import com.nepxion.discovery.plugin.strategy.sentinel.datasource.processor.SentinelStrategyRuleRedisProcessor; +import com.nepxion.discovery.plugin.strategy.sentinel.datasource.processor.SentinelStrategyRuleZookeeperProcessor; +import com.taobao.text.Color; + +@Configuration +@ConditionalOnProperty(value = SentinelStrategyDataSourceConstant.SPRING_APPLICATION_STRATEGY_SENTINEL_DATASOURCE_ENABLED, matchIfMissing = false) +public class SentinelStrategyDataSourceAutoConfiguration { + static { + LogoBanner logoBanner = new LogoBanner(SentinelStrategyDataSourceAutoConfiguration.class, "/com/nepxion/sentinel/resource/logo.txt", "Welcome to Nepxion", 8, 5, new Color[] { Color.red, Color.green, Color.cyan, Color.blue, Color.yellow, Color.magenta, Color.red, Color.green }, true); + + NepxionBanner.show(logoBanner, new Description("Protector:", ProtectorType.SENTINEL.toString(), 0, 1), new Description(BannerConstant.GITHUB + ":", BannerConstant.NEPXION_GITHUB + "/Discovery", 0, 1)); + } + + @Bean + public SentinelStrategyFlowRuleParser sentinelStrategyFlowRuleParser() { + return new SentinelStrategyFlowRuleParser(); + } + + @Bean + public SentinelStrategyDegradeRuleParser sentinelStrategyDegradeRuleParser() { + return new SentinelStrategyDegradeRuleParser(); + } + + @Bean + public SentinelStrategyAuthorityRuleParser sentinelStrategyAuthorityRuleParser() { + return new SentinelStrategyAuthorityRuleParser(); + } + + @Bean + public SentinelStrategySystemRuleParser sentinelStrategySystemRuleParser() { + return new SentinelStrategySystemRuleParser(); + } + + @Bean + public SentinelStrategyParamFlowRuleParser sentinelStrategyParamFlowRuleParser() { + return new SentinelStrategyParamFlowRuleParser(); + } + + @Bean + public SentinelStrategyRuleLoader sentinelStrategyRuleLoader() { + return new SentinelStrategyRuleLoader(); + } + + @ConditionalOnClass(NacosProcessor.class) + protected static class SentinelStrategyNacosConfiguration { + @Bean + public NacosProcessor sentinelStrategyFlowRuleNacosProcessor() { + return new SentinelStrategyRuleNacosProcessor(SentinelRuleType.FLOW); + } + + @Bean + public NacosProcessor sentinelStrategyDegradeRuleNacosProcessor() { + return new SentinelStrategyRuleNacosProcessor(SentinelRuleType.DEGRADE); + } + + @Bean + public NacosProcessor sentinelStrategyAuthorityRuleNacosProcessor() { + return new SentinelStrategyRuleNacosProcessor(SentinelRuleType.AUTHORITY); + } + + @Bean + public NacosProcessor sentinelStrategySystemRuleNacosProcessor() { + return new SentinelStrategyRuleNacosProcessor(SentinelRuleType.SYSTEM); + } + + @Bean + public NacosProcessor sentinelStrategyParamFlowRuleNacosProcessor() { + return new SentinelStrategyRuleNacosProcessor(SentinelRuleType.PARAM_FLOW); + } + } + + @ConditionalOnClass(ApolloProcessor.class) + protected static class SentinelStrategyApolloConfiguration { + @Bean + public ApolloProcessor sentinelStrategyFlowRuleApolloProcessor() { + return new SentinelStrategyRuleApolloProcessor(SentinelRuleType.FLOW); + } + + @Bean + public ApolloProcessor sentinelStrategyDegradeRuleApolloProcessor() { + return new SentinelStrategyRuleApolloProcessor(SentinelRuleType.DEGRADE); + } + + @Bean + public ApolloProcessor sentinelStrategyAuthorityRuleApolloProcessor() { + return new SentinelStrategyRuleApolloProcessor(SentinelRuleType.AUTHORITY); + } + + @Bean + public ApolloProcessor sentinelStrategySystemRuleApolloProcessor() { + return new SentinelStrategyRuleApolloProcessor(SentinelRuleType.SYSTEM); + } + + @Bean + public ApolloProcessor sentinelStrategyParamFlowRuleApolloProcessor() { + return new SentinelStrategyRuleApolloProcessor(SentinelRuleType.PARAM_FLOW); + } + } + + @ConditionalOnClass(RedisProcessor.class) + protected static class SentinelStrategyRedisConfiguration { + @Bean + public RedisProcessor sentinelStrategyFlowRuleRedisProcessor() { + return new SentinelStrategyRuleRedisProcessor(SentinelRuleType.FLOW); + } + + @Bean + public RedisProcessor sentinelStrategyDegradeRuleRedisProcessor() { + return new SentinelStrategyRuleRedisProcessor(SentinelRuleType.DEGRADE); + } + + @Bean + public RedisProcessor sentinelStrategyAuthorityRuleRedisProcessor() { + return new SentinelStrategyRuleRedisProcessor(SentinelRuleType.AUTHORITY); + } + + @Bean + public RedisProcessor sentinelStrategySystemRuleRedisProcessor() { + return new SentinelStrategyRuleRedisProcessor(SentinelRuleType.SYSTEM); + } + + @Bean + public RedisProcessor sentinelStrategyParamFlowRuleRedisProcessor() { + return new SentinelStrategyRuleRedisProcessor(SentinelRuleType.PARAM_FLOW); + } + } + + @ConditionalOnClass(ZookeeperProcessor.class) + protected static class SentinelStrategyZookeeperConfiguration { + @Bean + public ZookeeperProcessor sentinelStrategyFlowRuleZookeeperProcessor() { + return new SentinelStrategyRuleZookeeperProcessor(SentinelRuleType.FLOW); + } + + @Bean + public ZookeeperProcessor sentinelStrategyDegradeRuleZookeeperProcessor() { + return new SentinelStrategyRuleZookeeperProcessor(SentinelRuleType.DEGRADE); + } + + @Bean + public ZookeeperProcessor sentinelStrategyAuthorityRuleZookeeperProcessor() { + return new SentinelStrategyRuleZookeeperProcessor(SentinelRuleType.AUTHORITY); + } + + @Bean + public ZookeeperProcessor sentinelStrategySystemRuleZookeeperProcessor() { + return new SentinelStrategyRuleZookeeperProcessor(SentinelRuleType.SYSTEM); + } + + @Bean + public ZookeeperProcessor sentinelStrategyParamFlowRuleZookeeperProcessor() { + return new SentinelStrategyRuleZookeeperProcessor(SentinelRuleType.PARAM_FLOW); + } + } + + @ConditionalOnClass(ConsulProcessor.class) + protected static class SentinelStrategyConsulConfiguration { + @Bean + public ConsulProcessor sentinelStrategyFlowRuleConsulProcessor() { + return new SentinelStrategyRuleConsulProcessor(SentinelRuleType.FLOW); + } + + @Bean + public ConsulProcessor sentinelStrategyDegradeRuleConsulProcessor() { + return new SentinelStrategyRuleConsulProcessor(SentinelRuleType.DEGRADE); + } + + @Bean + public ConsulProcessor sentinelStrategyAuthorityRuleConsulProcessor() { + return new SentinelStrategyRuleConsulProcessor(SentinelRuleType.AUTHORITY); + } + + @Bean + public ConsulProcessor sentinelStrategySystemRuleConsulProcessor() { + return new SentinelStrategyRuleConsulProcessor(SentinelRuleType.SYSTEM); + } + + @Bean + public ConsulProcessor sentinelStrategyParamFlowRuleConsulProcessor() { + return new SentinelStrategyRuleConsulProcessor(SentinelRuleType.PARAM_FLOW); + } + } + + @ConditionalOnClass(EtcdProcessor.class) + protected static class SentinelStrategyEtcdConfiguration { + @Bean + public EtcdProcessor sentinelStrategyFlowRuleEtcdProcessor() { + return new SentinelStrategyRuleEtcdProcessor(SentinelRuleType.FLOW); + } + + @Bean + public EtcdProcessor sentinelStrategyDegradeRuleEtcdProcessor() { + return new SentinelStrategyRuleEtcdProcessor(SentinelRuleType.DEGRADE); + } + + @Bean + public EtcdProcessor sentinelStrategyAuthorityRuleEtcdProcessor() { + return new SentinelStrategyRuleEtcdProcessor(SentinelRuleType.AUTHORITY); + } + + @Bean + public EtcdProcessor sentinelStrategySystemRuleEtcdProcessor() { + return new SentinelStrategyRuleEtcdProcessor(SentinelRuleType.SYSTEM); + } + + @Bean + public EtcdProcessor sentinelStrategyParamFlowRuleEtcdProcessor() { + return new SentinelStrategyRuleEtcdProcessor(SentinelRuleType.PARAM_FLOW); + } + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-datasource/src/main/java/com/nepxion/discovery/plugin/strategy/sentinel/datasource/constant/SentinelStrategyDataSourceConstant.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-datasource/src/main/java/com/nepxion/discovery/plugin/strategy/sentinel/datasource/constant/SentinelStrategyDataSourceConstant.java new file mode 100644 index 0000000000..82359bcb19 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-datasource/src/main/java/com/nepxion/discovery/plugin/strategy/sentinel/datasource/constant/SentinelStrategyDataSourceConstant.java @@ -0,0 +1,20 @@ +package com.nepxion.discovery.plugin.strategy.sentinel.datasource.constant; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Weihua Wang + * @author Haojun Ren + * @version 1.0 + */ + +public class SentinelStrategyDataSourceConstant { + public static final String SPRING_APPLICATION_STRATEGY_SENTINEL_DATASOURCE_ENABLED = "spring.application.strategy.sentinel.datasource.enabled"; + public static final String SPRING_APPLICATION_STRATEGY_SENTINEL_FLOW_PATH = "spring.application.strategy.sentinel.flow.path"; + public static final String SPRING_APPLICATION_STRATEGY_SENTINEL_DEGRADE_PATH = "spring.application.strategy.sentinel.degrade.path"; + public static final String SPRING_APPLICATION_STRATEGY_SENTINEL_AUTHORITY_PATH = "spring.application.strategy.sentinel.authority.path"; + public static final String SPRING_APPLICATION_STRATEGY_SENTINEL_SYSTEM_PATH = "spring.application.strategy.sentinel.system.path"; + public static final String SPRING_APPLICATION_STRATEGY_SENTINEL_PARAM_FLOW_PATH = "spring.application.strategy.sentinel.param.flow.path"; +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-datasource/src/main/java/com/nepxion/discovery/plugin/strategy/sentinel/datasource/loader/SentinelStrategyRuleLoader.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-datasource/src/main/java/com/nepxion/discovery/plugin/strategy/sentinel/datasource/loader/SentinelStrategyRuleLoader.java new file mode 100644 index 0000000000..beba858acb --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-datasource/src/main/java/com/nepxion/discovery/plugin/strategy/sentinel/datasource/loader/SentinelStrategyRuleLoader.java @@ -0,0 +1,186 @@ +package com.nepxion.discovery.plugin.strategy.sentinel.datasource.loader; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.ApplicationContext; + +import com.alibaba.csp.sentinel.slots.block.authority.AuthorityRuleManager; +import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager; +import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager; +import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowRuleManager; +import com.alibaba.csp.sentinel.slots.system.SystemRuleManager; +import com.nepxion.discovery.common.constant.DiscoveryConstant; +import com.nepxion.discovery.common.entity.SentinelRuleType; +import com.nepxion.discovery.common.util.FileUtil; +import com.nepxion.discovery.plugin.strategy.sentinel.datasource.constant.SentinelStrategyDataSourceConstant; +import com.nepxion.discovery.plugin.strategy.sentinel.datasource.parser.SentinelStrategyAuthorityRuleParser; +import com.nepxion.discovery.plugin.strategy.sentinel.datasource.parser.SentinelStrategyDegradeRuleParser; +import com.nepxion.discovery.plugin.strategy.sentinel.datasource.parser.SentinelStrategyFlowRuleParser; +import com.nepxion.discovery.plugin.strategy.sentinel.datasource.parser.SentinelStrategyParamFlowRuleParser; +import com.nepxion.discovery.plugin.strategy.sentinel.datasource.parser.SentinelStrategySystemRuleParser; + +public class SentinelStrategyRuleLoader { + private static final Logger LOG = LoggerFactory.getLogger(SentinelStrategyRuleLoader.class); + + @Value("${" + SentinelStrategyDataSourceConstant.SPRING_APPLICATION_STRATEGY_SENTINEL_FLOW_PATH + ":" + DiscoveryConstant.PREFIX_CLASSPATH + DiscoveryConstant.SENTINEL_FLOW_KEY + "." + DiscoveryConstant.JSON_FORMAT + "}") + private String sentinelStrategyFlowPath; + + @Value("${" + SentinelStrategyDataSourceConstant.SPRING_APPLICATION_STRATEGY_SENTINEL_DEGRADE_PATH + ":" + DiscoveryConstant.PREFIX_CLASSPATH + DiscoveryConstant.SENTINEL_DEGRADE_KEY + "." + DiscoveryConstant.JSON_FORMAT + "}") + private String sentinelStrategyDegradePath; + + @Value("${" + SentinelStrategyDataSourceConstant.SPRING_APPLICATION_STRATEGY_SENTINEL_AUTHORITY_PATH + ":" + DiscoveryConstant.PREFIX_CLASSPATH + DiscoveryConstant.SENTINEL_AUTHORITY_KEY + "." + DiscoveryConstant.JSON_FORMAT + "}") + private String sentinelStrategyAuthorityPath; + + @Value("${" + SentinelStrategyDataSourceConstant.SPRING_APPLICATION_STRATEGY_SENTINEL_SYSTEM_PATH + ":" + DiscoveryConstant.PREFIX_CLASSPATH + DiscoveryConstant.SENTINEL_SYSTEM_KEY + "." + DiscoveryConstant.JSON_FORMAT + "}") + private String sentinelStrategySystemPath; + + @Value("${" + SentinelStrategyDataSourceConstant.SPRING_APPLICATION_STRATEGY_SENTINEL_PARAM_FLOW_PATH + ":" + DiscoveryConstant.PREFIX_CLASSPATH + DiscoveryConstant.SENTINEL_PARAM_FLOW_KEY + "." + DiscoveryConstant.JSON_FORMAT + "}") + private String sentinelStrategyParamFlowPath; + + @Autowired + private SentinelStrategyFlowRuleParser sentinelStrategyFlowRuleParser; + + @Autowired + private SentinelStrategyDegradeRuleParser sentinelStrategyDegradeRuleParser; + + @Autowired + private SentinelStrategyAuthorityRuleParser sentinelStrategyAuthorityRuleParser; + + @Autowired + private SentinelStrategySystemRuleParser sentinelStrategySystemRuleParser; + + @Autowired + private SentinelStrategyParamFlowRuleParser sentinelStrategyParamFlowRuleParser; + + @Autowired + private ApplicationContext applicationContext; + + private boolean sentinelStrategyFlowRuleRetrieved = false; + + private boolean sentinelStrategyDegradeRuleRetrieved = false; + + private boolean sentinelStrategyAuthorityRuleRetrieved = false; + + private boolean sentinelStrategySystemRuleRetrieved = false; + + private boolean sentinelStrategyParamFlowRuleRetrieved = false; + + public void loadFileRules(SentinelRuleType sentinelRuleType) { + String ruleTypeDescription = sentinelRuleType.getDescription(); + + switch (sentinelRuleType) { + case FLOW: + if (!sentinelStrategyFlowRuleRetrieved) { + String sentinelStrategyRule = getRules(sentinelStrategyFlowPath); + if (StringUtils.isNotBlank(sentinelStrategyRule)) { + loadRules(sentinelRuleType, sentinelStrategyRule); + } + } else { + LOG.info("{} is retrieved from remote config, ignore to load from file...", ruleTypeDescription); + } + break; + case DEGRADE: + if (!sentinelStrategyDegradeRuleRetrieved) { + String sentinelStrategyRule = getRules(sentinelStrategyDegradePath); + if (StringUtils.isNotBlank(sentinelStrategyRule)) { + loadRules(sentinelRuleType, sentinelStrategyRule); + } + } else { + LOG.info("{} is retrieved from remote config, ignore to load from file...", ruleTypeDescription); + } + break; + case AUTHORITY: + if (!sentinelStrategyAuthorityRuleRetrieved) { + String sentinelStrategyRule = getRules(sentinelStrategyAuthorityPath); + if (StringUtils.isNotBlank(sentinelStrategyRule)) { + loadRules(sentinelRuleType, sentinelStrategyRule); + } + } else { + LOG.info("{} is retrieved from remote config, ignore to load from file...", ruleTypeDescription); + } + break; + case SYSTEM: + if (!sentinelStrategySystemRuleRetrieved) { + String sentinelStrategyRule = getRules(sentinelStrategySystemPath); + if (StringUtils.isNotBlank(sentinelStrategyRule)) { + loadRules(sentinelRuleType, sentinelStrategyRule); + } + } else { + LOG.info("{} is retrieved from remote config, ignore to load from file...", ruleTypeDescription); + } + break; + case PARAM_FLOW: + if (!sentinelStrategyParamFlowRuleRetrieved) { + String sentinelStrategyRule = getRules(sentinelStrategyParamFlowPath); + if (StringUtils.isNotBlank(sentinelStrategyRule)) { + loadRules(sentinelRuleType, sentinelStrategyRule); + } + } else { + LOG.info("{} is retrieved from remote config, ignore to load from file...", ruleTypeDescription); + } + break; + } + } + + public void loadRules(SentinelRuleType sentinelRuleType, String sentinelStrategyRule) { + if (StringUtils.isBlank(sentinelStrategyRule)) { + sentinelStrategyRule = DiscoveryConstant.EMPTY_JSON_RULE_MULTIPLE; + } + + String ruleTypeDescription = sentinelRuleType.getDescription(); + + switch (sentinelRuleType) { + case FLOW: + FlowRuleManager.loadRules(sentinelStrategyFlowRuleParser.convert(sentinelStrategyRule)); + + sentinelStrategyFlowRuleRetrieved = true; + + LOG.info("Loaded {} count={}", ruleTypeDescription, FlowRuleManager.getRules().size()); + break; + case DEGRADE: + DegradeRuleManager.loadRules(sentinelStrategyDegradeRuleParser.convert(sentinelStrategyRule)); + + sentinelStrategyDegradeRuleRetrieved = true; + + LOG.info("Loaded {} count={}", ruleTypeDescription, DegradeRuleManager.getRules().size()); + break; + case AUTHORITY: + AuthorityRuleManager.loadRules(sentinelStrategyAuthorityRuleParser.convert(sentinelStrategyRule)); + + sentinelStrategyAuthorityRuleRetrieved = true; + + LOG.info("Loaded {} count={}", ruleTypeDescription, AuthorityRuleManager.getRules().size()); + break; + case SYSTEM: + SystemRuleManager.loadRules(sentinelStrategySystemRuleParser.convert(sentinelStrategyRule)); + + sentinelStrategySystemRuleRetrieved = true; + + LOG.info("Loaded {} count={}", ruleTypeDescription, SystemRuleManager.getRules().size()); + break; + case PARAM_FLOW: + ParamFlowRuleManager.loadRules(sentinelStrategyParamFlowRuleParser.convert(sentinelStrategyRule)); + + sentinelStrategyParamFlowRuleRetrieved = true; + + LOG.info("Loaded {} count={}", ruleTypeDescription, ParamFlowRuleManager.getRules().size()); + break; + } + } + + public String getRules(String path) { + return FileUtil.getText(applicationContext, path); + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-datasource/src/main/java/com/nepxion/discovery/plugin/strategy/sentinel/datasource/parser/SentinelStrategyAuthorityRuleParser.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-datasource/src/main/java/com/nepxion/discovery/plugin/strategy/sentinel/datasource/parser/SentinelStrategyAuthorityRuleParser.java new file mode 100644 index 0000000000..a5deb28d6b --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-datasource/src/main/java/com/nepxion/discovery/plugin/strategy/sentinel/datasource/parser/SentinelStrategyAuthorityRuleParser.java @@ -0,0 +1,25 @@ +package com.nepxion.discovery.plugin.strategy.sentinel.datasource.parser; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.List; + +import com.alibaba.csp.sentinel.datasource.Converter; +import com.alibaba.csp.sentinel.slots.block.authority.AuthorityRule; +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.TypeReference; + +public class SentinelStrategyAuthorityRuleParser implements Converter> { + @Override + public List convert(String source) { + return JSON.parseObject(source, new TypeReference>() { + }); + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-datasource/src/main/java/com/nepxion/discovery/plugin/strategy/sentinel/datasource/parser/SentinelStrategyDegradeRuleParser.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-datasource/src/main/java/com/nepxion/discovery/plugin/strategy/sentinel/datasource/parser/SentinelStrategyDegradeRuleParser.java new file mode 100644 index 0000000000..3743d41ee6 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-datasource/src/main/java/com/nepxion/discovery/plugin/strategy/sentinel/datasource/parser/SentinelStrategyDegradeRuleParser.java @@ -0,0 +1,25 @@ +package com.nepxion.discovery.plugin.strategy.sentinel.datasource.parser; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.List; + +import com.alibaba.csp.sentinel.datasource.Converter; +import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule; +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.TypeReference; + +public class SentinelStrategyDegradeRuleParser implements Converter> { + @Override + public List convert(String source) { + return JSON.parseObject(source, new TypeReference>() { + }); + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-datasource/src/main/java/com/nepxion/discovery/plugin/strategy/sentinel/datasource/parser/SentinelStrategyFlowRuleParser.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-datasource/src/main/java/com/nepxion/discovery/plugin/strategy/sentinel/datasource/parser/SentinelStrategyFlowRuleParser.java new file mode 100644 index 0000000000..e9d7301163 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-datasource/src/main/java/com/nepxion/discovery/plugin/strategy/sentinel/datasource/parser/SentinelStrategyFlowRuleParser.java @@ -0,0 +1,25 @@ +package com.nepxion.discovery.plugin.strategy.sentinel.datasource.parser; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.List; + +import com.alibaba.csp.sentinel.datasource.Converter; +import com.alibaba.csp.sentinel.slots.block.flow.FlowRule; +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.TypeReference; + +public class SentinelStrategyFlowRuleParser implements Converter> { + @Override + public List convert(String source) { + return JSON.parseObject(source, new TypeReference>() { + }); + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-datasource/src/main/java/com/nepxion/discovery/plugin/strategy/sentinel/datasource/parser/SentinelStrategyParamFlowRuleParser.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-datasource/src/main/java/com/nepxion/discovery/plugin/strategy/sentinel/datasource/parser/SentinelStrategyParamFlowRuleParser.java new file mode 100644 index 0000000000..29ec71168c --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-datasource/src/main/java/com/nepxion/discovery/plugin/strategy/sentinel/datasource/parser/SentinelStrategyParamFlowRuleParser.java @@ -0,0 +1,25 @@ +package com.nepxion.discovery.plugin.strategy.sentinel.datasource.parser; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.List; + +import com.alibaba.csp.sentinel.datasource.Converter; +import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowRule; +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.TypeReference; + +public class SentinelStrategyParamFlowRuleParser implements Converter> { + @Override + public List convert(String source) { + return JSON.parseObject(source, new TypeReference>() { + }); + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-datasource/src/main/java/com/nepxion/discovery/plugin/strategy/sentinel/datasource/parser/SentinelStrategySystemRuleParser.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-datasource/src/main/java/com/nepxion/discovery/plugin/strategy/sentinel/datasource/parser/SentinelStrategySystemRuleParser.java new file mode 100644 index 0000000000..d29919ff8e --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-datasource/src/main/java/com/nepxion/discovery/plugin/strategy/sentinel/datasource/parser/SentinelStrategySystemRuleParser.java @@ -0,0 +1,25 @@ +package com.nepxion.discovery.plugin.strategy.sentinel.datasource.parser; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.List; + +import com.alibaba.csp.sentinel.datasource.Converter; +import com.alibaba.csp.sentinel.slots.system.SystemRule; +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.TypeReference; + +public class SentinelStrategySystemRuleParser implements Converter> { + @Override + public List convert(String source) { + return JSON.parseObject(source, new TypeReference>() { + }); + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-datasource/src/main/java/com/nepxion/discovery/plugin/strategy/sentinel/datasource/processor/SentinelStrategyRuleApolloProcessor.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-datasource/src/main/java/com/nepxion/discovery/plugin/strategy/sentinel/datasource/processor/SentinelStrategyRuleApolloProcessor.java new file mode 100644 index 0000000000..bb57fca701 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-datasource/src/main/java/com/nepxion/discovery/plugin/strategy/sentinel/datasource/processor/SentinelStrategyRuleApolloProcessor.java @@ -0,0 +1,56 @@ +package com.nepxion.discovery.plugin.strategy.sentinel.datasource.processor; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.springframework.beans.factory.annotation.Autowired; + +import com.nepxion.discovery.common.apollo.proccessor.ApolloProcessor; +import com.nepxion.discovery.common.entity.SentinelRuleType; +import com.nepxion.discovery.plugin.framework.adapter.PluginAdapter; +import com.nepxion.discovery.plugin.strategy.sentinel.datasource.loader.SentinelStrategyRuleLoader; + +public class SentinelStrategyRuleApolloProcessor extends ApolloProcessor { + @Autowired + private PluginAdapter pluginAdapter; + + @Autowired + private SentinelStrategyRuleLoader sentinelStrategyRuleLoader; + + private SentinelRuleType sentinelRuleType; + + public SentinelStrategyRuleApolloProcessor(SentinelRuleType sentinelRuleType) { + this.sentinelRuleType = sentinelRuleType; + } + + @Override + public void afterInitialization() { + sentinelStrategyRuleLoader.loadFileRules(sentinelRuleType); + } + + @Override + public String getGroup() { + return pluginAdapter.getGroup(); + } + + @Override + public String getDataId() { + return pluginAdapter.getServiceId() + "-" + sentinelRuleType.getKey(); + } + + @Override + public String getDescription() { + return sentinelRuleType.getDescription(); + } + + @Override + public void callbackConfig(String config) { + sentinelStrategyRuleLoader.loadRules(sentinelRuleType, config); + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-datasource/src/main/java/com/nepxion/discovery/plugin/strategy/sentinel/datasource/processor/SentinelStrategyRuleConsulProcessor.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-datasource/src/main/java/com/nepxion/discovery/plugin/strategy/sentinel/datasource/processor/SentinelStrategyRuleConsulProcessor.java new file mode 100644 index 0000000000..631359fc26 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-datasource/src/main/java/com/nepxion/discovery/plugin/strategy/sentinel/datasource/processor/SentinelStrategyRuleConsulProcessor.java @@ -0,0 +1,56 @@ +package com.nepxion.discovery.plugin.strategy.sentinel.datasource.processor; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.springframework.beans.factory.annotation.Autowired; + +import com.nepxion.discovery.common.consul.proccessor.ConsulProcessor; +import com.nepxion.discovery.common.entity.SentinelRuleType; +import com.nepxion.discovery.plugin.framework.adapter.PluginAdapter; +import com.nepxion.discovery.plugin.strategy.sentinel.datasource.loader.SentinelStrategyRuleLoader; + +public class SentinelStrategyRuleConsulProcessor extends ConsulProcessor { + @Autowired + private PluginAdapter pluginAdapter; + + @Autowired + private SentinelStrategyRuleLoader sentinelStrategyRuleLoader; + + private SentinelRuleType sentinelRuleType; + + public SentinelStrategyRuleConsulProcessor(SentinelRuleType sentinelRuleType) { + this.sentinelRuleType = sentinelRuleType; + } + + @Override + public void afterInitialization() { + sentinelStrategyRuleLoader.loadFileRules(sentinelRuleType); + } + + @Override + public String getGroup() { + return pluginAdapter.getGroup(); + } + + @Override + public String getDataId() { + return pluginAdapter.getServiceId() + "-" + sentinelRuleType.getKey(); + } + + @Override + public String getDescription() { + return sentinelRuleType.getDescription(); + } + + @Override + public void callbackConfig(String config) { + sentinelStrategyRuleLoader.loadRules(sentinelRuleType, config); + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-datasource/src/main/java/com/nepxion/discovery/plugin/strategy/sentinel/datasource/processor/SentinelStrategyRuleEtcdProcessor.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-datasource/src/main/java/com/nepxion/discovery/plugin/strategy/sentinel/datasource/processor/SentinelStrategyRuleEtcdProcessor.java new file mode 100644 index 0000000000..46e5e99a76 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-datasource/src/main/java/com/nepxion/discovery/plugin/strategy/sentinel/datasource/processor/SentinelStrategyRuleEtcdProcessor.java @@ -0,0 +1,56 @@ +package com.nepxion.discovery.plugin.strategy.sentinel.datasource.processor; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.springframework.beans.factory.annotation.Autowired; + +import com.nepxion.discovery.common.entity.SentinelRuleType; +import com.nepxion.discovery.common.etcd.proccessor.EtcdProcessor; +import com.nepxion.discovery.plugin.framework.adapter.PluginAdapter; +import com.nepxion.discovery.plugin.strategy.sentinel.datasource.loader.SentinelStrategyRuleLoader; + +public class SentinelStrategyRuleEtcdProcessor extends EtcdProcessor { + @Autowired + private PluginAdapter pluginAdapter; + + @Autowired + private SentinelStrategyRuleLoader sentinelStrategyRuleLoader; + + private SentinelRuleType sentinelRuleType; + + public SentinelStrategyRuleEtcdProcessor(SentinelRuleType sentinelRuleType) { + this.sentinelRuleType = sentinelRuleType; + } + + @Override + public void afterInitialization() { + sentinelStrategyRuleLoader.loadFileRules(sentinelRuleType); + } + + @Override + public String getGroup() { + return pluginAdapter.getGroup(); + } + + @Override + public String getDataId() { + return pluginAdapter.getServiceId() + "-" + sentinelRuleType.getKey(); + } + + @Override + public String getDescription() { + return sentinelRuleType.getDescription(); + } + + @Override + public void callbackConfig(String config) { + sentinelStrategyRuleLoader.loadRules(sentinelRuleType, config); + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-datasource/src/main/java/com/nepxion/discovery/plugin/strategy/sentinel/datasource/processor/SentinelStrategyRuleNacosProcessor.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-datasource/src/main/java/com/nepxion/discovery/plugin/strategy/sentinel/datasource/processor/SentinelStrategyRuleNacosProcessor.java new file mode 100644 index 0000000000..b7a7bea806 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-datasource/src/main/java/com/nepxion/discovery/plugin/strategy/sentinel/datasource/processor/SentinelStrategyRuleNacosProcessor.java @@ -0,0 +1,56 @@ +package com.nepxion.discovery.plugin.strategy.sentinel.datasource.processor; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.springframework.beans.factory.annotation.Autowired; + +import com.nepxion.discovery.common.entity.SentinelRuleType; +import com.nepxion.discovery.common.nacos.proccessor.NacosProcessor; +import com.nepxion.discovery.plugin.framework.adapter.PluginAdapter; +import com.nepxion.discovery.plugin.strategy.sentinel.datasource.loader.SentinelStrategyRuleLoader; + +public class SentinelStrategyRuleNacosProcessor extends NacosProcessor { + @Autowired + private PluginAdapter pluginAdapter; + + @Autowired + private SentinelStrategyRuleLoader sentinelStrategyRuleLoader; + + private SentinelRuleType sentinelRuleType; + + public SentinelStrategyRuleNacosProcessor(SentinelRuleType sentinelRuleType) { + this.sentinelRuleType = sentinelRuleType; + } + + @Override + public void afterInitialization() { + sentinelStrategyRuleLoader.loadFileRules(sentinelRuleType); + } + + @Override + public String getGroup() { + return pluginAdapter.getGroup(); + } + + @Override + public String getDataId() { + return pluginAdapter.getServiceId() + "-" + sentinelRuleType.getKey(); + } + + @Override + public String getDescription() { + return sentinelRuleType.getDescription(); + } + + @Override + public void callbackConfig(String config) { + sentinelStrategyRuleLoader.loadRules(sentinelRuleType, config); + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-datasource/src/main/java/com/nepxion/discovery/plugin/strategy/sentinel/datasource/processor/SentinelStrategyRuleRedisProcessor.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-datasource/src/main/java/com/nepxion/discovery/plugin/strategy/sentinel/datasource/processor/SentinelStrategyRuleRedisProcessor.java new file mode 100644 index 0000000000..50dc5bb3f9 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-datasource/src/main/java/com/nepxion/discovery/plugin/strategy/sentinel/datasource/processor/SentinelStrategyRuleRedisProcessor.java @@ -0,0 +1,56 @@ +package com.nepxion.discovery.plugin.strategy.sentinel.datasource.processor; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.springframework.beans.factory.annotation.Autowired; + +import com.nepxion.discovery.common.entity.SentinelRuleType; +import com.nepxion.discovery.common.redis.proccessor.RedisProcessor; +import com.nepxion.discovery.plugin.framework.adapter.PluginAdapter; +import com.nepxion.discovery.plugin.strategy.sentinel.datasource.loader.SentinelStrategyRuleLoader; + +public class SentinelStrategyRuleRedisProcessor extends RedisProcessor { + @Autowired + private PluginAdapter pluginAdapter; + + @Autowired + private SentinelStrategyRuleLoader sentinelStrategyRuleLoader; + + private SentinelRuleType sentinelRuleType; + + public SentinelStrategyRuleRedisProcessor(SentinelRuleType sentinelRuleType) { + this.sentinelRuleType = sentinelRuleType; + } + + @Override + public void afterInitialization() { + sentinelStrategyRuleLoader.loadFileRules(sentinelRuleType); + } + + @Override + public String getGroup() { + return pluginAdapter.getGroup(); + } + + @Override + public String getDataId() { + return pluginAdapter.getServiceId() + "-" + sentinelRuleType.getKey(); + } + + @Override + public String getDescription() { + return sentinelRuleType.getDescription(); + } + + @Override + public void callbackConfig(String config) { + sentinelStrategyRuleLoader.loadRules(sentinelRuleType, config); + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-datasource/src/main/java/com/nepxion/discovery/plugin/strategy/sentinel/datasource/processor/SentinelStrategyRuleZookeeperProcessor.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-datasource/src/main/java/com/nepxion/discovery/plugin/strategy/sentinel/datasource/processor/SentinelStrategyRuleZookeeperProcessor.java new file mode 100644 index 0000000000..8362cc0d3f --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-datasource/src/main/java/com/nepxion/discovery/plugin/strategy/sentinel/datasource/processor/SentinelStrategyRuleZookeeperProcessor.java @@ -0,0 +1,56 @@ +package com.nepxion.discovery.plugin.strategy.sentinel.datasource.processor; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.springframework.beans.factory.annotation.Autowired; + +import com.nepxion.discovery.common.entity.SentinelRuleType; +import com.nepxion.discovery.common.zookeeper.proccessor.ZookeeperProcessor; +import com.nepxion.discovery.plugin.framework.adapter.PluginAdapter; +import com.nepxion.discovery.plugin.strategy.sentinel.datasource.loader.SentinelStrategyRuleLoader; + +public class SentinelStrategyRuleZookeeperProcessor extends ZookeeperProcessor { + @Autowired + private PluginAdapter pluginAdapter; + + @Autowired + private SentinelStrategyRuleLoader sentinelStrategyRuleLoader; + + private SentinelRuleType sentinelRuleType; + + public SentinelStrategyRuleZookeeperProcessor(SentinelRuleType sentinelRuleType) { + this.sentinelRuleType = sentinelRuleType; + } + + @Override + public void afterInitialization() { + sentinelStrategyRuleLoader.loadFileRules(sentinelRuleType); + } + + @Override + public String getGroup() { + return pluginAdapter.getGroup(); + } + + @Override + public String getDataId() { + return pluginAdapter.getServiceId() + "-" + sentinelRuleType.getKey(); + } + + @Override + public String getDescription() { + return sentinelRuleType.getDescription(); + } + + @Override + public void callbackConfig(String config) { + sentinelStrategyRuleLoader.loadRules(sentinelRuleType, config); + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-datasource/src/main/resources/META-INF/additional-spring-configuration-metadata.json b/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-datasource/src/main/resources/META-INF/additional-spring-configuration-metadata.json new file mode 100644 index 0000000000..0314bcafae --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-datasource/src/main/resources/META-INF/additional-spring-configuration-metadata.json @@ -0,0 +1,40 @@ +{ + "properties": [ + { + "name": "spring.application.strategy.sentinel.datasource.enabled", + "type": "java.lang.Boolean", + "defaultValue": false, + "description": "Whether strategy sentinel datasource is enabled." + }, + { + "name": "spring.application.strategy.sentinel.flow.path", + "type": "java.lang.String", + "defaultValue": "classpath:sentinel-flow.json", + "description": "Strategy sentinel flow path, it can be classpath:xxx.json or file:xxx.json." + }, + { + "name": "spring.application.strategy.sentinel.degrade.path", + "type": "java.lang.String", + "defaultValue": "classpath:sentinel-degrade.json", + "description": "Strategy sentinel degrade path, it can be classpath:xxx.json or file:xxx.json." + }, + { + "name": "spring.application.strategy.sentinel.authority.path", + "type": "java.lang.String", + "defaultValue": "classpath:sentinel-authority.json", + "description": "Strategy sentinel authority path, it can be classpath:xxx.json or file:xxx.json." + }, + { + "name": "spring.application.strategy.sentinel.system.path", + "type": "java.lang.String", + "defaultValue": "classpath:sentinel-system.json", + "description": "Strategy sentinel system path, it can be classpath:xxx.json or file:xxx.json." + }, + { + "name": "spring.application.strategy.sentinel.param.flow.path", + "type": "java.lang.String", + "defaultValue": "classpath:sentinel-param-flow.json", + "description": "Strategy sentinel param flow path, it can be classpath:xxx.json or file:xxx.json." + } + ] +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-datasource/src/main/resources/META-INF/spring.factories b/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-datasource/src/main/resources/META-INF/spring.factories new file mode 100644 index 0000000000..0573acb2b2 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-datasource/src/main/resources/META-INF/spring.factories @@ -0,0 +1,2 @@ +org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ +com.nepxion.discovery.plugin.strategy.sentinel.datasource.configuration.SentinelStrategyDataSourceAutoConfiguration \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-limiter/pom.xml b/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-limiter/pom.xml new file mode 100644 index 0000000000..5c0ec142e4 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-limiter/pom.xml @@ -0,0 +1,38 @@ + + + discovery-plugin-strategy-starter-sentinel-limiter + Nepxion Discovery Plugin Strategy Starter Sentinel Limiter + jar + 4.0.0 + Nepxion Discovery is a solution for Spring Cloud with blue green, gray, weight, limitation, circuit breaker, degrade, isolation, monitor, tracing, dye, failover, async agent + http://www.nepxion.com + + + com.nepxion + discovery-plugin-strategy + 6.23.0 + + + + + ${project.groupId} + discovery-plugin-strategy-starter + + + + com.alibaba.csp + sentinel-annotation-aspectj + + + + com.alibaba.csp + sentinel-web-servlet + + + + org.springframework.boot + spring-boot-starter-web + + + \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-limiter/src/main/java/com/nepxion/discovery/plugin/strategy/sentinel/limiter/adapter/DefaultSentinelStrategyRequestOriginAdapter.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-limiter/src/main/java/com/nepxion/discovery/plugin/strategy/sentinel/limiter/adapter/DefaultSentinelStrategyRequestOriginAdapter.java new file mode 100644 index 0000000000..6e16cd649d --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-limiter/src/main/java/com/nepxion/discovery/plugin/strategy/sentinel/limiter/adapter/DefaultSentinelStrategyRequestOriginAdapter.java @@ -0,0 +1,33 @@ +package com.nepxion.discovery.plugin.strategy.sentinel.limiter.adapter; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; + +import com.nepxion.discovery.common.constant.DiscoveryConstant; +import com.nepxion.discovery.plugin.framework.adapter.PluginAdapter; +import com.nepxion.discovery.plugin.strategy.sentinel.limiter.constant.SentinelStrategyLimiterConstant; + +public abstract class DefaultSentinelStrategyRequestOriginAdapter implements SentinelStrategyRequestOriginAdapter { + @Value("${" + SentinelStrategyLimiterConstant.SPRING_APPLICATION_STRATEGY_SENTINEL_REQUEST_ORIGIN_KEY + ":" + DiscoveryConstant.N_D_SERVICE_ID + "}") + protected String requestOriginKey; + + @Autowired + protected PluginAdapter pluginAdapter; + + public String getRequestOriginKey() { + return requestOriginKey; + } + + public PluginAdapter getPluginAdapter() { + return pluginAdapter; + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-limiter/src/main/java/com/nepxion/discovery/plugin/strategy/sentinel/limiter/adapter/SentinelStrategyRequestOriginAdapter.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-limiter/src/main/java/com/nepxion/discovery/plugin/strategy/sentinel/limiter/adapter/SentinelStrategyRequestOriginAdapter.java new file mode 100644 index 0000000000..ecc75112a6 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-limiter/src/main/java/com/nepxion/discovery/plugin/strategy/sentinel/limiter/adapter/SentinelStrategyRequestOriginAdapter.java @@ -0,0 +1,16 @@ +package com.nepxion.discovery.plugin.strategy.sentinel.limiter.adapter; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import javax.servlet.http.HttpServletRequest; + +public interface SentinelStrategyRequestOriginAdapter { + String parseOrigin(HttpServletRequest request); +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-limiter/src/main/java/com/nepxion/discovery/plugin/strategy/sentinel/limiter/configuration/SentinelStrategyLimiterAutoConfiguration.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-limiter/src/main/java/com/nepxion/discovery/plugin/strategy/sentinel/limiter/configuration/SentinelStrategyLimiterAutoConfiguration.java new file mode 100644 index 0000000000..563fcc9223 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-limiter/src/main/java/com/nepxion/discovery/plugin/strategy/sentinel/limiter/configuration/SentinelStrategyLimiterAutoConfiguration.java @@ -0,0 +1,44 @@ +package com.nepxion.discovery.plugin.strategy.sentinel.limiter.configuration; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Weihua Wang + * @author Haojun Ren + * @version 1.0 + */ + +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import com.alibaba.csp.sentinel.adapter.servlet.CommonFilter; +import com.alibaba.csp.sentinel.adapter.servlet.callback.RequestOriginParser; +import com.alibaba.csp.sentinel.annotation.aspectj.SentinelResourceAspect; +import com.nepxion.discovery.plugin.strategy.sentinel.limiter.constant.SentinelStrategyLimiterConstant; +import com.nepxion.discovery.plugin.strategy.sentinel.limiter.parser.SentinelStrategyRequestOriginParser; + +@Configuration +@ConditionalOnProperty(value = SentinelStrategyLimiterConstant.SPRING_APPLICATION_STRATEGY_SENTINEL_LIMIT_APP_ENABLED, matchIfMissing = false) +public class SentinelStrategyLimiterAutoConfiguration { + @Bean + @ConditionalOnMissingBean + public CommonFilter commonFilter() { + return new CommonFilter(); + } + + @Bean + @ConditionalOnMissingBean + public SentinelResourceAspect sentinelResourceAspect() { + return new SentinelResourceAspect(); + } + + @Bean + @ConditionalOnMissingBean + public RequestOriginParser sentinelStrategyRequestOriginParser() { + return new SentinelStrategyRequestOriginParser(); + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-limiter/src/main/java/com/nepxion/discovery/plugin/strategy/sentinel/limiter/constant/SentinelStrategyLimiterConstant.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-limiter/src/main/java/com/nepxion/discovery/plugin/strategy/sentinel/limiter/constant/SentinelStrategyLimiterConstant.java new file mode 100644 index 0000000000..72202f8133 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-limiter/src/main/java/com/nepxion/discovery/plugin/strategy/sentinel/limiter/constant/SentinelStrategyLimiterConstant.java @@ -0,0 +1,16 @@ +package com.nepxion.discovery.plugin.strategy.sentinel.limiter.constant; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Weihua Wang + * @author Haojun Ren + * @version 1.0 + */ + +public class SentinelStrategyLimiterConstant { + public static final String SPRING_APPLICATION_STRATEGY_SENTINEL_LIMIT_APP_ENABLED = "spring.application.strategy.sentinel.limit.app.enabled"; + public static final String SPRING_APPLICATION_STRATEGY_SENTINEL_REQUEST_ORIGIN_KEY = "spring.application.strategy.sentinel.request.origin.key"; +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-limiter/src/main/java/com/nepxion/discovery/plugin/strategy/sentinel/limiter/parser/SentinelStrategyRequestOriginParser.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-limiter/src/main/java/com/nepxion/discovery/plugin/strategy/sentinel/limiter/parser/SentinelStrategyRequestOriginParser.java new file mode 100644 index 0000000000..f14699295b --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-limiter/src/main/java/com/nepxion/discovery/plugin/strategy/sentinel/limiter/parser/SentinelStrategyRequestOriginParser.java @@ -0,0 +1,46 @@ +package com.nepxion.discovery.plugin.strategy.sentinel.limiter.parser; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Weihua Wang + * @author Haojun Ren + * @version 1.0 + */ + +import javax.servlet.http.HttpServletRequest; + +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; + +import com.alibaba.csp.sentinel.adapter.servlet.callback.RequestOriginParser; +import com.alibaba.csp.sentinel.adapter.servlet.callback.WebCallbackManager; +import com.nepxion.discovery.common.constant.DiscoveryConstant; +import com.nepxion.discovery.plugin.strategy.sentinel.limiter.adapter.SentinelStrategyRequestOriginAdapter; +import com.nepxion.discovery.plugin.strategy.sentinel.limiter.constant.SentinelStrategyLimiterConstant; + +public class SentinelStrategyRequestOriginParser implements RequestOriginParser { + @Value("${" + SentinelStrategyLimiterConstant.SPRING_APPLICATION_STRATEGY_SENTINEL_REQUEST_ORIGIN_KEY + ":" + DiscoveryConstant.N_D_SERVICE_ID + "}") + protected String requestOriginKey; + + @Autowired(required = false) + protected SentinelStrategyRequestOriginAdapter sentinelStrategyRequestOriginAdapter; + + public SentinelStrategyRequestOriginParser() { + WebCallbackManager.setRequestOriginParser(this); + } + + @Override + public String parseOrigin(HttpServletRequest request) { + if (sentinelStrategyRequestOriginAdapter != null) { + return sentinelStrategyRequestOriginAdapter.parseOrigin(request); + } else { + String requestOriginValue = request.getHeader(requestOriginKey); + + return StringUtils.isNotEmpty(requestOriginValue) ? requestOriginValue : DiscoveryConstant.UNKNOWN; + } + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-limiter/src/main/resources/META-INF/additional-spring-configuration-metadata.json b/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-limiter/src/main/resources/META-INF/additional-spring-configuration-metadata.json new file mode 100644 index 0000000000..daf2beb5be --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-limiter/src/main/resources/META-INF/additional-spring-configuration-metadata.json @@ -0,0 +1,16 @@ +{ + "properties": [ + { + "name": "spring.application.strategy.sentinel.limit.app.enabled", + "type": "java.lang.Boolean", + "defaultValue": false, + "description": "Whether strategy sentinel limit app is enabled." + }, + { + "name": "spring.application.strategy.sentinel.request.origin.key", + "type": "java.lang.String", + "defaultValue": "n-d-service-id", + "description": "Strategy sentinel request origin key, it can be http header value." + } + ] +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-limiter/src/main/resources/META-INF/spring.factories b/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-limiter/src/main/resources/META-INF/spring.factories new file mode 100644 index 0000000000..cc8bc226d4 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-limiter/src/main/resources/META-INF/spring.factories @@ -0,0 +1,2 @@ +org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ +com.nepxion.discovery.plugin.strategy.sentinel.limiter.configuration.SentinelStrategyLimiterAutoConfiguration \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-micrometer/pom.xml b/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-micrometer/pom.xml new file mode 100644 index 0000000000..90848d99cb --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-micrometer/pom.xml @@ -0,0 +1,33 @@ + + + discovery-plugin-strategy-starter-sentinel-micrometer + Nepxion Discovery Plugin Strategy Starter Sentinel Micrometer + jar + 4.0.0 + Nepxion Discovery is a solution for Spring Cloud with blue green, gray, weight, limitation, circuit breaker, degrade, isolation, monitor, tracing, dye, failover, async agent + http://www.nepxion.com + + + com.nepxion + discovery-plugin-strategy + 6.23.0 + + + + + ${project.groupId} + discovery-plugin-strategy-starter + + + + com.alibaba.csp + sentinel-core + + + + io.micrometer + micrometer-core + + + \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-micrometer/src/main/java/com/nepxion/discovery/plugin/strategy/sentinel/micrometer/monitor/configuration/SentinelMicrometerAutoConfiguration.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-micrometer/src/main/java/com/nepxion/discovery/plugin/strategy/sentinel/micrometer/monitor/configuration/SentinelMicrometerAutoConfiguration.java new file mode 100644 index 0000000000..ee8e25aa34 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-micrometer/src/main/java/com/nepxion/discovery/plugin/strategy/sentinel/micrometer/monitor/configuration/SentinelMicrometerAutoConfiguration.java @@ -0,0 +1,23 @@ +package com.nepxion.discovery.plugin.strategy.sentinel.micrometer.monitor.configuration; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Tank + * @version 1.0 + */ + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import com.nepxion.discovery.plugin.strategy.sentinel.micrometer.monitor.metric.SentinelMicrometerMetricInitializer; + +@Configuration +public class SentinelMicrometerAutoConfiguration { + @Bean + public SentinelMicrometerMetricInitializer sentinelMicrometerMetricInitializer() { + return new SentinelMicrometerMetricInitializer(); + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-micrometer/src/main/java/com/nepxion/discovery/plugin/strategy/sentinel/micrometer/monitor/constant/SentinelMicrometerMetricConstant.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-micrometer/src/main/java/com/nepxion/discovery/plugin/strategy/sentinel/micrometer/monitor/constant/SentinelMicrometerMetricConstant.java new file mode 100644 index 0000000000..356e7c6bde --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-micrometer/src/main/java/com/nepxion/discovery/plugin/strategy/sentinel/micrometer/monitor/constant/SentinelMicrometerMetricConstant.java @@ -0,0 +1,19 @@ +package com.nepxion.discovery.plugin.strategy.sentinel.micrometer.monitor.constant; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Tank + * @version 1.0 + */ + +public class SentinelMicrometerMetricConstant { + public static final String SPRING_APPLICATION_STRATEGY_METRIC_SENTINEL_PASS_QPS_OUTPUT_ENABLED = "spring.application.strategy.metric.sentinel.pass.qps.output.enabled"; + public static final String SPRING_APPLICATION_STRATEGY_METRIC_SENTINEL_BLOCK_QPS_OUTPUT_ENABLED = "spring.application.strategy.metric.sentinel.block.qps.output.enabled"; + public static final String SPRING_APPLICATION_STRATEGY_METRIC_SENTINEL_SUCCESS_QPS_OUTPUT_ENABLED = "spring.application.strategy.metric.sentinel.success.qps.output.enabled"; + public static final String SPRING_APPLICATION_STRATEGY_METRIC_SENTINEL_EXCEPTION_QPS_OUTPUT_ENABLED = "spring.application.strategy.metric.sentinel.exception.qps.output.enabled"; + + public static final String RESOURCE = "resource"; +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-micrometer/src/main/java/com/nepxion/discovery/plugin/strategy/sentinel/micrometer/monitor/metric/SentinelMicrometerMetricExtension.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-micrometer/src/main/java/com/nepxion/discovery/plugin/strategy/sentinel/micrometer/monitor/metric/SentinelMicrometerMetricExtension.java new file mode 100644 index 0000000000..ba42b4b3eb --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-micrometer/src/main/java/com/nepxion/discovery/plugin/strategy/sentinel/micrometer/monitor/metric/SentinelMicrometerMetricExtension.java @@ -0,0 +1,73 @@ +package com.nepxion.discovery.plugin.strategy.sentinel.micrometer.monitor.metric; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Tank + * @version 1.0 + */ + +import io.micrometer.core.instrument.Metrics; + +import org.springframework.core.env.Environment; + +import com.alibaba.csp.sentinel.metric.extension.MetricExtension; +import com.alibaba.csp.sentinel.slots.block.BlockException; +import com.nepxion.discovery.common.entity.SentinelMetricType; +import com.nepxion.discovery.plugin.framework.context.PluginContextAware; +import com.nepxion.discovery.plugin.strategy.sentinel.micrometer.monitor.constant.SentinelMicrometerMetricConstant; + +public class SentinelMicrometerMetricExtension implements MetricExtension { + @Override + public void addPass(String resource, int n, Object... args) { + Environment environment = PluginContextAware.getStaticEnvironment(); + Boolean metricSentinelPassQpsOutputEnabled = environment.getProperty(SentinelMicrometerMetricConstant.SPRING_APPLICATION_STRATEGY_METRIC_SENTINEL_PASS_QPS_OUTPUT_ENABLED, Boolean.class, Boolean.TRUE); + if (metricSentinelPassQpsOutputEnabled) { + Metrics.counter(SentinelMetricType.PASS_QPS.toString(), SentinelMicrometerMetricConstant.RESOURCE, resource).increment(n); + } + } + + @Override + public void addBlock(String resource, int n, String origin, BlockException blockException, Object... args) { + Environment environment = PluginContextAware.getStaticEnvironment(); + Boolean metricSentinelBlockQpsOutputEnabled = environment.getProperty(SentinelMicrometerMetricConstant.SPRING_APPLICATION_STRATEGY_METRIC_SENTINEL_BLOCK_QPS_OUTPUT_ENABLED, Boolean.class, Boolean.TRUE); + if (metricSentinelBlockQpsOutputEnabled) { + Metrics.counter(SentinelMetricType.BLOCK_QPS.toString(), SentinelMicrometerMetricConstant.RESOURCE, resource).increment(n); + } + } + + @Override + public void addSuccess(String resource, int n, Object... args) { + Environment environment = PluginContextAware.getStaticEnvironment(); + Boolean metricSentinelSuccessQpsOutputEnabled = environment.getProperty(SentinelMicrometerMetricConstant.SPRING_APPLICATION_STRATEGY_METRIC_SENTINEL_SUCCESS_QPS_OUTPUT_ENABLED, Boolean.class, Boolean.TRUE); + if (metricSentinelSuccessQpsOutputEnabled) { + Metrics.counter(SentinelMetricType.SUCCESS_QPS.toString(), SentinelMicrometerMetricConstant.RESOURCE, resource).increment(n); + } + } + + @Override + public void addException(String resource, int n, Throwable throwable) { + Environment environment = PluginContextAware.getStaticEnvironment(); + Boolean metricSentinelExceptionQpsOutputEnabled = environment.getProperty(SentinelMicrometerMetricConstant.SPRING_APPLICATION_STRATEGY_METRIC_SENTINEL_EXCEPTION_QPS_OUTPUT_ENABLED, Boolean.class, Boolean.TRUE); + if (metricSentinelExceptionQpsOutputEnabled) { + Metrics.counter(SentinelMetricType.EXCEPTION_QPS.toString(), SentinelMicrometerMetricConstant.RESOURCE, resource).increment(n); + } + } + + @Override + public void addRt(String resource, long rt, Object... args) { + + } + + @Override + public void increaseThreadNum(String resource, Object... args) { + + } + + @Override + public void decreaseThreadNum(String resource, Object... args) { + + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-micrometer/src/main/java/com/nepxion/discovery/plugin/strategy/sentinel/micrometer/monitor/metric/SentinelMicrometerMetricInitializer.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-micrometer/src/main/java/com/nepxion/discovery/plugin/strategy/sentinel/micrometer/monitor/metric/SentinelMicrometerMetricInitializer.java new file mode 100644 index 0000000000..67b0792c55 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-micrometer/src/main/java/com/nepxion/discovery/plugin/strategy/sentinel/micrometer/monitor/metric/SentinelMicrometerMetricInitializer.java @@ -0,0 +1,33 @@ +package com.nepxion.discovery.plugin.strategy.sentinel.micrometer.monitor.metric; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Tank + * @version 1.0 + */ + +import io.micrometer.core.instrument.Counter; +import io.micrometer.core.instrument.MeterRegistry; + +import javax.annotation.PostConstruct; + +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; + +import com.nepxion.discovery.common.entity.SentinelMetricType; +import com.nepxion.discovery.plugin.strategy.sentinel.micrometer.monitor.constant.SentinelMicrometerMetricConstant; + +public class SentinelMicrometerMetricInitializer { + @Autowired + private MeterRegistry registry; + + @PostConstruct + public void initialize() { + for (SentinelMetricType sentinelMetricType : SentinelMetricType.values()) { + Counter.builder(sentinelMetricType.toString()).tag(SentinelMicrometerMetricConstant.RESOURCE, StringUtils.EMPTY).register(registry); + } + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-micrometer/src/main/resources/META-INF/additional-spring-configuration-metadata.json b/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-micrometer/src/main/resources/META-INF/additional-spring-configuration-metadata.json new file mode 100644 index 0000000000..171edbf41a --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-micrometer/src/main/resources/META-INF/additional-spring-configuration-metadata.json @@ -0,0 +1,28 @@ +{ + "properties": [ + { + "name": "spring.application.strategy.metric.sentinel.pass.qps.output.enabled", + "type": "java.lang.Boolean", + "defaultValue": true, + "description": "Whether strategy metric sentinel pass qps output is enabled." + }, + { + "name": "spring.application.strategy.metric.sentinel.block.qps.output.enabled", + "type": "java.lang.Boolean", + "defaultValue": true, + "description": "Whether strategy metric sentinel block qps output is enabled." + }, + { + "name": "spring.application.strategy.metric.sentinel.success.qps.output.enabled", + "type": "java.lang.Boolean", + "defaultValue": true, + "description": "Whether strategy metric sentinel success qps output is enabled." + }, + { + "name": "spring.application.strategy.metric.sentinel.exception.qps.output.enabled", + "type": "java.lang.Boolean", + "defaultValue": true, + "description": "Whether strategy metric sentinel exception qps output is enabled." + } + ] +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-micrometer/src/main/resources/META-INF/services/com.alibaba.csp.sentinel.metric.extension.MetricExtension b/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-micrometer/src/main/resources/META-INF/services/com.alibaba.csp.sentinel.metric.extension.MetricExtension new file mode 100644 index 0000000000..50183d7f9c --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-micrometer/src/main/resources/META-INF/services/com.alibaba.csp.sentinel.metric.extension.MetricExtension @@ -0,0 +1 @@ +com.nepxion.discovery.plugin.strategy.sentinel.micrometer.monitor.metric.SentinelMicrometerMetricExtension \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-micrometer/src/main/resources/META-INF/spring.factories b/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-micrometer/src/main/resources/META-INF/spring.factories new file mode 100644 index 0000000000..9fc6190df9 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-micrometer/src/main/resources/META-INF/spring.factories @@ -0,0 +1,2 @@ +org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ +com.nepxion.discovery.plugin.strategy.sentinel.micrometer.monitor.configuration.SentinelMicrometerAutoConfiguration \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-monitor/pom.xml b/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-monitor/pom.xml new file mode 100644 index 0000000000..fab2bb15d8 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-monitor/pom.xml @@ -0,0 +1,28 @@ + + + discovery-plugin-strategy-starter-sentinel-monitor + Nepxion Discovery Plugin Strategy Starter Sentinel Monitor + jar + 4.0.0 + Nepxion Discovery is a solution for Spring Cloud with blue green, gray, weight, limitation, circuit breaker, degrade, isolation, monitor, tracing, dye, failover, async agent + http://www.nepxion.com + + + com.nepxion + discovery-plugin-strategy + 6.23.0 + + + + + ${project.groupId} + discovery-plugin-strategy-starter + + + + com.alibaba.csp + sentinel-transport-simple-http + + + \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-monitor/src/main/java/com/nepxion/discovery/plugin/strategy/sentinel/monitor/callback/SentinelTracerProcessorSlotEntryCallback.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-monitor/src/main/java/com/nepxion/discovery/plugin/strategy/sentinel/monitor/callback/SentinelTracerProcessorSlotEntryCallback.java new file mode 100644 index 0000000000..8d2bc16cc8 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-monitor/src/main/java/com/nepxion/discovery/plugin/strategy/sentinel/monitor/callback/SentinelTracerProcessorSlotEntryCallback.java @@ -0,0 +1,95 @@ +package com.nepxion.discovery.plugin.strategy.sentinel.monitor.callback; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author zhang shun + * @version 1.0 + */ + +import org.apache.commons.lang3.StringUtils; +import org.springframework.context.ApplicationContext; +import org.springframework.core.env.Environment; + +import com.alibaba.csp.sentinel.context.Context; +import com.alibaba.csp.sentinel.node.DefaultNode; +import com.alibaba.csp.sentinel.slotchain.ProcessorSlotEntryCallback; +import com.alibaba.csp.sentinel.slotchain.ResourceWrapper; +import com.alibaba.csp.sentinel.slots.block.BlockException; +import com.alibaba.fastjson.JSON; +import com.nepxion.discovery.common.constant.DiscoveryConstant; +import com.nepxion.discovery.plugin.framework.adapter.PluginAdapter; +import com.nepxion.discovery.plugin.framework.context.PluginContextAware; +import com.nepxion.discovery.plugin.strategy.sentinel.monitor.constant.SentinelStrategyMonitorConstant; + +public abstract class SentinelTracerProcessorSlotEntryCallback implements ProcessorSlotEntryCallback { + @Override + public void onPass(Context context, ResourceWrapper resourceWrapper, DefaultNode param, int count, Object... args) throws Exception { + + } + + @Override + public void onBlocked(BlockException e, Context context, ResourceWrapper resourceWrapper, DefaultNode param, int count, Object... args) { + S span = buildSpan(); + + ApplicationContext applicationContext = PluginContextAware.getStaticApplicationContext(); + PluginAdapter pluginAdapter = applicationContext.getBean(PluginAdapter.class); + + Environment staticEnvironment = PluginContextAware.getStaticEnvironment(); + Boolean tracerSentinelRuleOutputEnabled = staticEnvironment.getProperty(SentinelStrategyMonitorConstant.SPRING_APPLICATION_STRATEGY_TRACER_SENTINEL_RULE_OUTPUT_ENABLED, Boolean.class, Boolean.TRUE); + Boolean tracerSentinelArgsOutputEnabled = staticEnvironment.getProperty(SentinelStrategyMonitorConstant.SPRING_APPLICATION_STRATEGY_TRACER_SENTINEL_ARGS_OUTPUT_ENABLED, Boolean.class, Boolean.FALSE); + + outputSpan(span, DiscoveryConstant.SPAN_TAG_PLUGIN_NAME, context.getName()); + outputSpan(span, DiscoveryConstant.N_D_SERVICE_GROUP, pluginAdapter.getGroup()); + outputSpan(span, DiscoveryConstant.N_D_SERVICE_TYPE, pluginAdapter.getServiceType()); + String serviceAppId = pluginAdapter.getServiceAppId(); + if (StringUtils.isNotEmpty(serviceAppId)) { + outputSpan(span, DiscoveryConstant.N_D_SERVICE_APP_ID, serviceAppId); + } + outputSpan(span, DiscoveryConstant.N_D_SERVICE_ID, pluginAdapter.getServiceId()); + outputSpan(span, DiscoveryConstant.N_D_SERVICE_ADDRESS, pluginAdapter.getHost() + ":" + pluginAdapter.getPort()); + String version = pluginAdapter.getVersion(); + if (StringUtils.isNotEmpty(version) && !StringUtils.equals(version, DiscoveryConstant.DEFAULT)) { + outputSpan(span, DiscoveryConstant.N_D_SERVICE_VERSION, version); + } + String region = pluginAdapter.getRegion(); + if (StringUtils.isNotEmpty(region) && !StringUtils.equals(region, DiscoveryConstant.DEFAULT)) { + outputSpan(span, DiscoveryConstant.N_D_SERVICE_REGION, region); + } + String environment = pluginAdapter.getEnvironment(); + if (StringUtils.isNotEmpty(environment) && !StringUtils.equals(environment, DiscoveryConstant.DEFAULT)) { + outputSpan(span, DiscoveryConstant.N_D_SERVICE_ENVIRONMENT, environment); + } + String zone = pluginAdapter.getZone(); + if (StringUtils.isNotEmpty(zone) && !StringUtils.equals(zone, DiscoveryConstant.DEFAULT)) { + outputSpan(span, DiscoveryConstant.N_D_SERVICE_ZONE, zone); + } + + outputSpan(span, SentinelStrategyMonitorConstant.ORIGIN, context.getOrigin()); + outputSpan(span, SentinelStrategyMonitorConstant.ASYNC, String.valueOf(context.isAsync())); + outputSpan(span, SentinelStrategyMonitorConstant.RESOURCE_NAME, resourceWrapper.getName()); + outputSpan(span, SentinelStrategyMonitorConstant.RESOURCE_SHOW_NAME, resourceWrapper.getShowName()); + outputSpan(span, SentinelStrategyMonitorConstant.RESOURCE_TYPE, String.valueOf(resourceWrapper.getResourceType())); + outputSpan(span, SentinelStrategyMonitorConstant.ENTRY_TYPE, resourceWrapper.getEntryType().toString()); + outputSpan(span, SentinelStrategyMonitorConstant.RULE_LIMIT_APP, e.getRuleLimitApp()); + if (tracerSentinelRuleOutputEnabled) { + outputSpan(span, SentinelStrategyMonitorConstant.RULE, e.getRule() != null ? e.getRule().toString() : StringUtils.EMPTY); + } + outputSpan(span, SentinelStrategyMonitorConstant.CAUSE, e.getClass().getName()); + outputSpan(span, SentinelStrategyMonitorConstant.BLOCK_EXCEPTION, e.getMessage()); + outputSpan(span, SentinelStrategyMonitorConstant.COUNT, String.valueOf(count)); + if (tracerSentinelArgsOutputEnabled) { + outputSpan(span, SentinelStrategyMonitorConstant.ARGS, JSON.toJSONString(args)); + } + + finishSpan(span); + } + + protected abstract S buildSpan(); + + protected abstract void outputSpan(S span, String key, String value); + + protected abstract void finishSpan(S span); +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-monitor/src/main/java/com/nepxion/discovery/plugin/strategy/sentinel/monitor/constant/SentinelStrategyMonitorConstant.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-monitor/src/main/java/com/nepxion/discovery/plugin/strategy/sentinel/monitor/constant/SentinelStrategyMonitorConstant.java new file mode 100644 index 0000000000..26dc71f214 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-monitor/src/main/java/com/nepxion/discovery/plugin/strategy/sentinel/monitor/constant/SentinelStrategyMonitorConstant.java @@ -0,0 +1,31 @@ +package com.nepxion.discovery.plugin.strategy.sentinel.monitor.constant; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Weihua Wang + * @author Haojun Ren + * @version 1.0 + */ + +public class SentinelStrategyMonitorConstant { + public static final String SPRING_APPLICATION_STRATEGY_TRACER_SENTINEL_RULE_OUTPUT_ENABLED = "spring.application.strategy.tracer.sentinel.rule.output.enabled"; + public static final String SPRING_APPLICATION_STRATEGY_TRACER_SENTINEL_ARGS_OUTPUT_ENABLED = "spring.application.strategy.tracer.sentinel.args.output.enabled"; + + public static final String TRACER_NAME = "SENTINEL-TRACER"; + public static final String SPAN_NAME = "SENTINEL"; + public static final String ORIGIN = "origin"; + public static final String ASYNC = "async"; + public static final String RESOURCE_NAME = "resource.name"; + public static final String RESOURCE_SHOW_NAME = "resource.showname"; + public static final String RESOURCE_TYPE = "resource.type"; + public static final String ENTRY_TYPE = "entry.type"; + public static final String RULE_LIMIT_APP = "rule.limit.app"; + public static final String RULE = "rule"; + public static final String CAUSE = "cause"; + public static final String BLOCK_EXCEPTION = "block.exception"; + public static final String COUNT = "count"; + public static final String ARGS = "args"; +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-monitor/src/main/resources/META-INF/additional-spring-configuration-metadata.json b/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-monitor/src/main/resources/META-INF/additional-spring-configuration-metadata.json new file mode 100644 index 0000000000..6c1cb3e6f7 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-monitor/src/main/resources/META-INF/additional-spring-configuration-metadata.json @@ -0,0 +1,16 @@ +{ + "properties": [ + { + "name": "spring.application.strategy.tracer.sentinel.rule.output.enabled", + "type": "java.lang.Boolean", + "defaultValue": true, + "description": "Whether strategy tracer sentinel rule output is enabled." + }, + { + "name": "spring.application.strategy.tracer.sentinel.args.output.enabled", + "type": "java.lang.Boolean", + "defaultValue": false, + "description": "Whether strategy tracer sentinel args output is enabled." + } + ] +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-opentelemetry/pom.xml b/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-opentelemetry/pom.xml new file mode 100644 index 0000000000..89ef376124 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-opentelemetry/pom.xml @@ -0,0 +1,41 @@ + + + discovery-plugin-strategy-starter-sentinel-opentelemetry + Nepxion Discovery Plugin Strategy Starter Sentinel OpenTelemetry + jar + 4.0.0 + Nepxion Discovery is a solution for Spring Cloud with blue green, gray, weight, limitation, circuit breaker, degrade, isolation, monitor, tracing, dye, failover, async agent + http://www.nepxion.com + + + com.nepxion + discovery-plugin-strategy + 6.23.0 + + + + + ${project.groupId} + discovery-plugin-strategy-starter-sentinel-monitor + + + + io.opentelemetry + opentelemetry-api + ${opentelemetry.version} + provided + + + + + + + src/main/resources + + **/META-INF/** + + + + + \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-opentelemetry/src/main/java/com/nepxion/discovery/plugin/strategy/sentinel/opentelemetry/monitor/SentinelOpenTelemetryInitFunc.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-opentelemetry/src/main/java/com/nepxion/discovery/plugin/strategy/sentinel/opentelemetry/monitor/SentinelOpenTelemetryInitFunc.java new file mode 100644 index 0000000000..eaa955a33d --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-opentelemetry/src/main/java/com/nepxion/discovery/plugin/strategy/sentinel/opentelemetry/monitor/SentinelOpenTelemetryInitFunc.java @@ -0,0 +1,20 @@ +package com.nepxion.discovery.plugin.strategy.sentinel.opentelemetry.monitor; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import com.alibaba.csp.sentinel.init.InitFunc; +import com.alibaba.csp.sentinel.slots.statistic.StatisticSlotCallbackRegistry; + +public class SentinelOpenTelemetryInitFunc implements InitFunc { + @Override + public void init() throws Exception { + StatisticSlotCallbackRegistry.addEntryCallback(SentinelOpenTelemetryProcessorSlotEntryCallback.class.getName(), new SentinelOpenTelemetryProcessorSlotEntryCallback()); + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-opentelemetry/src/main/java/com/nepxion/discovery/plugin/strategy/sentinel/opentelemetry/monitor/SentinelOpenTelemetryProcessorSlotEntryCallback.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-opentelemetry/src/main/java/com/nepxion/discovery/plugin/strategy/sentinel/opentelemetry/monitor/SentinelOpenTelemetryProcessorSlotEntryCallback.java new file mode 100644 index 0000000000..b1f77a724b --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-opentelemetry/src/main/java/com/nepxion/discovery/plugin/strategy/sentinel/opentelemetry/monitor/SentinelOpenTelemetryProcessorSlotEntryCallback.java @@ -0,0 +1,42 @@ +package com.nepxion.discovery.plugin.strategy.sentinel.opentelemetry.monitor; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Weihua Wang + * @author Haojun Ren + * @version 1.0 + */ + +import io.opentelemetry.api.GlobalOpenTelemetry; +import io.opentelemetry.api.trace.Span; + +import org.springframework.core.env.Environment; + +import com.nepxion.discovery.plugin.framework.context.PluginContextAware; +import com.nepxion.discovery.plugin.strategy.sentinel.monitor.callback.SentinelTracerProcessorSlotEntryCallback; +import com.nepxion.discovery.plugin.strategy.sentinel.monitor.constant.SentinelStrategyMonitorConstant; + +public class SentinelOpenTelemetryProcessorSlotEntryCallback extends SentinelTracerProcessorSlotEntryCallback { + public static final String INSTRUMENTATION_NAME = "opentelemetry.trace.tracer.name"; + + @Override + protected Span buildSpan() { + Environment environment = PluginContextAware.getStaticEnvironment(); + String instrumentationName = environment.getProperty(INSTRUMENTATION_NAME, String.class, SentinelStrategyMonitorConstant.TRACER_NAME); + + return GlobalOpenTelemetry.getTracer(instrumentationName).spanBuilder(SentinelStrategyMonitorConstant.SPAN_NAME).startSpan(); + } + + @Override + protected void outputSpan(Span span, String key, String value) { + span.setAttribute(key, value); + } + + @Override + protected void finishSpan(Span span) { + span.end(); + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-opentelemetry/src/main/resources/META-INF/services/com.alibaba.csp.sentinel.init.InitFunc b/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-opentelemetry/src/main/resources/META-INF/services/com.alibaba.csp.sentinel.init.InitFunc new file mode 100644 index 0000000000..6ef485ab68 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-opentelemetry/src/main/resources/META-INF/services/com.alibaba.csp.sentinel.init.InitFunc @@ -0,0 +1 @@ +com.nepxion.discovery.plugin.strategy.sentinel.opentelemetry.monitor.SentinelOpenTelemetryInitFunc \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-opentracing/pom.xml b/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-opentracing/pom.xml new file mode 100644 index 0000000000..e724dc028f --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-opentracing/pom.xml @@ -0,0 +1,48 @@ + + + discovery-plugin-strategy-starter-sentinel-opentracing + Nepxion Discovery Plugin Strategy Starter Sentinel OpenTracing + jar + 4.0.0 + Nepxion Discovery is a solution for Spring Cloud with blue green, gray, weight, limitation, circuit breaker, degrade, isolation, monitor, tracing, dye, failover, async agent + http://www.nepxion.com + + + com.nepxion + discovery-plugin-strategy + 6.23.0 + + + + + ${project.groupId} + discovery-plugin-strategy-starter-sentinel-monitor + + + + io.opentracing + opentracing-api + ${opentracing.version} + provided + + + + io.opentracing + opentracing-util + ${opentracing.version} + provided + + + + + + + src/main/resources + + **/META-INF/** + + + + + \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-opentracing/src/main/java/com/nepxion/discovery/plugin/strategy/sentinel/opentracing/monitor/SentinelOpenTracingInitFunc.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-opentracing/src/main/java/com/nepxion/discovery/plugin/strategy/sentinel/opentracing/monitor/SentinelOpenTracingInitFunc.java new file mode 100644 index 0000000000..7853313054 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-opentracing/src/main/java/com/nepxion/discovery/plugin/strategy/sentinel/opentracing/monitor/SentinelOpenTracingInitFunc.java @@ -0,0 +1,20 @@ +package com.nepxion.discovery.plugin.strategy.sentinel.opentracing.monitor; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author zhang shun + * @version 1.0 + */ + +import com.alibaba.csp.sentinel.init.InitFunc; +import com.alibaba.csp.sentinel.slots.statistic.StatisticSlotCallbackRegistry; + +public class SentinelOpenTracingInitFunc implements InitFunc { + @Override + public void init() throws Exception { + StatisticSlotCallbackRegistry.addEntryCallback(SentinelOpenTracingProcessorSlotEntryCallback.class.getName(), new SentinelOpenTracingProcessorSlotEntryCallback()); + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-opentracing/src/main/java/com/nepxion/discovery/plugin/strategy/sentinel/opentracing/monitor/SentinelOpenTracingProcessorSlotEntryCallback.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-opentracing/src/main/java/com/nepxion/discovery/plugin/strategy/sentinel/opentracing/monitor/SentinelOpenTracingProcessorSlotEntryCallback.java new file mode 100644 index 0000000000..d6533b889d --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-opentracing/src/main/java/com/nepxion/discovery/plugin/strategy/sentinel/opentracing/monitor/SentinelOpenTracingProcessorSlotEntryCallback.java @@ -0,0 +1,33 @@ +package com.nepxion.discovery.plugin.strategy.sentinel.opentracing.monitor; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author zhang shun + * @version 1.0 + */ + +import io.opentracing.Span; +import io.opentracing.util.GlobalTracer; + +import com.nepxion.discovery.plugin.strategy.sentinel.monitor.callback.SentinelTracerProcessorSlotEntryCallback; +import com.nepxion.discovery.plugin.strategy.sentinel.monitor.constant.SentinelStrategyMonitorConstant; + +public class SentinelOpenTracingProcessorSlotEntryCallback extends SentinelTracerProcessorSlotEntryCallback { + @Override + protected Span buildSpan() { + return GlobalTracer.get().buildSpan(SentinelStrategyMonitorConstant.SPAN_NAME).start(); + } + + @Override + protected void outputSpan(Span span, String key, String value) { + span.setTag(key, value); + } + + @Override + protected void finishSpan(Span span) { + span.finish(); + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-opentracing/src/main/resources/META-INF/services/com.alibaba.csp.sentinel.init.InitFunc b/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-opentracing/src/main/resources/META-INF/services/com.alibaba.csp.sentinel.init.InitFunc new file mode 100644 index 0000000000..91ffa4980e --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-opentracing/src/main/resources/META-INF/services/com.alibaba.csp.sentinel.init.InitFunc @@ -0,0 +1 @@ +com.nepxion.discovery.plugin.strategy.sentinel.opentracing.monitor.SentinelOpenTracingInitFunc \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-skywalking/pom.xml b/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-skywalking/pom.xml new file mode 100644 index 0000000000..ce3f3167be --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-skywalking/pom.xml @@ -0,0 +1,40 @@ + + + discovery-plugin-strategy-starter-sentinel-skywalking + Nepxion Discovery Plugin Strategy Starter Sentinel SkyWalking + jar + 4.0.0 + Nepxion Discovery is a solution for Spring Cloud with blue green, gray, weight, limitation, circuit breaker, degrade, isolation, monitor, tracing, dye, failover, async agent + http://www.nepxion.com + + + com.nepxion + discovery-plugin-strategy + 6.23.0 + + + + + ${project.groupId} + discovery-plugin-strategy-starter-sentinel-monitor + + + + org.apache.skywalking + apm-toolkit-opentracing + ${skywalking.version} + + + + + + + src/main/resources + + **/META-INF/** + + + + + \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-skywalking/src/main/java/com/nepxion/discovery/plugin/strategy/sentinel/skywalking/monitor/SentinelSkyWalkingInitFunc.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-skywalking/src/main/java/com/nepxion/discovery/plugin/strategy/sentinel/skywalking/monitor/SentinelSkyWalkingInitFunc.java new file mode 100644 index 0000000000..2e572020c2 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-skywalking/src/main/java/com/nepxion/discovery/plugin/strategy/sentinel/skywalking/monitor/SentinelSkyWalkingInitFunc.java @@ -0,0 +1,20 @@ +package com.nepxion.discovery.plugin.strategy.sentinel.skywalking.monitor; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author zhang shun + * @version 1.0 + */ + +import com.alibaba.csp.sentinel.init.InitFunc; +import com.alibaba.csp.sentinel.slots.statistic.StatisticSlotCallbackRegistry; + +public class SentinelSkyWalkingInitFunc implements InitFunc { + @Override + public void init() throws Exception { + StatisticSlotCallbackRegistry.addEntryCallback(SentinelSkyWalkingProcessorSlotEntryCallback.class.getName(), new SentinelSkyWalkingProcessorSlotEntryCallback()); + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-skywalking/src/main/java/com/nepxion/discovery/plugin/strategy/sentinel/skywalking/monitor/SentinelSkyWalkingProcessorSlotEntryCallback.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-skywalking/src/main/java/com/nepxion/discovery/plugin/strategy/sentinel/skywalking/monitor/SentinelSkyWalkingProcessorSlotEntryCallback.java new file mode 100644 index 0000000000..8e4332e0ec --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-skywalking/src/main/java/com/nepxion/discovery/plugin/strategy/sentinel/skywalking/monitor/SentinelSkyWalkingProcessorSlotEntryCallback.java @@ -0,0 +1,37 @@ +package com.nepxion.discovery.plugin.strategy.sentinel.skywalking.monitor; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author zhang shun + * @version 1.0 + */ + +import io.opentracing.Span; +import io.opentracing.Tracer; + +import org.apache.skywalking.apm.toolkit.opentracing.SkywalkingTracer; + +import com.nepxion.discovery.plugin.strategy.sentinel.monitor.callback.SentinelTracerProcessorSlotEntryCallback; +import com.nepxion.discovery.plugin.strategy.sentinel.monitor.constant.SentinelStrategyMonitorConstant; + +public class SentinelSkyWalkingProcessorSlotEntryCallback extends SentinelTracerProcessorSlotEntryCallback { + private Tracer tracer = new SkywalkingTracer(); + + @Override + protected Span buildSpan() { + return tracer.buildSpan(SentinelStrategyMonitorConstant.SPAN_NAME).startManual(); + } + + @Override + protected void outputSpan(Span span, String key, String value) { + span.setTag(key, value); + } + + @Override + protected void finishSpan(Span span) { + span.finish(); + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-skywalking/src/main/resources/META-INF/services/com.alibaba.csp.sentinel.init.InitFunc b/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-skywalking/src/main/resources/META-INF/services/com.alibaba.csp.sentinel.init.InitFunc new file mode 100644 index 0000000000..4cec42b8cd --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-skywalking/src/main/resources/META-INF/services/com.alibaba.csp.sentinel.init.InitFunc @@ -0,0 +1 @@ +com.nepxion.discovery.plugin.strategy.sentinel.skywalking.monitor.SentinelSkyWalkingInitFunc \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/pom.xml b/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/pom.xml new file mode 100644 index 0000000000..37cd63b017 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/pom.xml @@ -0,0 +1,38 @@ + + + discovery-plugin-strategy-starter-service + Nepxion Discovery Plugin Strategy Starter Service + jar + 4.0.0 + Nepxion Discovery is a solution for Spring Cloud with blue green, gray, weight, limitation, circuit breaker, degrade, isolation, monitor, tracing, dye, failover, async agent + http://www.nepxion.com + + + com.nepxion + discovery-plugin-strategy + 6.23.0 + + + + + ${project.groupId} + discovery-plugin-strategy-starter + + + + ${project.groupId} + matrix-aop-starter + + + + org.springframework.cloud + spring-cloud-starter-openfeign + + + + org.springframework.boot + spring-boot-starter-web + + + \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/annotation/ServiceMonitorIgnore.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/annotation/ServiceMonitorIgnore.java new file mode 100644 index 0000000000..aa0a22fe1a --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/annotation/ServiceMonitorIgnore.java @@ -0,0 +1,25 @@ +package com.nepxion.discovery.plugin.strategy.service.annotation; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Inherited; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Target({ ElementType.METHOD, ElementType.TYPE }) +@Retention(RetentionPolicy.RUNTIME) +@Inherited +@Documented +public @interface ServiceMonitorIgnore { + +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/annotation/ServiceStrategy.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/annotation/ServiceStrategy.java new file mode 100644 index 0000000000..8ae218fb8a --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/annotation/ServiceStrategy.java @@ -0,0 +1,25 @@ +package com.nepxion.discovery.plugin.strategy.service.annotation; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Inherited; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Target({ ElementType.TYPE }) +@Retention(RetentionPolicy.RUNTIME) +@Inherited +@Documented +public @interface ServiceStrategy { + +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/configuration/ServiceStrategyAutoConfiguration.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/configuration/ServiceStrategyAutoConfiguration.java new file mode 100644 index 0000000000..3614c961f6 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/configuration/ServiceStrategyAutoConfiguration.java @@ -0,0 +1,197 @@ +package com.nepxion.discovery.plugin.strategy.service.configuration; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.ArrayList; +import java.util.List; + +import org.apache.commons.collections4.CollectionUtils; +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.AutoConfigureBefore; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.cloud.netflix.ribbon.RibbonClientConfiguration; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.env.ConfigurableEnvironment; + +import com.nepxion.discovery.common.constant.DiscoveryConstant; +import com.nepxion.discovery.common.entity.PackagesInjectorType; +import com.nepxion.discovery.common.exception.DiscoveryException; +import com.nepxion.discovery.common.util.StringUtil; +import com.nepxion.discovery.plugin.strategy.constant.StrategyConstant; +import com.nepxion.discovery.plugin.strategy.extractor.StrategyPackagesExtractor; +import com.nepxion.discovery.plugin.strategy.injector.StrategyPackagesInjector; +import com.nepxion.discovery.plugin.strategy.injector.StrategyPackagesResolver; +import com.nepxion.discovery.plugin.strategy.service.constant.ServiceStrategyConstant; +import com.nepxion.discovery.plugin.strategy.service.context.ServiceStrategyContextListener; +import com.nepxion.discovery.plugin.strategy.service.filter.DefaultServiceStrategyFilterExclusion; +import com.nepxion.discovery.plugin.strategy.service.filter.DefaultServiceStrategyRouteFilter; +import com.nepxion.discovery.plugin.strategy.service.filter.ServiceStrategyFilterExclusion; +import com.nepxion.discovery.plugin.strategy.service.filter.ServiceStrategyRouteFilter; +import com.nepxion.discovery.plugin.strategy.service.isolation.ServiceProviderIsolationStrategyAutoScanProxy; +import com.nepxion.discovery.plugin.strategy.service.isolation.ServiceProviderIsolationStrategyInterceptor; +import com.nepxion.discovery.plugin.strategy.service.monitor.DefaultServiceStrategyMonitor; +import com.nepxion.discovery.plugin.strategy.service.monitor.ServiceStrategyMonitor; +import com.nepxion.discovery.plugin.strategy.service.monitor.ServiceStrategyMonitorAutoScanProxy; +import com.nepxion.discovery.plugin.strategy.service.monitor.ServiceStrategyMonitorInterceptor; +import com.nepxion.discovery.plugin.strategy.service.rpc.ServiceRpcStrategyAutoScanProxy; +import com.nepxion.discovery.plugin.strategy.service.rpc.ServiceRpcStrategyInterceptor; +import com.nepxion.discovery.plugin.strategy.service.wrapper.DefaultServiceStrategyCallableWrapper; +import com.nepxion.discovery.plugin.strategy.service.wrapper.ServiceStrategyCallableWrapper; + +@Configuration +@AutoConfigureBefore(RibbonClientConfiguration.class) +public class ServiceStrategyAutoConfiguration { + @Autowired + private ConfigurableEnvironment environment; + + @Autowired + private StrategyPackagesExtractor strategyPackagesExtractor; + + @Autowired(required = false) + private List strategyPackagesInjectorList; + + @Bean + @ConditionalOnProperty(value = ServiceStrategyConstant.SPRING_APPLICATION_STRATEGY_RPC_INTERCEPT_ENABLED, matchIfMissing = false) + public ServiceRpcStrategyAutoScanProxy serviceRpcStrategyAutoScanProxy() { + String scanPackages = getConfigScanPackages(); + + scanPackages = getInjectorScanPackages(scanPackages, PackagesInjectorType.RPC); + + if (StringUtils.isEmpty(scanPackages)) { + throw new DiscoveryException(ServiceStrategyConstant.SPRING_APPLICATION_STRATEGY_SCAN_PACKAGES + "'s value can't be empty"); + } + + return new ServiceRpcStrategyAutoScanProxy(scanPackages); + } + + @Bean + @ConditionalOnProperty(value = ServiceStrategyConstant.SPRING_APPLICATION_STRATEGY_RPC_INTERCEPT_ENABLED, matchIfMissing = false) + public ServiceRpcStrategyInterceptor serviceRpcStrategyInterceptor() { + return new ServiceRpcStrategyInterceptor(); + } + + @Bean + @ConditionalOnMissingBean + @ConditionalOnProperty(value = StrategyConstant.SPRING_APPLICATION_STRATEGY_PROVIDER_ISOLATION_ENABLED, matchIfMissing = false) + public ServiceProviderIsolationStrategyAutoScanProxy serviceProviderIsolationStrategyAutoScanProxy() { + String scanPackages = getConfigScanPackages(); + + scanPackages = getInjectorScanPackages(scanPackages, PackagesInjectorType.PROVIDER_ISOLATION); + + if (StringUtils.isEmpty(scanPackages)) { + throw new DiscoveryException(ServiceStrategyConstant.SPRING_APPLICATION_STRATEGY_SCAN_PACKAGES + "'s value can't be empty"); + } + + return new ServiceProviderIsolationStrategyAutoScanProxy(scanPackages); + } + + @Bean + @ConditionalOnMissingBean + @ConditionalOnProperty(value = StrategyConstant.SPRING_APPLICATION_STRATEGY_PROVIDER_ISOLATION_ENABLED, matchIfMissing = false) + public ServiceProviderIsolationStrategyInterceptor serviceProviderIsolationStrategyInterceptor() { + return new ServiceProviderIsolationStrategyInterceptor(); + } + + @Bean + @ConditionalOnMissingBean + public ServiceStrategyRouteFilter serviceStrategyRouteFilter() { + return new DefaultServiceStrategyRouteFilter(); + } + + @Bean + @ConditionalOnMissingBean + public ServiceStrategyFilterExclusion serviceStrategyFilterExclusion() { + return new DefaultServiceStrategyFilterExclusion(); + } + + @Bean + @ConditionalOnMissingBean + @ConditionalOnProperty(value = StrategyConstant.SPRING_APPLICATION_STRATEGY_MONITOR_ENABLED, matchIfMissing = false) + public ServiceStrategyMonitor serviceStrategyMonitor() { + return new DefaultServiceStrategyMonitor(); + } + + @Bean + @ConditionalOnMissingBean + @ConditionalOnProperty(value = StrategyConstant.SPRING_APPLICATION_STRATEGY_MONITOR_ENABLED, matchIfMissing = false) + public ServiceStrategyMonitorAutoScanProxy serviceStrategyMonitorAutoScanProxy() { + String scanPackages = getConfigScanPackages(); + + scanPackages = getInjectorScanPackages(scanPackages, PackagesInjectorType.TRACER); + + scanPackages = getEndpointScanPackages(scanPackages); + + if (StringUtils.isEmpty(scanPackages)) { + throw new DiscoveryException(ServiceStrategyConstant.SPRING_APPLICATION_STRATEGY_SCAN_PACKAGES + "'s value can't be empty"); + } + + return new ServiceStrategyMonitorAutoScanProxy(scanPackages); + } + + @Bean + @ConditionalOnMissingBean + @ConditionalOnProperty(value = StrategyConstant.SPRING_APPLICATION_STRATEGY_MONITOR_ENABLED, matchIfMissing = false) + public ServiceStrategyMonitorInterceptor serviceStrategyMonitorInterceptor() { + return new ServiceStrategyMonitorInterceptor(); + } + + @Bean + @ConditionalOnMissingBean + @ConditionalOnProperty(value = StrategyConstant.SPRING_APPLICATION_STRATEGY_HYSTRIX_THREADLOCAL_SUPPORTED, matchIfMissing = false) + public ServiceStrategyCallableWrapper serviceStrategyCallableWrapper() { + return new DefaultServiceStrategyCallableWrapper(); + } + + @Bean + public ServiceStrategyContextListener serviceStrategyContextListener() { + return new ServiceStrategyContextListener(); + } + + public String getConfigScanPackages() { + String scanPackages = environment.getProperty(ServiceStrategyConstant.SPRING_APPLICATION_STRATEGY_SCAN_PACKAGES, StringUtils.EMPTY); + if (StringUtils.isNotEmpty(scanPackages)) { + if (scanPackages.endsWith(DiscoveryConstant.SEPARATE)) { + throw new DiscoveryException(ServiceStrategyConstant.SPRING_APPLICATION_STRATEGY_SCAN_PACKAGES + "'s value can't end with '" + DiscoveryConstant.SEPARATE + "'"); + } + } else { + scanPackages = strategyPackagesExtractor.getAllPackages(); + } + + return scanPackages; + } + + public String getInjectorScanPackages(String scanPackages, PackagesInjectorType packagesInjectorType) { + List scanPackageList = new ArrayList(StringUtil.splitToList(scanPackages)); + + List packageList = StrategyPackagesResolver.getInjectedPackages(strategyPackagesInjectorList, packagesInjectorType); + if (CollectionUtils.isNotEmpty(packageList)) { + for (String pkg : packageList) { + if (!scanPackageList.contains(pkg)) { + scanPackageList.add(pkg); + } + } + } + + return StringUtil.convertToString(scanPackageList); + } + + public String getEndpointScanPackages(String scanPackages) { + List scanPackageList = new ArrayList(StringUtil.splitToList(scanPackages)); + + if (!scanPackageList.contains(DiscoveryConstant.ENDPOINT_SCAN_PACKAGES)) { + scanPackageList.add(DiscoveryConstant.ENDPOINT_SCAN_PACKAGES); + } + + return StringUtil.convertToString(scanPackageList); + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/configuration/ServiceStrategyContextAutoConfiguration.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/configuration/ServiceStrategyContextAutoConfiguration.java similarity index 88% rename from discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/configuration/ServiceStrategyContextAutoConfiguration.java rename to discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/configuration/ServiceStrategyContextAutoConfiguration.java index 1ef91a51e4..c8bf7f1c93 100644 --- a/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/configuration/ServiceStrategyContextAutoConfiguration.java +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/configuration/ServiceStrategyContextAutoConfiguration.java @@ -10,6 +10,7 @@ */ import org.springframework.boot.autoconfigure.AutoConfigureBefore; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.cloud.netflix.ribbon.RibbonClientConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -20,6 +21,7 @@ @AutoConfigureBefore(RibbonClientConfiguration.class) public class ServiceStrategyContextAutoConfiguration { @Bean + @ConditionalOnMissingBean public ServiceStrategyContextHolder serviceStrategyContextHolder() { return new ServiceStrategyContextHolder(); } diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/constant/ServiceStrategyConstant.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/constant/ServiceStrategyConstant.java new file mode 100644 index 0000000000..3b3ea8078a --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/constant/ServiceStrategyConstant.java @@ -0,0 +1,20 @@ +package com.nepxion.discovery.plugin.strategy.service.constant; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +public class ServiceStrategyConstant { + public static final String SPRING_APPLICATION_STRATEGY_SERVICE_ROUTE_FILTER_ORDER = "spring.application.strategy.service.route.filter.order"; + public static final String SPRING_APPLICATION_STRATEGY_RPC_INTERCEPT_ENABLED = "spring.application.strategy.rpc.intercept.enabled"; + public static final String SPRING_APPLICATION_STRATEGY_SCAN_PACKAGES = "spring.application.strategy.scan.packages"; + public static final String SPRING_APPLICATION_STRATEGY_REST_REQUEST_DECORATOR_ENABLED = "spring.application.strategy.rest.request.decorator.enabled"; + public static final String SPRING_APPLICATION_STRATEGY_SERVICE_HEADER_PRIORITY = "spring.application.strategy.service.header.priority"; + public static final String SPRING_APPLICATION_STRATEGY_URI_FILTER_EXCLUSION = "spring.application.strategy.uri.filter.exclusion"; + public static final int SPRING_APPLICATION_STRATEGY_SERVICE_ROUTE_FILTER_ORDER_VALUE = 0; +} \ No newline at end of file diff --git a/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/context/RestStrategyContext.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/context/RestStrategyContext.java similarity index 100% rename from discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/context/RestStrategyContext.java rename to discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/context/RestStrategyContext.java diff --git a/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/context/RpcStrategyContext.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/context/RpcStrategyContext.java similarity index 89% rename from discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/context/RpcStrategyContext.java rename to discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/context/RpcStrategyContext.java index 0afd75cbb6..9514d4b6c2 100644 --- a/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/context/RpcStrategyContext.java +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/context/RpcStrategyContext.java @@ -9,7 +9,6 @@ * @version 1.0 */ -import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; @@ -26,7 +25,7 @@ protected RpcStrategyContext initialValue() { } }; - private final Map attributes = new LinkedHashMap(); + private Map attributes = new LinkedHashMap(); public static RpcStrategyContext getCurrentContext() { return THREAD_LOCAL.get(); @@ -59,7 +58,11 @@ public RpcStrategyContext clear() { } public Map getAttributes() { - return Collections.unmodifiableMap(attributes); + return attributes; + } + + public void setAttributes(Map attributes) { + this.attributes = attributes; } @Override diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/context/ServiceStrategyContextHolder.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/context/ServiceStrategyContextHolder.java new file mode 100644 index 0000000000..3f0ff7ff75 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/context/ServiceStrategyContextHolder.java @@ -0,0 +1,179 @@ +package com.nepxion.discovery.plugin.strategy.service.context; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @author Fan Yang + * @version 1.0 + */ + +import java.util.Collections; +import java.util.Enumeration; +import java.util.List; +import java.util.Map; + +import javax.servlet.http.Cookie; +import javax.servlet.http.HttpServletRequest; + +import org.apache.commons.collections4.MapUtils; +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.web.context.request.RequestAttributes; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; + +import com.nepxion.discovery.plugin.strategy.context.AbstractStrategyContextHolder; +import com.nepxion.discovery.plugin.strategy.service.constant.ServiceStrategyConstant; + +public class ServiceStrategyContextHolder extends AbstractStrategyContextHolder { + // 如果外界也传了相同的Header,例如,从Postman传递过来的Header,当下面的变量为true,以服务设置为优先,否则以外界传值为优先 + @Value("${" + ServiceStrategyConstant.SPRING_APPLICATION_STRATEGY_SERVICE_HEADER_PRIORITY + ":true}") + protected Boolean serviceHeaderPriority; + + public ServletRequestAttributes getRestAttributes() { + RequestAttributes requestAttributes = RestStrategyContext.getCurrentContext().getRequestAttributes(); + if (requestAttributes == null) { + requestAttributes = RequestContextHolder.getRequestAttributes(); + } + + return (ServletRequestAttributes) requestAttributes; + } + + public Map getRpcAttributes() { + return RpcStrategyContext.getCurrentContext().getAttributes(); + } + + public HttpServletRequest getHttpServletRequest() { + ServletRequestAttributes attributes = getRestAttributes(); + if (attributes == null) { + // LOG.warn("The ServletRequestAttributes object is lost for thread switched probably"); + + return null; + } + + HttpServletRequest request = attributes.getRequest(); + if (request == null) { + // LOG.warn("The HttpServletRequest object is lost for thread switched probably"); + + return null; + } + + return request; + } + + @Override + public Enumeration getHeaderNames() { + HttpServletRequest request = getHttpServletRequest(); + if (request == null) { + return null; + } + + Enumeration headerNames = request.getHeaderNames(); + + Map headerMap = strategyWrapper.getHeaderMap(); + if (MapUtils.isNotEmpty(headerMap)) { + List headerNameList = Collections.list(headerNames); + + for (Map.Entry entry : headerMap.entrySet()) { + String headerName = entry.getKey(); + if (!headerNameList.contains(headerName)) { + headerNameList.add(headerName); + } + } + + return Collections.enumeration(headerNameList); + } + + return headerNames; + } + + @Override + public String getHeader(String name) { + if (serviceHeaderPriority) { + String header = strategyWrapper.getHeader(name); + if (StringUtils.isEmpty(header)) { + HttpServletRequest request = getHttpServletRequest(); + if (request != null) { + header = request.getHeader(name); + } + } + + return header; + } else { + String header = null; + HttpServletRequest request = getHttpServletRequest(); + if (request != null) { + header = request.getHeader(name); + } + + if (StringUtils.isEmpty(header)) { + header = strategyWrapper.getHeader(name); + } + + return header; + } + } + + @Override + public String getParameter(String name) { + HttpServletRequest request = getHttpServletRequest(); + if (request == null) { + return null; + } + + return request.getParameter(name); + } + + public Cookie getHttpCookie(String name) { + HttpServletRequest request = getHttpServletRequest(); + if (request == null) { + return null; + } + + Cookie[] cookies = request.getCookies(); + if (cookies == null) { + return null; + } + + for (int i = 0; i < cookies.length; i++) { + Cookie cookie = cookies[i]; + String cookieName = cookie.getName(); + if (StringUtils.equals(cookieName, name)) { + return cookie; + } + } + + return null; + } + + @Override + public String getCookie(String name) { + Cookie cookie = getHttpCookie(name); + if (cookie != null) { + return cookie.getValue(); + } + + return null; + } + + public String getRequestURL() { + HttpServletRequest request = getHttpServletRequest(); + if (request == null) { + return null; + } + + return request.getRequestURL().toString(); + } + + public String getRequestURI() { + HttpServletRequest request = getHttpServletRequest(); + if (request == null) { + return null; + } + + return request.getRequestURI(); + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/context/ServiceStrategyContextListener.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/context/ServiceStrategyContextListener.java new file mode 100644 index 0000000000..3b1183c06d --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/context/ServiceStrategyContextListener.java @@ -0,0 +1,27 @@ +package com.nepxion.discovery.plugin.strategy.service.context; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.context.ApplicationListener; +import org.springframework.context.event.ContextRefreshedEvent; + +public class ServiceStrategyContextListener implements ApplicationListener { + private static final Logger LOG = LoggerFactory.getLogger(ServiceStrategyContextListener.class); + + @Override + public void onApplicationEvent(ContextRefreshedEvent event) { + // 异步调用下,第一次启动在某些情况下可能存在丢失上下文的问题 + LOG.info("Initialize Service Strategy Context after Application started..."); + RestStrategyContext.getCurrentContext(); + RpcStrategyContext.getCurrentContext(); + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/context/ServiceStrategyEnvironmentPostProcessor.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/context/ServiceStrategyEnvironmentPostProcessor.java new file mode 100644 index 0000000000..07c7d4bdc4 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/context/ServiceStrategyEnvironmentPostProcessor.java @@ -0,0 +1,33 @@ +package com.nepxion.discovery.plugin.strategy.service.context; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.env.EnvironmentPostProcessor; +import org.springframework.core.Ordered; +import org.springframework.core.env.ConfigurableEnvironment; + +import com.nepxion.discovery.common.constant.DiscoveryConstant; +import com.nepxion.discovery.common.entity.ServiceType; +import com.nepxion.discovery.common.util.EnvironmentUtil; + +public class ServiceStrategyEnvironmentPostProcessor implements EnvironmentPostProcessor, Ordered { + @Override + public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { + if (EnvironmentUtil.isStandardEnvironment(environment)) { + System.setProperty(DiscoveryConstant.SPRING_APPLICATION_TYPE, ServiceType.SERVICE.toString()); + } + } + + @Override + public int getOrder() { + return Ordered.HIGHEST_PRECEDENCE; + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/decorator/ServiceStrategyRequestDecorator.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/decorator/ServiceStrategyRequestDecorator.java new file mode 100644 index 0000000000..7592564bc1 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/decorator/ServiceStrategyRequestDecorator.java @@ -0,0 +1,64 @@ +package com.nepxion.discovery.plugin.strategy.service.decorator; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author liquanjin + * @version 1.0 + */ + +import java.util.Collections; +import java.util.Enumeration; +import java.util.List; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletRequestWrapper; + +import org.apache.commons.collections4.CollectionUtils; +import org.springframework.util.LinkedCaseInsensitiveMap; + +public class ServiceStrategyRequestDecorator extends HttpServletRequestWrapper { + private Map> headers; + + public ServiceStrategyRequestDecorator(HttpServletRequest request) { + super(request); + + headers = initializeHeaders(request); + } + + private Map> initializeHeaders(HttpServletRequest request) { + // 不区分大小写Key的Map用于适配不同的Web容器对于大小写Header的不同处理逻辑 + Map> headers = new LinkedCaseInsensitiveMap>(); + Enumeration headerNames = request.getHeaderNames(); + while (headerNames.hasMoreElements()) { + String headerName = headerNames.nextElement(); + if (headerName != null) { + headers.put(headerName, Collections.list(request.getHeaders(headerName))); + } + } + + return headers; + } + + @Override + public String getHeader(String name) { + List headerValues = headers.get(name); + + return CollectionUtils.isEmpty(headerValues) ? null : headerValues.get(0); + } + + @Override + public Enumeration getHeaders(String name) { + List headerValues = headers.get(name); + + return Collections.enumeration(headerValues != null ? headerValues : Collections.emptySet()); + } + + @Override + public Enumeration getHeaderNames() { + return Collections.enumeration(headers.keySet()); + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/decorator/ServiceStrategyRequestDecoratorFactory.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/decorator/ServiceStrategyRequestDecoratorFactory.java new file mode 100644 index 0000000000..af024e695f --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/decorator/ServiceStrategyRequestDecoratorFactory.java @@ -0,0 +1,23 @@ +package com.nepxion.discovery.plugin.strategy.service.decorator; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author liquanjin + * @version 1.0 + */ + +import javax.servlet.http.HttpServletRequest; + +import org.springframework.web.context.request.RequestAttributes; +import org.springframework.web.context.request.ServletRequestAttributes; + +public class ServiceStrategyRequestDecoratorFactory { + public static RequestAttributes decorateRequestAttributes(RequestAttributes requestAttributes) { + HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest(); + + return new ServletRequestAttributes(new ServiceStrategyRequestDecorator(request)); + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/filter/AbstractServiceStrategyRouteFilter.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/filter/AbstractServiceStrategyRouteFilter.java new file mode 100644 index 0000000000..e93ef0e5d0 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/filter/AbstractServiceStrategyRouteFilter.java @@ -0,0 +1,172 @@ +package com.nepxion.discovery.plugin.strategy.service.filter; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.io.IOException; +import java.util.Map; + +import javax.servlet.FilterChain; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.commons.collections4.MapUtils; +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; + +import com.nepxion.discovery.common.constant.DiscoveryConstant; +import com.nepxion.discovery.plugin.framework.adapter.PluginAdapter; +import com.nepxion.discovery.plugin.strategy.constant.StrategyConstant; +import com.nepxion.discovery.plugin.strategy.service.constant.ServiceStrategyConstant; +import com.nepxion.discovery.plugin.strategy.wrapper.StrategyWrapper; + +public abstract class AbstractServiceStrategyRouteFilter extends ServiceStrategyRouteFilter { + @Autowired + protected PluginAdapter pluginAdapter; + + @Autowired + protected StrategyWrapper strategyWrapper; + + @Autowired + protected ServiceStrategyFilterExclusion serviceStrategyFilterExclusion; + + // 如果外界也传了相同的Header,例如,从Postman传递过来的Header,当下面的变量为true,以服务设置为优先,否则以外界传值为优先 + @Value("${" + ServiceStrategyConstant.SPRING_APPLICATION_STRATEGY_SERVICE_HEADER_PRIORITY + ":true}") + protected Boolean serviceHeaderPriority; + + // Service上核心策略Header是否传递。当全局订阅启动时,可以关闭核心策略Header传递,这样可以节省传递数据的大小,一定程度上可以提升性能 + // 核心策略Header指n-d-开头的Header(不包括n-d-env,因为环境路由隔离,必须传递该Header),不包括n-d-service开头的Header + @Value("${" + StrategyConstant.SPRING_APPLICATION_STRATEGY_FEIGN_CORE_HEADER_TRANSMISSION_ENABLED + ":true}") + protected Boolean feignCoreHeaderTransmissionEnabled; + + @Value("${" + StrategyConstant.SPRING_APPLICATION_STRATEGY_REST_TEMPLATE_CORE_HEADER_TRANSMISSION_ENABLED + ":true}") + protected Boolean restTemplateCoreHeaderTransmissionEnabled; + + @Value("${" + StrategyConstant.SPRING_APPLICATION_STRATEGY_WEB_CLIENT_CORE_HEADER_TRANSMISSION_ENABLED + ":true}") + protected Boolean webClientCoreHeaderTransmissionEnabled; + + @Value("${" + ServiceStrategyConstant.SPRING_APPLICATION_STRATEGY_SERVICE_ROUTE_FILTER_ORDER + ":" + ServiceStrategyConstant.SPRING_APPLICATION_STRATEGY_SERVICE_ROUTE_FILTER_ORDER_VALUE + "}") + protected Integer filterOrder; + + @Override + public int getOrder() { + return filterOrder; + } + + @Override + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { + boolean isExclusion = serviceStrategyFilterExclusion.isExclusion(request, response); + if (isExclusion) { + filterChain.doFilter(request, response); + + return; + } + + // 通过过滤器设置路由Header头部信息,并全链路传递到服务端 + ServiceStrategyRouteFilterRequest serviceStrategyRouteFilterRequest = new ServiceStrategyRouteFilterRequest(request); + + // 处理内部Header的转发 + applyInnerHeader(serviceStrategyRouteFilterRequest); + + // 处理外部Header的转发 + applyOuterHeader(serviceStrategyRouteFilterRequest); + + filterChain.doFilter(serviceStrategyRouteFilterRequest, response); + } + + // 处理内部Header的转发,即把本地服务的相关属性封装成Header转发到下游服务去 + private void applyInnerHeader(ServiceStrategyRouteFilterRequest serviceStrategyRouteFilterRequest) { + // 通过Spring OncePerRequestFilter实现Header前置拦截外部Header,内部Header不需要处理 + } + + // 处理外部Header的转发,即外部服务传递过来的Header,中继转发到下游服务去 + private void applyOuterHeader(ServiceStrategyRouteFilterRequest serviceStrategyRouteFilterRequest) { + String routeEnvironment = getRouteEnvironment(); + if (StringUtils.isNotEmpty(routeEnvironment)) { + ServiceStrategyFilterResolver.setHeader(serviceStrategyRouteFilterRequest, DiscoveryConstant.N_D_ENVIRONMENT, routeEnvironment, false); + } + + if (feignCoreHeaderTransmissionEnabled || restTemplateCoreHeaderTransmissionEnabled || webClientCoreHeaderTransmissionEnabled) { + // 内置Header预先塞入 + Map headerMap = strategyWrapper.getHeaderMap(); + if (MapUtils.isNotEmpty(headerMap)) { + for (Map.Entry entry : headerMap.entrySet()) { + String key = entry.getKey(); + String value = entry.getValue(); + + ServiceStrategyFilterResolver.setHeader(serviceStrategyRouteFilterRequest, key, value, serviceHeaderPriority); + } + } + + String routeVersion = getRouteVersion(); + String routeRegion = getRouteRegion(); + String routeAddress = getRouteAddress(); + String routeVersionWeight = getRouteVersionWeight(); + String routeRegionWeight = getRouteRegionWeight(); + String routeVersionPrefer = getRouteVersionPrefer(); + String routeVersionFailover = getRouteVersionFailover(); + String routeRegionTransfer = getRouteRegionTransfer(); + String routeRegionFailover = getRouteRegionFailover(); + String routeEnvironmentFailover = getRouteEnvironmentFailover(); + String routeZoneFailover = getRouteZoneFailover(); + String routeAddressFailover = getRouteAddressFailover(); + String routeIdBlacklist = getRouteIdBlacklist(); + String routeAddressBlacklist = getRouteAddressBlacklist(); + + if (StringUtils.isNotEmpty(routeVersion)) { + ServiceStrategyFilterResolver.setHeader(serviceStrategyRouteFilterRequest, DiscoveryConstant.N_D_VERSION, routeVersion, serviceHeaderPriority); + } + if (StringUtils.isNotEmpty(routeRegion)) { + ServiceStrategyFilterResolver.setHeader(serviceStrategyRouteFilterRequest, DiscoveryConstant.N_D_REGION, routeRegion, serviceHeaderPriority); + } + if (StringUtils.isNotEmpty(routeAddress)) { + ServiceStrategyFilterResolver.setHeader(serviceStrategyRouteFilterRequest, DiscoveryConstant.N_D_ADDRESS, routeAddress, serviceHeaderPriority); + } + if (StringUtils.isNotEmpty(routeVersionWeight)) { + ServiceStrategyFilterResolver.setHeader(serviceStrategyRouteFilterRequest, DiscoveryConstant.N_D_VERSION_WEIGHT, routeVersionWeight, serviceHeaderPriority); + } + if (StringUtils.isNotEmpty(routeRegionWeight)) { + ServiceStrategyFilterResolver.setHeader(serviceStrategyRouteFilterRequest, DiscoveryConstant.N_D_REGION_WEIGHT, routeRegionWeight, serviceHeaderPriority); + } + if (StringUtils.isNotEmpty(routeVersionPrefer)) { + ServiceStrategyFilterResolver.setHeader(serviceStrategyRouteFilterRequest, DiscoveryConstant.N_D_VERSION_PREFER, routeVersionPrefer, serviceHeaderPriority); + } + if (StringUtils.isNotEmpty(routeVersionFailover)) { + ServiceStrategyFilterResolver.setHeader(serviceStrategyRouteFilterRequest, DiscoveryConstant.N_D_VERSION_FAILOVER, routeVersionFailover, serviceHeaderPriority); + } + if (StringUtils.isNotEmpty(routeRegionTransfer)) { + ServiceStrategyFilterResolver.setHeader(serviceStrategyRouteFilterRequest, DiscoveryConstant.N_D_REGION_TRANSFER, routeRegionTransfer, serviceHeaderPriority); + } + if (StringUtils.isNotEmpty(routeRegionFailover)) { + ServiceStrategyFilterResolver.setHeader(serviceStrategyRouteFilterRequest, DiscoveryConstant.N_D_REGION_FAILOVER, routeRegionFailover, serviceHeaderPriority); + } + if (StringUtils.isNotEmpty(routeEnvironmentFailover)) { + ServiceStrategyFilterResolver.setHeader(serviceStrategyRouteFilterRequest, DiscoveryConstant.N_D_ENVIRONMENT_FAILOVER, routeEnvironmentFailover, serviceHeaderPriority); + } + if (StringUtils.isNotEmpty(routeZoneFailover)) { + ServiceStrategyFilterResolver.setHeader(serviceStrategyRouteFilterRequest, DiscoveryConstant.N_D_ZONE_FAILOVER, routeZoneFailover, serviceHeaderPriority); + } + if (StringUtils.isNotEmpty(routeAddressFailover)) { + ServiceStrategyFilterResolver.setHeader(serviceStrategyRouteFilterRequest, DiscoveryConstant.N_D_ADDRESS_FAILOVER, routeAddressFailover, serviceHeaderPriority); + } + if (StringUtils.isNotEmpty(routeIdBlacklist)) { + ServiceStrategyFilterResolver.setHeader(serviceStrategyRouteFilterRequest, DiscoveryConstant.N_D_ID_BLACKLIST, routeIdBlacklist, serviceHeaderPriority); + } + if (StringUtils.isNotEmpty(routeAddressBlacklist)) { + ServiceStrategyFilterResolver.setHeader(serviceStrategyRouteFilterRequest, DiscoveryConstant.N_D_ADDRESS_BLACKLIST, routeAddressBlacklist, serviceHeaderPriority); + } + } + } + + public PluginAdapter getPluginAdapter() { + return pluginAdapter; + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/filter/DefaultServiceStrategyFilterExclusion.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/filter/DefaultServiceStrategyFilterExclusion.java new file mode 100644 index 0000000000..5861b76da8 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/filter/DefaultServiceStrategyFilterExclusion.java @@ -0,0 +1,50 @@ +package com.nepxion.discovery.plugin.strategy.service.filter; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.ArrayList; +import java.util.List; + +import javax.annotation.PostConstruct; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Value; + +import com.nepxion.discovery.common.util.StringUtil; +import com.nepxion.discovery.plugin.strategy.service.constant.ServiceStrategyConstant; + +public class DefaultServiceStrategyFilterExclusion implements ServiceStrategyFilterExclusion { + @Value("${" + ServiceStrategyConstant.SPRING_APPLICATION_STRATEGY_URI_FILTER_EXCLUSION + ":/actuator/}") + protected String uriFilterExclusion; + + protected List uriFilterExclusionList = new ArrayList(); + + @PostConstruct + public void initialize() { + if (StringUtils.isNotEmpty(uriFilterExclusion)) { + uriFilterExclusionList = StringUtil.splitToList(uriFilterExclusion); + } + } + + @Override + public boolean isExclusion(HttpServletRequest request, HttpServletResponse response) { + String requestURI = request.getRequestURI(); + + for (String uriFilterExclusionValue : uriFilterExclusionList) { + if (requestURI.contains(uriFilterExclusionValue)) { + return true; + } + } + + return false; + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/filter/DefaultServiceStrategyRouteFilter.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/filter/DefaultServiceStrategyRouteFilter.java new file mode 100644 index 0000000000..1bed267eec --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/filter/DefaultServiceStrategyRouteFilter.java @@ -0,0 +1,99 @@ +package com.nepxion.discovery.plugin.strategy.service.filter; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.springframework.beans.factory.annotation.Autowired; + +import com.nepxion.discovery.plugin.strategy.context.StrategyContextHolder; + +// 负载均衡前执行路由过滤 +public class DefaultServiceStrategyRouteFilter extends AbstractServiceStrategyRouteFilter { + @Autowired + protected StrategyContextHolder strategyContextHolder; + + @Override + public String getRouteVersion() { + return strategyContextHolder.getRouteVersion(); + } + + @Override + public String getRouteRegion() { + return strategyContextHolder.getRouteRegion(); + } + + @Override + public String getRouteEnvironment() { + return strategyContextHolder.getRouteEnvironment(); + } + + @Override + public String getRouteAddress() { + return strategyContextHolder.getRouteAddress(); + } + + @Override + public String getRouteVersionWeight() { + return strategyContextHolder.getRouteVersionWeight(); + } + + @Override + public String getRouteRegionWeight() { + return strategyContextHolder.getRouteRegionWeight(); + } + + @Override + public String getRouteVersionPrefer() { + return strategyContextHolder.getRouteVersionPrefer(); + } + + @Override + public String getRouteVersionFailover() { + return strategyContextHolder.getRouteVersionFailover(); + } + + @Override + public String getRouteRegionTransfer() { + return strategyContextHolder.getRouteRegionTransfer(); + } + + @Override + public String getRouteRegionFailover() { + return strategyContextHolder.getRouteRegionFailover(); + } + + @Override + public String getRouteEnvironmentFailover() { + return strategyContextHolder.getRouteEnvironmentFailover(); + } + + @Override + public String getRouteZoneFailover() { + return strategyContextHolder.getRouteZoneFailover(); + } + + @Override + public String getRouteAddressFailover() { + return strategyContextHolder.getRouteAddressFailover(); + } + + @Override + public String getRouteIdBlacklist() { + return strategyContextHolder.getRouteIdBlacklist(); + } + + @Override + public String getRouteAddressBlacklist() { + return strategyContextHolder.getRouteAddressBlacklist(); + } + + public StrategyContextHolder getStrategyContextHolder() { + return strategyContextHolder; + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/filter/ServiceStrategyFilter.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/filter/ServiceStrategyFilter.java new file mode 100644 index 0000000000..eb64767b15 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/filter/ServiceStrategyFilter.java @@ -0,0 +1,16 @@ +package com.nepxion.discovery.plugin.strategy.service.filter; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.springframework.web.filter.OncePerRequestFilter; + +public abstract class ServiceStrategyFilter extends OncePerRequestFilter { + +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/filter/ServiceStrategyFilterExclusion.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/filter/ServiceStrategyFilterExclusion.java new file mode 100644 index 0000000000..cad732d9c1 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/filter/ServiceStrategyFilterExclusion.java @@ -0,0 +1,17 @@ +package com.nepxion.discovery.plugin.strategy.service.filter; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +public interface ServiceStrategyFilterExclusion { + boolean isExclusion(HttpServletRequest request, HttpServletResponse response); +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/filter/ServiceStrategyFilterResolver.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/filter/ServiceStrategyFilterResolver.java new file mode 100644 index 0000000000..71c859fe97 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/filter/ServiceStrategyFilterResolver.java @@ -0,0 +1,32 @@ +package com.nepxion.discovery.plugin.strategy.service.filter; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.apache.commons.lang3.StringUtils; + +public class ServiceStrategyFilterResolver { + public static void setHeader(ServiceStrategyRouteFilterRequest serviceStrategyRouteFilterRequest, String headerName, String headerValue, Boolean serviceHeaderPriority) { + if (StringUtils.isEmpty(headerValue)) { + return; + } + + // 内置策略,例如,AbstractServiceStrategyRouteFilter中String routeVersion = getRouteVersion();是从strategyWrapper.getRouteVersion()获取 + // 服务设置为优先的时候,直接把内置策略加入。在负载均衡前,通过OncePerRequestFilter装饰方式代替掉外界的Header + if (serviceHeaderPriority) { + serviceStrategyRouteFilterRequest.addHeader(headerName, headerValue); + } else { + // 外界传值为优先的时候,外界已传值,则返回;外界未传值,则需要把内置策略加入 + String originalHeaderValue = serviceStrategyRouteFilterRequest.getOriginalRequest().getHeader(headerName); + if (StringUtils.isEmpty(originalHeaderValue)) { + serviceStrategyRouteFilterRequest.addHeader(headerName, headerValue); + } + } + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/filter/ServiceStrategyRouteFilter.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/filter/ServiceStrategyRouteFilter.java new file mode 100644 index 0000000000..411677fd07 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/filter/ServiceStrategyRouteFilter.java @@ -0,0 +1,18 @@ +package com.nepxion.discovery.plugin.strategy.service.filter; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.springframework.core.Ordered; + +import com.nepxion.discovery.plugin.strategy.filter.StrategyRouteFilter; + +public abstract class ServiceStrategyRouteFilter extends ServiceStrategyFilter implements StrategyRouteFilter, Ordered { + +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/filter/ServiceStrategyRouteFilterRequest.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/filter/ServiceStrategyRouteFilterRequest.java new file mode 100644 index 0000000000..ae4de9dfcf --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/filter/ServiceStrategyRouteFilterRequest.java @@ -0,0 +1,81 @@ +package com.nepxion.discovery.plugin.strategy.service.filter; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.Arrays; +import java.util.Collections; +import java.util.Enumeration; +import java.util.List; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletRequestWrapper; + +import org.apache.commons.collections4.MapUtils; +import org.springframework.util.LinkedCaseInsensitiveMap; + +public class ServiceStrategyRouteFilterRequest extends HttpServletRequestWrapper { + private HttpServletRequest originalRequest; + + private Map headers; + + public ServiceStrategyRouteFilterRequest(HttpServletRequest request) { + super(request); + + this.originalRequest = request; + + // 不区分大小写Key的Map用于适配不同的Web容器对于大小写Header的不同处理逻辑 + headers = new LinkedCaseInsensitiveMap(); + } + + public void addHeader(String name, String value) { + headers.put(name, value); + } + + @Override + public String getHeader(String name) { + if (headers.containsKey(name)) { + return headers.get(name); + } + + return super.getHeader(name); + } + + @Override + public Enumeration getHeaderNames() { + if (MapUtils.isNotEmpty(headers)) { + List names = Collections.list(super.getHeaderNames()); + for (String name : headers.keySet()) { + if (!names.contains(name)) { + names.add(name); + } + } + + return Collections.enumeration(names); + } + + return super.getHeaderNames(); + } + + @Override + public Enumeration getHeaders(String name) { + if (headers.containsKey(name)) { + List values = Arrays.asList(headers.get(name)); + + return Collections.enumeration(values); + } + + return super.getHeaders(name); + } + + public HttpServletRequest getOriginalRequest() { + return originalRequest; + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/isolation/ServiceProviderIsolationStrategyAutoScanProxy.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/isolation/ServiceProviderIsolationStrategyAutoScanProxy.java new file mode 100644 index 0000000000..901abe9976 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/isolation/ServiceProviderIsolationStrategyAutoScanProxy.java @@ -0,0 +1,51 @@ +package com.nepxion.discovery.plugin.strategy.service.isolation; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.lang.annotation.Annotation; + +import org.springframework.web.bind.annotation.RestController; + +import com.nepxion.discovery.plugin.strategy.service.annotation.ServiceStrategy; +import com.nepxion.matrix.proxy.aop.DefaultAutoScanProxy; +import com.nepxion.matrix.proxy.mode.ProxyMode; +import com.nepxion.matrix.proxy.mode.ScanMode; + +public class ServiceProviderIsolationStrategyAutoScanProxy extends DefaultAutoScanProxy { + private static final long serialVersionUID = 6147822053647878553L; + + private String[] commonInterceptorNames; + + @SuppressWarnings("rawtypes") + private Class[] classAnnotations; + + public ServiceProviderIsolationStrategyAutoScanProxy(String scanPackages) { + super(scanPackages, ProxyMode.BY_CLASS_ANNOTATION_ONLY, ScanMode.FOR_CLASS_ANNOTATION_ONLY); + } + + @Override + protected String[] getCommonInterceptorNames() { + if (commonInterceptorNames == null) { + commonInterceptorNames = new String[] { "serviceProviderIsolationStrategyInterceptor" }; + } + + return commonInterceptorNames; + } + + @SuppressWarnings("unchecked") + @Override + protected Class[] getClassAnnotations() { + if (classAnnotations == null) { + classAnnotations = new Class[] { RestController.class, ServiceStrategy.class }; + } + + return classAnnotations; + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/isolation/ServiceProviderIsolationStrategyInterceptor.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/isolation/ServiceProviderIsolationStrategyInterceptor.java new file mode 100644 index 0000000000..13b2925064 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/isolation/ServiceProviderIsolationStrategyInterceptor.java @@ -0,0 +1,51 @@ +package com.nepxion.discovery.plugin.strategy.service.isolation; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.aopalliance.intercept.MethodInvocation; +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.InitBinder; + +import com.nepxion.discovery.common.constant.DiscoveryConstant; +import com.nepxion.discovery.common.exception.DiscoveryException; +import com.nepxion.discovery.plugin.framework.adapter.PluginAdapter; +import com.nepxion.discovery.plugin.strategy.service.context.ServiceStrategyContextHolder; +import com.nepxion.matrix.proxy.aop.AbstractInterceptor; + +public class ServiceProviderIsolationStrategyInterceptor extends AbstractInterceptor { + @Autowired + protected PluginAdapter pluginAdapter; + + @Autowired + protected ServiceStrategyContextHolder serviceStrategyContextHolder; + + @Override + public Object invoke(MethodInvocation invocation) throws Throwable { + boolean hasInitBinderAnnotation = getMethod(invocation).isAnnotationPresent(InitBinder.class); + if (hasInitBinderAnnotation) { + return invocation.proceed(); + } + + // N_D_SERVICE_GROUP的Header属于上游服务传入 + String groupHeader = serviceStrategyContextHolder.getHeader(DiscoveryConstant.N_D_SERVICE_GROUP); + if (StringUtils.isEmpty(groupHeader)) { + // N_D_GROUP的Header属于外部URL调用传入 + groupHeader = serviceStrategyContextHolder.getHeader(DiscoveryConstant.N_D_GROUP); + } + String group = pluginAdapter.getGroup(); + String serviceId = pluginAdapter.getServiceId(); + if (!StringUtils.equals(groupHeader, group)) { + throw new DiscoveryException("Reject to invoke because of isolation with different group for serviceId=" + serviceId); + } + + return invocation.proceed(); + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/monitor/DefaultServiceStrategyMonitor.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/monitor/DefaultServiceStrategyMonitor.java new file mode 100644 index 0000000000..5ee17950c4 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/monitor/DefaultServiceStrategyMonitor.java @@ -0,0 +1,109 @@ +package com.nepxion.discovery.plugin.strategy.service.monitor; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import org.aopalliance.intercept.MethodInvocation; +import org.apache.commons.collections4.CollectionUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; + +import com.nepxion.discovery.common.constant.DiscoveryConstant; +import com.nepxion.discovery.common.util.ClassUtil; +import com.nepxion.discovery.plugin.strategy.constant.StrategyConstant; +import com.nepxion.discovery.plugin.strategy.monitor.StrategyMonitor; + +public class DefaultServiceStrategyMonitor extends StrategyMonitor implements ServiceStrategyMonitor { + @Value("${" + StrategyConstant.SPRING_APPLICATION_STRATEGY_TRACER_ENABLED + ":false}") + protected Boolean tracerEnabled; + + @Value("${" + StrategyConstant.SPRING_APPLICATION_STRATEGY_TRACER_METHOD_CONTEXT_OUTPUT_ENABLED + ":false}") + protected Boolean tracerMethodContextOutputEnabled; + + @Value("${" + StrategyConstant.SPRING_APPLICATION_STRATEGY_ALARM_ENABLED + ":false}") + protected Boolean alarmEnabled; + + @Autowired(required = false) + protected List serviceStrategyMonitorAdapterList; + + @Override + public void monitor(ServiceStrategyMonitorInterceptor interceptor, MethodInvocation invocation) { + spanBuild(); + + loggerOutput(); + loggerDebug(); + + alarm(createContextMap(interceptor, invocation)); + } + + @Override + public void monitor(ServiceStrategyMonitorInterceptor interceptor, MethodInvocation invocation, Object returnValue) { + spanOutput(createContextMap(interceptor, invocation, returnValue)); + } + + @Override + public void error(ServiceStrategyMonitorInterceptor interceptor, MethodInvocation invocation, Throwable e) { + spanError(e); + } + + @Override + public void release(ServiceStrategyMonitorInterceptor interceptor, MethodInvocation invocation) { + loggerClear(); + + spanFinish(); + } + + private Map createContextMap(ServiceStrategyMonitorInterceptor interceptor, MethodInvocation invocation) { + if (!alarmEnabled) { + return null; + } + + Map contextMap = new LinkedHashMap(); + + String className = interceptor.getMethod(invocation).getDeclaringClass().getName(); + String methodName = interceptor.getMethodName(invocation); + contextMap.put(DiscoveryConstant.CLASS, className); + contextMap.put(DiscoveryConstant.METHOD, methodName); + + return contextMap; + } + + private Map createContextMap(ServiceStrategyMonitorInterceptor interceptor, MethodInvocation invocation, Object returnValue) { + if (!tracerEnabled) { + return null; + } + + Map contextMap = new LinkedHashMap(); + + String className = interceptor.getMethod(invocation).getDeclaringClass().getName(); + String methodName = interceptor.getMethodName(invocation); + contextMap.put("* " + DiscoveryConstant.CLASS, className); + contextMap.put("* " + DiscoveryConstant.METHOD, methodName); + + if (tracerMethodContextOutputEnabled) { + String[] methodParameterNames = interceptor.getMethodParameterNames(invocation); + Object[] arguments = interceptor.getArguments(invocation); + Map parameterMap = ClassUtil.getParameterMap(methodParameterNames, arguments); + if (CollectionUtils.isNotEmpty(serviceStrategyMonitorAdapterList)) { + for (ServiceStrategyMonitorAdapter serviceStrategyMonitorAdapter : serviceStrategyMonitorAdapterList) { + Map customizationMap = serviceStrategyMonitorAdapter.getCustomizationMap(interceptor, invocation, parameterMap, returnValue); + for (Map.Entry entry : customizationMap.entrySet()) { + contextMap.put("* " + entry.getKey(), entry.getValue()); + } + } + } + } + + return contextMap; + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/monitor/ServiceStrategyMonitor.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/monitor/ServiceStrategyMonitor.java new file mode 100644 index 0000000000..30045352db --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/monitor/ServiceStrategyMonitor.java @@ -0,0 +1,22 @@ +package com.nepxion.discovery.plugin.strategy.service.monitor; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.aopalliance.intercept.MethodInvocation; + +public interface ServiceStrategyMonitor { + void monitor(ServiceStrategyMonitorInterceptor interceptor, MethodInvocation invocation); + + void monitor(ServiceStrategyMonitorInterceptor interceptor, MethodInvocation invocation, Object returnValue); + + void error(ServiceStrategyMonitorInterceptor interceptor, MethodInvocation invocation, Throwable e); + + void release(ServiceStrategyMonitorInterceptor interceptor, MethodInvocation invocation); +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/monitor/ServiceStrategyMonitorAdapter.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/monitor/ServiceStrategyMonitorAdapter.java new file mode 100644 index 0000000000..b796496e72 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/monitor/ServiceStrategyMonitorAdapter.java @@ -0,0 +1,18 @@ +package com.nepxion.discovery.plugin.strategy.service.monitor; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.Map; + +import org.aopalliance.intercept.MethodInvocation; + +public interface ServiceStrategyMonitorAdapter { + Map getCustomizationMap(ServiceStrategyMonitorInterceptor interceptor, MethodInvocation invocation, Map parameterMap, Object returnValue); +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/monitor/ServiceStrategyMonitorAutoScanProxy.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/monitor/ServiceStrategyMonitorAutoScanProxy.java new file mode 100644 index 0000000000..df82e0f24f --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/monitor/ServiceStrategyMonitorAutoScanProxy.java @@ -0,0 +1,51 @@ +package com.nepxion.discovery.plugin.strategy.service.monitor; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.lang.annotation.Annotation; + +import org.springframework.web.bind.annotation.RestController; + +import com.nepxion.discovery.plugin.strategy.service.annotation.ServiceStrategy; +import com.nepxion.matrix.proxy.aop.DefaultAutoScanProxy; +import com.nepxion.matrix.proxy.mode.ProxyMode; +import com.nepxion.matrix.proxy.mode.ScanMode; + +public class ServiceStrategyMonitorAutoScanProxy extends DefaultAutoScanProxy { + private static final long serialVersionUID = 2204522253627697121L; + + private String[] commonInterceptorNames; + + @SuppressWarnings("rawtypes") + private Class[] classAnnotations; + + public ServiceStrategyMonitorAutoScanProxy(String scanPackages) { + super(scanPackages, ProxyMode.BY_CLASS_ANNOTATION_ONLY, ScanMode.FOR_CLASS_ANNOTATION_ONLY); + } + + @Override + protected String[] getCommonInterceptorNames() { + if (commonInterceptorNames == null) { + commonInterceptorNames = new String[] { "serviceStrategyMonitorInterceptor" }; + } + + return commonInterceptorNames; + } + + @SuppressWarnings("unchecked") + @Override + protected Class[] getClassAnnotations() { + if (classAnnotations == null) { + classAnnotations = new Class[] { RestController.class, ServiceStrategy.class }; + } + + return classAnnotations; + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/monitor/ServiceStrategyMonitorInterceptor.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/monitor/ServiceStrategyMonitorInterceptor.java new file mode 100644 index 0000000000..56e97075ff --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/monitor/ServiceStrategyMonitorInterceptor.java @@ -0,0 +1,105 @@ +package com.nepxion.discovery.plugin.strategy.service.monitor; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.aopalliance.intercept.MethodInvocation; +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.web.bind.annotation.InitBinder; + +import com.nepxion.discovery.common.constant.DiscoveryConstant; +import com.nepxion.discovery.plugin.strategy.constant.StrategyConstant; +import com.nepxion.discovery.plugin.strategy.service.annotation.ServiceMonitorIgnore; +import com.nepxion.matrix.proxy.aop.AbstractInterceptor; + +public class ServiceStrategyMonitorInterceptor extends AbstractInterceptor { + @Value("${" + StrategyConstant.SPRING_APPLICATION_STRATEGY_TRACER_METHOD_CONTEXT_OUTPUT_ENABLED + ":false}") + protected Boolean tracerMethodContextOutputEnabled; + + @Autowired + protected ServiceStrategyMonitor serviceStrategyMonitor; + + @Override + public Object invoke(MethodInvocation invocation) throws Throwable { + boolean hasInitBinderAnnotation = getMethod(invocation).isAnnotationPresent(InitBinder.class); + if (hasInitBinderAnnotation) { + return invocation.proceed(); + } + + String className = getMethod(invocation).getDeclaringClass().getName(); + String methodName = getMethodName(invocation); + boolean isMonitorIgnored = false; + boolean isMonitored = false; + boolean isMethodContextMonitored = false; + try { + // 拦截侦测请求 + if (StringUtils.equals(className, DiscoveryConstant.INSPECTOR_ENDPOINT_CLASS_NAME) && StringUtils.equals(methodName, DiscoveryConstant.INSPECTOR_ENDPOINT_METHOD_NAME)) { + // 埋点创建、日志输出、告警输出 + serviceStrategyMonitor.monitor(this, invocation); + isMonitored = true; + + // 埋点输出 + serviceStrategyMonitor.monitor(this, invocation, "* " + DiscoveryConstant.IGNORED); + isMethodContextMonitored = true; + + return invocation.proceed(); + } else { + isMonitorIgnored = getMethod(invocation).isAnnotationPresent(ServiceMonitorIgnore.class); + if (isMonitorIgnored) { + return invocation.proceed(); + } + + // 埋点创建、日志输出、告警输出 + serviceStrategyMonitor.monitor(this, invocation); + isMonitored = true; + + if (tracerMethodContextOutputEnabled) { + // 先执行调用,根据调用结果再输出返回值的埋点 + Object returnValue = invocation.proceed(); + + // 埋点输出 + serviceStrategyMonitor.monitor(this, invocation, returnValue); + isMethodContextMonitored = true; + + return returnValue; + } else { + // 埋点方法上下文输出 + serviceStrategyMonitor.monitor(this, invocation, null); + isMethodContextMonitored = true; + + return invocation.proceed(); + } + } + } catch (Throwable e) { + if (!isMonitorIgnored) { + if (!isMonitored) { + // 埋点创建、日志输出、告警输出 + serviceStrategyMonitor.monitor(this, invocation); + isMonitored = true; + } + if (!isMethodContextMonitored) { + // 埋点输出 + serviceStrategyMonitor.monitor(this, invocation, null); + isMethodContextMonitored = true; + } + // 埋点异常输出 + serviceStrategyMonitor.error(this, invocation, e); + } + + throw e; + } finally { + if (!isMonitorIgnored && isMonitored && isMethodContextMonitored) { + // 埋点提交、日志清除 + serviceStrategyMonitor.release(this, invocation); + } + } + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/rpc/ServiceRpcStrategyAutoScanProxy.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/rpc/ServiceRpcStrategyAutoScanProxy.java new file mode 100644 index 0000000000..3856941fe4 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/rpc/ServiceRpcStrategyAutoScanProxy.java @@ -0,0 +1,51 @@ +package com.nepxion.discovery.plugin.strategy.service.rpc; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.lang.annotation.Annotation; + +import org.springframework.web.bind.annotation.RestController; + +import com.nepxion.discovery.plugin.strategy.service.annotation.ServiceStrategy; +import com.nepxion.matrix.proxy.aop.DefaultAutoScanProxy; +import com.nepxion.matrix.proxy.mode.ProxyMode; +import com.nepxion.matrix.proxy.mode.ScanMode; + +public class ServiceRpcStrategyAutoScanProxy extends DefaultAutoScanProxy { + private static final long serialVersionUID = 8436914718400274011L; + + private String[] commonInterceptorNames; + + @SuppressWarnings("rawtypes") + private Class[] classAnnotations; + + public ServiceRpcStrategyAutoScanProxy(String scanPackages) { + super(scanPackages, ProxyMode.BY_CLASS_ANNOTATION_ONLY, ScanMode.FOR_CLASS_ANNOTATION_ONLY); + } + + @Override + protected String[] getCommonInterceptorNames() { + if (commonInterceptorNames == null) { + commonInterceptorNames = new String[] { "serviceRpcStrategyInterceptor" }; + } + + return commonInterceptorNames; + } + + @SuppressWarnings("unchecked") + @Override + protected Class[] getClassAnnotations() { + if (classAnnotations == null) { + classAnnotations = new Class[] { RestController.class, ServiceStrategy.class }; + } + + return classAnnotations; + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/rpc/ServiceRpcStrategyInterceptor.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/rpc/ServiceRpcStrategyInterceptor.java new file mode 100644 index 0000000000..b912f629ca --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/rpc/ServiceRpcStrategyInterceptor.java @@ -0,0 +1,47 @@ +package com.nepxion.discovery.plugin.strategy.service.rpc; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.Map; + +import org.aopalliance.intercept.MethodInvocation; +import org.springframework.web.bind.annotation.InitBinder; + +import com.nepxion.discovery.common.constant.DiscoveryConstant; +import com.nepxion.discovery.common.util.ClassUtil; +import com.nepxion.discovery.plugin.strategy.service.context.RpcStrategyContext; +import com.nepxion.matrix.proxy.aop.AbstractInterceptor; + +public class ServiceRpcStrategyInterceptor extends AbstractInterceptor { + @Override + public Object invoke(MethodInvocation invocation) throws Throwable { + boolean hasInitBinderAnnotation = getMethod(invocation).isAnnotationPresent(InitBinder.class); + if (hasInitBinderAnnotation) { + return invocation.proceed(); + } + + Class clazz = getMethod(invocation).getDeclaringClass(); + String methodName = getMethodName(invocation); + String[] methodParameterNames = getMethodParameterNames(invocation); + Object[] arguments = getArguments(invocation); + Map parameterMap = ClassUtil.getParameterMap(methodParameterNames, arguments); + + RpcStrategyContext context = RpcStrategyContext.getCurrentContext(); + context.add(DiscoveryConstant.CLASS, clazz); + context.add(DiscoveryConstant.METHOD, methodName); + context.add(DiscoveryConstant.PARAMETER_MAP, parameterMap); + + try { + return invocation.proceed(); + } finally { + RpcStrategyContext.clearCurrentContext(); + } + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/wrapper/DefaultServiceStrategyCallableWrapper.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/wrapper/DefaultServiceStrategyCallableWrapper.java new file mode 100644 index 0000000000..8a1813e2e9 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/wrapper/DefaultServiceStrategyCallableWrapper.java @@ -0,0 +1,66 @@ +package com.nepxion.discovery.plugin.strategy.service.wrapper; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @author Hao Huang + * @version 1.0 + */ + +import java.util.Map; +import java.util.concurrent.Callable; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.web.context.request.RequestAttributes; +import org.springframework.web.context.request.RequestContextHolder; + +import com.nepxion.discovery.plugin.strategy.monitor.StrategyTracerContext; +import com.nepxion.discovery.plugin.strategy.service.constant.ServiceStrategyConstant; +import com.nepxion.discovery.plugin.strategy.service.context.RestStrategyContext; +import com.nepxion.discovery.plugin.strategy.service.context.RpcStrategyContext; +import com.nepxion.discovery.plugin.strategy.service.decorator.ServiceStrategyRequestDecoratorFactory; + +public class DefaultServiceStrategyCallableWrapper implements ServiceStrategyCallableWrapper { + @Value("${" + ServiceStrategyConstant.SPRING_APPLICATION_STRATEGY_REST_REQUEST_DECORATOR_ENABLED + ":true}") + protected Boolean requestDecoratorEnabled; + + @Override + public Callable wrapCallable(Callable callable) { + RequestAttributes originRequestAttributes = RequestContextHolder.getRequestAttributes(); + if (requestDecoratorEnabled) { + if (originRequestAttributes != null) { + originRequestAttributes = ServiceStrategyRequestDecoratorFactory.decorateRequestAttributes(originRequestAttributes); + } + } + + RequestAttributes requestAttributes = originRequestAttributes; + + Map attributes = RpcStrategyContext.getCurrentContext().getAttributes(); + + Object span = StrategyTracerContext.getCurrentContext().getSpan(); + + return new Callable() { + @Override + public T call() throws Exception { + try { + RequestContextHolder.setRequestAttributes(requestAttributes); + RestStrategyContext.getCurrentContext().setRequestAttributes(requestAttributes); + RpcStrategyContext.getCurrentContext().setAttributes(attributes); + + StrategyTracerContext.getCurrentContext().setSpan(span); + + return callable.call(); + } finally { + RequestContextHolder.resetRequestAttributes(); + RestStrategyContext.clearCurrentContext(); + RpcStrategyContext.clearCurrentContext(); + + StrategyTracerContext.clearCurrentContext(); + } + } + }; + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/wrapper/ServiceStrategyCallableWrapper.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/wrapper/ServiceStrategyCallableWrapper.java new file mode 100644 index 0000000000..6c723b9506 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/wrapper/ServiceStrategyCallableWrapper.java @@ -0,0 +1,16 @@ +package com.nepxion.discovery.plugin.strategy.service.wrapper; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import com.nepxion.discovery.plugin.strategy.wrapper.StrategyCallableWrapper; + +public interface ServiceStrategyCallableWrapper extends StrategyCallableWrapper { + +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/resources/META-INF/additional-spring-configuration-metadata.json b/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/resources/META-INF/additional-spring-configuration-metadata.json new file mode 100644 index 0000000000..676eebfe8c --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/resources/META-INF/additional-spring-configuration-metadata.json @@ -0,0 +1,39 @@ +{ + "properties": [ + { + "name": "spring.application.strategy.service.route.filter.order", + "type": "java.lang.Integer", + "defaultValue": 0, + "description": "Strategy service route filter order." + }, + { + "name": "spring.application.strategy.rpc.intercept.enabled", + "type": "java.lang.String", + "defaultValue": false, + "description": "Whether strategy rpc intercept is enabled." + }, + { + "name": "spring.application.strategy.scan.packages", + "type": "java.lang.String", + "description": "Strategy scan packages." + }, + { + "name": "spring.application.strategy.rest.request.decorator.enabled", + "type": "java.lang.String", + "defaultValue": true, + "description": "Whether strategy rest request decorator is enabled." + }, + { + "name": "spring.application.strategy.service.header.priority", + "type": "java.lang.Boolean", + "defaultValue": true, + "description": "Whether strategy service header priority is enabled." + }, + { + "name": "spring.application.strategy.uri.filter.exclusion", + "type": "java.lang.String", + "defaultValue": "/actuator/", + "description": "Strategy uri filter exclusion." + } + ] +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/resources/META-INF/spring.factories b/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/resources/META-INF/spring.factories new file mode 100644 index 0000000000..eecccb1643 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/resources/META-INF/spring.factories @@ -0,0 +1,6 @@ +org.springframework.boot.env.EnvironmentPostProcessor=\ +com.nepxion.discovery.plugin.strategy.service.context.ServiceStrategyEnvironmentPostProcessor + +org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ +com.nepxion.discovery.plugin.strategy.service.configuration.ServiceStrategyAutoConfiguration,\ +com.nepxion.discovery.plugin.strategy.service.configuration.ServiceStrategyContextAutoConfiguration \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-skywalking/pom.xml b/discovery-plugin-strategy/discovery-plugin-strategy-starter-skywalking/pom.xml new file mode 100644 index 0000000000..1d053cc692 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-skywalking/pom.xml @@ -0,0 +1,35 @@ + + + discovery-plugin-strategy-starter-skywalking + Nepxion Discovery Plugin Strategy Starter SkyWalking + jar + 4.0.0 + Nepxion Discovery is a solution for Spring Cloud with blue green, gray, weight, limitation, circuit breaker, degrade, isolation, monitor, tracing, dye, failover, async agent + http://www.nepxion.com + + + com.nepxion + discovery-plugin-strategy + 6.23.0 + + + + + ${project.groupId} + discovery-plugin-strategy-starter + + + + org.apache.skywalking + apm-toolkit-opentracing + ${skywalking.version} + + + + org.apache.skywalking + apm-toolkit-trace + ${skywalking.version} + + + \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-skywalking/src/main/java/com/nepxion/discovery/plugin/strategy/skywalking/configuration/SkyWalkingStrategyAutoConfiguration.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-skywalking/src/main/java/com/nepxion/discovery/plugin/strategy/skywalking/configuration/SkyWalkingStrategyAutoConfiguration.java new file mode 100644 index 0000000000..6a85712b02 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-skywalking/src/main/java/com/nepxion/discovery/plugin/strategy/skywalking/configuration/SkyWalkingStrategyAutoConfiguration.java @@ -0,0 +1,41 @@ +package com.nepxion.discovery.plugin.strategy.skywalking.configuration; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import com.nepxion.banner.BannerConstant; +import com.nepxion.banner.Description; +import com.nepxion.banner.LogoBanner; +import com.nepxion.banner.NepxionBanner; +import com.nepxion.discovery.common.entity.TracingType; +import com.nepxion.discovery.plugin.strategy.constant.StrategyConstant; +import com.nepxion.discovery.plugin.strategy.monitor.StrategyTracer; +import com.nepxion.discovery.plugin.strategy.skywalking.monitor.SkyWalkingStrategyTracer; +import com.taobao.text.Color; + +@Configuration +public class SkyWalkingStrategyAutoConfiguration { + static { + LogoBanner logoBanner = new LogoBanner(SkyWalkingStrategyAutoConfiguration.class, "/com/nepxion/skywalking/resource/logo.txt", "Welcome to Nepxion", 7, 5, new Color[] { Color.red, Color.green, Color.cyan, Color.blue, Color.yellow, Color.magenta, Color.red }, true); + + NepxionBanner.show(logoBanner, new Description("Tracing:", TracingType.SKYWALKING.toString(), 0, 1), new Description(BannerConstant.GITHUB + ":", BannerConstant.NEPXION_GITHUB + "/Discovery", 0, 1)); + } + + @Bean + @ConditionalOnMissingBean + @ConditionalOnProperty(value = StrategyConstant.SPRING_APPLICATION_STRATEGY_MONITOR_ENABLED, matchIfMissing = false) + public StrategyTracer strategyTracer() { + return new SkyWalkingStrategyTracer(); + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-skywalking/src/main/java/com/nepxion/discovery/plugin/strategy/skywalking/constant/SkyWalkingStrategyConstant.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-skywalking/src/main/java/com/nepxion/discovery/plugin/strategy/skywalking/constant/SkyWalkingStrategyConstant.java new file mode 100644 index 0000000000..bffba2f631 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-skywalking/src/main/java/com/nepxion/discovery/plugin/strategy/skywalking/constant/SkyWalkingStrategyConstant.java @@ -0,0 +1,14 @@ +package com.nepxion.discovery.plugin.strategy.skywalking.constant; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +public class SkyWalkingStrategyConstant { + +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-skywalking/src/main/java/com/nepxion/discovery/plugin/strategy/skywalking/monitor/SkyWalkingStrategySpan.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-skywalking/src/main/java/com/nepxion/discovery/plugin/strategy/skywalking/monitor/SkyWalkingStrategySpan.java new file mode 100644 index 0000000000..29b971654a --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-skywalking/src/main/java/com/nepxion/discovery/plugin/strategy/skywalking/monitor/SkyWalkingStrategySpan.java @@ -0,0 +1,143 @@ +package com.nepxion.discovery.plugin.strategy.skywalking.monitor; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import io.opentracing.Span; +import io.opentracing.SpanContext; + +import java.util.Map; + +import org.apache.skywalking.apm.toolkit.trace.TraceContext; + +import com.nepxion.discovery.common.constant.DiscoveryConstant; +import com.nepxion.discovery.plugin.strategy.monitor.StrategySpan; +import com.nepxion.discovery.plugin.strategy.monitor.StrategyTracerContext; + +public class SkyWalkingStrategySpan implements Span { + private Span span; + private String traceId; + private String spanId; + + public SkyWalkingStrategySpan(Span span) { + this.span = span; + this.traceId = createTraceId(); + this.spanId = createSpanId(); + } + + @Override + public Span setOperationName(String operationName) { + return span.setOperationName(operationName); + } + + @Override + public Span log(long timestampMicroseconds, Map fields) { + return span.log(timestampMicroseconds, fields); + } + + @Override + public void finish(long finishMicros) { + span.finish(finishMicros); + } + + @Override + public Span log(long timestampMicroseconds, String event) { + return span.log(timestampMicroseconds, event); + } + + @Override + public void finish() { + span.finish(); + } + + @Override + public SpanContext context() { + return span.context(); + } + + @Override + public Span setTag(String key, String value) { + return span.setTag(key, value); + } + + @Override + public Span setTag(String key, boolean value) { + return span.setTag(key, value); + } + + @Override + public Span setTag(String key, Number value) { + return span.setTag(key, value); + } + + @Override + public Span log(Map fields) { + return span.log(fields); + } + + @Override + public Span log(String event) { + return span.log(event); + } + + @Override + public Span setBaggageItem(String key, String value) { + return span.setBaggageItem(key, value); + } + + @Override + public String getBaggageItem(String key) { + return span.getBaggageItem(key); + } + + @Deprecated + @Override + public Span log(String eventName, Object payload) { + return span.log(eventName, payload); + } + + @Deprecated + @Override + public Span log(long timestampMicroseconds, String eventName, Object payload) { + return span.log(timestampMicroseconds, eventName, payload); + } + + public String toTraceId() { + return traceId; + } + + public String toSpanId() { + return spanId; + } + + private String createTraceId() { + try { + Object span = StrategyTracerContext.getCurrentContext().getSpan(); + if (span != null) { + // 该方式适用在WebFlux模式下 + StrategySpan strategySpan = (StrategySpan) span; + + return strategySpan.getTraceId(); + } else { + // 该方式适用在WebMvc模式下 + return TraceContext.traceId(); + } + } catch (Exception e) { + return null; + } + } + + private String createSpanId() { + try { + return DiscoveryConstant.IGNORED; + } catch (Exception e) { + return null; + } + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-skywalking/src/main/java/com/nepxion/discovery/plugin/strategy/skywalking/monitor/SkyWalkingStrategyTracer.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-skywalking/src/main/java/com/nepxion/discovery/plugin/strategy/skywalking/monitor/SkyWalkingStrategyTracer.java new file mode 100644 index 0000000000..6805a6d653 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-skywalking/src/main/java/com/nepxion/discovery/plugin/strategy/skywalking/monitor/SkyWalkingStrategyTracer.java @@ -0,0 +1,67 @@ +package com.nepxion.discovery.plugin.strategy.skywalking.monitor; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import io.opentracing.Tracer; + +import org.apache.commons.lang3.exception.ExceptionUtils; +import org.apache.skywalking.apm.toolkit.opentracing.SkywalkingTracer; +import org.springframework.beans.factory.annotation.Value; + +import com.nepxion.discovery.common.constant.DiscoveryConstant; +import com.nepxion.discovery.plugin.strategy.constant.StrategyConstant; +import com.nepxion.discovery.plugin.strategy.monitor.AbstractStrategyTracer; + +public class SkyWalkingStrategyTracer extends AbstractStrategyTracer { + @Value("${" + StrategyConstant.SPRING_APPLICATION_STRATEGY_TRACER_EXCEPTION_DETAIL_OUTPUT_ENABLED + ":false}") + protected Boolean tracerExceptionDetailOutputEnabled; + + private Tracer tracer = new SkywalkingTracer(); + + @Override + protected SkyWalkingStrategySpan buildSpan() { + return new SkyWalkingStrategySpan(tracer.buildSpan(tracerSpanValue).startManual()); + } + + @Override + protected void outputSpan(SkyWalkingStrategySpan span, String key, String value) { + span.setTag(key, value); + } + + @Override + protected void errorSpan(SkyWalkingStrategySpan span, Throwable e) { + if (tracerExceptionDetailOutputEnabled) { + span.setTag(DiscoveryConstant.ERROR_OBJECT, ExceptionUtils.getStackTrace(e)); + } else { + span.setTag(DiscoveryConstant.ERROR_OBJECT, e.getMessage()); + } + } + + @Override + protected void finishSpan(SkyWalkingStrategySpan span) { + span.finish(); + } + + // Never used probably + @Override + protected SkyWalkingStrategySpan getActiveSpan() { + return null; + } + + @Override + protected String toTraceId(SkyWalkingStrategySpan span) { + return span.toTraceId(); + } + + @Override + protected String toSpanId(SkyWalkingStrategySpan span) { + return span.toSpanId(); + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-skywalking/src/main/resources/META-INF/spring.factories b/discovery-plugin-strategy/discovery-plugin-strategy-starter-skywalking/src/main/resources/META-INF/spring.factories new file mode 100644 index 0000000000..cff85157b8 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-skywalking/src/main/resources/META-INF/spring.factories @@ -0,0 +1,2 @@ +org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ +com.nepxion.discovery.plugin.strategy.skywalking.configuration.SkyWalkingStrategyAutoConfiguration \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/pom.xml b/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/pom.xml new file mode 100644 index 0000000000..b9e3f63ce6 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/pom.xml @@ -0,0 +1,64 @@ + + + discovery-plugin-strategy-starter-zuul + Nepxion Discovery Plugin Strategy Starter Zuul + jar + 4.0.0 + Nepxion Discovery is a solution for Spring Cloud with blue green, gray, weight, limitation, circuit breaker, degrade, isolation, monitor, tracing, dye, failover, async agent + http://www.nepxion.com + + + com.nepxion + discovery-plugin-strategy + 6.23.0 + + + + + ${project.groupId} + discovery-plugin-strategy-starter + + + + ${project.groupId} + discovery-common-nacos + provided + + + + ${project.groupId} + discovery-common-apollo + provided + + + + ${project.groupId} + discovery-common-redis + provided + + + + ${project.groupId} + discovery-common-zookeeper + provided + + + + ${project.groupId} + discovery-common-consul + provided + + + + ${project.groupId} + discovery-common-etcd + provided + + + + org.springframework.cloud + spring-cloud-starter-netflix-zuul + + + \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/configuration/ZuulStrategyAutoConfiguration.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/configuration/ZuulStrategyAutoConfiguration.java new file mode 100644 index 0000000000..d84c114b5b --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/configuration/ZuulStrategyAutoConfiguration.java @@ -0,0 +1,144 @@ +package com.nepxion.discovery.plugin.strategy.zuul.configuration; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @author Ning Zhang + * @version 1.0 + */ + +import org.springframework.boot.autoconfigure.AutoConfigureBefore; +import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.boot.autoconfigure.web.ServerProperties; +import org.springframework.cloud.netflix.ribbon.RibbonClientConfiguration; +import org.springframework.cloud.netflix.zuul.filters.ZuulProperties; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import com.nepxion.discovery.common.apollo.proccessor.ApolloProcessor; +import com.nepxion.discovery.common.consul.proccessor.ConsulProcessor; +import com.nepxion.discovery.common.etcd.proccessor.EtcdProcessor; +import com.nepxion.discovery.common.nacos.proccessor.NacosProcessor; +import com.nepxion.discovery.common.redis.proccessor.RedisProcessor; +import com.nepxion.discovery.common.zookeeper.proccessor.ZookeeperProcessor; +import com.nepxion.discovery.plugin.strategy.constant.StrategyConstant; +import com.nepxion.discovery.plugin.strategy.zuul.constant.ZuulStrategyConstant; +import com.nepxion.discovery.plugin.strategy.zuul.context.ZuulStrategyContextListener; +import com.nepxion.discovery.plugin.strategy.zuul.filter.DefaultZuulStrategyClearFilter; +import com.nepxion.discovery.plugin.strategy.zuul.filter.DefaultZuulStrategyRouteFilter; +import com.nepxion.discovery.plugin.strategy.zuul.filter.ZuulStrategyClearFilter; +import com.nepxion.discovery.plugin.strategy.zuul.filter.ZuulStrategyRouteFilter; +import com.nepxion.discovery.plugin.strategy.zuul.monitor.DefaultZuulStrategyMonitor; +import com.nepxion.discovery.plugin.strategy.zuul.monitor.ZuulStrategyMonitor; +import com.nepxion.discovery.plugin.strategy.zuul.processor.ZuulStrategyRouteApolloProcessor; +import com.nepxion.discovery.plugin.strategy.zuul.processor.ZuulStrategyRouteConsulProcessor; +import com.nepxion.discovery.plugin.strategy.zuul.processor.ZuulStrategyRouteEtcdProcessor; +import com.nepxion.discovery.plugin.strategy.zuul.processor.ZuulStrategyRouteNacosProcessor; +import com.nepxion.discovery.plugin.strategy.zuul.processor.ZuulStrategyRouteRedisProcessor; +import com.nepxion.discovery.plugin.strategy.zuul.processor.ZuulStrategyRouteZookeeperProcessor; +import com.nepxion.discovery.plugin.strategy.zuul.route.DefaultZuulStrategyRoute; +import com.nepxion.discovery.plugin.strategy.zuul.route.ZuulStrategyRoute; +import com.nepxion.discovery.plugin.strategy.zuul.wrapper.DefaultZuulStrategyCallableWrapper; +import com.nepxion.discovery.plugin.strategy.zuul.wrapper.ZuulStrategyCallableWrapper; + +@Configuration +@AutoConfigureBefore(RibbonClientConfiguration.class) +public class ZuulStrategyAutoConfiguration { + @Bean + @ConditionalOnMissingBean + public ZuulStrategyRouteFilter zuulStrategyRouteFilter() { + return new DefaultZuulStrategyRouteFilter(); + } + + // 只用于监控模块的调用链 + @Bean + @ConditionalOnMissingBean + @ConditionalOnProperty(value = StrategyConstant.SPRING_APPLICATION_STRATEGY_MONITOR_ENABLED, matchIfMissing = false) + public ZuulStrategyClearFilter zuulStrategyClearFilter() { + return new DefaultZuulStrategyClearFilter(); + } + + @Bean + @ConditionalOnMissingBean + @ConditionalOnProperty(value = StrategyConstant.SPRING_APPLICATION_STRATEGY_MONITOR_ENABLED, matchIfMissing = false) + public ZuulStrategyMonitor zuulStrategyMonitor() { + return new DefaultZuulStrategyMonitor(); + } + + @Bean + @ConditionalOnMissingBean + public ZuulStrategyRoute zuulStrategyRoute(ServerProperties serverProperties, ZuulProperties zuulProperties) { + return new DefaultZuulStrategyRoute(serverProperties.getServlet().getContextPath(), zuulProperties); + } + + @Bean + @ConditionalOnMissingBean + @ConditionalOnProperty(value = StrategyConstant.SPRING_APPLICATION_STRATEGY_HYSTRIX_THREADLOCAL_SUPPORTED, matchIfMissing = false) + public ZuulStrategyCallableWrapper zuulStrategyCallableWrapper() { + return new DefaultZuulStrategyCallableWrapper(); + } + + @Bean + public ZuulStrategyContextListener zuulStrategyContextListener() { + return new ZuulStrategyContextListener(); + } + + @ConditionalOnClass(NacosProcessor.class) + @ConditionalOnProperty(value = ZuulStrategyConstant.SPRING_APPLICATION_STRATEGY_ZUUL_DYNAMIC_ROUTE_ENABLED, matchIfMissing = false) + protected static class ZuulRouteNacosConfiguration { + @Bean + public NacosProcessor zuulStrategyRouteNacosProcessor() { + return new ZuulStrategyRouteNacosProcessor(); + } + } + + @ConditionalOnClass(ApolloProcessor.class) + @ConditionalOnProperty(value = ZuulStrategyConstant.SPRING_APPLICATION_STRATEGY_ZUUL_DYNAMIC_ROUTE_ENABLED, matchIfMissing = false) + protected static class ZuulRouteApolloConfiguration { + @Bean + public ApolloProcessor zuulStrategyRouteApolloProcessor() { + return new ZuulStrategyRouteApolloProcessor(); + } + } + + @ConditionalOnClass(RedisProcessor.class) + @ConditionalOnProperty(value = ZuulStrategyConstant.SPRING_APPLICATION_STRATEGY_ZUUL_DYNAMIC_ROUTE_ENABLED, matchIfMissing = false) + protected static class ZuulRouteRedisConfiguration { + @Bean + public RedisProcessor zuulStrategyRouteRedisProcessor() { + return new ZuulStrategyRouteRedisProcessor(); + } + } + + @ConditionalOnClass(ZookeeperProcessor.class) + @ConditionalOnProperty(value = ZuulStrategyConstant.SPRING_APPLICATION_STRATEGY_ZUUL_DYNAMIC_ROUTE_ENABLED, matchIfMissing = false) + protected static class ZuulRouteZookeeperConfiguration { + @Bean + public ZookeeperProcessor zuulStrategyRouteZookeeperProcessor() { + return new ZuulStrategyRouteZookeeperProcessor(); + } + } + + @ConditionalOnClass(ConsulProcessor.class) + @ConditionalOnProperty(value = ZuulStrategyConstant.SPRING_APPLICATION_STRATEGY_ZUUL_DYNAMIC_ROUTE_ENABLED, matchIfMissing = false) + protected static class ZuulRouteConsulConfiguration { + @Bean + public ConsulProcessor zuulStrategyRouteConsulProcessor() { + return new ZuulStrategyRouteConsulProcessor(); + } + } + + @ConditionalOnClass(EtcdProcessor.class) + @ConditionalOnProperty(value = ZuulStrategyConstant.SPRING_APPLICATION_STRATEGY_ZUUL_DYNAMIC_ROUTE_ENABLED, matchIfMissing = false) + protected static class ZuulRouteEtcdConfiguration { + @Bean + public EtcdProcessor zuulStrategyRouteEtcdProcessor() { + return new ZuulStrategyRouteEtcdProcessor(); + } + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/configuration/ZuulStrategyContextAutoConfiguration.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/configuration/ZuulStrategyContextAutoConfiguration.java similarity index 88% rename from discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/configuration/ZuulStrategyContextAutoConfiguration.java rename to discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/configuration/ZuulStrategyContextAutoConfiguration.java index ccbe592ec8..8346777cdd 100644 --- a/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/configuration/ZuulStrategyContextAutoConfiguration.java +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/configuration/ZuulStrategyContextAutoConfiguration.java @@ -10,6 +10,7 @@ */ import org.springframework.boot.autoconfigure.AutoConfigureBefore; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.cloud.netflix.ribbon.RibbonClientConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -20,6 +21,7 @@ @AutoConfigureBefore(RibbonClientConfiguration.class) public class ZuulStrategyContextAutoConfiguration { @Bean + @ConditionalOnMissingBean public ZuulStrategyContextHolder zuulStrategyContextHolder() { return new ZuulStrategyContextHolder(); } diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/constant/ZuulStrategyConstant.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/constant/ZuulStrategyConstant.java new file mode 100644 index 0000000000..982c5d4734 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/constant/ZuulStrategyConstant.java @@ -0,0 +1,19 @@ +package com.nepxion.discovery.plugin.strategy.zuul.constant; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +public class ZuulStrategyConstant { + public static final String SPRING_APPLICATION_STRATEGY_ZUUL_ROUTE_FILTER_ORDER = "spring.application.strategy.zuul.route.filter.order"; + public static final String SPRING_APPLICATION_STRATEGY_ZUUL_HEADER_PRIORITY = "spring.application.strategy.zuul.header.priority"; + public static final String SPRING_APPLICATION_STRATEGY_ZUUL_ORIGINAL_HEADER_IGNORED = "spring.application.strategy.zuul.original.header.ignored"; + public static final String SPRING_APPLICATION_STRATEGY_ZUUL_CORE_HEADER_TRANSMISSION_ENABLED = "spring.application.strategy.zuul.core.header.transmission.enabled"; + public static final String SPRING_APPLICATION_STRATEGY_ZUUL_DYNAMIC_ROUTE_ENABLED = "spring.application.strategy.zuul.dynamic.route.enabled"; + public static final int SPRING_APPLICATION_STRATEGY_ZUUL_ROUTE_FILTER_ORDER_VALUE = 0; +} \ No newline at end of file diff --git a/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/context/ZuulStrategyContext.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/context/ZuulStrategyContext.java similarity index 97% rename from discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/context/ZuulStrategyContext.java rename to discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/context/ZuulStrategyContext.java index 70801687fa..f1fb5a3ae7 100644 --- a/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/context/ZuulStrategyContext.java +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/context/ZuulStrategyContext.java @@ -28,8 +28,6 @@ protected ZuulStrategyContext initialValue() { }; private HttpServletRequest request; - - // 只适用于Hystrix线程隔离模式下 private Map headers; public static ZuulStrategyContext getCurrentContext() { diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/context/ZuulStrategyContextHolder.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/context/ZuulStrategyContextHolder.java new file mode 100644 index 0000000000..b26fab4f05 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/context/ZuulStrategyContextHolder.java @@ -0,0 +1,205 @@ +package com.nepxion.discovery.plugin.strategy.zuul.context; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @author Fan Yang + * @version 1.0 + */ + +import java.util.Collections; +import java.util.Enumeration; +import java.util.List; +import java.util.Map; + +import javax.servlet.http.Cookie; +import javax.servlet.http.HttpServletRequest; + +import org.apache.commons.collections4.MapUtils; +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Value; + +import com.nepxion.discovery.plugin.strategy.context.AbstractStrategyContextHolder; +import com.nepxion.discovery.plugin.strategy.util.StrategyUtil; +import com.nepxion.discovery.plugin.strategy.zuul.constant.ZuulStrategyConstant; +import com.netflix.zuul.context.RequestContext; + +public class ZuulStrategyContextHolder extends AbstractStrategyContextHolder { + // 如果外界也传了相同的Header,例如,从Postman传递过来的Header,当下面的变量为true,以网关设置为优先,否则以外界传值为优先 + @Value("${" + ZuulStrategyConstant.SPRING_APPLICATION_STRATEGY_ZUUL_HEADER_PRIORITY + ":true}") + protected Boolean zuulHeaderPriority; + + // 当以网关设置为优先的时候,网关未配置Header,而外界配置了Header,仍旧忽略外界的Header + @Value("${" + ZuulStrategyConstant.SPRING_APPLICATION_STRATEGY_ZUUL_ORIGINAL_HEADER_IGNORED + ":true}") + protected Boolean zuulOriginalHeaderIgnored; + + // Zuul上核心策略Header是否传递。当全局订阅启动时,可以关闭核心策略Header传递,这样可以节省传递数据的大小,一定程度上可以提升性能 + // 核心策略Header指n-d-开头的Header(不包括n-d-env,因为环境路由隔离,必须传递该Header),不包括n-d-service开头的Header + @Value("${" + ZuulStrategyConstant.SPRING_APPLICATION_STRATEGY_ZUUL_CORE_HEADER_TRANSMISSION_ENABLED + ":true}") + protected Boolean zuulCoreHeaderTransmissionEnabled; + + public HttpServletRequest getRequest() { + HttpServletRequest request = ZuulStrategyContext.getCurrentContext().getRequest(); + if (request == null) { + request = RequestContext.getCurrentContext().getRequest(); + } + + if (request == null) { + // LOG.warn("The HttpServletRequest object is lost for thread switched, or it is got before context filter probably"); + + return null; + } + + return request; + } + + public Map getZuulRequestHeaders() { + Map headers = ZuulStrategyContext.getCurrentContext().getHeaders(); + if (headers == null) { + headers = RequestContext.getCurrentContext().getZuulRequestHeaders(); + } + + if (headers == null) { + // LOG.warn("The Headers object is lost for thread switched, or it is got before context filter probably"); + + return null; + } + + return headers; + } + + @Override + public Enumeration getHeaderNames() { + HttpServletRequest request = getRequest(); + if (request == null) { + return null; + } + + Enumeration headerNames = request.getHeaderNames(); + + Map headers = getZuulRequestHeaders(); + if (MapUtils.isNotEmpty(headers)) { + List headerNameList = Collections.list(headerNames); + + for (Map.Entry entry : headers.entrySet()) { + String headerName = entry.getKey(); + if (!headerNameList.contains(headerName)) { + headerNameList.add(headerName); + } + } + + return Collections.enumeration(headerNameList); + } + + return headerNames; + } + + @Override + public String getHeader(String name) { + HttpServletRequest request = getRequest(); + if (request == null) { + return null; + } + + if (!zuulCoreHeaderTransmissionEnabled) { + boolean isCoreHeaderContains = StrategyUtil.isCoreHeaderContains(name); + if (isCoreHeaderContains) { + return null; + } + } + + if (zuulHeaderPriority) { + // 来自于Zuul Filter的Header + Map headers = getZuulRequestHeaders(); + String header = null; + if (MapUtils.isNotEmpty(headers)) { + header = headers.get(name); + } + if (StringUtils.isEmpty(header)) { + if (StrategyUtil.isCoreHeaderContains(name) && zuulOriginalHeaderIgnored) { + header = null; + } else { + // 来自于外界的Header + header = request.getHeader(name); + } + } + + return header; + } else { + // 来自于外界的Header + String header = request.getHeader(name); + if (StringUtils.isEmpty(header)) { + // 来自于Zuul Filter的Header + Map headers = getZuulRequestHeaders(); + if (MapUtils.isNotEmpty(headers)) { + header = headers.get(name); + } + } + + return header; + } + } + + @Override + public String getParameter(String name) { + HttpServletRequest request = getRequest(); + if (request == null) { + return null; + } + + return request.getParameter(name); + } + + public Cookie getHttpCookie(String name) { + HttpServletRequest request = getRequest(); + if (request == null) { + return null; + } + + Cookie[] cookies = request.getCookies(); + if (cookies == null) { + return null; + } + + for (int i = 0; i < cookies.length; i++) { + Cookie cookie = cookies[i]; + String cookieName = cookie.getName(); + if (StringUtils.equals(cookieName, name)) { + return cookie; + } + } + + return null; + } + + @Override + public String getCookie(String name) { + Cookie cookie = getHttpCookie(name); + if (cookie != null) { + return cookie.getValue(); + } + + return null; + } + + public String getRequestURL() { + HttpServletRequest request = getRequest(); + if (request == null) { + return null; + } + + return request.getRequestURL().toString(); + } + + public String getRequestURI() { + HttpServletRequest request = getRequest(); + if (request == null) { + return null; + } + + return request.getRequestURI(); + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/context/ZuulStrategyContextListener.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/context/ZuulStrategyContextListener.java new file mode 100644 index 0000000000..1e78e8387e --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/context/ZuulStrategyContextListener.java @@ -0,0 +1,26 @@ +package com.nepxion.discovery.plugin.strategy.zuul.context; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.context.ApplicationListener; +import org.springframework.context.event.ContextRefreshedEvent; + +public class ZuulStrategyContextListener implements ApplicationListener { + private static final Logger LOG = LoggerFactory.getLogger(ZuulStrategyContextListener.class); + + @Override + public void onApplicationEvent(ContextRefreshedEvent event) { + // 异步调用下,第一次启动在某些情况下可能存在丢失上下文的问题 + LOG.info("Initialize Zuul Strategy Context after Application started..."); + ZuulStrategyContext.getCurrentContext(); + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/context/ZuulStrategyEnvironmentPostProcessor.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/context/ZuulStrategyEnvironmentPostProcessor.java new file mode 100644 index 0000000000..be4ac44aa7 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/context/ZuulStrategyEnvironmentPostProcessor.java @@ -0,0 +1,35 @@ +package com.nepxion.discovery.plugin.strategy.zuul.context; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.env.EnvironmentPostProcessor; +import org.springframework.core.Ordered; +import org.springframework.core.env.ConfigurableEnvironment; + +import com.nepxion.discovery.common.constant.DiscoveryConstant; +import com.nepxion.discovery.common.entity.GatewayType; +import com.nepxion.discovery.common.entity.ServiceType; +import com.nepxion.discovery.common.util.EnvironmentUtil; + +public class ZuulStrategyEnvironmentPostProcessor implements EnvironmentPostProcessor, Ordered { + @Override + public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { + if (EnvironmentUtil.isStandardEnvironment(environment)) { + System.setProperty(DiscoveryConstant.SPRING_APPLICATION_TYPE, ServiceType.GATEWAY.toString()); + System.setProperty(DiscoveryConstant.SPRING_APPLICATION_GATEWAY_TYPE, GatewayType.ZUUL.toString()); + } + } + + @Override + public int getOrder() { + return Ordered.HIGHEST_PRECEDENCE; + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/event/ZuulStrategyRouteAddedEvent.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/event/ZuulStrategyRouteAddedEvent.java new file mode 100644 index 0000000000..e311495339 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/event/ZuulStrategyRouteAddedEvent.java @@ -0,0 +1,28 @@ +package com.nepxion.discovery.plugin.strategy.zuul.event; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.io.Serializable; + +import com.nepxion.discovery.common.entity.ZuulStrategyRouteEntity; + +public class ZuulStrategyRouteAddedEvent implements Serializable { + private static final long serialVersionUID = 7279933450263031027L; + + private ZuulStrategyRouteEntity zuulStrategyRouteEntity; + + public ZuulStrategyRouteAddedEvent(ZuulStrategyRouteEntity zuulStrategyRouteEntity) { + this.zuulStrategyRouteEntity = zuulStrategyRouteEntity; + } + + public ZuulStrategyRouteEntity getZuulStrategyRouteEntity() { + return zuulStrategyRouteEntity; + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/event/ZuulStrategyRouteDeletedEvent.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/event/ZuulStrategyRouteDeletedEvent.java new file mode 100644 index 0000000000..9027415cff --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/event/ZuulStrategyRouteDeletedEvent.java @@ -0,0 +1,26 @@ +package com.nepxion.discovery.plugin.strategy.zuul.event; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.io.Serializable; + +public class ZuulStrategyRouteDeletedEvent implements Serializable { + private static final long serialVersionUID = -819386359251658004L; + + private String routeId; + + public ZuulStrategyRouteDeletedEvent(String routeId) { + this.routeId = routeId; + } + + public String getRouteId() { + return routeId; + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/event/ZuulStrategyRouteModifiedEvent.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/event/ZuulStrategyRouteModifiedEvent.java new file mode 100644 index 0000000000..aa4b76b363 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/event/ZuulStrategyRouteModifiedEvent.java @@ -0,0 +1,28 @@ +package com.nepxion.discovery.plugin.strategy.zuul.event; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.io.Serializable; + +import com.nepxion.discovery.common.entity.ZuulStrategyRouteEntity; + +public class ZuulStrategyRouteModifiedEvent implements Serializable { + private static final long serialVersionUID = 3805426536724590753L; + + private ZuulStrategyRouteEntity zuulStrategyRouteEntity; + + public ZuulStrategyRouteModifiedEvent(ZuulStrategyRouteEntity zuulStrategyRouteEntity) { + this.zuulStrategyRouteEntity = zuulStrategyRouteEntity; + } + + public ZuulStrategyRouteEntity getZuulStrategyRouteEntity() { + return zuulStrategyRouteEntity; + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/event/ZuulStrategyRouteUpdatedAllEvent.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/event/ZuulStrategyRouteUpdatedAllEvent.java new file mode 100644 index 0000000000..43c037b49b --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/event/ZuulStrategyRouteUpdatedAllEvent.java @@ -0,0 +1,29 @@ +package com.nepxion.discovery.plugin.strategy.zuul.event; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.io.Serializable; +import java.util.List; + +import com.nepxion.discovery.common.entity.ZuulStrategyRouteEntity; + +public class ZuulStrategyRouteUpdatedAllEvent implements Serializable { + private static final long serialVersionUID = 4059761231628294140L; + + private List zuulStrategyRouteEntityList; + + public ZuulStrategyRouteUpdatedAllEvent(List zuulStrategyRouteEntityList) { + this.zuulStrategyRouteEntityList = zuulStrategyRouteEntityList; + } + + public List getZuulStrategyRouteEntityList() { + return zuulStrategyRouteEntityList; + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/filter/AbstractZuulStrategyRouteFilter.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/filter/AbstractZuulStrategyRouteFilter.java new file mode 100644 index 0000000000..be6af43596 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/filter/AbstractZuulStrategyRouteFilter.java @@ -0,0 +1,268 @@ +package com.nepxion.discovery.plugin.strategy.zuul.filter; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.Map; + +import org.apache.commons.collections4.MapUtils; +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants; + +import com.nepxion.discovery.common.constant.DiscoveryConstant; +import com.nepxion.discovery.plugin.framework.adapter.PluginAdapter; +import com.nepxion.discovery.plugin.strategy.wrapper.StrategyWrapper; +import com.nepxion.discovery.plugin.strategy.zuul.constant.ZuulStrategyConstant; +import com.nepxion.discovery.plugin.strategy.zuul.monitor.ZuulStrategyMonitor; +import com.netflix.zuul.context.RequestContext; + +public abstract class AbstractZuulStrategyRouteFilter extends ZuulStrategyRouteFilter { + @Autowired + protected PluginAdapter pluginAdapter; + + @Autowired + protected StrategyWrapper strategyWrapper; + + @Autowired(required = false) + protected ZuulStrategyMonitor zuulStrategyMonitor; + + // 如果外界也传了相同的Header,例如,从Postman传递过来的Header,当下面的变量为true,以网关设置为优先,否则以外界传值为优先 + @Value("${" + ZuulStrategyConstant.SPRING_APPLICATION_STRATEGY_ZUUL_HEADER_PRIORITY + ":true}") + protected Boolean zuulHeaderPriority; + + // 当以网关设置为优先的时候,网关未配置Header,而外界配置了Header,仍旧忽略外界的Header + @Value("${" + ZuulStrategyConstant.SPRING_APPLICATION_STRATEGY_ZUUL_ORIGINAL_HEADER_IGNORED + ":true}") + protected Boolean zuulOriginalHeaderIgnored; + + // Zuul上核心策略Header是否传递。当全局订阅启动时,可以关闭核心策略Header传递,这样可以节省传递数据的大小,一定程度上可以提升性能 + // 核心策略Header指n-d-开头的Header(不包括n-d-env,因为环境路由隔离,必须传递该Header),不包括n-d-service开头的Header + @Value("${" + ZuulStrategyConstant.SPRING_APPLICATION_STRATEGY_ZUUL_CORE_HEADER_TRANSMISSION_ENABLED + ":true}") + protected Boolean zuulCoreHeaderTransmissionEnabled; + + @Value("${" + ZuulStrategyConstant.SPRING_APPLICATION_STRATEGY_ZUUL_ROUTE_FILTER_ORDER + ":" + ZuulStrategyConstant.SPRING_APPLICATION_STRATEGY_ZUUL_ROUTE_FILTER_ORDER_VALUE + "}") + protected Integer filterOrder; + + @Override + public String filterType() { + return FilterConstants.PRE_TYPE; + } + + @Override + public int filterOrder() { + return filterOrder; + } + + @Override + public boolean shouldFilter() { + return true; + } + + @Override + public Object run() { + // 通过过滤器设置路由Header头部信息,并全链路传递到服务端 + RequestContext context = RequestContext.getCurrentContext(); + + // 处理内部Header的转发 + applyInnerHeader(context); + + // 处理外部Header的转发 + applyOuterHeader(context); + + // 调用链监控 + if (zuulStrategyMonitor != null) { + zuulStrategyMonitor.monitor(context); + } + + // 拦截侦测请求 + String path = context.getRequest().getServletPath(); + if (path.contains(DiscoveryConstant.INSPECTOR_ENDPOINT_URL)) { + ZuulStrategyFilterResolver.setHeader(context, DiscoveryConstant.INSPECTOR_ENDPOINT_HEADER, pluginAdapter.getPluginInfo(null), true); + } + + return null; + } + + // 处理内部Header的转发,即把本地服务的相关属性封装成Header转发到下游服务去 + private void applyInnerHeader(RequestContext context) { + // 设置本地组名到Header中,并全链路传递 + // 对于服务A -> 网关 -> 服务B调用链 + // 域网关下(zuulHeaderPriority=true),只传递网关自身的group,不传递上游服务A的group,起到基于组的网关端服务调用隔离 + // 非域网关下(zuulHeaderPriority=false),优先传递上游服务A的group,基于组的网关端服务调用隔离不生效,但可以实现基于相关参数的熔断限流等功能 + ZuulStrategyFilterResolver.setHeader(context, DiscoveryConstant.N_D_SERVICE_GROUP, pluginAdapter.getGroup(), zuulHeaderPriority); + + // 网关只负责传递服务A的相关参数(例如:serviceId),不传递自身的参数,实现基于相关参数的熔断限流等功能 + ZuulStrategyFilterResolver.setHeader(context, DiscoveryConstant.N_D_SERVICE_TYPE, pluginAdapter.getServiceType(), false); + String serviceAppId = pluginAdapter.getServiceAppId(); + if (StringUtils.isNotEmpty(serviceAppId)) { + ZuulStrategyFilterResolver.setHeader(context, DiscoveryConstant.N_D_SERVICE_APP_ID, serviceAppId, false); + } + ZuulStrategyFilterResolver.setHeader(context, DiscoveryConstant.N_D_SERVICE_ID, pluginAdapter.getServiceId(), false); + ZuulStrategyFilterResolver.setHeader(context, DiscoveryConstant.N_D_SERVICE_ADDRESS, pluginAdapter.getHost() + ":" + pluginAdapter.getPort(), false); + String version = pluginAdapter.getVersion(); + if (StringUtils.isNotEmpty(version) && !StringUtils.equals(version, DiscoveryConstant.DEFAULT)) { + ZuulStrategyFilterResolver.setHeader(context, DiscoveryConstant.N_D_SERVICE_VERSION, version, false); + } + String region = pluginAdapter.getRegion(); + if (StringUtils.isNotEmpty(region) && !StringUtils.equals(region, DiscoveryConstant.DEFAULT)) { + ZuulStrategyFilterResolver.setHeader(context, DiscoveryConstant.N_D_SERVICE_REGION, region, false); + } + String environment = pluginAdapter.getEnvironment(); + if (StringUtils.isNotEmpty(environment) && !StringUtils.equals(environment, DiscoveryConstant.DEFAULT)) { + ZuulStrategyFilterResolver.setHeader(context, DiscoveryConstant.N_D_SERVICE_ENVIRONMENT, environment, false); + } + String zone = pluginAdapter.getZone(); + if (StringUtils.isNotEmpty(zone) && !StringUtils.equals(zone, DiscoveryConstant.DEFAULT)) { + ZuulStrategyFilterResolver.setHeader(context, DiscoveryConstant.N_D_SERVICE_ZONE, zone, false); + } + } + + // 处理外部Header的转发,即外部服务传递过来的Header,中继转发到下游服务去 + private void applyOuterHeader(RequestContext context) { + String routeEnvironment = getRouteEnvironment(); + if (StringUtils.isNotEmpty(routeEnvironment)) { + ZuulStrategyFilterResolver.setHeader(context, DiscoveryConstant.N_D_ENVIRONMENT, routeEnvironment, false); + } + + // 外置Header预先塞入 + Map externalHeaderMap = getExternalHeaderMap(); + if (MapUtils.isNotEmpty(externalHeaderMap)) { + for (Map.Entry entry : externalHeaderMap.entrySet()) { + String key = entry.getKey(); + String value = entry.getValue(); + + ZuulStrategyFilterResolver.setHeader(context, key, value, zuulHeaderPriority); + } + } + + if (zuulCoreHeaderTransmissionEnabled) { + // 内置Header预先塞入 + Map internalHeaderMap = strategyWrapper.getHeaderMap(); + if (MapUtils.isNotEmpty(internalHeaderMap)) { + for (Map.Entry entry : internalHeaderMap.entrySet()) { + String key = entry.getKey(); + String value = entry.getValue(); + + ZuulStrategyFilterResolver.setHeader(context, key, value, zuulHeaderPriority); + } + } + + String routeVersion = getRouteVersion(); + String routeRegion = getRouteRegion(); + String routeAddress = getRouteAddress(); + String routeVersionWeight = getRouteVersionWeight(); + String routeRegionWeight = getRouteRegionWeight(); + String routeVersionPrefer = getRouteVersionPrefer(); + String routeVersionFailover = getRouteVersionFailover(); + String routeRegionTransfer = getRouteRegionTransfer(); + String routeRegionFailover = getRouteRegionFailover(); + String routeEnvironmentFailover = getRouteEnvironmentFailover(); + String routeZoneFailover = getRouteZoneFailover(); + String routeAddressFailover = getRouteAddressFailover(); + String routeIdBlacklist = getRouteIdBlacklist(); + String routeAddressBlacklist = getRouteAddressBlacklist(); + + if (StringUtils.isNotEmpty(routeVersion)) { + ZuulStrategyFilterResolver.setHeader(context, DiscoveryConstant.N_D_VERSION, routeVersion, zuulHeaderPriority); + } else { + ZuulStrategyFilterResolver.ignoreHeader(context, DiscoveryConstant.N_D_VERSION, zuulHeaderPriority, zuulOriginalHeaderIgnored); + } + if (StringUtils.isNotEmpty(routeRegion)) { + ZuulStrategyFilterResolver.setHeader(context, DiscoveryConstant.N_D_REGION, routeRegion, zuulHeaderPriority); + } else { + ZuulStrategyFilterResolver.ignoreHeader(context, DiscoveryConstant.N_D_REGION, zuulHeaderPriority, zuulOriginalHeaderIgnored); + } + if (StringUtils.isNotEmpty(routeAddress)) { + ZuulStrategyFilterResolver.setHeader(context, DiscoveryConstant.N_D_ADDRESS, routeAddress, zuulHeaderPriority); + } else { + ZuulStrategyFilterResolver.ignoreHeader(context, DiscoveryConstant.N_D_ADDRESS, zuulHeaderPriority, zuulOriginalHeaderIgnored); + } + if (StringUtils.isNotEmpty(routeVersionWeight)) { + ZuulStrategyFilterResolver.setHeader(context, DiscoveryConstant.N_D_VERSION_WEIGHT, routeVersionWeight, zuulHeaderPriority); + } else { + ZuulStrategyFilterResolver.ignoreHeader(context, DiscoveryConstant.N_D_VERSION_WEIGHT, zuulHeaderPriority, zuulOriginalHeaderIgnored); + } + if (StringUtils.isNotEmpty(routeRegionWeight)) { + ZuulStrategyFilterResolver.setHeader(context, DiscoveryConstant.N_D_REGION_WEIGHT, routeRegionWeight, zuulHeaderPriority); + } else { + ZuulStrategyFilterResolver.ignoreHeader(context, DiscoveryConstant.N_D_REGION_WEIGHT, zuulHeaderPriority, zuulOriginalHeaderIgnored); + } + if (StringUtils.isNotEmpty(routeVersionPrefer)) { + ZuulStrategyFilterResolver.setHeader(context, DiscoveryConstant.N_D_VERSION_PREFER, routeVersionPrefer, zuulHeaderPriority); + } else { + ZuulStrategyFilterResolver.ignoreHeader(context, DiscoveryConstant.N_D_VERSION_PREFER, zuulHeaderPriority, zuulOriginalHeaderIgnored); + } + if (StringUtils.isNotEmpty(routeVersionFailover)) { + ZuulStrategyFilterResolver.setHeader(context, DiscoveryConstant.N_D_VERSION_FAILOVER, routeVersionFailover, zuulHeaderPriority); + } else { + ZuulStrategyFilterResolver.ignoreHeader(context, DiscoveryConstant.N_D_VERSION_FAILOVER, zuulHeaderPriority, zuulOriginalHeaderIgnored); + } + if (StringUtils.isNotEmpty(routeRegionTransfer)) { + ZuulStrategyFilterResolver.setHeader(context, DiscoveryConstant.N_D_REGION_TRANSFER, routeRegionTransfer, zuulHeaderPriority); + } else { + ZuulStrategyFilterResolver.ignoreHeader(context, DiscoveryConstant.N_D_REGION_TRANSFER, zuulHeaderPriority, zuulOriginalHeaderIgnored); + } + if (StringUtils.isNotEmpty(routeRegionFailover)) { + ZuulStrategyFilterResolver.setHeader(context, DiscoveryConstant.N_D_REGION_FAILOVER, routeRegionFailover, zuulHeaderPriority); + } else { + ZuulStrategyFilterResolver.ignoreHeader(context, DiscoveryConstant.N_D_REGION_FAILOVER, zuulHeaderPriority, zuulOriginalHeaderIgnored); + } + if (StringUtils.isNotEmpty(routeEnvironmentFailover)) { + ZuulStrategyFilterResolver.setHeader(context, DiscoveryConstant.N_D_ENVIRONMENT_FAILOVER, routeEnvironmentFailover, zuulHeaderPriority); + } else { + ZuulStrategyFilterResolver.ignoreHeader(context, DiscoveryConstant.N_D_ENVIRONMENT_FAILOVER, zuulHeaderPriority, zuulOriginalHeaderIgnored); + } + if (StringUtils.isNotEmpty(routeZoneFailover)) { + ZuulStrategyFilterResolver.setHeader(context, DiscoveryConstant.N_D_ZONE_FAILOVER, routeZoneFailover, zuulHeaderPriority); + } else { + ZuulStrategyFilterResolver.ignoreHeader(context, DiscoveryConstant.N_D_ZONE_FAILOVER, zuulHeaderPriority, zuulOriginalHeaderIgnored); + } + if (StringUtils.isNotEmpty(routeAddressFailover)) { + ZuulStrategyFilterResolver.setHeader(context, DiscoveryConstant.N_D_ADDRESS_FAILOVER, routeAddressFailover, zuulHeaderPriority); + } else { + ZuulStrategyFilterResolver.ignoreHeader(context, DiscoveryConstant.N_D_ADDRESS_FAILOVER, zuulHeaderPriority, zuulOriginalHeaderIgnored); + } + if (StringUtils.isNotEmpty(routeIdBlacklist)) { + ZuulStrategyFilterResolver.setHeader(context, DiscoveryConstant.N_D_ID_BLACKLIST, routeIdBlacklist, zuulHeaderPriority); + } else { + ZuulStrategyFilterResolver.ignoreHeader(context, DiscoveryConstant.N_D_ID_BLACKLIST, zuulHeaderPriority, zuulOriginalHeaderIgnored); + } + if (StringUtils.isNotEmpty(routeAddressBlacklist)) { + ZuulStrategyFilterResolver.setHeader(context, DiscoveryConstant.N_D_ADDRESS_BLACKLIST, routeAddressBlacklist, zuulHeaderPriority); + } else { + ZuulStrategyFilterResolver.ignoreHeader(context, DiscoveryConstant.N_D_ADDRESS_BLACKLIST, zuulHeaderPriority, zuulOriginalHeaderIgnored); + } + } else { + // 当核心Header传值开关关闭的时候,执行忽略Header设置的相关逻辑 + ZuulStrategyFilterResolver.ignoreHeader(context, DiscoveryConstant.N_D_VERSION); + ZuulStrategyFilterResolver.ignoreHeader(context, DiscoveryConstant.N_D_REGION); + ZuulStrategyFilterResolver.ignoreHeader(context, DiscoveryConstant.N_D_ADDRESS); + ZuulStrategyFilterResolver.ignoreHeader(context, DiscoveryConstant.N_D_VERSION_WEIGHT); + ZuulStrategyFilterResolver.ignoreHeader(context, DiscoveryConstant.N_D_REGION_WEIGHT); + ZuulStrategyFilterResolver.ignoreHeader(context, DiscoveryConstant.N_D_VERSION_PREFER); + ZuulStrategyFilterResolver.ignoreHeader(context, DiscoveryConstant.N_D_VERSION_FAILOVER); + ZuulStrategyFilterResolver.ignoreHeader(context, DiscoveryConstant.N_D_REGION_TRANSFER); + ZuulStrategyFilterResolver.ignoreHeader(context, DiscoveryConstant.N_D_REGION_FAILOVER); + ZuulStrategyFilterResolver.ignoreHeader(context, DiscoveryConstant.N_D_ENVIRONMENT_FAILOVER); + ZuulStrategyFilterResolver.ignoreHeader(context, DiscoveryConstant.N_D_ZONE_FAILOVER); + ZuulStrategyFilterResolver.ignoreHeader(context, DiscoveryConstant.N_D_ADDRESS_FAILOVER); + ZuulStrategyFilterResolver.ignoreHeader(context, DiscoveryConstant.N_D_ID_BLACKLIST); + ZuulStrategyFilterResolver.ignoreHeader(context, DiscoveryConstant.N_D_ADDRESS_BLACKLIST); + } + } + + public Map getExternalHeaderMap() { + return null; + } + + public PluginAdapter getPluginAdapter() { + return pluginAdapter; + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/filter/DefaultZuulStrategyClearFilter.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/filter/DefaultZuulStrategyClearFilter.java new file mode 100644 index 0000000000..7ae2e398b4 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/filter/DefaultZuulStrategyClearFilter.java @@ -0,0 +1,47 @@ +package com.nepxion.discovery.plugin.strategy.zuul.filter; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants; + +import com.nepxion.discovery.plugin.strategy.zuul.monitor.ZuulStrategyMonitor; +import com.netflix.zuul.context.RequestContext; + +public class DefaultZuulStrategyClearFilter extends ZuulStrategyClearFilter { + @Autowired(required = false) + protected ZuulStrategyMonitor zuulStrategyMonitor; + + @Override + public String filterType() { + return FilterConstants.POST_TYPE; + } + + @Override + public int filterOrder() { + return 0; + } + + @Override + public boolean shouldFilter() { + return true; + } + + @Override + public Object run() { + // 调用链释放 + RequestContext context = RequestContext.getCurrentContext(); + if (zuulStrategyMonitor != null) { + zuulStrategyMonitor.release(context); + } + + return null; + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/filter/DefaultZuulStrategyRouteFilter.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/filter/DefaultZuulStrategyRouteFilter.java new file mode 100644 index 0000000000..3c354fdf99 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/filter/DefaultZuulStrategyRouteFilter.java @@ -0,0 +1,99 @@ +package com.nepxion.discovery.plugin.strategy.zuul.filter; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.springframework.beans.factory.annotation.Autowired; + +import com.nepxion.discovery.plugin.strategy.context.StrategyContextHolder; + +// 负载均衡前执行路由过滤 +public class DefaultZuulStrategyRouteFilter extends AbstractZuulStrategyRouteFilter { + @Autowired + protected StrategyContextHolder strategyContextHolder; + + @Override + public String getRouteVersion() { + return strategyContextHolder.getRouteVersion(); + } + + @Override + public String getRouteRegion() { + return strategyContextHolder.getRouteRegion(); + } + + @Override + public String getRouteEnvironment() { + return strategyContextHolder.getRouteEnvironment(); + } + + @Override + public String getRouteAddress() { + return strategyContextHolder.getRouteAddress(); + } + + @Override + public String getRouteVersionWeight() { + return strategyContextHolder.getRouteVersionWeight(); + } + + @Override + public String getRouteRegionWeight() { + return strategyContextHolder.getRouteRegionWeight(); + } + + @Override + public String getRouteVersionPrefer() { + return strategyContextHolder.getRouteVersionPrefer(); + } + + @Override + public String getRouteVersionFailover() { + return strategyContextHolder.getRouteVersionFailover(); + } + + @Override + public String getRouteRegionTransfer() { + return strategyContextHolder.getRouteRegionTransfer(); + } + + @Override + public String getRouteRegionFailover() { + return strategyContextHolder.getRouteRegionFailover(); + } + + @Override + public String getRouteEnvironmentFailover() { + return strategyContextHolder.getRouteEnvironmentFailover(); + } + + @Override + public String getRouteZoneFailover() { + return strategyContextHolder.getRouteZoneFailover(); + } + + @Override + public String getRouteAddressFailover() { + return strategyContextHolder.getRouteAddressFailover(); + } + + @Override + public String getRouteIdBlacklist() { + return strategyContextHolder.getRouteIdBlacklist(); + } + + @Override + public String getRouteAddressBlacklist() { + return strategyContextHolder.getRouteAddressBlacklist(); + } + + public StrategyContextHolder getStrategyContextHolder() { + return strategyContextHolder; + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/filter/ZuulStrategyClearFilter.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/filter/ZuulStrategyClearFilter.java new file mode 100644 index 0000000000..d5b53a41d9 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/filter/ZuulStrategyClearFilter.java @@ -0,0 +1,14 @@ +package com.nepxion.discovery.plugin.strategy.zuul.filter; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +public abstract class ZuulStrategyClearFilter extends ZuulStrategyFilter { + +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/filter/ZuulStrategyFilter.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/filter/ZuulStrategyFilter.java new file mode 100644 index 0000000000..2ad4341429 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/filter/ZuulStrategyFilter.java @@ -0,0 +1,16 @@ +package com.nepxion.discovery.plugin.strategy.zuul.filter; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import com.netflix.zuul.ZuulFilter; + +public abstract class ZuulStrategyFilter extends ZuulFilter { + +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/filter/ZuulStrategyFilterResolver.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/filter/ZuulStrategyFilterResolver.java new file mode 100644 index 0000000000..d43b47b98d --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/filter/ZuulStrategyFilterResolver.java @@ -0,0 +1,47 @@ +package com.nepxion.discovery.plugin.strategy.zuul.filter; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.apache.commons.lang3.StringUtils; + +import com.netflix.zuul.context.RequestContext; + +public class ZuulStrategyFilterResolver { + public static void setHeader(RequestContext context, String headerName, String headerValue, Boolean zuulHeaderPriority) { + if (StringUtils.isEmpty(headerValue)) { + return; + } + + if (zuulHeaderPriority) { + // 通过Zuul Filter的Header直接把外界的Header替换掉,并传递 + context.addZuulRequestHeader(headerName, headerValue); + } else { + // 在外界的Header不存在的前提下,通过Zuul Filter的Header传递 + String header = context.getRequest().getHeader(headerName); + if (StringUtils.isEmpty(header)) { + context.addZuulRequestHeader(headerName, headerValue); + } + } + } + + public static void ignoreHeader(RequestContext context, String headerName, Boolean zuulHeaderPriority, Boolean zuulOriginalHeaderIgnored) { + if (zuulHeaderPriority && zuulOriginalHeaderIgnored) { + ignoreHeader(context, headerName); + } + } + + public static void ignoreHeader(RequestContext context, String headerName) { + String header = context.getRequest().getHeader(headerName); + if (StringUtils.isNotEmpty(header)) { + // 通过Zuul Filter的Header直接把外界的Header替换成空字符串 + context.addZuulRequestHeader(headerName, StringUtils.EMPTY); + } + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/filter/ZuulStrategyRouteFilter.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/filter/ZuulStrategyRouteFilter.java new file mode 100644 index 0000000000..3c9dc1f2e1 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/filter/ZuulStrategyRouteFilter.java @@ -0,0 +1,16 @@ +package com.nepxion.discovery.plugin.strategy.zuul.filter; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import com.nepxion.discovery.plugin.strategy.filter.StrategyRouteFilter; + +public abstract class ZuulStrategyRouteFilter extends ZuulStrategyFilter implements StrategyRouteFilter { + +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/monitor/DefaultZuulStrategyMonitor.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/monitor/DefaultZuulStrategyMonitor.java new file mode 100644 index 0000000000..b43b9c4670 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/monitor/DefaultZuulStrategyMonitor.java @@ -0,0 +1,34 @@ +package com.nepxion.discovery.plugin.strategy.zuul.monitor; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import com.nepxion.discovery.plugin.strategy.monitor.StrategyMonitor; +import com.netflix.zuul.context.RequestContext; + +public class DefaultZuulStrategyMonitor extends StrategyMonitor implements ZuulStrategyMonitor { + @Override + public void monitor(RequestContext context) { + spanBuild(); + + loggerOutput(); + loggerDebug(); + + alarm(null); + + spanOutput(null); + } + + @Override + public void release(RequestContext context) { + loggerClear(); + + spanFinish(); + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/monitor/ZuulStrategyMonitor.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/monitor/ZuulStrategyMonitor.java new file mode 100644 index 0000000000..063faa8f53 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/monitor/ZuulStrategyMonitor.java @@ -0,0 +1,18 @@ +package com.nepxion.discovery.plugin.strategy.zuul.monitor; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import com.netflix.zuul.context.RequestContext; + +public interface ZuulStrategyMonitor { + void monitor(RequestContext context); + + void release(RequestContext context); +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/processor/ZuulStrategyRouteApolloProcessor.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/processor/ZuulStrategyRouteApolloProcessor.java new file mode 100644 index 0000000000..3e1e4a08ae --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/processor/ZuulStrategyRouteApolloProcessor.java @@ -0,0 +1,45 @@ +package com.nepxion.discovery.plugin.strategy.zuul.processor; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.springframework.beans.factory.annotation.Autowired; + +import com.nepxion.discovery.common.apollo.proccessor.ApolloProcessor; +import com.nepxion.discovery.common.constant.DiscoveryConstant; +import com.nepxion.discovery.plugin.framework.adapter.PluginAdapter; +import com.nepxion.discovery.plugin.strategy.zuul.route.ZuulStrategyRoute; + +public class ZuulStrategyRouteApolloProcessor extends ApolloProcessor { + @Autowired + private PluginAdapter pluginAdapter; + + @Autowired + private ZuulStrategyRoute zuulStrategyRoute; + + @Override + public String getGroup() { + return pluginAdapter.getGroup(); + } + + @Override + public String getDataId() { + return pluginAdapter.getServiceId() + "-" + DiscoveryConstant.DYNAMIC_ROUTE_KEY; + } + + @Override + public String getDescription() { + return DiscoveryConstant.ZUUL_DYNAMIC_ROUTE_DESCRIPTION; + } + + @Override + public void callbackConfig(String config) { + zuulStrategyRoute.updateAll(config); + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/processor/ZuulStrategyRouteConsulProcessor.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/processor/ZuulStrategyRouteConsulProcessor.java new file mode 100644 index 0000000000..4a5caefa7b --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/processor/ZuulStrategyRouteConsulProcessor.java @@ -0,0 +1,45 @@ +package com.nepxion.discovery.plugin.strategy.zuul.processor; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.springframework.beans.factory.annotation.Autowired; + +import com.nepxion.discovery.common.constant.DiscoveryConstant; +import com.nepxion.discovery.common.consul.proccessor.ConsulProcessor; +import com.nepxion.discovery.plugin.framework.adapter.PluginAdapter; +import com.nepxion.discovery.plugin.strategy.zuul.route.ZuulStrategyRoute; + +public class ZuulStrategyRouteConsulProcessor extends ConsulProcessor { + @Autowired + private PluginAdapter pluginAdapter; + + @Autowired + private ZuulStrategyRoute zuulStrategyRoute; + + @Override + public String getGroup() { + return pluginAdapter.getGroup(); + } + + @Override + public String getDataId() { + return pluginAdapter.getServiceId() + "-" + DiscoveryConstant.DYNAMIC_ROUTE_KEY; + } + + @Override + public String getDescription() { + return DiscoveryConstant.ZUUL_DYNAMIC_ROUTE_DESCRIPTION; + } + + @Override + public void callbackConfig(String config) { + zuulStrategyRoute.updateAll(config); + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/processor/ZuulStrategyRouteEtcdProcessor.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/processor/ZuulStrategyRouteEtcdProcessor.java new file mode 100644 index 0000000000..7629caabdc --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/processor/ZuulStrategyRouteEtcdProcessor.java @@ -0,0 +1,45 @@ +package com.nepxion.discovery.plugin.strategy.zuul.processor; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.springframework.beans.factory.annotation.Autowired; + +import com.nepxion.discovery.common.constant.DiscoveryConstant; +import com.nepxion.discovery.common.etcd.proccessor.EtcdProcessor; +import com.nepxion.discovery.plugin.framework.adapter.PluginAdapter; +import com.nepxion.discovery.plugin.strategy.zuul.route.ZuulStrategyRoute; + +public class ZuulStrategyRouteEtcdProcessor extends EtcdProcessor { + @Autowired + private PluginAdapter pluginAdapter; + + @Autowired + private ZuulStrategyRoute zuulStrategyRoute; + + @Override + public String getGroup() { + return pluginAdapter.getGroup(); + } + + @Override + public String getDataId() { + return pluginAdapter.getServiceId() + "-" + DiscoveryConstant.DYNAMIC_ROUTE_KEY; + } + + @Override + public String getDescription() { + return DiscoveryConstant.ZUUL_DYNAMIC_ROUTE_DESCRIPTION; + } + + @Override + public void callbackConfig(String config) { + zuulStrategyRoute.updateAll(config); + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/processor/ZuulStrategyRouteNacosProcessor.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/processor/ZuulStrategyRouteNacosProcessor.java new file mode 100644 index 0000000000..ad73f9fdee --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/processor/ZuulStrategyRouteNacosProcessor.java @@ -0,0 +1,45 @@ +package com.nepxion.discovery.plugin.strategy.zuul.processor; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.springframework.beans.factory.annotation.Autowired; + +import com.nepxion.discovery.common.constant.DiscoveryConstant; +import com.nepxion.discovery.common.nacos.proccessor.NacosProcessor; +import com.nepxion.discovery.plugin.framework.adapter.PluginAdapter; +import com.nepxion.discovery.plugin.strategy.zuul.route.ZuulStrategyRoute; + +public class ZuulStrategyRouteNacosProcessor extends NacosProcessor { + @Autowired + private PluginAdapter pluginAdapter; + + @Autowired + private ZuulStrategyRoute zuulStrategyRoute; + + @Override + public String getGroup() { + return pluginAdapter.getGroup(); + } + + @Override + public String getDataId() { + return pluginAdapter.getServiceId() + "-" + DiscoveryConstant.DYNAMIC_ROUTE_KEY; + } + + @Override + public String getDescription() { + return DiscoveryConstant.ZUUL_DYNAMIC_ROUTE_DESCRIPTION; + } + + @Override + public void callbackConfig(String config) { + zuulStrategyRoute.updateAll(config); + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/processor/ZuulStrategyRouteRedisProcessor.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/processor/ZuulStrategyRouteRedisProcessor.java new file mode 100644 index 0000000000..bd2a522681 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/processor/ZuulStrategyRouteRedisProcessor.java @@ -0,0 +1,45 @@ +package com.nepxion.discovery.plugin.strategy.zuul.processor; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.springframework.beans.factory.annotation.Autowired; + +import com.nepxion.discovery.common.constant.DiscoveryConstant; +import com.nepxion.discovery.common.redis.proccessor.RedisProcessor; +import com.nepxion.discovery.plugin.framework.adapter.PluginAdapter; +import com.nepxion.discovery.plugin.strategy.zuul.route.ZuulStrategyRoute; + +public class ZuulStrategyRouteRedisProcessor extends RedisProcessor { + @Autowired + private PluginAdapter pluginAdapter; + + @Autowired + private ZuulStrategyRoute zuulStrategyRoute; + + @Override + public String getGroup() { + return pluginAdapter.getGroup(); + } + + @Override + public String getDataId() { + return pluginAdapter.getServiceId() + "-" + DiscoveryConstant.DYNAMIC_ROUTE_KEY; + } + + @Override + public String getDescription() { + return DiscoveryConstant.ZUUL_DYNAMIC_ROUTE_DESCRIPTION; + } + + @Override + public void callbackConfig(String config) { + zuulStrategyRoute.updateAll(config); + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/processor/ZuulStrategyRouteZookeeperProcessor.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/processor/ZuulStrategyRouteZookeeperProcessor.java new file mode 100644 index 0000000000..025f423b84 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/processor/ZuulStrategyRouteZookeeperProcessor.java @@ -0,0 +1,45 @@ +package com.nepxion.discovery.plugin.strategy.zuul.processor; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.springframework.beans.factory.annotation.Autowired; + +import com.nepxion.discovery.common.constant.DiscoveryConstant; +import com.nepxion.discovery.common.zookeeper.proccessor.ZookeeperProcessor; +import com.nepxion.discovery.plugin.framework.adapter.PluginAdapter; +import com.nepxion.discovery.plugin.strategy.zuul.route.ZuulStrategyRoute; + +public class ZuulStrategyRouteZookeeperProcessor extends ZookeeperProcessor { + @Autowired + private PluginAdapter pluginAdapter; + + @Autowired + private ZuulStrategyRoute zuulStrategyRoute; + + @Override + public String getGroup() { + return pluginAdapter.getGroup(); + } + + @Override + public String getDataId() { + return pluginAdapter.getServiceId() + "-" + DiscoveryConstant.DYNAMIC_ROUTE_KEY; + } + + @Override + public String getDescription() { + return DiscoveryConstant.ZUUL_DYNAMIC_ROUTE_DESCRIPTION; + } + + @Override + public void callbackConfig(String config) { + zuulStrategyRoute.updateAll(config); + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/route/AbstractZuulStrategyRoute.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/route/AbstractZuulStrategyRoute.java new file mode 100644 index 0000000000..9713d2d5b4 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/route/AbstractZuulStrategyRoute.java @@ -0,0 +1,334 @@ +package com.nepxion.discovery.plugin.strategy.zuul.route; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Ning Zhang + * @author Haojun Ren + * @version 1.0 + */ + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeSet; +import java.util.stream.Collectors; + +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cloud.netflix.zuul.RoutesRefreshedEvent; +import org.springframework.cloud.netflix.zuul.filters.RefreshableRouteLocator; +import org.springframework.cloud.netflix.zuul.filters.SimpleRouteLocator; +import org.springframework.cloud.netflix.zuul.filters.ZuulProperties; +import org.springframework.context.ApplicationEventPublisher; +import org.springframework.context.ApplicationEventPublisherAware; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.nepxion.discovery.common.constant.DiscoveryConstant; +import com.nepxion.discovery.common.entity.ZuulStrategyRouteEntity; +import com.nepxion.discovery.common.exception.DiscoveryException; +import com.nepxion.discovery.common.util.JsonUtil; +import com.nepxion.discovery.plugin.framework.event.PluginPublisher; +import com.nepxion.discovery.plugin.strategy.zuul.event.ZuulStrategyRouteAddedEvent; +import com.nepxion.discovery.plugin.strategy.zuul.event.ZuulStrategyRouteDeletedEvent; +import com.nepxion.discovery.plugin.strategy.zuul.event.ZuulStrategyRouteModifiedEvent; +import com.nepxion.discovery.plugin.strategy.zuul.event.ZuulStrategyRouteUpdatedAllEvent; + +// Zuul的存储结构 +// zuulProperties.getRoutes()返回值的Key为routeId +// locateRoutes()返回值的Key为path +public abstract class AbstractZuulStrategyRoute extends SimpleRouteLocator implements ZuulStrategyRoute, RefreshableRouteLocator, ApplicationEventPublisherAware { + private static final Logger LOG = LoggerFactory.getLogger(AbstractZuulStrategyRoute.class); + + @Autowired + private PluginPublisher pluginPublisher; + + private ZuulProperties zuulProperties; + + private ApplicationEventPublisher applicationEventPublisher; + + public AbstractZuulStrategyRoute(String servletPath, ZuulProperties zuulProperties) { + super(servletPath, zuulProperties); + + this.zuulProperties = zuulProperties; + } + + @Override + public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) { + this.applicationEventPublisher = applicationEventPublisher; + } + + @Override + public synchronized void add(ZuulStrategyRouteEntity zuulStrategyRouteEntity) { + if (zuulStrategyRouteEntity == null) { + throw new DiscoveryException("Zuul dynamic route is null"); + } + + Map idRouteMap = zuulProperties.getRoutes(); + String routeId = zuulStrategyRouteEntity.getId(); + if (idRouteMap.containsKey(routeId)) { + throw new DiscoveryException("Zuul dynamic route for routeId=[" + routeId + "] is duplicated"); + } + + /*Map pathRouteMap = locateRoutes(); + String path = zuulStrategyRouteEntity.getPath(); + if (pathRouteMap.containsKey(path)) { + throw new DiscoveryException("Zuul dynamic route for path=[" + path + "] is duplicated"); + }*/ + + ZuulProperties.ZuulRoute route = convertRoute(zuulStrategyRouteEntity); + addRoute(route); + + LOG.info("Added Zuul dynamic route={}", route); + + applicationEventPublisher.publishEvent(new RoutesRefreshedEvent(this)); + + pluginPublisher.asyncPublish(new ZuulStrategyRouteAddedEvent(zuulStrategyRouteEntity)); + } + + @Override + public synchronized void modify(ZuulStrategyRouteEntity zuulStrategyRouteEntity) { + if (zuulStrategyRouteEntity == null) { + throw new DiscoveryException("Zuul dynamic route is null"); + } + + Map idRouteMap = zuulProperties.getRoutes(); + String routeId = zuulStrategyRouteEntity.getId(); + if (!idRouteMap.containsKey(routeId)) { + throw new DiscoveryException("Zuul dynamic route for routeId=[" + routeId + "] isn't found"); + } + + /*Map pathRouteMap = locateRoutes(); + String path = zuulStrategyRouteEntity.getPath(); + if (pathRouteMap.containsKey(path)) { + throw new DiscoveryException("Zuul dynamic route for path=[" + path + "] is duplicated"); + }*/ + + ZuulProperties.ZuulRoute route = convertRoute(zuulStrategyRouteEntity); + modifyRoute(route); + + LOG.info("Modified Zuul dynamic route={}", route); + + applicationEventPublisher.publishEvent(new RoutesRefreshedEvent(this)); + + pluginPublisher.asyncPublish(new ZuulStrategyRouteModifiedEvent(zuulStrategyRouteEntity)); + } + + @Override + public synchronized void delete(String routeId) { + if (StringUtils.isEmpty(routeId)) { + throw new DiscoveryException("RouteId is empty"); + } + + Map idRouteMap = zuulProperties.getRoutes(); + if (!idRouteMap.containsKey(routeId)) { + throw new DiscoveryException("Zuul dynamic route for routeId=[" + routeId + "] isn't found"); + } + + ZuulProperties.ZuulRoute route = idRouteMap.get(routeId); + deleteRoute(route); + + LOG.info("Deleted Zuul dynamic route for routeId={}", routeId); + + applicationEventPublisher.publishEvent(new RoutesRefreshedEvent(this)); + + pluginPublisher.asyncPublish(new ZuulStrategyRouteDeletedEvent(routeId)); + } + + @Override + public synchronized void updateAll(List zuulStrategyRouteEntityList) { + if (zuulStrategyRouteEntityList == null) { + throw new DiscoveryException("Zuul dynamic routes are null"); + } + + boolean isIdDuplicated = isIdDuplicated(zuulStrategyRouteEntityList); + if (isIdDuplicated) { + throw new DiscoveryException("Zuul dynamic routes have duplicated routeIds"); + } + + /*boolean isPathDuplicated = isPathDuplicated(zuulStrategyRouteEntityList); + if (isPathDuplicated) { + throw new DiscoveryException("Zuul dynamic routes have duplicated paths"); + }*/ + + Map dynamicRouteMap = zuulStrategyRouteEntityList.stream().collect(Collectors.toMap(ZuulStrategyRouteEntity::getId, this::convertRoute)); + Map currentRouteMap = zuulProperties.getRoutes(); + + List addRouteList = new ArrayList(dynamicRouteMap.size()); + List modifyRouteList = new ArrayList(dynamicRouteMap.size()); + List deleteRouteList = new ArrayList(dynamicRouteMap.size()); + + for (Map.Entry entry : dynamicRouteMap.entrySet()) { + String routeId = entry.getKey(); + ZuulProperties.ZuulRoute route = entry.getValue(); + if (!currentRouteMap.containsKey(routeId)) { + addRouteList.add(route); + } + } + + for (Map.Entry entry : dynamicRouteMap.entrySet()) { + String routeId = entry.getKey(); + ZuulProperties.ZuulRoute route = entry.getValue(); + if (currentRouteMap.containsKey(routeId)) { + ZuulProperties.ZuulRoute currentRoute = currentRouteMap.get(routeId); + if (!currentRoute.equals(route)) { + modifyRouteList.add(route); + } + } + } + + for (Map.Entry entry : currentRouteMap.entrySet()) { + String routeId = entry.getKey(); + ZuulProperties.ZuulRoute route = entry.getValue(); + if (!dynamicRouteMap.containsKey(routeId)) { + deleteRouteList.add(route); + } + } + + for (ZuulProperties.ZuulRoute zuulRoute : addRouteList) { + addRoute(zuulRoute); + } + + for (ZuulProperties.ZuulRoute zuulRoute : modifyRouteList) { + modifyRoute(zuulRoute); + } + + for (ZuulProperties.ZuulRoute zuulRoute : deleteRouteList) { + deleteRoute(zuulRoute); + } + + LOG.info("----- Zuul Dynamic Routes Update Information -----"); + LOG.info("Total count={}", zuulStrategyRouteEntityList.size()); + LOG.info("Added count={}", addRouteList.size()); + LOG.info("Modified count={}", modifyRouteList.size()); + LOG.info("Deleted count={}", deleteRouteList.size()); + LOG.info("--------------------------------------------------"); + + if (addRouteList.isEmpty() && modifyRouteList.isEmpty() && deleteRouteList.isEmpty()) { + return; + } + + applicationEventPublisher.publishEvent(new RoutesRefreshedEvent(this)); + + pluginPublisher.asyncPublish(new ZuulStrategyRouteUpdatedAllEvent(zuulStrategyRouteEntityList)); + } + + @Override + public synchronized void updateAll(String zuulStrategyRouteConfig) { + if (StringUtils.isBlank(zuulStrategyRouteConfig)) { + zuulStrategyRouteConfig = DiscoveryConstant.EMPTY_JSON_RULE_MULTIPLE; + } + + List zuulStrategyRouteEntityList = JsonUtil.fromJson(zuulStrategyRouteConfig, new TypeReference>() { + }); + + updateAll(zuulStrategyRouteEntityList); + } + + @Override + public ZuulStrategyRouteEntity view(String routeId) { + if (StringUtils.isEmpty(routeId)) { + throw new DiscoveryException("RouteId is empty"); + } + + Map idRouteMap = zuulProperties.getRoutes(); + if (!idRouteMap.containsKey(routeId)) { + throw new DiscoveryException("Zuul dynamic route for routeId=[" + routeId + "] isn't found"); + } + + ZuulProperties.ZuulRoute route = idRouteMap.get(routeId); + + return convertRoute(route); + } + + @Override + public List viewAll() { + List zuulStrategyRouteEntityList = new ArrayList(); + + Map routeMap = locateRoutes(); + for (Map.Entry entry : routeMap.entrySet()) { + ZuulProperties.ZuulRoute route = entry.getValue(); + ZuulStrategyRouteEntity zuulStrategyRouteEntity = convertRoute(route); + zuulStrategyRouteEntityList.add(zuulStrategyRouteEntity); + } + + return zuulStrategyRouteEntityList; + } + + @Override + public void refresh() { + doRefresh(); + } + + public boolean isIdDuplicated(List zuulStrategyRouteEntityList) { + Set zuulStrategyRouteEntitySet = new TreeSet(new Comparator() { + public int compare(ZuulStrategyRouteEntity zuulStrategyRouteEntity1, ZuulStrategyRouteEntity zuulStrategyRouteEntity2) { + return zuulStrategyRouteEntity1.getId().compareTo(zuulStrategyRouteEntity2.getId()); + } + }); + zuulStrategyRouteEntitySet.addAll(zuulStrategyRouteEntityList); + + return zuulStrategyRouteEntitySet.size() < zuulStrategyRouteEntityList.size(); + } + + public boolean isPathDuplicated(List zuulStrategyRouteEntityList) { + Set zuulStrategyRouteEntitySet = new TreeSet(new Comparator() { + public int compare(ZuulStrategyRouteEntity zuulStrategyRouteEntity1, ZuulStrategyRouteEntity zuulStrategyRouteEntity2) { + return zuulStrategyRouteEntity1.getPath().compareTo(zuulStrategyRouteEntity2.getPath()); + } + }); + zuulStrategyRouteEntitySet.addAll(zuulStrategyRouteEntityList); + + return zuulStrategyRouteEntitySet.size() < zuulStrategyRouteEntityList.size(); + } + + public ZuulProperties.ZuulRoute convertRoute(ZuulStrategyRouteEntity zuulStrategyRouteEntity) { + ZuulProperties.ZuulRoute route = new ZuulProperties.ZuulRoute(); + route.setId(StringUtils.isNotBlank(zuulStrategyRouteEntity.getId()) ? zuulStrategyRouteEntity.getId() : zuulStrategyRouteEntity.getServiceId()); + route.setServiceId(zuulStrategyRouteEntity.getServiceId()); + route.setPath(zuulStrategyRouteEntity.getPath()); + route.setUrl(zuulStrategyRouteEntity.getUrl()); + route.setStripPrefix(zuulStrategyRouteEntity.isStripPrefix()); + route.setRetryable(zuulStrategyRouteEntity.getRetryable()); + route.setSensitiveHeaders(zuulStrategyRouteEntity.getSensitiveHeaders()); + route.setCustomSensitiveHeaders(zuulStrategyRouteEntity.getSensitiveHeaders() != null && !zuulStrategyRouteEntity.getSensitiveHeaders().isEmpty()); + + return route; + } + + public ZuulStrategyRouteEntity convertRoute(ZuulProperties.ZuulRoute route) { + ZuulStrategyRouteEntity zuulStrategyRouteEntity = new ZuulStrategyRouteEntity(); + zuulStrategyRouteEntity.setId(route.getId()); + zuulStrategyRouteEntity.setServiceId(route.getServiceId()); + zuulStrategyRouteEntity.setPath(route.getPath()); + zuulStrategyRouteEntity.setUrl(route.getUrl()); + zuulStrategyRouteEntity.setStripPrefix(route.isStripPrefix()); + zuulStrategyRouteEntity.setRetryable(route.getRetryable()); + zuulStrategyRouteEntity.setSensitiveHeaders(route.getSensitiveHeaders()); + zuulStrategyRouteEntity.setCustomSensitiveHeaders(route.isCustomSensitiveHeaders()); + + return zuulStrategyRouteEntity; + } + + public void addRoute(ZuulProperties.ZuulRoute route) { + zuulProperties.getRoutes().put(route.getId(), route); + } + + public void modifyRoute(ZuulProperties.ZuulRoute route) { + zuulProperties.getRoutes().put(route.getId(), route); + } + + public void deleteRoute(ZuulProperties.ZuulRoute route) { + zuulProperties.getRoutes().remove(route.getId()); + } + + public void clearRoutes() { + zuulProperties.getRoutes().clear(); + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/route/DefaultZuulStrategyRoute.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/route/DefaultZuulStrategyRoute.java new file mode 100644 index 0000000000..af360a7f68 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/route/DefaultZuulStrategyRoute.java @@ -0,0 +1,18 @@ +package com.nepxion.discovery.plugin.strategy.zuul.route; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.springframework.cloud.netflix.zuul.filters.ZuulProperties; + +public class DefaultZuulStrategyRoute extends AbstractZuulStrategyRoute { + public DefaultZuulStrategyRoute(String servletPath, ZuulProperties zuulProperties) { + super(servletPath, zuulProperties); + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/route/ZuulStrategyRoute.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/route/ZuulStrategyRoute.java new file mode 100644 index 0000000000..c5ef4568f2 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/route/ZuulStrategyRoute.java @@ -0,0 +1,31 @@ +package com.nepxion.discovery.plugin.strategy.zuul.route; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Ning Zhang + * @author Haojun Ren + * @version 1.0 + */ + +import java.util.List; + +import com.nepxion.discovery.common.entity.ZuulStrategyRouteEntity; + +public interface ZuulStrategyRoute { + void add(ZuulStrategyRouteEntity zuulStrategyRouteEntity); + + void modify(ZuulStrategyRouteEntity zuulStrategyRouteEntity); + + void delete(String routeId); + + void updateAll(List zuulStrategyRouteEntityList); + + void updateAll(String zuulStrategyRouteConfig); + + ZuulStrategyRouteEntity view(String routeId); + + List viewAll(); +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/wrapper/DefaultZuulStrategyCallableWrapper.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/wrapper/DefaultZuulStrategyCallableWrapper.java new file mode 100644 index 0000000000..08715d85a7 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/wrapper/DefaultZuulStrategyCallableWrapper.java @@ -0,0 +1,48 @@ +package com.nepxion.discovery.plugin.strategy.zuul.wrapper; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @author Hao Huang + * @version 1.0 + */ + +import java.util.Map; +import java.util.concurrent.Callable; + +import javax.servlet.http.HttpServletRequest; + +import com.nepxion.discovery.plugin.strategy.monitor.StrategyTracerContext; +import com.nepxion.discovery.plugin.strategy.zuul.context.ZuulStrategyContext; +import com.netflix.zuul.context.RequestContext; + +public class DefaultZuulStrategyCallableWrapper implements ZuulStrategyCallableWrapper { + @Override + public Callable wrapCallable(Callable callable) { + HttpServletRequest request = RequestContext.getCurrentContext().getRequest(); + Map headers = RequestContext.getCurrentContext().getZuulRequestHeaders(); + + Object span = StrategyTracerContext.getCurrentContext().getSpan(); + + return new Callable() { + @Override + public T call() throws Exception { + try { + ZuulStrategyContext.getCurrentContext().setRequest(request); + ZuulStrategyContext.getCurrentContext().setHeaders(headers); + + StrategyTracerContext.getCurrentContext().setSpan(span); + + return callable.call(); + } finally { + ZuulStrategyContext.clearCurrentContext(); + + StrategyTracerContext.clearCurrentContext(); + } + } + }; + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/wrapper/ZuulStrategyCallableWrapper.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/wrapper/ZuulStrategyCallableWrapper.java new file mode 100644 index 0000000000..95154d588e --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/wrapper/ZuulStrategyCallableWrapper.java @@ -0,0 +1,17 @@ +package com.nepxion.discovery.plugin.strategy.zuul.wrapper; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @author Hao Huang + * @version 1.0 + */ + +import com.nepxion.discovery.plugin.strategy.wrapper.StrategyCallableWrapper; + +public interface ZuulStrategyCallableWrapper extends StrategyCallableWrapper { + +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/resources/META-INF/additional-spring-configuration-metadata.json b/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/resources/META-INF/additional-spring-configuration-metadata.json new file mode 100644 index 0000000000..146cf897ca --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/resources/META-INF/additional-spring-configuration-metadata.json @@ -0,0 +1,34 @@ +{ + "properties": [ + { + "name": "spring.application.strategy.zuul.route.filter.order", + "type": "java.lang.Integer", + "defaultValue": 0, + "description": "Strategy zuul route filter order." + }, + { + "name": "spring.application.strategy.zuul.header.priority", + "type": "java.lang.Boolean", + "defaultValue": true, + "description": "Whether strategy zuul header priority is enabled." + }, + { + "name": "spring.application.strategy.zuul.original.header.ignored", + "type": "java.lang.Boolean", + "defaultValue": true, + "description": "Whether strategy zuul original header ignored is enabled." + }, + { + "name": "spring.application.strategy.zuul.core.header.transmission.enabled", + "type": "java.lang.Boolean", + "defaultValue": true, + "description": "Whether strategy zuul core header transmission is enabled." + }, + { + "name": "spring.application.strategy.zuul.dynamic.route.enabled", + "type": "java.lang.Boolean", + "defaultValue": false, + "description": "Whether strategy zuul dynamic route is enabled." + } + ] +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/resources/META-INF/spring.factories b/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/resources/META-INF/spring.factories new file mode 100644 index 0000000000..36b94e02fb --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/resources/META-INF/spring.factories @@ -0,0 +1,6 @@ +org.springframework.boot.env.EnvironmentPostProcessor=\ +com.nepxion.discovery.plugin.strategy.zuul.context.ZuulStrategyEnvironmentPostProcessor + +org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ +com.nepxion.discovery.plugin.strategy.zuul.configuration.ZuulStrategyAutoConfiguration,\ +com.nepxion.discovery.plugin.strategy.zuul.configuration.ZuulStrategyContextAutoConfiguration \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter/pom.xml b/discovery-plugin-strategy/discovery-plugin-strategy-starter/pom.xml new file mode 100644 index 0000000000..8a3d657176 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter/pom.xml @@ -0,0 +1,35 @@ + + + discovery-plugin-strategy-starter + Nepxion Discovery Plugin Strategy Starter + jar + 4.0.0 + Nepxion Discovery is a solution for Spring Cloud with blue green, gray, weight, limitation, circuit breaker, degrade, isolation, monitor, tracing, dye, failover, async agent + http://www.nepxion.com + + + com.nepxion + discovery-plugin-strategy + 6.23.0 + + + + + ${project.groupId} + discovery-plugin-framework-starter + + + + org.springframework.cloud + spring-cloud-starter-openfeign + provided + + + + org.springframework.boot + spring-boot-starter-webflux + provided + + + \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/adapter/DefaultDiscoveryEnabledAdapter.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/adapter/DefaultDiscoveryEnabledAdapter.java new file mode 100644 index 0000000000..ac17aad67d --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/adapter/DefaultDiscoveryEnabledAdapter.java @@ -0,0 +1,49 @@ +package com.nepxion.discovery.plugin.strategy.adapter; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.util.CollectionUtils; + +import com.nepxion.discovery.plugin.strategy.filter.StrategyEnabledFilter; +import com.netflix.loadbalancer.Server; + +public class DefaultDiscoveryEnabledAdapter implements DiscoveryEnabledAdapter { + @Autowired + protected List strategyEnabledFilterList; + + @Autowired(required = false) + protected List discoveryEnabledStrategyList; + + @Override + public void filter(List servers) { + for (StrategyEnabledFilter strategyEnabledFilter : strategyEnabledFilterList) { + strategyEnabledFilter.filter(servers); + } + } + + @Override + public boolean apply(Server server) { + if (CollectionUtils.isEmpty(discoveryEnabledStrategyList)) { + return true; + } + + for (DiscoveryEnabledStrategy discoveryEnabledStrategy : discoveryEnabledStrategyList) { + boolean enabled = discoveryEnabledStrategy.apply(server); + if (!enabled) { + return false; + } + } + + return true; + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/adapter/DefaultDiscoveryEnabledStrategy.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/adapter/DefaultDiscoveryEnabledStrategy.java new file mode 100644 index 0000000000..49acdf5433 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/adapter/DefaultDiscoveryEnabledStrategy.java @@ -0,0 +1,33 @@ +package com.nepxion.discovery.plugin.strategy.adapter; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Lazy; + +import com.nepxion.discovery.plugin.framework.adapter.PluginAdapter; +import com.nepxion.discovery.plugin.strategy.context.StrategyContextHolder; + +public abstract class DefaultDiscoveryEnabledStrategy implements DiscoveryEnabledStrategy { + @Autowired + protected PluginAdapter pluginAdapter; + + @Autowired + @Lazy + protected StrategyContextHolder strategyContextHolder; + + public PluginAdapter getPluginAdapter() { + return pluginAdapter; + } + + public StrategyContextHolder getStrategyContextHolder() { + return strategyContextHolder; + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/adapter/DefaultStrategyTracerAdapter.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/adapter/DefaultStrategyTracerAdapter.java new file mode 100644 index 0000000000..e90fed3274 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/adapter/DefaultStrategyTracerAdapter.java @@ -0,0 +1,48 @@ +package com.nepxion.discovery.plugin.strategy.adapter; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.Map; + +import org.springframework.beans.factory.annotation.Autowired; + +import com.nepxion.discovery.plugin.framework.adapter.PluginAdapter; +import com.nepxion.discovery.plugin.strategy.context.StrategyContextHolder; + +public class DefaultStrategyTracerAdapter implements StrategyTracerAdapter { + @Autowired + protected PluginAdapter pluginAdapter; + + @Autowired + protected StrategyContextHolder strategyContextHolder; + + @Override + public String getTraceId() { + return null; + } + + @Override + public String getSpanId() { + return null; + } + + @Override + public Map getCustomizationMap() { + return null; + } + + public PluginAdapter getPluginAdapter() { + return pluginAdapter; + } + + public StrategyContextHolder getStrategyContextHolder() { + return strategyContextHolder; + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/adapter/DefaultStrategyVersionFilterAdapter.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/adapter/DefaultStrategyVersionFilterAdapter.java new file mode 100644 index 0000000000..a7b5ab1d6c --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/adapter/DefaultStrategyVersionFilterAdapter.java @@ -0,0 +1,23 @@ +package com.nepxion.discovery.plugin.strategy.adapter; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.List; + +public class DefaultStrategyVersionFilterAdapter implements StrategyVersionFilterAdapter { + @Override + public List filter(List versionList) { + String version = versionList.get(0); + versionList.clear(); + versionList.add(version); + + return versionList; + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/adapter/DiscoveryEnabledAdapter.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/adapter/DiscoveryEnabledAdapter.java new file mode 100644 index 0000000000..9a5d8e79ea --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/adapter/DiscoveryEnabledAdapter.java @@ -0,0 +1,16 @@ +package com.nepxion.discovery.plugin.strategy.adapter; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import com.nepxion.discovery.plugin.framework.loadbalance.DiscoveryEnabledLoadBalance; + +public interface DiscoveryEnabledAdapter extends DiscoveryEnabledLoadBalance { + +} \ No newline at end of file diff --git a/discovery-plugin-strategy/src/main/java/com/nepxion/discovery/plugin/strategy/adapter/DiscoveryEnabledStrategy.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/adapter/DiscoveryEnabledStrategy.java similarity index 100% rename from discovery-plugin-strategy/src/main/java/com/nepxion/discovery/plugin/strategy/adapter/DiscoveryEnabledStrategy.java rename to discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/adapter/DiscoveryEnabledStrategy.java diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/adapter/StrategyTracerAdapter.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/adapter/StrategyTracerAdapter.java new file mode 100644 index 0000000000..a6f7b684bb --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/adapter/StrategyTracerAdapter.java @@ -0,0 +1,20 @@ +package com.nepxion.discovery.plugin.strategy.adapter; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.Map; + +public interface StrategyTracerAdapter { + public String getTraceId(); + + public String getSpanId(); + + public Map getCustomizationMap(); +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/adapter/StrategyVersionFilterAdapter.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/adapter/StrategyVersionFilterAdapter.java new file mode 100644 index 0000000000..8db346a937 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/adapter/StrategyVersionFilterAdapter.java @@ -0,0 +1,16 @@ +package com.nepxion.discovery.plugin.strategy.adapter; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.List; + +public interface StrategyVersionFilterAdapter { + List filter(List versionList); +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/aop/AbstractStrategyInterceptor.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/aop/AbstractStrategyInterceptor.java new file mode 100644 index 0000000000..0a273f88f6 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/aop/AbstractStrategyInterceptor.java @@ -0,0 +1,107 @@ +package com.nepxion.discovery.plugin.strategy.aop; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.Enumeration; +import java.util.List; + +import javax.annotation.PostConstruct; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; + +import com.nepxion.discovery.common.constant.DiscoveryConstant; +import com.nepxion.discovery.common.entity.InterceptorType; +import com.nepxion.discovery.plugin.framework.adapter.PluginAdapter; +import com.nepxion.discovery.plugin.strategy.constant.StrategyConstant; +import com.nepxion.discovery.plugin.strategy.context.StrategyContextHolder; +import com.nepxion.discovery.plugin.strategy.context.StrategyHeaderContext; +import com.nepxion.discovery.plugin.strategy.util.StrategyUtil; + +public abstract class AbstractStrategyInterceptor { + private static final Logger LOG = LoggerFactory.getLogger(AbstractStrategyInterceptor.class); + + @Autowired + protected PluginAdapter pluginAdapter; + + @Autowired + protected StrategyContextHolder strategyContextHolder; + + @Autowired + protected StrategyHeaderContext strategyHeaderContext; + + @Value("${" + StrategyConstant.SPRING_APPLICATION_STRATEGY_REST_INTERCEPT_DEBUG_ENABLED + ":false}") + protected Boolean interceptDebugEnabled; + + protected List requestHeaderNameList; + + @PostConstruct + public void initialize() { + requestHeaderNameList = strategyHeaderContext.getRequestHeaderNameList(); + + InterceptorType interceptorType = getInterceptorType(); + + LOG.info("--------- Strategy Intercept Information ---------"); + LOG.info("{} desires to intercept customer headers are {}", interceptorType, requestHeaderNameList); + LOG.info("--------------------------------------------------"); + } + + protected void interceptInputHeader() { + if (!interceptDebugEnabled) { + return; + } + + Enumeration headerNames = strategyContextHolder.getHeaderNames(); + if (headerNames != null) { + InterceptorType interceptorType = getInterceptorType(); + Logger log = getInterceptorLogger(); + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.append("\n"); + switch (interceptorType) { + case FEIGN: + stringBuilder.append("--------- Feign Intercept Input Header Information ---------").append("\n"); + break; + case REST_TEMPLATE: + stringBuilder.append("----- RestTemplate Intercept Input Header Information ------").append("\n"); + break; + case WEB_CLIENT: + stringBuilder.append("------- WebClient Intercept Input Header Information -------").append("\n"); + break; + } + while (headerNames.hasMoreElements()) { + String headerName = headerNames.nextElement(); + boolean isHeaderContains = isHeaderContains(headerName.toLowerCase()); + if (isHeaderContains) { + String headerValue = strategyContextHolder.getHeader(headerName); + + stringBuilder.append(headerName + "=" + headerValue).append("\n"); + } + } + stringBuilder.append("------------------------------------------------------------"); + log.info(stringBuilder.toString()); + } + } + + protected boolean isHeaderContains(String headerName) { + return headerName.startsWith(DiscoveryConstant.N_D_PREFIX) || requestHeaderNameList.contains(headerName); + } + + protected boolean isHeaderContainsExcludeInner(String headerName) { + return isHeaderContains(headerName) && !StrategyUtil.isInnerHeaderContains(headerName); + + // return isHeaderContains(headerName) && !headerName.startsWith(DiscoveryConstant.N_D_SERVICE_PREFIX); + } + + protected abstract InterceptorType getInterceptorType(); + + protected abstract Logger getInterceptorLogger(); +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/aop/FeignStrategyInterceptor.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/aop/FeignStrategyInterceptor.java new file mode 100644 index 0000000000..954c789caf --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/aop/FeignStrategyInterceptor.java @@ -0,0 +1,234 @@ +package com.nepxion.discovery.plugin.strategy.aop; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @author Fengfeng Li + * @version 1.0 + */ + +import feign.RequestInterceptor; +import feign.RequestTemplate; + +import java.util.Collection; +import java.util.Enumeration; +import java.util.Map; + +import org.apache.commons.collections4.CollectionUtils; +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; + +import com.nepxion.discovery.common.constant.DiscoveryConstant; +import com.nepxion.discovery.common.entity.InterceptorType; +import com.nepxion.discovery.plugin.strategy.constant.StrategyConstant; +import com.nepxion.discovery.plugin.strategy.context.StrategyContextHolder; +import com.nepxion.discovery.plugin.strategy.util.StrategyUtil; + +public class FeignStrategyInterceptor extends AbstractStrategyInterceptor implements RequestInterceptor { + private static final Logger LOG = LoggerFactory.getLogger(FeignStrategyInterceptor.class); + + @Autowired + protected StrategyContextHolder strategyContextHolder; + + // Feign上核心策略Header是否传递。当全局订阅启动时,可以关闭核心策略Header传递,这样可以节省传递数据的大小,一定程度上可以提升性能 + // 核心策略Header指n-d-开头的Header(不包括n-d-env,因为环境路由隔离,必须传递该Header),不包括n-d-service开头的Header + @Value("${" + StrategyConstant.SPRING_APPLICATION_STRATEGY_FEIGN_CORE_HEADER_TRANSMISSION_ENABLED + ":true}") + protected Boolean feignCoreHeaderTransmissionEnabled; + + @Override + public void apply(RequestTemplate requestTemplate) { + // 拦截打印输入的Header + interceptInputHeader(); + + // 处理内部Header的转发 + applyInnerHeader(requestTemplate); + + // 处理外部Header的转发 + applyOuterHeader(requestTemplate); + + // 拦截打印输出的Header + interceptOutputHeader(requestTemplate); + } + + // 处理内部Header的转发,即把本地服务的相关属性封装成Header转发到下游服务去 + private void applyInnerHeader(RequestTemplate requestTemplate) { + requestTemplate.header(DiscoveryConstant.N_D_SERVICE_GROUP, pluginAdapter.getGroup()); + requestTemplate.header(DiscoveryConstant.N_D_SERVICE_TYPE, pluginAdapter.getServiceType()); + String serviceAppId = pluginAdapter.getServiceAppId(); + if (StringUtils.isNotEmpty(serviceAppId)) { + requestTemplate.header(DiscoveryConstant.N_D_SERVICE_APP_ID, serviceAppId); + } + requestTemplate.header(DiscoveryConstant.N_D_SERVICE_ID, pluginAdapter.getServiceId()); + requestTemplate.header(DiscoveryConstant.N_D_SERVICE_ADDRESS, pluginAdapter.getHost() + ":" + pluginAdapter.getPort()); + String version = pluginAdapter.getVersion(); + if (StringUtils.isNotEmpty(version) && !StringUtils.equals(version, DiscoveryConstant.DEFAULT)) { + requestTemplate.header(DiscoveryConstant.N_D_SERVICE_VERSION, version); + } + String region = pluginAdapter.getRegion(); + if (StringUtils.isNotEmpty(region) && !StringUtils.equals(region, DiscoveryConstant.DEFAULT)) { + requestTemplate.header(DiscoveryConstant.N_D_SERVICE_REGION, region); + } + String environment = pluginAdapter.getEnvironment(); + if (StringUtils.isNotEmpty(environment) && !StringUtils.equals(environment, DiscoveryConstant.DEFAULT)) { + requestTemplate.header(DiscoveryConstant.N_D_SERVICE_ENVIRONMENT, environment); + } + String zone = pluginAdapter.getZone(); + if (StringUtils.isNotEmpty(zone) && !StringUtils.equals(zone, DiscoveryConstant.DEFAULT)) { + requestTemplate.header(DiscoveryConstant.N_D_SERVICE_ZONE, zone); + } + } + + // 处理外部Header的转发,即外部服务传递过来的Header,中继转发到下游服务去 + private void applyOuterHeader(RequestTemplate requestTemplate) { + Enumeration headerNames = strategyContextHolder.getHeaderNames(); + if (headerNames != null) { + while (headerNames.hasMoreElements()) { + String headerName = headerNames.nextElement(); + String headerValue = strategyContextHolder.getHeader(headerName); + boolean isHeaderContains = isHeaderContainsExcludeInner(headerName.toLowerCase()); + if (isHeaderContains) { + if (feignCoreHeaderTransmissionEnabled) { + requestTemplate.header(headerName, headerValue); + } else { + boolean isCoreHeaderContains = StrategyUtil.isCoreHeaderContains(headerName); + if (!isCoreHeaderContains) { + requestTemplate.header(headerName, headerValue); + } + } + } + } + } + + if (feignCoreHeaderTransmissionEnabled) { + Map> headers = requestTemplate.headers(); + if (CollectionUtils.isEmpty(headers.get(DiscoveryConstant.N_D_VERSION))) { + String routeVersion = strategyContextHolder.getRouteVersion(); + if (StringUtils.isNotEmpty(routeVersion)) { + requestTemplate.header(DiscoveryConstant.N_D_VERSION, routeVersion); + } + } + if (CollectionUtils.isEmpty(headers.get(DiscoveryConstant.N_D_REGION))) { + String routeRegion = strategyContextHolder.getRouteRegion(); + if (StringUtils.isNotEmpty(routeRegion)) { + requestTemplate.header(DiscoveryConstant.N_D_REGION, routeRegion); + } + } + if (CollectionUtils.isEmpty(headers.get(DiscoveryConstant.N_D_ENVIRONMENT))) { + String routeEnvironment = strategyContextHolder.getRouteEnvironment(); + if (StringUtils.isNotEmpty(routeEnvironment)) { + requestTemplate.header(DiscoveryConstant.N_D_ENVIRONMENT, routeEnvironment); + } + } + if (CollectionUtils.isEmpty(headers.get(DiscoveryConstant.N_D_ADDRESS))) { + String routeAddress = strategyContextHolder.getRouteAddress(); + if (StringUtils.isNotEmpty(routeAddress)) { + requestTemplate.header(DiscoveryConstant.N_D_ADDRESS, routeAddress); + } + } + if (CollectionUtils.isEmpty(headers.get(DiscoveryConstant.N_D_VERSION_WEIGHT))) { + String routeVersionWeight = strategyContextHolder.getRouteVersionWeight(); + if (StringUtils.isNotEmpty(routeVersionWeight)) { + requestTemplate.header(DiscoveryConstant.N_D_VERSION_WEIGHT, routeVersionWeight); + } + } + if (CollectionUtils.isEmpty(headers.get(DiscoveryConstant.N_D_REGION_WEIGHT))) { + String routeRegionWeight = strategyContextHolder.getRouteRegionWeight(); + if (StringUtils.isNotEmpty(routeRegionWeight)) { + requestTemplate.header(DiscoveryConstant.N_D_REGION_WEIGHT, routeRegionWeight); + } + } + if (CollectionUtils.isEmpty(headers.get(DiscoveryConstant.N_D_VERSION_PREFER))) { + String routeVersionPrefer = strategyContextHolder.getRouteVersionPrefer(); + if (StringUtils.isNotEmpty(routeVersionPrefer)) { + requestTemplate.header(DiscoveryConstant.N_D_VERSION_PREFER, routeVersionPrefer); + } + } + if (CollectionUtils.isEmpty(headers.get(DiscoveryConstant.N_D_VERSION_FAILOVER))) { + String routeVersionFailover = strategyContextHolder.getRouteVersionFailover(); + if (StringUtils.isNotEmpty(routeVersionFailover)) { + requestTemplate.header(DiscoveryConstant.N_D_VERSION_FAILOVER, routeVersionFailover); + } + } + if (CollectionUtils.isEmpty(headers.get(DiscoveryConstant.N_D_REGION_TRANSFER))) { + String routeRegionTransfer = strategyContextHolder.getRouteRegionTransfer(); + if (StringUtils.isNotEmpty(routeRegionTransfer)) { + requestTemplate.header(DiscoveryConstant.N_D_REGION_TRANSFER, routeRegionTransfer); + } + } + if (CollectionUtils.isEmpty(headers.get(DiscoveryConstant.N_D_REGION_FAILOVER))) { + String routeRegionFailover = strategyContextHolder.getRouteRegionFailover(); + if (StringUtils.isNotEmpty(routeRegionFailover)) { + requestTemplate.header(DiscoveryConstant.N_D_REGION_FAILOVER, routeRegionFailover); + } + } + if (CollectionUtils.isEmpty(headers.get(DiscoveryConstant.N_D_ENVIRONMENT_FAILOVER))) { + String routeEnvironmentFailover = strategyContextHolder.getRouteEnvironmentFailover(); + if (StringUtils.isNotEmpty(routeEnvironmentFailover)) { + requestTemplate.header(DiscoveryConstant.N_D_ENVIRONMENT_FAILOVER, routeEnvironmentFailover); + } + } + if (CollectionUtils.isEmpty(headers.get(DiscoveryConstant.N_D_ZONE_FAILOVER))) { + String routeZoneFailover = strategyContextHolder.getRouteZoneFailover(); + if (StringUtils.isNotEmpty(routeZoneFailover)) { + requestTemplate.header(DiscoveryConstant.N_D_ZONE_FAILOVER, routeZoneFailover); + } + } + if (CollectionUtils.isEmpty(headers.get(DiscoveryConstant.N_D_ADDRESS_FAILOVER))) { + String routeAddressFailover = strategyContextHolder.getRouteAddressFailover(); + if (StringUtils.isNotEmpty(routeAddressFailover)) { + requestTemplate.header(DiscoveryConstant.N_D_ADDRESS_FAILOVER, routeAddressFailover); + } + } + if (CollectionUtils.isEmpty(headers.get(DiscoveryConstant.N_D_ID_BLACKLIST))) { + String routeIdBlacklist = strategyContextHolder.getRouteIdBlacklist(); + if (StringUtils.isNotEmpty(routeIdBlacklist)) { + requestTemplate.header(DiscoveryConstant.N_D_ID_BLACKLIST, routeIdBlacklist); + } + } + if (CollectionUtils.isEmpty(headers.get(DiscoveryConstant.N_D_ADDRESS_BLACKLIST))) { + String routeAddressBlacklist = strategyContextHolder.getRouteAddressBlacklist(); + if (StringUtils.isNotEmpty(routeAddressBlacklist)) { + requestTemplate.header(DiscoveryConstant.N_D_ADDRESS_BLACKLIST, routeAddressBlacklist); + } + } + } + } + + private void interceptOutputHeader(RequestTemplate requestTemplate) { + if (!interceptDebugEnabled) { + return; + } + + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.append("\n"); + stringBuilder.append("-------- Feign Intercept Output Header Information ---------").append("\n"); + Map> headers = requestTemplate.headers(); + for (Map.Entry> entry : headers.entrySet()) { + String headerName = entry.getKey(); + boolean isHeaderContains = isHeaderContains(headerName.toLowerCase()); + if (isHeaderContains) { + Collection headerValue = entry.getValue(); + + stringBuilder.append(headerName + "=" + headerValue).append("\n"); + } + } + stringBuilder.append("------------------------------------------------------------"); + LOG.info(stringBuilder.toString()); + } + + @Override + protected InterceptorType getInterceptorType() { + return InterceptorType.FEIGN; + } + + @Override + protected Logger getInterceptorLogger() { + return LOG; + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/aop/RestTemplateStrategyBeanPostProcessor.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/aop/RestTemplateStrategyBeanPostProcessor.java new file mode 100644 index 0000000000..679d205489 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/aop/RestTemplateStrategyBeanPostProcessor.java @@ -0,0 +1,35 @@ +package com.nepxion.discovery.plugin.strategy.aop; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.springframework.beans.BeansException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.BeanPostProcessor; +import org.springframework.web.client.RestTemplate; + +public class RestTemplateStrategyBeanPostProcessor implements BeanPostProcessor { + @Autowired + protected RestTemplateStrategyInterceptor restTemplateStrategyInterceptor; + + @Override + public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { + return bean; + } + + @Override + public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { + if (bean instanceof RestTemplate) { + RestTemplate restTemplate = (RestTemplate) bean; + restTemplate.getInterceptors().add(restTemplateStrategyInterceptor); + } + + return bean; + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/aop/RestTemplateStrategyInterceptor.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/aop/RestTemplateStrategyInterceptor.java new file mode 100644 index 0000000000..47f28f78ab --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/aop/RestTemplateStrategyInterceptor.java @@ -0,0 +1,243 @@ +package com.nepxion.discovery.plugin.strategy.aop; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @author Fengfeng Li + * @version 1.0 + */ + +import java.io.IOException; +import java.util.Enumeration; +import java.util.Iterator; +import java.util.List; +import java.util.Map.Entry; + +import org.apache.commons.collections4.CollectionUtils; +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpRequest; +import org.springframework.http.client.ClientHttpRequestExecution; +import org.springframework.http.client.ClientHttpRequestInterceptor; +import org.springframework.http.client.ClientHttpResponse; + +import com.nepxion.discovery.common.constant.DiscoveryConstant; +import com.nepxion.discovery.common.entity.InterceptorType; +import com.nepxion.discovery.plugin.strategy.constant.StrategyConstant; +import com.nepxion.discovery.plugin.strategy.context.StrategyContextHolder; +import com.nepxion.discovery.plugin.strategy.util.StrategyUtil; + +public class RestTemplateStrategyInterceptor extends AbstractStrategyInterceptor implements ClientHttpRequestInterceptor { + private static final Logger LOG = LoggerFactory.getLogger(RestTemplateStrategyInterceptor.class); + + @Autowired + protected StrategyContextHolder strategyContextHolder; + + // RestTemplate核心策略Header是否传递。当全局订阅启动时,可以关闭核心策略Header传递,这样可以节省传递数据的大小,一定程度上可以提升性能 + // 核心策略Header指n-d-开头的Header(不包括n-d-env,因为环境路由隔离,必须传递该Header),不包括n-d-service开头的Header + @Value("${" + StrategyConstant.SPRING_APPLICATION_STRATEGY_REST_TEMPLATE_CORE_HEADER_TRANSMISSION_ENABLED + ":true}") + protected Boolean restTemplateCoreHeaderTransmissionEnabled; + + @Override + public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { + // 拦截打印输入的Header + interceptInputHeader(); + + // 处理内部Header的转发 + applyInnerHeader(request); + + // 处理外部Header的转发 + applyOuterHeader(request); + + // 拦截打印输出的Header + interceptOutputHeader(request); + + return execution.execute(request, body); + } + + // 处理内部Header的转发,即把本地服务的相关属性封装成Header转发到下游服务去 + private void applyInnerHeader(HttpRequest request) { + HttpHeaders headers = request.getHeaders(); + headers.add(DiscoveryConstant.N_D_SERVICE_GROUP, pluginAdapter.getGroup()); + headers.add(DiscoveryConstant.N_D_SERVICE_TYPE, pluginAdapter.getServiceType()); + String serviceAppId = pluginAdapter.getServiceAppId(); + if (StringUtils.isNotEmpty(serviceAppId)) { + headers.add(DiscoveryConstant.N_D_SERVICE_APP_ID, serviceAppId); + } + headers.add(DiscoveryConstant.N_D_SERVICE_ID, pluginAdapter.getServiceId()); + headers.add(DiscoveryConstant.N_D_SERVICE_ADDRESS, pluginAdapter.getHost() + ":" + pluginAdapter.getPort()); + String version = pluginAdapter.getVersion(); + if (StringUtils.isNotEmpty(version) && !StringUtils.equals(version, DiscoveryConstant.DEFAULT)) { + headers.add(DiscoveryConstant.N_D_SERVICE_VERSION, version); + } + String region = pluginAdapter.getRegion(); + if (StringUtils.isNotEmpty(region) && !StringUtils.equals(region, DiscoveryConstant.DEFAULT)) { + headers.add(DiscoveryConstant.N_D_SERVICE_REGION, region); + } + String environment = pluginAdapter.getEnvironment(); + if (StringUtils.isNotEmpty(environment) && !StringUtils.equals(environment, DiscoveryConstant.DEFAULT)) { + headers.add(DiscoveryConstant.N_D_SERVICE_ENVIRONMENT, environment); + } + String zone = pluginAdapter.getZone(); + if (StringUtils.isNotEmpty(zone) && !StringUtils.equals(zone, DiscoveryConstant.DEFAULT)) { + headers.add(DiscoveryConstant.N_D_SERVICE_ZONE, zone); + } + } + + // 处理外部Header的转发,即外部服务传递过来的Header,中继转发到下游服务去 + private void applyOuterHeader(HttpRequest request) { + Enumeration headerNames = strategyContextHolder.getHeaderNames(); + if (headerNames != null) { + HttpHeaders headers = request.getHeaders(); + while (headerNames.hasMoreElements()) { + String headerName = headerNames.nextElement(); + String headerValue = strategyContextHolder.getHeader(headerName); + boolean isHeaderContains = isHeaderContainsExcludeInner(headerName.toLowerCase()); + if (isHeaderContains) { + if (restTemplateCoreHeaderTransmissionEnabled) { + headers.add(headerName, headerValue); + } else { + boolean isCoreHeaderContains = StrategyUtil.isCoreHeaderContains(headerName); + if (!isCoreHeaderContains) { + headers.add(headerName, headerValue); + } + } + } + } + } + + if (restTemplateCoreHeaderTransmissionEnabled) { + HttpHeaders headers = request.getHeaders(); + if (CollectionUtils.isEmpty(headers.get(DiscoveryConstant.N_D_VERSION))) { + String routeVersion = strategyContextHolder.getRouteVersion(); + if (StringUtils.isNotEmpty(routeVersion)) { + headers.add(DiscoveryConstant.N_D_VERSION, routeVersion); + } + } + if (CollectionUtils.isEmpty(headers.get(DiscoveryConstant.N_D_REGION))) { + String routeRegion = strategyContextHolder.getRouteRegion(); + if (StringUtils.isNotEmpty(routeRegion)) { + headers.add(DiscoveryConstant.N_D_REGION, routeRegion); + } + } + if (CollectionUtils.isEmpty(headers.get(DiscoveryConstant.N_D_ENVIRONMENT))) { + String routeEnvironment = strategyContextHolder.getRouteEnvironment(); + if (StringUtils.isNotEmpty(routeEnvironment)) { + headers.add(DiscoveryConstant.N_D_ENVIRONMENT, routeEnvironment); + } + } + if (CollectionUtils.isEmpty(headers.get(DiscoveryConstant.N_D_ADDRESS))) { + String routeAddress = strategyContextHolder.getRouteAddress(); + if (StringUtils.isNotEmpty(routeAddress)) { + headers.add(DiscoveryConstant.N_D_ADDRESS, routeAddress); + } + } + if (CollectionUtils.isEmpty(headers.get(DiscoveryConstant.N_D_VERSION_WEIGHT))) { + String routeVersionWeight = strategyContextHolder.getRouteVersionWeight(); + if (StringUtils.isNotEmpty(routeVersionWeight)) { + headers.add(DiscoveryConstant.N_D_VERSION_WEIGHT, routeVersionWeight); + } + } + if (CollectionUtils.isEmpty(headers.get(DiscoveryConstant.N_D_REGION_WEIGHT))) { + String routeRegionWeight = strategyContextHolder.getRouteRegionWeight(); + if (StringUtils.isNotEmpty(routeRegionWeight)) { + headers.add(DiscoveryConstant.N_D_REGION_WEIGHT, routeRegionWeight); + } + } + if (CollectionUtils.isEmpty(headers.get(DiscoveryConstant.N_D_VERSION_PREFER))) { + String routeVersionPrefer = strategyContextHolder.getRouteVersionPrefer(); + if (StringUtils.isNotEmpty(routeVersionPrefer)) { + headers.add(DiscoveryConstant.N_D_VERSION_PREFER, routeVersionPrefer); + } + } + if (CollectionUtils.isEmpty(headers.get(DiscoveryConstant.N_D_VERSION_FAILOVER))) { + String routeVersionFailover = strategyContextHolder.getRouteVersionFailover(); + if (StringUtils.isNotEmpty(routeVersionFailover)) { + headers.add(DiscoveryConstant.N_D_VERSION_FAILOVER, routeVersionFailover); + } + } + if (CollectionUtils.isEmpty(headers.get(DiscoveryConstant.N_D_REGION_TRANSFER))) { + String routeRegionTransfer = strategyContextHolder.getRouteRegionTransfer(); + if (StringUtils.isNotEmpty(routeRegionTransfer)) { + headers.add(DiscoveryConstant.N_D_REGION_TRANSFER, routeRegionTransfer); + } + } + if (CollectionUtils.isEmpty(headers.get(DiscoveryConstant.N_D_REGION_FAILOVER))) { + String routeRegionFailover = strategyContextHolder.getRouteRegionFailover(); + if (StringUtils.isNotEmpty(routeRegionFailover)) { + headers.add(DiscoveryConstant.N_D_REGION_FAILOVER, routeRegionFailover); + } + } + if (CollectionUtils.isEmpty(headers.get(DiscoveryConstant.N_D_ENVIRONMENT_FAILOVER))) { + String routeEnvironmentFailover = strategyContextHolder.getRouteEnvironmentFailover(); + if (StringUtils.isNotEmpty(routeEnvironmentFailover)) { + headers.add(DiscoveryConstant.N_D_ENVIRONMENT_FAILOVER, routeEnvironmentFailover); + } + } + if (CollectionUtils.isEmpty(headers.get(DiscoveryConstant.N_D_ZONE_FAILOVER))) { + String routeZoneFailover = strategyContextHolder.getRouteZoneFailover(); + if (StringUtils.isNotEmpty(routeZoneFailover)) { + headers.add(DiscoveryConstant.N_D_ZONE_FAILOVER, routeZoneFailover); + } + } + if (CollectionUtils.isEmpty(headers.get(DiscoveryConstant.N_D_ADDRESS_FAILOVER))) { + String routeAddressFailover = strategyContextHolder.getRouteAddressFailover(); + if (StringUtils.isNotEmpty(routeAddressFailover)) { + headers.add(DiscoveryConstant.N_D_ADDRESS_FAILOVER, routeAddressFailover); + } + } + if (CollectionUtils.isEmpty(headers.get(DiscoveryConstant.N_D_ID_BLACKLIST))) { + String routeIdBlacklist = strategyContextHolder.getRouteIdBlacklist(); + if (StringUtils.isNotEmpty(routeIdBlacklist)) { + headers.add(DiscoveryConstant.N_D_ID_BLACKLIST, routeIdBlacklist); + } + } + if (CollectionUtils.isEmpty(headers.get(DiscoveryConstant.N_D_ADDRESS_BLACKLIST))) { + String routeAddressBlacklist = strategyContextHolder.getRouteAddressBlacklist(); + if (StringUtils.isNotEmpty(routeAddressBlacklist)) { + headers.add(DiscoveryConstant.N_D_ADDRESS_BLACKLIST, routeAddressBlacklist); + } + } + } + } + + private void interceptOutputHeader(HttpRequest request) { + if (!interceptDebugEnabled) { + return; + } + + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.append("\n"); + stringBuilder.append("----- RestTemplate Intercept Output Header Information -----").append("\n"); + HttpHeaders headers = request.getHeaders(); + for (Iterator>> iterator = headers.entrySet().iterator(); iterator.hasNext();) { + Entry> header = iterator.next(); + String headerName = header.getKey(); + boolean isHeaderContains = isHeaderContains(headerName.toLowerCase()); + if (isHeaderContains) { + List headerValue = header.getValue(); + + stringBuilder.append(headerName + "=" + headerValue).append("\n"); + } + } + stringBuilder.append("------------------------------------------------------------"); + LOG.info(stringBuilder.toString()); + } + + @Override + protected InterceptorType getInterceptorType() { + return InterceptorType.REST_TEMPLATE; + } + + @Override + protected Logger getInterceptorLogger() { + return LOG; + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/aop/WebClientStrategyBeanPostProcessor.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/aop/WebClientStrategyBeanPostProcessor.java new file mode 100644 index 0000000000..1ca9be359a --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/aop/WebClientStrategyBeanPostProcessor.java @@ -0,0 +1,36 @@ +package com.nepxion.discovery.plugin.strategy.aop; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.springframework.beans.BeansException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.BeanPostProcessor; +import org.springframework.web.reactive.function.client.WebClient; + +public class WebClientStrategyBeanPostProcessor implements BeanPostProcessor { + @Autowired + protected WebClientStrategyInterceptor webClientStrategyInterceptor; + + @Override + public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { + return bean; + } + + @Override + public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { + if (bean instanceof WebClient.Builder) { + WebClient.Builder webClientBuilder = (WebClient.Builder) bean; + + webClientBuilder.filter(webClientStrategyInterceptor); + } + + return bean; + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/aop/WebClientStrategyInterceptor.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/aop/WebClientStrategyInterceptor.java new file mode 100644 index 0000000000..4aac89b0fe --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/aop/WebClientStrategyInterceptor.java @@ -0,0 +1,247 @@ +package com.nepxion.discovery.plugin.strategy.aop; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @author Fengfeng Li + * @version 1.0 + */ + +import reactor.core.publisher.Mono; + +import java.util.Enumeration; +import java.util.Iterator; +import java.util.List; +import java.util.Map.Entry; + +import org.apache.commons.collections4.CollectionUtils; +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.http.HttpHeaders; +import org.springframework.web.reactive.function.client.ClientRequest; +import org.springframework.web.reactive.function.client.ClientResponse; +import org.springframework.web.reactive.function.client.ExchangeFilterFunction; +import org.springframework.web.reactive.function.client.ExchangeFunction; + +import com.nepxion.discovery.common.constant.DiscoveryConstant; +import com.nepxion.discovery.common.entity.InterceptorType; +import com.nepxion.discovery.plugin.strategy.constant.StrategyConstant; +import com.nepxion.discovery.plugin.strategy.context.StrategyContextHolder; +import com.nepxion.discovery.plugin.strategy.util.StrategyUtil; + +public class WebClientStrategyInterceptor extends AbstractStrategyInterceptor implements ExchangeFilterFunction { + private static final Logger LOG = LoggerFactory.getLogger(WebClientStrategyInterceptor.class); + + @Autowired + protected StrategyContextHolder strategyContextHolder; + + // WebClient核心策略Header是否传递。当全局订阅启动时,可以关闭核心策略Header传递,这样可以节省传递数据的大小,一定程度上可以提升性能 + // 核心策略Header指n-d-开头的Header(不包括n-d-env,因为环境路由隔离,必须传递该Header),不包括n-d-service开头的Header + @Value("${" + StrategyConstant.SPRING_APPLICATION_STRATEGY_WEB_CLIENT_CORE_HEADER_TRANSMISSION_ENABLED + ":true}") + protected Boolean webClientCoreHeaderTransmissionEnabled; + + @Override + public Mono filter(ClientRequest request, ExchangeFunction next) { + ClientRequest.Builder requestBuilder = ClientRequest.from(request); + + // 拦截打印输入的Header + interceptInputHeader(); + + // 处理内部Header的转发 + applyInnerHeader(requestBuilder); + + // 处理外部Header的转发 + applyOuterHeader(requestBuilder); + + ClientRequest newRequest = requestBuilder.build(); + + // 拦截打印输出的Header + interceptOutputHeader(newRequest); + + return next.exchange(newRequest); + } + + // 处理内部Header的转发,即把本地服务的相关属性封装成Header转发到下游服务去 + private void applyInnerHeader(ClientRequest.Builder requestBuilder) { + requestBuilder.header(DiscoveryConstant.N_D_SERVICE_GROUP, pluginAdapter.getGroup()); + requestBuilder.header(DiscoveryConstant.N_D_SERVICE_TYPE, pluginAdapter.getServiceType()); + String serviceAppId = pluginAdapter.getServiceAppId(); + if (StringUtils.isNotEmpty(serviceAppId)) { + requestBuilder.header(DiscoveryConstant.N_D_SERVICE_APP_ID, serviceAppId); + } + requestBuilder.header(DiscoveryConstant.N_D_SERVICE_ID, pluginAdapter.getServiceId()); + requestBuilder.header(DiscoveryConstant.N_D_SERVICE_ADDRESS, pluginAdapter.getHost() + ":" + pluginAdapter.getPort()); + String version = pluginAdapter.getVersion(); + if (StringUtils.isNotEmpty(version) && !StringUtils.equals(version, DiscoveryConstant.DEFAULT)) { + requestBuilder.header(DiscoveryConstant.N_D_SERVICE_VERSION, version); + } + String region = pluginAdapter.getRegion(); + if (StringUtils.isNotEmpty(region) && !StringUtils.equals(region, DiscoveryConstant.DEFAULT)) { + requestBuilder.header(DiscoveryConstant.N_D_SERVICE_REGION, region); + } + String environment = pluginAdapter.getEnvironment(); + if (StringUtils.isNotEmpty(environment) && !StringUtils.equals(environment, DiscoveryConstant.DEFAULT)) { + requestBuilder.header(DiscoveryConstant.N_D_SERVICE_ENVIRONMENT, environment); + } + String zone = pluginAdapter.getZone(); + if (StringUtils.isNotEmpty(zone) && !StringUtils.equals(zone, DiscoveryConstant.DEFAULT)) { + requestBuilder.header(DiscoveryConstant.N_D_SERVICE_ZONE, zone); + } + } + + // 处理外部Header的转发,即外部服务传递过来的Header,中继转发到下游服务去 + private void applyOuterHeader(ClientRequest.Builder requestBuilder) { + Enumeration headerNames = strategyContextHolder.getHeaderNames(); + if (headerNames != null) { + while (headerNames.hasMoreElements()) { + String headerName = headerNames.nextElement(); + String headerValue = strategyContextHolder.getHeader(headerName); + boolean isHeaderContains = isHeaderContainsExcludeInner(headerName.toLowerCase()); + if (isHeaderContains) { + if (webClientCoreHeaderTransmissionEnabled) { + requestBuilder.header(headerName, headerValue); + } else { + boolean isCoreHeaderContains = StrategyUtil.isCoreHeaderContains(headerName); + if (!isCoreHeaderContains) { + requestBuilder.header(headerName, headerValue); + } + } + } + } + } + + if (webClientCoreHeaderTransmissionEnabled) { + ClientRequest request = requestBuilder.build(); + HttpHeaders headers = request.headers(); + if (CollectionUtils.isEmpty(headers.get(DiscoveryConstant.N_D_VERSION))) { + String routeVersion = strategyContextHolder.getRouteVersion(); + if (StringUtils.isNotEmpty(routeVersion)) { + requestBuilder.header(DiscoveryConstant.N_D_VERSION, routeVersion); + } + } + if (CollectionUtils.isEmpty(headers.get(DiscoveryConstant.N_D_REGION))) { + String routeRegion = strategyContextHolder.getRouteRegion(); + if (StringUtils.isNotEmpty(routeRegion)) { + requestBuilder.header(DiscoveryConstant.N_D_REGION, routeRegion); + } + } + if (CollectionUtils.isEmpty(headers.get(DiscoveryConstant.N_D_ENVIRONMENT))) { + String routeEnvironment = strategyContextHolder.getRouteEnvironment(); + if (StringUtils.isNotEmpty(routeEnvironment)) { + requestBuilder.header(DiscoveryConstant.N_D_ENVIRONMENT, routeEnvironment); + } + } + if (CollectionUtils.isEmpty(headers.get(DiscoveryConstant.N_D_ADDRESS))) { + String routeAddress = strategyContextHolder.getRouteAddress(); + if (StringUtils.isNotEmpty(routeAddress)) { + requestBuilder.header(DiscoveryConstant.N_D_ADDRESS, routeAddress); + } + } + if (CollectionUtils.isEmpty(headers.get(DiscoveryConstant.N_D_VERSION_WEIGHT))) { + String routeVersionWeight = strategyContextHolder.getRouteVersionWeight(); + if (StringUtils.isNotEmpty(routeVersionWeight)) { + requestBuilder.header(DiscoveryConstant.N_D_VERSION_WEIGHT, routeVersionWeight); + } + } + if (CollectionUtils.isEmpty(headers.get(DiscoveryConstant.N_D_REGION_WEIGHT))) { + String routeRegionWeight = strategyContextHolder.getRouteRegionWeight(); + if (StringUtils.isNotEmpty(routeRegionWeight)) { + requestBuilder.header(DiscoveryConstant.N_D_REGION_WEIGHT, routeRegionWeight); + } + } + if (CollectionUtils.isEmpty(headers.get(DiscoveryConstant.N_D_VERSION_PREFER))) { + String routeVersionPrefer = strategyContextHolder.getRouteVersionPrefer(); + if (StringUtils.isNotEmpty(routeVersionPrefer)) { + requestBuilder.header(DiscoveryConstant.N_D_VERSION_PREFER, routeVersionPrefer); + } + } + if (CollectionUtils.isEmpty(headers.get(DiscoveryConstant.N_D_VERSION_FAILOVER))) { + String routeVersionFailover = strategyContextHolder.getRouteVersionFailover(); + if (StringUtils.isNotEmpty(routeVersionFailover)) { + requestBuilder.header(DiscoveryConstant.N_D_VERSION_FAILOVER, routeVersionFailover); + } + } + if (CollectionUtils.isEmpty(headers.get(DiscoveryConstant.N_D_REGION_TRANSFER))) { + String routeRegionTransfer = strategyContextHolder.getRouteRegionTransfer(); + if (StringUtils.isNotEmpty(routeRegionTransfer)) { + requestBuilder.header(DiscoveryConstant.N_D_REGION_TRANSFER, routeRegionTransfer); + } + } + if (CollectionUtils.isEmpty(headers.get(DiscoveryConstant.N_D_REGION_FAILOVER))) { + String routeRegionFailover = strategyContextHolder.getRouteRegionFailover(); + if (StringUtils.isNotEmpty(routeRegionFailover)) { + requestBuilder.header(DiscoveryConstant.N_D_REGION_FAILOVER, routeRegionFailover); + } + } + if (CollectionUtils.isEmpty(headers.get(DiscoveryConstant.N_D_ENVIRONMENT_FAILOVER))) { + String routeEnvironmentFailover = strategyContextHolder.getRouteEnvironmentFailover(); + if (StringUtils.isNotEmpty(routeEnvironmentFailover)) { + requestBuilder.header(DiscoveryConstant.N_D_ENVIRONMENT_FAILOVER, routeEnvironmentFailover); + } + } + if (CollectionUtils.isEmpty(headers.get(DiscoveryConstant.N_D_ZONE_FAILOVER))) { + String routeZoneFailover = strategyContextHolder.getRouteZoneFailover(); + if (StringUtils.isNotEmpty(routeZoneFailover)) { + requestBuilder.header(DiscoveryConstant.N_D_ZONE_FAILOVER, routeZoneFailover); + } + } + if (CollectionUtils.isEmpty(headers.get(DiscoveryConstant.N_D_ADDRESS_FAILOVER))) { + String routeAddressFailover = strategyContextHolder.getRouteAddressFailover(); + if (StringUtils.isNotEmpty(routeAddressFailover)) { + requestBuilder.header(DiscoveryConstant.N_D_ADDRESS_FAILOVER, routeAddressFailover); + } + } + if (CollectionUtils.isEmpty(headers.get(DiscoveryConstant.N_D_ID_BLACKLIST))) { + String routeIdBlacklist = strategyContextHolder.getRouteIdBlacklist(); + if (StringUtils.isNotEmpty(routeIdBlacklist)) { + requestBuilder.header(DiscoveryConstant.N_D_ID_BLACKLIST, routeIdBlacklist); + } + } + if (CollectionUtils.isEmpty(headers.get(DiscoveryConstant.N_D_ADDRESS_BLACKLIST))) { + String routeAddressBlacklist = strategyContextHolder.getRouteAddressBlacklist(); + if (StringUtils.isNotEmpty(routeAddressBlacklist)) { + requestBuilder.header(DiscoveryConstant.N_D_ADDRESS_BLACKLIST, routeAddressBlacklist); + } + } + } + } + + private void interceptOutputHeader(ClientRequest request) { + if (!interceptDebugEnabled) { + return; + } + + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.append("\n"); + stringBuilder.append("------ WebClient Intercept Output Header Information -------").append("\n"); + HttpHeaders headers = request.headers(); + for (Iterator>> iterator = headers.entrySet().iterator(); iterator.hasNext();) { + Entry> header = iterator.next(); + String headerName = header.getKey(); + boolean isHeaderContains = isHeaderContains(headerName.toLowerCase()); + if (isHeaderContains) { + List headerValue = header.getValue(); + + stringBuilder.append(headerName + "=" + headerValue).append("\n"); + } + } + stringBuilder.append("------------------------------------------------------------"); + LOG.info(stringBuilder.toString()); + } + + @Override + protected InterceptorType getInterceptorType() { + return InterceptorType.WEB_CLIENT; + } + + @Override + protected Logger getInterceptorLogger() { + return LOG; + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/condition/AbstractStrategyCondition.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/condition/AbstractStrategyCondition.java new file mode 100644 index 0000000000..f4e0f59ea8 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/condition/AbstractStrategyCondition.java @@ -0,0 +1,31 @@ +package com.nepxion.discovery.plugin.strategy.condition; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.expression.TypeComparator; + +import com.nepxion.discovery.plugin.strategy.context.StrategyContextHolder; + +public abstract class AbstractStrategyCondition implements StrategyCondition { + @Autowired + protected StrategyContextHolder strategyContextHolder; + + @Autowired + protected TypeComparator strategyTypeComparator; + + public StrategyContextHolder getStrategyContextHolder() { + return strategyContextHolder; + } + + public TypeComparator getStrategyTypeComparator() { + return strategyTypeComparator; + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/condition/DefaultStrategyTypeComparator.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/condition/DefaultStrategyTypeComparator.java new file mode 100644 index 0000000000..0bae4df5cf --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/condition/DefaultStrategyTypeComparator.java @@ -0,0 +1,16 @@ +package com.nepxion.discovery.plugin.strategy.condition; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import com.nepxion.discovery.common.expression.DiscoveryTypeComparator; + +public class DefaultStrategyTypeComparator extends DiscoveryTypeComparator { + +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/condition/ExpressionStrategyCondition.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/condition/ExpressionStrategyCondition.java new file mode 100644 index 0000000000..5f4a9e8aeb --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/condition/ExpressionStrategyCondition.java @@ -0,0 +1,81 @@ +package com.nepxion.discovery.plugin.strategy.condition; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; + +import com.nepxion.discovery.common.constant.DiscoveryConstant; +import com.nepxion.discovery.common.entity.StrategyConditionEntity; +import com.nepxion.discovery.common.expression.DiscoveryExpressionResolver; +import com.nepxion.discovery.plugin.strategy.wrapper.StrategyWrapper; + +public class ExpressionStrategyCondition extends AbstractStrategyCondition { + @Autowired + private StrategyWrapper strategyWrapper; + + @Override + public boolean isTriggered(StrategyConditionEntity strategyConditionEntity) { + Map map = createMap(strategyConditionEntity); + + return isTriggered(strategyConditionEntity, map); + } + + private Map createMap(StrategyConditionEntity strategyConditionEntity) { + String expression = strategyConditionEntity.getExpression(); + if (StringUtils.isEmpty(expression)) { + return null; + } + + Map map = new HashMap(); + + List list = DiscoveryExpressionResolver.extractList(expression); + for (String name : list) { + String value = null; + + // 从外置Parameter获取 + if (StringUtils.isBlank(value)) { + value = strategyContextHolder.getParameter(name); + } + + // 从外置Cookie获取 + if (StringUtils.isBlank(value)) { + value = strategyContextHolder.getCookie(name); + } + + // 从外置Header获取 + if (StringUtils.isBlank(value)) { + value = strategyContextHolder.getHeader(name); + } + + // 从内置Header获取 + if (StringUtils.isBlank(value)) { + value = strategyWrapper.getHeader(name); + } + + if (StringUtils.isNotBlank(value)) { + map.put(name, value); + } + } + + return map; + } + + @Override + public boolean isTriggered(StrategyConditionEntity strategyConditionEntity, Map map) { + String expression = strategyConditionEntity.getExpression(); + + return DiscoveryExpressionResolver.eval(expression, DiscoveryConstant.EXPRESSION_PREFIX, map, strategyTypeComparator); + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/condition/StrategyCondition.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/condition/StrategyCondition.java new file mode 100644 index 0000000000..b9135666d8 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/condition/StrategyCondition.java @@ -0,0 +1,20 @@ +package com.nepxion.discovery.plugin.strategy.condition; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.Map; + +import com.nepxion.discovery.common.entity.StrategyConditionEntity; + +public interface StrategyCondition { + boolean isTriggered(StrategyConditionEntity strategyConditionEntity); + + boolean isTriggered(StrategyConditionEntity strategyConditionEntity, Map map); +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/configuration/StrategyAutoConfiguration.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/configuration/StrategyAutoConfiguration.java new file mode 100644 index 0000000000..d117c2a263 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/configuration/StrategyAutoConfiguration.java @@ -0,0 +1,230 @@ +package com.nepxion.discovery.plugin.strategy.configuration; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import feign.Feign; + +import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.cloud.netflix.ribbon.RibbonClients; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.expression.TypeComparator; +import org.springframework.web.client.RestTemplate; +import org.springframework.web.reactive.function.client.WebClient; + +import com.nepxion.discovery.plugin.strategy.adapter.DefaultDiscoveryEnabledAdapter; +import com.nepxion.discovery.plugin.strategy.adapter.DefaultStrategyVersionFilterAdapter; +import com.nepxion.discovery.plugin.strategy.adapter.DiscoveryEnabledAdapter; +import com.nepxion.discovery.plugin.strategy.adapter.StrategyVersionFilterAdapter; +import com.nepxion.discovery.plugin.strategy.aop.FeignStrategyInterceptor; +import com.nepxion.discovery.plugin.strategy.aop.RestTemplateStrategyBeanPostProcessor; +import com.nepxion.discovery.plugin.strategy.aop.RestTemplateStrategyInterceptor; +import com.nepxion.discovery.plugin.strategy.aop.WebClientStrategyBeanPostProcessor; +import com.nepxion.discovery.plugin.strategy.aop.WebClientStrategyInterceptor; +import com.nepxion.discovery.plugin.strategy.condition.DefaultStrategyTypeComparator; +import com.nepxion.discovery.plugin.strategy.condition.ExpressionStrategyCondition; +import com.nepxion.discovery.plugin.strategy.condition.StrategyCondition; +import com.nepxion.discovery.plugin.strategy.constant.StrategyConstant; +import com.nepxion.discovery.plugin.strategy.context.StrategyHeaderContext; +import com.nepxion.discovery.plugin.strategy.extractor.StrategyPackagesExtractor; +import com.nepxion.discovery.plugin.strategy.filter.StrategyAddressBlacklistEnabledFilter; +import com.nepxion.discovery.plugin.strategy.filter.StrategyAddressEnabledFilter; +import com.nepxion.discovery.plugin.strategy.filter.StrategyEnvironmentEnabledFilter; +import com.nepxion.discovery.plugin.strategy.filter.StrategyGroupEnabledFilter; +import com.nepxion.discovery.plugin.strategy.filter.StrategyIdBlacklistEnabledFilter; +import com.nepxion.discovery.plugin.strategy.filter.StrategyRegionEnabledFilter; +import com.nepxion.discovery.plugin.strategy.filter.StrategyVersionEnabledFilter; +import com.nepxion.discovery.plugin.strategy.filter.StrategyZoneEnabledFilter; +import com.nepxion.discovery.plugin.strategy.matcher.DiscoveryAntPathMatcherStrategy; +import com.nepxion.discovery.plugin.strategy.matcher.DiscoveryMatcher; +import com.nepxion.discovery.plugin.strategy.matcher.DiscoveryMatcherStrategy; +import com.nepxion.discovery.plugin.strategy.monitor.DefaultStrategyAlarm; +import com.nepxion.discovery.plugin.strategy.monitor.DefaultStrategyLogger; +import com.nepxion.discovery.plugin.strategy.monitor.StrategyAlarm; +import com.nepxion.discovery.plugin.strategy.monitor.StrategyLogger; +import com.nepxion.discovery.plugin.strategy.monitor.StrategyMonitorContext; +import com.nepxion.discovery.plugin.strategy.monitor.StrategyTracerContextListener; +import com.nepxion.discovery.plugin.strategy.wrapper.StrategyWrapper; + +@Configuration +@RibbonClients(defaultConfiguration = { StrategyLoadBalanceConfiguration.class }) +public class StrategyAutoConfiguration { + @Bean + @ConditionalOnMissingBean + public StrategyIdBlacklistEnabledFilter strategyIdBlacklistEnabledFilter() { + return new StrategyIdBlacklistEnabledFilter(); + } + + @Bean + @ConditionalOnMissingBean + public StrategyAddressBlacklistEnabledFilter strategyAddressBlacklistEnabledFilter() { + return new StrategyAddressBlacklistEnabledFilter(); + } + + @Bean + @ConditionalOnMissingBean + public StrategyGroupEnabledFilter strategyGroupEnabledFilter() { + return new StrategyGroupEnabledFilter(); + } + + @Bean + @ConditionalOnMissingBean + public StrategyEnvironmentEnabledFilter strategyEnvironmentEnabledFilter() { + return new StrategyEnvironmentEnabledFilter(); + } + + @Bean + @ConditionalOnMissingBean + public StrategyZoneEnabledFilter strategyZoneEnabledFilter() { + return new StrategyZoneEnabledFilter(); + } + + @Bean + @ConditionalOnMissingBean + public StrategyAddressEnabledFilter strategyAddressEnabledFilter() { + return new StrategyAddressEnabledFilter(); + } + + @Bean + @ConditionalOnMissingBean + public StrategyRegionEnabledFilter strategyRegionEnabledFilter() { + return new StrategyRegionEnabledFilter(); + } + + @Bean + @ConditionalOnMissingBean + public StrategyVersionEnabledFilter strategyVersionEnabledFilter() { + return new StrategyVersionEnabledFilter(); + } + + @Bean + @ConditionalOnMissingBean + public DiscoveryEnabledAdapter discoveryEnabledAdapter() { + return new DefaultDiscoveryEnabledAdapter(); + } + + @Bean + @ConditionalOnMissingBean + public DiscoveryMatcherStrategy discoveryMatcherStrategy() { + return new DiscoveryAntPathMatcherStrategy(); + } + + @Bean + @ConditionalOnMissingBean + public DiscoveryMatcher discoveryMatcher() { + return new DiscoveryMatcher(); + } + + @Bean + @ConditionalOnMissingBean + public StrategyVersionFilterAdapter strategyVersionFilterAdapter() { + return new DefaultStrategyVersionFilterAdapter(); + } + + @Bean + public StrategyHeaderContext strategyHeaderContext() { + return new StrategyHeaderContext(); + } + + @Bean + public StrategyPackagesExtractor strategyPackagesExtractor() { + return new StrategyPackagesExtractor(); + } + + @Bean + @ConditionalOnMissingBean + @ConditionalOnProperty(value = StrategyConstant.SPRING_APPLICATION_STRATEGY_MONITOR_ENABLED, matchIfMissing = false) + public StrategyMonitorContext strategyMonitorContext() { + return new StrategyMonitorContext(); + } + + @Bean + @ConditionalOnMissingBean + @ConditionalOnProperty(value = StrategyConstant.SPRING_APPLICATION_STRATEGY_MONITOR_ENABLED, matchIfMissing = false) + public StrategyLogger strategyLogger() { + return new DefaultStrategyLogger(); + } + + @Bean + @ConditionalOnMissingBean + @ConditionalOnProperty(value = StrategyConstant.SPRING_APPLICATION_STRATEGY_MONITOR_ENABLED, matchIfMissing = false) + public StrategyAlarm strategyAlarm() { + return new DefaultStrategyAlarm(); + } + + @Bean + @ConditionalOnMissingBean + public StrategyWrapper strategyWrapper() { + return new StrategyWrapper(); + } + + @Bean + @ConditionalOnProperty(value = StrategyConstant.SPRING_APPLICATION_STRATEGY_MONITOR_ENABLED, matchIfMissing = false) + public StrategyTracerContextListener strategyTracerContextListener() { + return new StrategyTracerContextListener(); + } + + @Bean + @ConditionalOnMissingBean + public TypeComparator strategyTypeComparator() { + return new DefaultStrategyTypeComparator(); + } + + @Bean + @ConditionalOnMissingBean + public StrategyCondition strategyCondition() { + return new ExpressionStrategyCondition(); + } + + @ConditionalOnClass(Feign.class) + protected static class FeignStrategyConfiguration { + @Bean + @ConditionalOnProperty(value = StrategyConstant.SPRING_APPLICATION_STRATEGY_REST_INTERCEPT_ENABLED, matchIfMissing = true) + public FeignStrategyInterceptor feignStrategyInterceptor() { + return new FeignStrategyInterceptor(); + } + } + + @ConditionalOnClass(RestTemplate.class) + protected static class RestTemplateStrategyConfiguration { + @Bean + @ConditionalOnProperty(value = StrategyConstant.SPRING_APPLICATION_STRATEGY_REST_INTERCEPT_ENABLED, matchIfMissing = true) + public RestTemplateStrategyInterceptor restTemplateStrategyInterceptor() { + return new RestTemplateStrategyInterceptor(); + } + + @Bean + @ConditionalOnMissingBean + @ConditionalOnProperty(value = StrategyConstant.SPRING_APPLICATION_STRATEGY_REST_INTERCEPT_ENABLED, matchIfMissing = true) + public RestTemplateStrategyBeanPostProcessor restTemplateStrategyBeanPostProcessor() { + return new RestTemplateStrategyBeanPostProcessor(); + } + } + + @ConditionalOnClass(WebClient.class) + @ConditionalOnBean(WebClient.Builder.class) + protected static class WebClientStrategyConfiguration { + @Bean + @ConditionalOnProperty(value = StrategyConstant.SPRING_APPLICATION_STRATEGY_REST_INTERCEPT_ENABLED, matchIfMissing = true) + public WebClientStrategyInterceptor webClientStrategyInterceptor() { + return new WebClientStrategyInterceptor(); + } + + @Bean + @ConditionalOnMissingBean + @ConditionalOnProperty(value = StrategyConstant.SPRING_APPLICATION_STRATEGY_REST_INTERCEPT_ENABLED, matchIfMissing = true) + public WebClientStrategyBeanPostProcessor webClientStrategyBeanPostProcessor() { + return new WebClientStrategyBeanPostProcessor(); + } + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/src/main/java/com/nepxion/discovery/plugin/strategy/configuration/StrategyLoadBalanceConfiguration.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/configuration/StrategyLoadBalanceConfiguration.java similarity index 100% rename from discovery-plugin-strategy/src/main/java/com/nepxion/discovery/plugin/strategy/configuration/StrategyLoadBalanceConfiguration.java rename to discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/configuration/StrategyLoadBalanceConfiguration.java diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/constant/StrategyConstant.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/constant/StrategyConstant.java new file mode 100644 index 0000000000..c190d970c1 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/constant/StrategyConstant.java @@ -0,0 +1,56 @@ +package com.nepxion.discovery.plugin.strategy.constant; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +public class StrategyConstant { + public static final String SPRING_APPLICATION_STRATEGY_ZONE_AVOIDANCE_RULE_ENABLED = "spring.application.strategy.zone.avoidance.rule.enabled"; + public static final String SPRING_APPLICATION_STRATEGY_HYSTRIX_THREADLOCAL_SUPPORTED = "spring.application.strategy.hystrix.threadlocal.supported"; + public static final String SPRING_APPLICATION_STRATEGY_CONSUMER_ISOLATION_ENABLED = "spring.application.strategy.consumer.isolation.enabled"; + public static final String SPRING_APPLICATION_STRATEGY_PROVIDER_ISOLATION_ENABLED = "spring.application.strategy.provider.isolation.enabled"; + public static final String SPRING_APPLICATION_STRATEGY_ADDRESS_FAILOVER_ENABLED = "spring.application.strategy.address.failover.enabled"; + public static final String SPRING_APPLICATION_STRATEGY_ENVIRONMENT_FAILOVER_ENABLED = "spring.application.strategy.environment.failover.enabled"; + public static final String SPRING_APPLICATION_STRATEGY_ENVIRONMENT_FAILOVER_VALUE = "common"; + public static final String SPRING_APPLICATION_STRATEGY_ZONE_AFFINITY_ENABLED = "spring.application.strategy.zone.affinity.enabled"; + public static final String SPRING_APPLICATION_STRATEGY_ZONE_FAILOVER_ENABLED = "spring.application.strategy.zone.failover.enabled"; + public static final String SPRING_APPLICATION_STRATEGY_REGION_TRANSFER_ENABLED = "spring.application.strategy.region.transfer.enabled"; + public static final String SPRING_APPLICATION_STRATEGY_REGION_FAILOVER_ENABLED = "spring.application.strategy.region.failover.enabled"; + public static final String SPRING_APPLICATION_STRATEGY_VERSION_FAILOVER_ENABLED = "spring.application.strategy.version.failover.enabled"; + public static final String SPRING_APPLICATION_STRATEGY_VERSION_FAILOVER_STABLE_ENABLED = "spring.application.strategy.version.failover.stable.enabled"; + public static final String SPRING_APPLICATION_STRATEGY_VERSION_PREFER_ENABLED = "spring.application.strategy.version.prefer.enabled"; + public static final String SPRING_APPLICATION_STRATEGY_VERSION_SORT_TYPE = "spring.application.strategy.version.sort.type"; + + public static final String SPRING_APPLICATION_STRATEGY_REST_INTERCEPT_ENABLED = "spring.application.strategy.rest.intercept.enabled"; + public static final String SPRING_APPLICATION_STRATEGY_REST_INTERCEPT_DEBUG_ENABLED = "spring.application.strategy.rest.intercept.debug.enabled"; + public static final String SPRING_APPLICATION_STRATEGY_FEIGN_CORE_HEADER_TRANSMISSION_ENABLED = "spring.application.strategy.feign.core.header.transmission.enabled"; + public static final String SPRING_APPLICATION_STRATEGY_REST_TEMPLATE_CORE_HEADER_TRANSMISSION_ENABLED = "spring.application.strategy.rest.template.core.header.transmission.enabled"; + public static final String SPRING_APPLICATION_STRATEGY_WEB_CLIENT_CORE_HEADER_TRANSMISSION_ENABLED = "spring.application.strategy.web.client.core.header.transmission.enabled"; + public static final String SPRING_APPLICATION_STRATEGY_CONTEXT_REQUEST_HEADERS = "spring.application.strategy.context.request.headers"; + public static final String SPRING_APPLICATION_STRATEGY_BUSINESS_REQUEST_HEADERS = "spring.application.strategy.business.request.headers"; + + public static final String SPRING_APPLICATION_STRATEGY_MONITOR_ENABLED = "spring.application.strategy.monitor.enabled"; + public static final String SPRING_APPLICATION_STRATEGY_LOGGER_ENABLED = "spring.application.strategy.logger.enabled"; + public static final String SPRING_APPLICATION_STRATEGY_LOGGER_MDC_KEY_SHOWN = "spring.application.strategy.logger.mdc.key.shown"; + public static final String SPRING_APPLICATION_STRATEGY_LOGGER_DEBUG_ENABLED = "spring.application.strategy.logger.debug.enabled"; + public static final String SPRING_APPLICATION_STRATEGY_TRACER_ENABLED = "spring.application.strategy.tracer.enabled"; + public static final String SPRING_APPLICATION_STRATEGY_TRACER_SEPARATE_SPAN_ENABLED = "spring.application.strategy.tracer.separate.span.enabled"; + public static final String SPRING_APPLICATION_STRATEGY_TRACER_RULE_OUTPUT_ENABLED = "spring.application.strategy.tracer.rule.output.enabled"; + public static final String SPRING_APPLICATION_STRATEGY_TRACER_EXCEPTION_DETAIL_OUTPUT_ENABLED = "spring.application.strategy.tracer.exception.detail.output.enabled"; + public static final String SPRING_APPLICATION_STRATEGY_TRACER_METHOD_CONTEXT_OUTPUT_ENABLED = "spring.application.strategy.tracer.method.context.output.enabled"; + public static final String SPRING_APPLICATION_STRATEGY_TRACER_SPAN_VALUE = "spring.application.strategy.tracer.span.value"; + public static final String SPRING_APPLICATION_STRATEGY_TRACER_SPAN_TAG_PLUGIN_VALUE = "spring.application.strategy.tracer.span.tag.plugin.value"; + public static final String SPRING_APPLICATION_STRATEGY_ALARM_ENABLED = "spring.application.strategy.alarm.enabled"; + + public static final String SPRING_APPLICATION_STRATEGY_AUTO_SCAN_PACKAGES_ENABLED = "spring.application.strategy.auto.scan.packages.enabled"; + public static final String SPRING_APPLICATION_STRATEGY_AUTO_SCAN_RECURSION_ENABLED = "spring.application.strategy.auto.scan.recursion.enabled"; + + public static final String STRATEGY_DEBUG = "strategy.debug"; + + public static final String STRATEGY_CONTEXT_ALARM = "strategy-context-alarm"; +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/context/AbstractStrategyContextHolder.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/context/AbstractStrategyContextHolder.java new file mode 100644 index 0000000000..8af99091ef --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/context/AbstractStrategyContextHolder.java @@ -0,0 +1,286 @@ +package com.nepxion.discovery.plugin.strategy.context; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; + +import com.nepxion.discovery.common.constant.DiscoveryConstant; +import com.nepxion.discovery.plugin.framework.adapter.PluginAdapter; +import com.nepxion.discovery.plugin.framework.context.PluginContextHolder; +import com.nepxion.discovery.plugin.strategy.monitor.StrategyMonitorContext; +import com.nepxion.discovery.plugin.strategy.wrapper.StrategyWrapper; + +public abstract class AbstractStrategyContextHolder implements PluginContextHolder, StrategyContextHolder { + @Autowired + protected PluginAdapter pluginAdapter; + + @Autowired + protected StrategyWrapper strategyWrapper; + + @Autowired(required = false) + protected StrategyMonitorContext strategyMonitorContext; + + @Override + public String getContext(String name) { + return getHeader(name); + } + + @Override + public String getContextRouteVersion() { + String versionValue = getContext(DiscoveryConstant.N_D_VERSION); + if (StringUtils.isEmpty(versionValue)) { + versionValue = getRouteVersion(); + } + + return versionValue; + } + + @Override + public String getContextRouteRegion() { + String regionValue = getContext(DiscoveryConstant.N_D_REGION); + if (StringUtils.isEmpty(regionValue)) { + regionValue = getRouteRegion(); + } + + return regionValue; + } + + @Override + public String getContextRouteEnvironment() { + String environmentValue = getContext(DiscoveryConstant.N_D_ENVIRONMENT); + if (StringUtils.isEmpty(environmentValue)) { + environmentValue = getRouteEnvironment(); + } + + return environmentValue; + } + + @Override + public String getContextRouteAddress() { + String addressValue = getContext(DiscoveryConstant.N_D_ADDRESS); + if (StringUtils.isEmpty(addressValue)) { + addressValue = getRouteAddress(); + } + + return addressValue; + } + + @Override + public String getContextRouteVersionWeight() { + String versionWeightValue = getContext(DiscoveryConstant.N_D_VERSION_WEIGHT); + if (StringUtils.isEmpty(versionWeightValue)) { + versionWeightValue = getRouteVersionWeight(); + } + + return versionWeightValue; + } + + @Override + public String getContextRouteRegionWeight() { + String regionWeightValue = getContext(DiscoveryConstant.N_D_REGION_WEIGHT); + if (StringUtils.isEmpty(regionWeightValue)) { + regionWeightValue = getRouteRegionWeight(); + } + + return regionWeightValue; + } + + @Override + public String getContextRouteVersionPrefer() { + String versionPreferValue = getContext(DiscoveryConstant.N_D_VERSION_PREFER); + if (StringUtils.isEmpty(versionPreferValue)) { + versionPreferValue = getRouteVersionPrefer(); + } + + return versionPreferValue; + } + + @Override + public String getContextRouteVersionFailover() { + String versionFailoverValue = getContext(DiscoveryConstant.N_D_VERSION_FAILOVER); + if (StringUtils.isEmpty(versionFailoverValue)) { + versionFailoverValue = getRouteVersionFailover(); + } + + return versionFailoverValue; + } + + @Override + public String getContextRouteRegionTransfer() { + String regionTransferValue = getContext(DiscoveryConstant.N_D_REGION_TRANSFER); + if (StringUtils.isEmpty(regionTransferValue)) { + regionTransferValue = getRouteRegionTransfer(); + } + + return regionTransferValue; + } + + @Override + public String getContextRouteRegionFailover() { + String regionFailoverValue = getContext(DiscoveryConstant.N_D_REGION_FAILOVER); + if (StringUtils.isEmpty(regionFailoverValue)) { + regionFailoverValue = getRouteRegionFailover(); + } + + return regionFailoverValue; + } + + @Override + public String getContextRouteEnvironmentFailover() { + String environmentFailoverValue = getContext(DiscoveryConstant.N_D_ENVIRONMENT_FAILOVER); + if (StringUtils.isEmpty(environmentFailoverValue)) { + environmentFailoverValue = getRouteEnvironmentFailover(); + } + + return environmentFailoverValue; + } + + @Override + public String getContextRouteZoneFailover() { + String zoneFailoverValue = getContext(DiscoveryConstant.N_D_ZONE_FAILOVER); + if (StringUtils.isEmpty(zoneFailoverValue)) { + zoneFailoverValue = getRouteZoneFailover(); + } + + return zoneFailoverValue; + } + + @Override + public String getContextRouteAddressFailover() { + String addressFailoverValue = getContext(DiscoveryConstant.N_D_ADDRESS_FAILOVER); + if (StringUtils.isEmpty(addressFailoverValue)) { + addressFailoverValue = getRouteAddressFailover(); + } + + return addressFailoverValue; + } + + @Override + public String getContextRouteIdBlacklist() { + String idBlacklistValue = getContext(DiscoveryConstant.N_D_ID_BLACKLIST); + if (StringUtils.isEmpty(idBlacklistValue)) { + idBlacklistValue = getRouteIdBlacklist(); + } + + return idBlacklistValue; + } + + @Override + public String getContextRouteAddressBlacklist() { + String addressBlacklistValue = getContext(DiscoveryConstant.N_D_ADDRESS_BLACKLIST); + if (StringUtils.isEmpty(addressBlacklistValue)) { + addressBlacklistValue = getRouteAddressBlacklist(); + } + + return addressBlacklistValue; + } + + @Override + public String getRouteVersion() { + return strategyWrapper.getRouteVersion(); + } + + @Override + public String getRouteRegion() { + return strategyWrapper.getRouteRegion(); + } + + @Override + public String getRouteEnvironment() { + return null; + } + + @Override + public String getRouteAddress() { + return strategyWrapper.getRouteAddress(); + } + + @Override + public String getRouteVersionWeight() { + return strategyWrapper.getRouteVersionWeight(); + } + + @Override + public String getRouteRegionWeight() { + return strategyWrapper.getRouteRegionWeight(); + } + + @Override + public String getRouteVersionPrefer() { + return strategyWrapper.getRouteVersionPrefer(); + } + + @Override + public String getRouteVersionFailover() { + return strategyWrapper.getRouteVersionFailover(); + } + + @Override + public String getRouteRegionTransfer() { + return strategyWrapper.getRouteRegionTransfer(); + } + + @Override + public String getRouteRegionFailover() { + return strategyWrapper.getRouteRegionFailover(); + } + + @Override + public String getRouteEnvironmentFailover() { + return strategyWrapper.getRouteEnvironmentFailover(); + } + + @Override + public String getRouteZoneFailover() { + return strategyWrapper.getRouteZoneFailover(); + } + + @Override + public String getRouteAddressFailover() { + return strategyWrapper.getRouteAddressFailover(); + } + + @Override + public String getRouteIdBlacklist() { + return strategyWrapper.getRouteIdBlacklist(); + } + + @Override + public String getRouteAddressBlacklist() { + return strategyWrapper.getRouteAddressBlacklist(); + } + + @Override + public String getTraceId() { + if (strategyMonitorContext != null) { + return strategyMonitorContext.getTraceId(); + } + + return null; + } + + @Override + public String getSpanId() { + if (strategyMonitorContext != null) { + return strategyMonitorContext.getSpanId(); + } + + return null; + } + + public PluginAdapter getPluginAdapter() { + return pluginAdapter; + } + + public StrategyWrapper getStrategyWrapper() { + return strategyWrapper; + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/context/StrategyContextHolder.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/context/StrategyContextHolder.java new file mode 100644 index 0000000000..025a3c695d --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/context/StrategyContextHolder.java @@ -0,0 +1,52 @@ +package com.nepxion.discovery.plugin.strategy.context; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.Enumeration; + +public interface StrategyContextHolder { + Enumeration getHeaderNames(); + + String getHeader(String name); + + String getParameter(String name); + + String getCookie(String name); + + String getRouteVersion(); + + String getRouteRegion(); + + String getRouteEnvironment(); + + String getRouteAddress(); + + String getRouteVersionWeight(); + + String getRouteRegionWeight(); + + String getRouteVersionPrefer(); + + String getRouteVersionFailover(); + + String getRouteRegionTransfer(); + + String getRouteRegionFailover(); + + String getRouteEnvironmentFailover(); + + String getRouteZoneFailover(); + + String getRouteAddressFailover(); + + String getRouteIdBlacklist(); + + String getRouteAddressBlacklist(); +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/context/StrategyEnvironmentPostProcessor.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/context/StrategyEnvironmentPostProcessor.java new file mode 100644 index 0000000000..32a102c44e --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/context/StrategyEnvironmentPostProcessor.java @@ -0,0 +1,69 @@ +package com.nepxion.discovery.plugin.strategy.context; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.apache.commons.lang3.StringUtils; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.env.EnvironmentPostProcessor; +import org.springframework.core.Ordered; +import org.springframework.core.env.ConfigurableEnvironment; + +import com.nepxion.discovery.common.util.EnvironmentUtil; +import com.nepxion.discovery.plugin.strategy.constant.StrategyConstant; + +public class StrategyEnvironmentPostProcessor implements EnvironmentPostProcessor, Ordered { + @Override + public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { + if (EnvironmentUtil.isStandardEnvironment(environment)) { + processStrategyDebug(); + } + } + + private void processStrategyDebug() { + String strategyDebug = System.getProperty(StrategyConstant.STRATEGY_DEBUG); + if (StringUtils.isNotEmpty(strategyDebug)) { + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.append("\n"); + stringBuilder.append("==========================================================================================\n"); + stringBuilder.append("$ $\n"); + stringBuilder.append("$ Strategy Debug Information $\n"); + stringBuilder.append("$ $\n"); + + strategyDebug = strategyDebug.trim().toLowerCase(); + if (strategyDebug.matches(Boolean.TRUE + "|" + Boolean.FALSE)) { + System.setProperty(StrategyConstant.SPRING_APPLICATION_STRATEGY_MONITOR_ENABLED, strategyDebug); + System.setProperty(StrategyConstant.SPRING_APPLICATION_STRATEGY_REST_INTERCEPT_DEBUG_ENABLED, strategyDebug); + System.setProperty(StrategyConstant.SPRING_APPLICATION_STRATEGY_LOGGER_DEBUG_ENABLED, strategyDebug); + + if (StringUtils.equals(strategyDebug, Boolean.TRUE.toString())) { + stringBuilder.append("$ Debug for strategy context transmission is enabled $\n"); + stringBuilder.append("$ Following strategy Http data will display on console for troubleshooting : $\n"); + stringBuilder.append("$ 1. n-d-* $\n"); + stringBuilder.append("$ 2. " + StrategyConstant.SPRING_APPLICATION_STRATEGY_CONTEXT_REQUEST_HEADERS + " $\n"); + stringBuilder.append("$ 3. " + StrategyConstant.SPRING_APPLICATION_STRATEGY_BUSINESS_REQUEST_HEADERS + " $\n"); + } else { + stringBuilder.append("$ Debug for strategy context transmission is disabled $\n"); + } + } else { + stringBuilder.append("$ Debug for strategy context transmission isn't enabled $\n"); + stringBuilder.append("$ The value of '" + StrategyConstant.STRATEGY_DEBUG + "' must be a boolean type $\n"); + } + + stringBuilder.append("$ $\n"); + stringBuilder.append("==========================================================================================\n"); + System.out.println(stringBuilder.toString()); + } + } + + @Override + public int getOrder() { + return Ordered.HIGHEST_PRECEDENCE; + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/context/StrategyHeaderContext.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/context/StrategyHeaderContext.java new file mode 100644 index 0000000000..73378971fd --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/context/StrategyHeaderContext.java @@ -0,0 +1,59 @@ +package com.nepxion.discovery.plugin.strategy.context; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.ArrayList; +import java.util.List; + +import javax.annotation.PostConstruct; + +import org.apache.commons.collections4.CollectionUtils; +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.env.ConfigurableEnvironment; + +import com.nepxion.discovery.common.entity.HeadersInjectorType; +import com.nepxion.discovery.common.util.StringUtil; +import com.nepxion.discovery.plugin.strategy.constant.StrategyConstant; +import com.nepxion.discovery.plugin.strategy.injector.StrategyHeadersInjector; +import com.nepxion.discovery.plugin.strategy.injector.StrategyHeadersResolver; + +public class StrategyHeaderContext { + @Autowired + private ConfigurableEnvironment environment; + + @Autowired(required = false) + private List strategyHeadersInjectorList; + + private List requestHeaderNameList; + + @PostConstruct + public void initialize() { + requestHeaderNameList = new ArrayList(); + + String contextRequestHeaders = environment.getProperty(StrategyConstant.SPRING_APPLICATION_STRATEGY_CONTEXT_REQUEST_HEADERS); + String businessRequestHeaders = environment.getProperty(StrategyConstant.SPRING_APPLICATION_STRATEGY_BUSINESS_REQUEST_HEADERS); + List injectorRequestHeaders = StrategyHeadersResolver.getInjectedHeaders(strategyHeadersInjectorList, HeadersInjectorType.TRANSMISSION); + + if (StringUtils.isNotEmpty(contextRequestHeaders)) { + requestHeaderNameList.addAll(StringUtil.splitToList(contextRequestHeaders.toLowerCase())); + } + if (StringUtils.isNotEmpty(businessRequestHeaders)) { + requestHeaderNameList.addAll(StringUtil.splitToList(businessRequestHeaders.toLowerCase())); + } + if (CollectionUtils.isNotEmpty(injectorRequestHeaders)) { + requestHeaderNameList.addAll(injectorRequestHeaders); + } + } + + public List getRequestHeaderNameList() { + return requestHeaderNameList; + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/event/StrategyAlarmEvent.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/event/StrategyAlarmEvent.java new file mode 100644 index 0000000000..ceaecfa3a3 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/event/StrategyAlarmEvent.java @@ -0,0 +1,33 @@ +package com.nepxion.discovery.plugin.strategy.event; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.io.Serializable; +import java.util.Map; + +public class StrategyAlarmEvent implements Serializable { + private static final long serialVersionUID = 5966845230262521754L; + + private String alarmType; + private Map alarmMap; + + public StrategyAlarmEvent(String alarmType, Map alarmMap) { + this.alarmType = alarmType; + this.alarmMap = alarmMap; + } + + public String getAlarmType() { + return alarmType; + } + + public Map getAlarmMap() { + return alarmMap; + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/extractor/StrategyPackagesExtractor.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/extractor/StrategyPackagesExtractor.java new file mode 100644 index 0000000000..1b1a542e33 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/extractor/StrategyPackagesExtractor.java @@ -0,0 +1,206 @@ +package com.nepxion.discovery.plugin.strategy.extractor; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Xun Zhong + * @author Haojun Ren + * @version 1.0 + */ + +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; + +import org.apache.commons.collections4.CollectionUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.BeansException; +import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition; +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; +import org.springframework.beans.factory.support.BeanDefinitionRegistry; +import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor; +import org.springframework.boot.autoconfigure.AutoConfigurationPackages; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ApplicationContextAware; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.core.annotation.AnnotationAttributes; +import org.springframework.core.env.Environment; +import org.springframework.core.type.AnnotationMetadata; +import org.springframework.util.ClassUtils; + +import com.nepxion.discovery.common.util.StringUtil; +import com.nepxion.discovery.plugin.strategy.constant.StrategyConstant; + +public class StrategyPackagesExtractor implements BeanDefinitionRegistryPostProcessor, ApplicationContextAware { + private static final Logger LOG = LoggerFactory.getLogger(StrategyPackagesExtractor.class); + + private ApplicationContext applicationContext; + private Environment environment; + + private List basePackagesList; + private List scanningPackagesList; + private Set scanningPackagesSet; + private List allPackagesList; + + private String basePackages; + private String scanningPackages; + private String allPackages; + + @Override + public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { + this.applicationContext = applicationContext; + this.environment = applicationContext.getEnvironment(); + } + + @Override + public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { + + } + + @Override + public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException { + Boolean autoScanPackagesEnabled = environment.getProperty(StrategyConstant.SPRING_APPLICATION_STRATEGY_AUTO_SCAN_PACKAGES_ENABLED, Boolean.class, Boolean.TRUE); + if (!autoScanPackagesEnabled) { + return; + } + + try { + allPackagesList = new ArrayList(); + + basePackagesList = getComponentBasePackages(); + if (CollectionUtils.isNotEmpty(basePackagesList)) { + basePackages = StringUtil.convertToString(basePackagesList); + + for (String pkg : basePackagesList) { + if (!allPackagesList.contains(pkg)) { + allPackagesList.add(pkg); + } + } + } + + scanningPackagesSet = getComponentScanningPackages(registry, basePackagesList); + if (CollectionUtils.isNotEmpty(scanningPackagesSet)) { + scanningPackagesList = new ArrayList(scanningPackagesSet); + scanningPackages = StringUtil.convertToString(scanningPackagesList); + + for (String pkg : scanningPackagesList) { + if (!allPackagesList.contains(pkg)) { + allPackagesList.add(pkg); + } + } + } + + if (CollectionUtils.isNotEmpty(allPackagesList)) { + allPackages = StringUtil.convertToString(allPackagesList); + } + + LOG.info("--------- Auto Scan Packages Information ---------"); + LOG.info("Base packages is {}", basePackagesList); + LOG.info("Scanning packages is {}", scanningPackagesList); + LOG.info("All packages is {}", allPackagesList); + LOG.info("--------------------------------------------------"); + } catch (Exception e) { + LOG.warn("Get base and scanning packages failed, skip it..."); + } + } + + public List getBasePackagesList() { + return basePackagesList; + } + + public List getScanningPackagesList() { + return scanningPackagesList; + } + + public List getAllPackagesList() { + return allPackagesList; + } + + public String getBasePackages() { + return basePackages; + } + + public String getScanningPackages() { + return scanningPackages; + } + + public String getAllPackages() { + return allPackages; + } + + protected List getComponentBasePackages() { + return AutoConfigurationPackages.get(applicationContext); + } + + protected Set getComponentScanningPackages(BeanDefinitionRegistry registry, List basePackages) { + if (CollectionUtils.isEmpty(basePackages)) { + return null; + } + + Boolean autoScanRecursionEnabled = environment.getProperty(StrategyConstant.SPRING_APPLICATION_STRATEGY_AUTO_SCAN_RECURSION_ENABLED, Boolean.class, Boolean.FALSE); + + Set packages = new LinkedHashSet<>(); + String[] names = registry.getBeanDefinitionNames(); + for (String name : names) { + BeanDefinition definition = registry.getBeanDefinition(name); + String beanClassName = definition.getBeanClassName(); + if (definition instanceof AnnotatedBeanDefinition && beanClassName != null) { + String beanPackage = ClassUtils.getPackageName(beanClassName); + for (String pkg : basePackages) { + if (beanPackage.equals(pkg) || beanPackage.startsWith(pkg + '.')) { + AnnotatedBeanDefinition annotatedDefinition = (AnnotatedBeanDefinition) definition; + addComponentScanningPackages(packages, annotatedDefinition.getMetadata()); + + break; + } + } + + if (autoScanRecursionEnabled) { + for (String pkg : packages) { + if (beanPackage.equals(pkg) || beanPackage.startsWith(pkg + '.')) { + AnnotatedBeanDefinition annotatedDefinition = (AnnotatedBeanDefinition) definition; + addComponentScanningPackages(packages, annotatedDefinition.getMetadata()); + + break; + } + } + } + } + } + + return packages; + } + + private void addComponentScanningPackages(Set packages, AnnotationMetadata metadata) { + AnnotationAttributes attributes = AnnotationAttributes + .fromMap(metadata.getAnnotationAttributes(ComponentScan.class.getName(), true)); + if (attributes != null) { + addPackages(packages, attributes.getStringArray("value")); + addPackages(packages, attributes.getStringArray("basePackages")); + addClasses(packages, attributes.getStringArray("basePackageClasses")); + if (packages.isEmpty()) { + packages.add(ClassUtils.getPackageName(metadata.getClassName())); + } + } + } + + private void addPackages(Set packages, String[] values) { + if (values != null) { + Collections.addAll(packages, values); + } + } + + private void addClasses(Set packages, String[] values) { + if (values != null) { + for (String value : values) { + packages.add(ClassUtils.getPackageName(value)); + } + } + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/filter/AbstractStrategyEnabledFilter.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/filter/AbstractStrategyEnabledFilter.java new file mode 100644 index 0000000000..02b008dea9 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/filter/AbstractStrategyEnabledFilter.java @@ -0,0 +1,174 @@ +package com.nepxion.discovery.plugin.strategy.filter; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; + +import com.nepxion.discovery.common.constant.DiscoveryConstant; +import com.nepxion.discovery.common.entity.VersionSortEntity; +import com.nepxion.discovery.common.entity.VersionSortType; +import com.nepxion.discovery.common.util.VersionSortUtil; +import com.nepxion.discovery.plugin.framework.adapter.PluginAdapter; +import com.nepxion.discovery.plugin.framework.context.PluginContextHolder; +import com.nepxion.discovery.plugin.strategy.constant.StrategyConstant; +import com.nepxion.discovery.plugin.strategy.matcher.DiscoveryMatcher; +import com.netflix.loadbalancer.Server; + +public abstract class AbstractStrategyEnabledFilter implements StrategyEnabledFilter { + @Autowired + protected DiscoveryMatcher discoveryMatcher; + + @Autowired + protected PluginAdapter pluginAdapter; + + @Autowired + protected PluginContextHolder pluginContextHolder; + + @Value("${" + StrategyConstant.SPRING_APPLICATION_STRATEGY_VERSION_SORT_TYPE + ":" + DiscoveryConstant.SORT_BY_VERSION + "}") + protected String sortType; + + @Override + public void filter(List servers) { + Iterator iterator = servers.iterator(); + while (iterator.hasNext()) { + Server server = iterator.next(); + + boolean enabled = apply(servers, server); + if (!enabled) { + iterator.remove(); + } + } + } + + public boolean findByGroup(List servers, String group) { + for (Server server : servers) { + String serverGroup = pluginAdapter.getServerGroup(server); + if (StringUtils.equals(group, serverGroup)) { + return true; + } + } + + return false; + } + + public boolean findByVersion(List servers, String version) { + for (Server server : servers) { + String serverVersion = pluginAdapter.getServerVersion(server); + if (StringUtils.equals(version, serverVersion)) { + return true; + } + } + + return false; + } + + public boolean findByRegion(List servers, String region) { + for (Server server : servers) { + String serverRegion = pluginAdapter.getServerRegion(server); + if (StringUtils.equals(region, serverRegion)) { + return true; + } + } + + return false; + } + + public boolean findByEnvironment(List servers, String environment) { + for (Server server : servers) { + String serverEnvironment = pluginAdapter.getServerEnvironment(server); + if (StringUtils.equals(environment, serverEnvironment)) { + return true; + } + } + + return false; + } + + public boolean findByZone(List servers, String zone) { + for (Server server : servers) { + String serverZone = pluginAdapter.getServerZone(server); + if (StringUtils.equals(zone, serverZone)) { + return true; + } + } + + return false; + } + + public boolean matchByVersion(List servers, String versions) { + for (Server server : servers) { + String serverVersion = pluginAdapter.getServerVersion(server); + if (discoveryMatcher.match(versions, serverVersion, true)) { + return true; + } + } + + return false; + } + + public boolean matchByRegion(List servers, String regions) { + for (Server server : servers) { + String serverRegion = pluginAdapter.getServerRegion(server); + if (discoveryMatcher.match(regions, serverRegion, true)) { + return true; + } + } + + return false; + } + + public boolean matchByAddress(List servers, String addresses) { + for (Server server : servers) { + String serverHost = server.getHost(); + int serverPort = server.getPort(); + if (discoveryMatcher.matchAddress(addresses, serverHost, serverPort, true)) { + return true; + } + } + + return false; + } + + public List assembleVersionList(List servers) { + List versionSortEntityList = new ArrayList(); + for (Server server : servers) { + String serverVersion = pluginAdapter.getServerVersion(server); + String serverServiceUUId = pluginAdapter.getServerServiceUUId(server); + + VersionSortEntity versionSortEntity = new VersionSortEntity(); + versionSortEntity.setVersion(serverVersion); + versionSortEntity.setServiceUUId(serverServiceUUId); + + versionSortEntityList.add(versionSortEntity); + } + + VersionSortType versionSortType = VersionSortType.fromString(sortType); + + return VersionSortUtil.getVersionList(versionSortEntityList, versionSortType); + } + + public DiscoveryMatcher getDiscoveryMatcher() { + return discoveryMatcher; + } + + public PluginAdapter getPluginAdapter() { + return pluginAdapter; + } + + public PluginContextHolder getPluginContextHolder() { + return pluginContextHolder; + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/filter/StrategyAddressBlacklistEnabledFilter.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/filter/StrategyAddressBlacklistEnabledFilter.java new file mode 100644 index 0000000000..cfef57a79c --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/filter/StrategyAddressBlacklistEnabledFilter.java @@ -0,0 +1,36 @@ +package com.nepxion.discovery.plugin.strategy.filter; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.List; + +import org.apache.commons.lang3.StringUtils; + +import com.nepxion.discovery.common.util.JsonUtil; +import com.netflix.loadbalancer.Server; + +public class StrategyAddressBlacklistEnabledFilter extends AbstractStrategyEnabledFilter { + @Override + public boolean apply(List servers, Server server) { + String serviceId = pluginAdapter.getServerServiceId(server); + + String addresses = JsonUtil.fromJsonMap(pluginContextHolder.getContextRouteAddressBlacklist(), serviceId); + if (StringUtils.isEmpty(addresses)) { + return true; + } + + return discoveryMatcher.matchAddress(addresses, server.getHost(), server.getPort(), false); + } + + @Override + public int getOrder() { + return HIGHEST_PRECEDENCE + 1; + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/filter/StrategyAddressEnabledFilter.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/filter/StrategyAddressEnabledFilter.java new file mode 100644 index 0000000000..2a3e4865d9 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/filter/StrategyAddressEnabledFilter.java @@ -0,0 +1,53 @@ +package com.nepxion.discovery.plugin.strategy.filter; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.List; + +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Value; + +import com.nepxion.discovery.common.util.JsonUtil; +import com.nepxion.discovery.plugin.strategy.constant.StrategyConstant; +import com.netflix.loadbalancer.Server; + +public class StrategyAddressEnabledFilter extends AbstractStrategyEnabledFilter { + @Value("${" + StrategyConstant.SPRING_APPLICATION_STRATEGY_ADDRESS_FAILOVER_ENABLED + ":false}") + protected Boolean addressFailoverEnabled; + + @Override + public boolean apply(List servers, Server server) { + String serviceId = pluginAdapter.getServerServiceId(server); + + String addresses = JsonUtil.fromJsonMap(pluginContextHolder.getContextRouteAddress(), serviceId); + if (StringUtils.isEmpty(addresses)) { + return true; + } + + if (addressFailoverEnabled) { + boolean matched = matchByAddress(servers, addresses); + if (!matched) { + String addressFailovers = JsonUtil.fromJsonMap(pluginContextHolder.getContextRouteAddressFailover(), serviceId); + if (StringUtils.isEmpty(addressFailovers)) { + return true; + } else { + return discoveryMatcher.matchAddress(addressFailovers, server.getHost(), server.getPort(), true); + } + } + } + + return discoveryMatcher.matchAddress(addresses, server.getHost(), server.getPort(), true); + } + + @Override + public int getOrder() { + return HIGHEST_PRECEDENCE + 5; + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/filter/StrategyEnabledFilter.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/filter/StrategyEnabledFilter.java new file mode 100644 index 0000000000..6d57b818d8 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/filter/StrategyEnabledFilter.java @@ -0,0 +1,22 @@ +package com.nepxion.discovery.plugin.strategy.filter; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.List; + +import org.springframework.core.Ordered; + +import com.netflix.loadbalancer.Server; + +public interface StrategyEnabledFilter extends Ordered { + void filter(List servers); + + boolean apply(List servers, Server server); +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/filter/StrategyEnvironmentEnabledFilter.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/filter/StrategyEnvironmentEnabledFilter.java new file mode 100644 index 0000000000..2af277586c --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/filter/StrategyEnvironmentEnabledFilter.java @@ -0,0 +1,59 @@ +package com.nepxion.discovery.plugin.strategy.filter; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.List; + +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Value; + +import com.nepxion.discovery.common.util.JsonUtil; +import com.nepxion.discovery.plugin.strategy.constant.StrategyConstant; +import com.netflix.loadbalancer.Server; + +public class StrategyEnvironmentEnabledFilter extends AbstractStrategyEnabledFilter { + @Value("${" + StrategyConstant.SPRING_APPLICATION_STRATEGY_ENVIRONMENT_FAILOVER_ENABLED + ":false}") + protected Boolean environmentFailoverEnabled; + + @Override + public boolean apply(List servers, Server server) { + String environment = pluginContextHolder.getContextRouteEnvironment(); + if (StringUtils.isEmpty(environment)) { + return true; + } + + String serverEnvironment = pluginAdapter.getServerEnvironment(server); + + boolean found = findByEnvironment(servers, environment); + if (found) { + // 匹配到传递过来的环境Header的服务实例,返回匹配的环境的服务实例 + return StringUtils.equals(serverEnvironment, environment); + } else { + if (environmentFailoverEnabled) { + String serviceId = pluginAdapter.getServerServiceId(server); + + // 没有匹配上,则寻址Common环境,返回Common环境的服务实例 + String environmentFailovers = JsonUtil.fromJsonMap(pluginContextHolder.getContextRouteEnvironmentFailover(), serviceId); + if (StringUtils.isEmpty(environmentFailovers)) { + environmentFailovers = StrategyConstant.SPRING_APPLICATION_STRATEGY_ENVIRONMENT_FAILOVER_VALUE; + } + + return discoveryMatcher.match(environmentFailovers, serverEnvironment, true); + } + } + + return StringUtils.equals(serverEnvironment, environment); + } + + @Override + public int getOrder() { + return HIGHEST_PRECEDENCE + 3; + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/filter/StrategyGroupEnabledFilter.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/filter/StrategyGroupEnabledFilter.java new file mode 100644 index 0000000000..8ccdf4e287 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/filter/StrategyGroupEnabledFilter.java @@ -0,0 +1,46 @@ +package com.nepxion.discovery.plugin.strategy.filter; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.List; + +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Value; + +import com.nepxion.discovery.common.entity.ServiceType; +import com.nepxion.discovery.plugin.strategy.constant.StrategyConstant; +import com.netflix.loadbalancer.Server; + +public class StrategyGroupEnabledFilter extends AbstractStrategyEnabledFilter { + @Value("${" + StrategyConstant.SPRING_APPLICATION_STRATEGY_CONSUMER_ISOLATION_ENABLED + ":false}") + protected Boolean consumerIsolationEnabled; + + @Override + public boolean apply(List servers, Server server) { + if (!consumerIsolationEnabled) { + return true; + } + + String serverServiceType = pluginAdapter.getServerServiceType(server); + if (StringUtils.equals(serverServiceType, ServiceType.GATEWAY.toString())) { + return true; + } + + String serverGroup = pluginAdapter.getServerGroup(server); + String group = pluginAdapter.getGroup(); + + return StringUtils.equals(serverGroup, group); + } + + @Override + public int getOrder() { + return HIGHEST_PRECEDENCE + 2; + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/filter/StrategyIdBlacklistEnabledFilter.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/filter/StrategyIdBlacklistEnabledFilter.java new file mode 100644 index 0000000000..033606fdeb --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/filter/StrategyIdBlacklistEnabledFilter.java @@ -0,0 +1,38 @@ +package com.nepxion.discovery.plugin.strategy.filter; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.List; + +import org.apache.commons.lang3.StringUtils; + +import com.nepxion.discovery.common.util.JsonUtil; +import com.netflix.loadbalancer.Server; + +public class StrategyIdBlacklistEnabledFilter extends AbstractStrategyEnabledFilter { + @Override + public boolean apply(List servers, Server server) { + String serviceId = pluginAdapter.getServerServiceId(server); + + String ids = JsonUtil.fromJsonMap(pluginContextHolder.getContextRouteIdBlacklist(), serviceId); + if (StringUtils.isEmpty(ids)) { + return true; + } + + String id = pluginAdapter.getServerServiceUUId(server); + + return discoveryMatcher.match(ids, id, false); + } + + @Override + public int getOrder() { + return HIGHEST_PRECEDENCE; + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/filter/StrategyRegionEnabledFilter.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/filter/StrategyRegionEnabledFilter.java new file mode 100644 index 0000000000..e0f6c84fb3 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/filter/StrategyRegionEnabledFilter.java @@ -0,0 +1,81 @@ +package com.nepxion.discovery.plugin.strategy.filter; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.List; + +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Value; + +import com.nepxion.discovery.common.exception.DiscoveryException; +import com.nepxion.discovery.common.util.JsonUtil; +import com.nepxion.discovery.plugin.strategy.constant.StrategyConstant; +import com.netflix.loadbalancer.Server; + +public class StrategyRegionEnabledFilter extends AbstractStrategyEnabledFilter { + @Value("${" + StrategyConstant.SPRING_APPLICATION_STRATEGY_REGION_TRANSFER_ENABLED + ":false}") + protected Boolean regionTransferEnabled; + + @Value("${" + StrategyConstant.SPRING_APPLICATION_STRATEGY_REGION_FAILOVER_ENABLED + ":false}") + protected Boolean regionFailoverEnabled; + + @Override + public boolean apply(List servers, Server server) { + String serviceId = pluginAdapter.getServerServiceId(server); + + String region = pluginAdapter.getServerRegion(server); + + String regions = JsonUtil.fromJsonMap(pluginContextHolder.getContextRouteRegion(), serviceId); + if (StringUtils.isEmpty(regions)) { + // 流量路由到指定的区域下。当未对服务指定访问区域的时候,路由到事先指定的区域 + // 使用场景示例: + // 开发环境(个人电脑环境)在测试环境(线上环境)进行联调 + // 访问路径为A服务 -> B服务 -> C服务,A服务和B服务在开发环境上,C服务在测试环境上 + // 调用时候,在最前端传入的Header(n-d-region)指定为B的开发环境区域(用来保证A服务和B服务只在开发环境调用),而B服务会自动路由调用到测试环境上的C服务实例,但不会路由到其它个人电脑的C服务实例 + // 该功能的意义,个人电脑环境可以接入到测试环境联调,当多套个人环境接入时候,可以保护不同的个人环境间不会彼此调用 + if (regionTransferEnabled) { + String regionTransfers = JsonUtil.fromJsonMap(pluginContextHolder.getContextRouteRegionTransfer(), serviceId); + if (StringUtils.isEmpty(regionTransfers)) { + throw new DiscoveryException("The Region Transfer value is missing"); + } + + return discoveryMatcher.match(regionTransfers, region, true); + } else { + return true; + } + } + + if (regionFailoverEnabled) { + boolean matched = matchByRegion(servers, regions); + if (!matched) { + // 判断提供端服务的元数据多活标记 + boolean isServerActive = pluginAdapter.isServerActive(server); + // 如果提供端为多活服务,消费端不执行故障转移 + if (isServerActive) { + return false; + } + + String regionFailovers = JsonUtil.fromJsonMap(pluginContextHolder.getContextRouteRegionFailover(), serviceId); + if (StringUtils.isEmpty(regionFailovers)) { + return true; + } else { + return discoveryMatcher.match(regionFailovers, region, true); + } + } + } + + return discoveryMatcher.match(regions, region, true); + } + + @Override + public int getOrder() { + return HIGHEST_PRECEDENCE + 6; + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/filter/StrategyRouteFilter.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/filter/StrategyRouteFilter.java new file mode 100644 index 0000000000..1ef599fd86 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/filter/StrategyRouteFilter.java @@ -0,0 +1,42 @@ +package com.nepxion.discovery.plugin.strategy.filter; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +public interface StrategyRouteFilter { + String getRouteVersion(); + + String getRouteRegion(); + + String getRouteEnvironment(); + + String getRouteAddress(); + + String getRouteVersionWeight(); + + String getRouteRegionWeight(); + + String getRouteVersionPrefer(); + + String getRouteVersionFailover(); + + String getRouteRegionTransfer(); + + String getRouteRegionFailover(); + + String getRouteEnvironmentFailover(); + + String getRouteZoneFailover(); + + String getRouteAddressFailover(); + + String getRouteIdBlacklist(); + + String getRouteAddressBlacklist(); +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/filter/StrategyVersionEnabledFilter.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/filter/StrategyVersionEnabledFilter.java new file mode 100644 index 0000000000..389e33ae8d --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/filter/StrategyVersionEnabledFilter.java @@ -0,0 +1,105 @@ +package com.nepxion.discovery.plugin.strategy.filter; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.List; + +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; + +import com.nepxion.discovery.common.constant.DiscoveryConstant; +import com.nepxion.discovery.common.util.JsonUtil; +import com.nepxion.discovery.plugin.strategy.adapter.StrategyVersionFilterAdapter; +import com.nepxion.discovery.plugin.strategy.constant.StrategyConstant; +import com.netflix.loadbalancer.Server; + +public class StrategyVersionEnabledFilter extends AbstractStrategyEnabledFilter { + @Autowired + protected StrategyVersionFilterAdapter strategyVersionFilterAdapter; + + @Value("${" + StrategyConstant.SPRING_APPLICATION_STRATEGY_VERSION_FAILOVER_ENABLED + ":false}") + protected Boolean versionFailoverEnabled; + + @Value("${" + StrategyConstant.SPRING_APPLICATION_STRATEGY_VERSION_FAILOVER_STABLE_ENABLED + ":false}") + protected Boolean versionFailoverStableEnabled; + + @Value("${" + StrategyConstant.SPRING_APPLICATION_STRATEGY_VERSION_PREFER_ENABLED + ":false}") + protected Boolean versionPreferEnabled; + + @Override + public boolean apply(List servers, Server server) { + String serviceId = pluginAdapter.getServerServiceId(server); + + String version = pluginAdapter.getServerVersion(server); + + String versions = JsonUtil.fromJsonMap(pluginContextHolder.getContextRouteVersion(), serviceId); + if (StringUtils.isEmpty(versions)) { + // 版本偏好,即非蓝绿灰度发布场景下,路由到老的稳定版本的实例,或者指定版本的实例 + if (versionPreferEnabled) { + // 版本列表排序策略的(取最老的稳定版本的实例)偏好,即不管存在多少版本,直接路由到最老的稳定版本的实例 + String versionPrefers = JsonUtil.fromJsonMap(pluginContextHolder.getContextRouteVersionPrefer(), serviceId); + if (StringUtils.isEmpty(versionPrefers)) { + return containVersion(servers, server); + } else { + // 指定版本的偏好,即不管存在多少版本,直接路由到该版本实例 + return discoveryMatcher.match(versionPrefers, version, true); + } + } else { + return true; + } + } else { + // 版本故障转移,即无法找到相应版本的服务实例,路由到老的稳定版本的实例,或者指定版本的实例,或者执行负载均衡 + if (versionFailoverEnabled) { + boolean matched = matchByVersion(servers, versions); + if (!matched) { + String versionFailovers = JsonUtil.fromJsonMap(pluginContextHolder.getContextRouteVersionFailover(), serviceId); + if (StringUtils.isEmpty(versionFailovers)) { + if (versionFailoverStableEnabled) { + // 版本列表排序策略的(取最老的稳定版本的实例)故障转移,即找不到实例的时候,直接路由到最老的稳定版本的实例 + return containVersion(servers, server); + } else { + // 负载均衡策略的故障转移,即找不到实例的时候,执行负载均衡策略 + return true; + } + } else { + // 指定版本的故障转移,即找不到实例的时候,直接路由到该版本实例 + return discoveryMatcher.match(versionFailovers, version, true); + } + } + } + } + + return discoveryMatcher.match(versions, version, true); + } + + public boolean containVersion(List servers, Server server) { + String version = pluginAdapter.getServerVersion(server); + // 当服务未接入本框架或者版本号未设置(表现出来的值为DiscoveryConstant.DEFAULT),则不过滤,返回 + if (StringUtils.equals(version, DiscoveryConstant.DEFAULT)) { + return true; + } + + List versionList = assembleVersionList(servers); + if (versionList.size() <= 1) { + return true; + } + + // 过滤出老的稳定版的版本号列表,一般来说,老的稳定版的版本号只有一个,为了增加扩展性,支持多个 + List filterVersionList = strategyVersionFilterAdapter.filter(versionList); + + return filterVersionList.contains(version); + } + + @Override + public int getOrder() { + return HIGHEST_PRECEDENCE + 7; + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/filter/StrategyZoneEnabledFilter.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/filter/StrategyZoneEnabledFilter.java new file mode 100644 index 0000000000..1fd3b0dae3 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/filter/StrategyZoneEnabledFilter.java @@ -0,0 +1,63 @@ +package com.nepxion.discovery.plugin.strategy.filter; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.List; + +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Value; + +import com.nepxion.discovery.common.util.JsonUtil; +import com.nepxion.discovery.plugin.strategy.constant.StrategyConstant; +import com.netflix.loadbalancer.Server; + +public class StrategyZoneEnabledFilter extends AbstractStrategyEnabledFilter { + @Value("${" + StrategyConstant.SPRING_APPLICATION_STRATEGY_ZONE_AFFINITY_ENABLED + ":false}") + protected Boolean zoneAffinityEnabled; + + @Value("${" + StrategyConstant.SPRING_APPLICATION_STRATEGY_ZONE_FAILOVER_ENABLED + ":false}") + protected Boolean zoneFailoverEnabled; + + @Override + public boolean apply(List servers, Server server) { + if (!zoneAffinityEnabled) { + return true; + } + + String zone = pluginAdapter.getZone(); + + String serverZone = pluginAdapter.getServerZone(server); + + boolean found = findByZone(servers, zone); + if (found) { + // 可用区存在:执行可用区亲和性,即调用端实例和提供端实例的元数据Metadata的zone配置值相等才能调用 + return StringUtils.equals(serverZone, zone); + } else { + // 可用区不存在:路由开关打开,可路由到其它指定可用区;路由开关关闭,不可路由到其它可用区或者不归属任何可用区 + if (zoneFailoverEnabled) { + String serviceId = pluginAdapter.getServerServiceId(server); + + String zoneFailovers = JsonUtil.fromJsonMap(pluginContextHolder.getContextRouteZoneFailover(), serviceId); + if (StringUtils.isEmpty(zoneFailovers)) { + return true; + } else { + return discoveryMatcher.match(zoneFailovers, serverZone, true); + } + } + } + + return StringUtils.equals(serverZone, zone); + } + + @Override + public int getOrder() { + return HIGHEST_PRECEDENCE + 4; + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/injector/StrategyHeadersInjector.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/injector/StrategyHeadersInjector.java new file mode 100644 index 0000000000..46a700b73b --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/injector/StrategyHeadersInjector.java @@ -0,0 +1,18 @@ +package com.nepxion.discovery.plugin.strategy.injector; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.List; + +import com.nepxion.discovery.common.entity.HeadersInjectorEntity; + +public interface StrategyHeadersInjector { + List getHeadersInjectorEntityList(); +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/injector/StrategyHeadersResolver.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/injector/StrategyHeadersResolver.java new file mode 100644 index 0000000000..975e98614a --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/injector/StrategyHeadersResolver.java @@ -0,0 +1,47 @@ +package com.nepxion.discovery.plugin.strategy.injector; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.ArrayList; +import java.util.List; + +import org.apache.commons.collections4.CollectionUtils; + +import com.nepxion.discovery.common.entity.HeadersInjectorEntity; +import com.nepxion.discovery.common.entity.HeadersInjectorType; + +public class StrategyHeadersResolver { + public static List getInjectedHeaders(List strategyHeadersInjectorList, HeadersInjectorType headersInjectorType) { + List headerList = null; + if (CollectionUtils.isNotEmpty(strategyHeadersInjectorList)) { + headerList = new ArrayList(); + for (StrategyHeadersInjector strategyHeadersInjector : strategyHeadersInjectorList) { + List headersInjectorEntityList = strategyHeadersInjector.getHeadersInjectorEntityList(); + if (CollectionUtils.isNotEmpty(headersInjectorEntityList)) { + for (HeadersInjectorEntity headersInjectorEntity : headersInjectorEntityList) { + HeadersInjectorType injectorType = headersInjectorEntity.getHeadersInjectorType(); + List headers = headersInjectorEntity.getHeaders(); + if (injectorType == headersInjectorType || injectorType == HeadersInjectorType.ALL) { + if (CollectionUtils.isNotEmpty(headers)) { + for (String header : headers) { + if (!headerList.contains(header)) { + headerList.add(header); + } + } + } + } + } + } + } + } + + return headerList; + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/injector/StrategyPackagesInjector.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/injector/StrategyPackagesInjector.java new file mode 100644 index 0000000000..23373fc442 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/injector/StrategyPackagesInjector.java @@ -0,0 +1,19 @@ +package com.nepxion.discovery.plugin.strategy.injector; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Xun Zhong + * @author Haojun Ren + * @version 1.0 + */ + +import java.util.List; + +import com.nepxion.discovery.common.entity.PackagesInjectorEntity; + +public interface StrategyPackagesInjector { + List getPackagesInjectorEntityList(); +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/injector/StrategyPackagesResolver.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/injector/StrategyPackagesResolver.java new file mode 100644 index 0000000000..9bc2ff1d80 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/injector/StrategyPackagesResolver.java @@ -0,0 +1,47 @@ +package com.nepxion.discovery.plugin.strategy.injector; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.ArrayList; +import java.util.List; + +import org.apache.commons.collections4.CollectionUtils; + +import com.nepxion.discovery.common.entity.PackagesInjectorEntity; +import com.nepxion.discovery.common.entity.PackagesInjectorType; + +public class StrategyPackagesResolver { + public static List getInjectedPackages(List strategyPackagesInjectorList, PackagesInjectorType packagesInjectorType) { + List packageList = null; + if (CollectionUtils.isNotEmpty(strategyPackagesInjectorList)) { + packageList = new ArrayList(); + for (StrategyPackagesInjector strategyPackagesInjector : strategyPackagesInjectorList) { + List packagesInjectorEntityList = strategyPackagesInjector.getPackagesInjectorEntityList(); + if (CollectionUtils.isNotEmpty(packagesInjectorEntityList)) { + for (PackagesInjectorEntity packagesInjectorEntity : packagesInjectorEntityList) { + PackagesInjectorType injectorType = packagesInjectorEntity.getPackagesInjectorType(); + List packages = packagesInjectorEntity.getPackages(); + if (injectorType == packagesInjectorType || injectorType == PackagesInjectorType.ALL) { + if (CollectionUtils.isNotEmpty(packages)) { + for (String pkg : packages) { + if (!packageList.contains(pkg)) { + packageList.add(pkg); + } + } + } + } + } + } + } + } + + return packageList; + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/src/main/java/com/nepxion/discovery/plugin/strategy/matcher/DiscoveryAntPathMatcherStrategy.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/matcher/DiscoveryAntPathMatcherStrategy.java similarity index 100% rename from discovery-plugin-strategy/src/main/java/com/nepxion/discovery/plugin/strategy/matcher/DiscoveryAntPathMatcherStrategy.java rename to discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/matcher/DiscoveryAntPathMatcherStrategy.java diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/matcher/DiscoveryMatcher.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/matcher/DiscoveryMatcher.java new file mode 100644 index 0000000000..bf549a4565 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/matcher/DiscoveryMatcher.java @@ -0,0 +1,57 @@ +package com.nepxion.discovery.plugin.strategy.matcher; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; + +import com.nepxion.discovery.common.util.StringUtil; + +public class DiscoveryMatcher { + @Autowired + protected DiscoveryMatcherStrategy discoveryMatcherStrategy; + + public boolean match(String targetValues, String value, boolean returnValue) { + List targetValueList = StringUtil.splitToList(targetValues); + + // 如果精确匹配不满足,尝试用通配符匹配 + if (targetValueList.contains(value)) { + return returnValue; + } + + // 通配符匹配。前者是通配表达式,后者是具体值 + for (String targetValuePattern : targetValueList) { + if (discoveryMatcherStrategy.match(targetValuePattern, value)) { + return returnValue; + } + } + + return !returnValue; + } + + public boolean matchAddress(String addresses, String host, int port, boolean returnValue) { + List addressList = StringUtil.splitToList(addresses); + + // 如果精确匹配不满足,尝试用通配符匹配 + if (addressList.contains(host + ":" + port) || addressList.contains(host) || addressList.contains(String.valueOf(port))) { + return returnValue; + } + + // 通配符匹配。前者是通配表达式,后者是具体值 + for (String addressPattern : addressList) { + if (discoveryMatcherStrategy.match(addressPattern, host + ":" + port) || discoveryMatcherStrategy.match(addressPattern, host) || discoveryMatcherStrategy.match(addressPattern, String.valueOf(port))) { + return returnValue; + } + } + + return !returnValue; + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/src/main/java/com/nepxion/discovery/plugin/strategy/matcher/DiscoveryMatcherStrategy.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/matcher/DiscoveryMatcherStrategy.java similarity index 100% rename from discovery-plugin-strategy/src/main/java/com/nepxion/discovery/plugin/strategy/matcher/DiscoveryMatcherStrategy.java rename to discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/matcher/DiscoveryMatcherStrategy.java diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/monitor/AbstractStrategyTracer.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/monitor/AbstractStrategyTracer.java new file mode 100644 index 0000000000..e440ce1269 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/monitor/AbstractStrategyTracer.java @@ -0,0 +1,289 @@ +package com.nepxion.discovery.plugin.strategy.monitor; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.List; +import java.util.Map; + +import org.apache.commons.collections4.CollectionUtils; +import org.apache.commons.collections4.MapUtils; +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; + +import com.nepxion.discovery.common.constant.DiscoveryConstant; +import com.nepxion.discovery.plugin.framework.adapter.PluginAdapter; +import com.nepxion.discovery.plugin.strategy.constant.StrategyConstant; +import com.nepxion.discovery.plugin.strategy.context.StrategyContextHolder; + +public abstract class AbstractStrategyTracer implements StrategyTracer { + @Autowired + protected PluginAdapter pluginAdapter; + + @Autowired + protected StrategyContextHolder strategyContextHolder; + + @Autowired + protected StrategyMonitorContext strategyMonitorContext; + + @Value("${" + StrategyConstant.SPRING_APPLICATION_STRATEGY_TRACER_ENABLED + ":false}") + protected Boolean tracerEnabled; + + @Value("${" + StrategyConstant.SPRING_APPLICATION_STRATEGY_TRACER_SEPARATE_SPAN_ENABLED + ":true}") + protected Boolean tracerSeparateSpanEnabled; + + @Value("${" + StrategyConstant.SPRING_APPLICATION_STRATEGY_TRACER_RULE_OUTPUT_ENABLED + ":true}") + protected Boolean tracerRuleOutputEnabled; + + @Value("${" + StrategyConstant.SPRING_APPLICATION_STRATEGY_TRACER_SPAN_VALUE + ":" + DiscoveryConstant.NEPXION_UPPERCASE + "}") + protected String tracerSpanValue; + + @Value("${" + StrategyConstant.SPRING_APPLICATION_STRATEGY_TRACER_SPAN_TAG_PLUGIN_VALUE + ":" + DiscoveryConstant.NEPXION_DISCOVERY + "}") + protected String tracerSpanPluginValue; + + @Override + public void spanBuild() { + if (!tracerEnabled) { + return; + } + + if (!tracerSeparateSpanEnabled) { + return; + } + + S span = buildSpan(); + + StrategyTracerContext.getCurrentContext().setSpan(span); + } + + @Override + public void spanOutput(Map contextMap) { + if (!tracerEnabled) { + return; + } + + S span = getCurrentSpan(); + if (span == null) { + // LOG.error("Span not found in context to trace put"); + + return; + } + + if (tracerSeparateSpanEnabled) { + outputSpan(span, DiscoveryConstant.SPAN_TAG_PLUGIN_NAME, tracerSpanPluginValue); + } + outputSpan(span, DiscoveryConstant.TRACE_ID, toTraceId(span)); + outputSpan(span, DiscoveryConstant.SPAN_ID, toSpanId(span)); + outputSpan(span, DiscoveryConstant.N_D_SERVICE_GROUP, pluginAdapter.getGroup()); + outputSpan(span, DiscoveryConstant.N_D_SERVICE_TYPE, pluginAdapter.getServiceType()); + String serviceAppId = pluginAdapter.getServiceAppId(); + if (StringUtils.isNotEmpty(serviceAppId)) { + outputSpan(span, DiscoveryConstant.N_D_SERVICE_APP_ID, serviceAppId); + } + outputSpan(span, DiscoveryConstant.N_D_SERVICE_ID, pluginAdapter.getServiceId()); + outputSpan(span, DiscoveryConstant.N_D_SERVICE_ADDRESS, pluginAdapter.getHost() + ":" + pluginAdapter.getPort()); + String version = pluginAdapter.getVersion(); + if (StringUtils.isNotEmpty(version) && !StringUtils.equals(version, DiscoveryConstant.DEFAULT)) { + outputSpan(span, DiscoveryConstant.N_D_SERVICE_VERSION, version); + } + String region = pluginAdapter.getRegion(); + if (StringUtils.isNotEmpty(region) && !StringUtils.equals(region, DiscoveryConstant.DEFAULT)) { + outputSpan(span, DiscoveryConstant.N_D_SERVICE_REGION, region); + } + String environment = pluginAdapter.getEnvironment(); + if (StringUtils.isNotEmpty(environment) && !StringUtils.equals(environment, DiscoveryConstant.DEFAULT)) { + outputSpan(span, DiscoveryConstant.N_D_SERVICE_ENVIRONMENT, environment); + } + String zone = pluginAdapter.getZone(); + if (StringUtils.isNotEmpty(zone) && !StringUtils.equals(zone, DiscoveryConstant.DEFAULT)) { + outputSpan(span, DiscoveryConstant.N_D_SERVICE_ZONE, zone); + } + + if (tracerRuleOutputEnabled) { + String routeVersion = strategyContextHolder.getHeader(DiscoveryConstant.N_D_VERSION); + if (StringUtils.isNotEmpty(routeVersion)) { + outputSpan(span, DiscoveryConstant.N_D_VERSION, routeVersion); + } + String routeRegion = strategyContextHolder.getHeader(DiscoveryConstant.N_D_REGION); + if (StringUtils.isNotEmpty(routeRegion)) { + outputSpan(span, DiscoveryConstant.N_D_REGION, routeRegion); + } + String routeEnvironment = strategyContextHolder.getHeader(DiscoveryConstant.N_D_ENVIRONMENT); + if (StringUtils.isNotEmpty(routeEnvironment)) { + outputSpan(span, DiscoveryConstant.N_D_ENVIRONMENT, routeEnvironment); + } + String routeAddress = strategyContextHolder.getHeader(DiscoveryConstant.N_D_ADDRESS); + if (StringUtils.isNotEmpty(routeAddress)) { + outputSpan(span, DiscoveryConstant.N_D_ADDRESS, routeAddress); + } + String routeVersionWeight = strategyContextHolder.getHeader(DiscoveryConstant.N_D_VERSION_WEIGHT); + if (StringUtils.isNotEmpty(routeVersionWeight)) { + outputSpan(span, DiscoveryConstant.N_D_VERSION_WEIGHT, routeVersionWeight); + } + String routeRegionWeight = strategyContextHolder.getHeader(DiscoveryConstant.N_D_REGION_WEIGHT); + if (StringUtils.isNotEmpty(routeRegionWeight)) { + outputSpan(span, DiscoveryConstant.N_D_REGION_WEIGHT, routeRegionWeight); + } + String routeVersionPrefer = strategyContextHolder.getHeader(DiscoveryConstant.N_D_VERSION_PREFER); + if (StringUtils.isNotEmpty(routeVersionPrefer)) { + outputSpan(span, DiscoveryConstant.N_D_VERSION_PREFER, routeVersionPrefer); + } + String routeVersionFailover = strategyContextHolder.getHeader(DiscoveryConstant.N_D_VERSION_FAILOVER); + if (StringUtils.isNotEmpty(routeVersionFailover)) { + outputSpan(span, DiscoveryConstant.N_D_VERSION_FAILOVER, routeVersionFailover); + } + String routeRegionTransfer = strategyContextHolder.getHeader(DiscoveryConstant.N_D_REGION_TRANSFER); + if (StringUtils.isNotEmpty(routeRegionTransfer)) { + outputSpan(span, DiscoveryConstant.N_D_REGION_TRANSFER, routeRegionTransfer); + } + String routeRegionFailover = strategyContextHolder.getHeader(DiscoveryConstant.N_D_REGION_FAILOVER); + if (StringUtils.isNotEmpty(routeRegionFailover)) { + outputSpan(span, DiscoveryConstant.N_D_REGION_FAILOVER, routeRegionFailover); + } + String routeEnvironmentFailover = strategyContextHolder.getHeader(DiscoveryConstant.N_D_ENVIRONMENT_FAILOVER); + if (StringUtils.isNotEmpty(routeEnvironmentFailover)) { + outputSpan(span, DiscoveryConstant.N_D_ENVIRONMENT_FAILOVER, routeEnvironmentFailover); + } + String routeZoneFailover = strategyContextHolder.getHeader(DiscoveryConstant.N_D_ZONE_FAILOVER); + if (StringUtils.isNotEmpty(routeZoneFailover)) { + outputSpan(span, DiscoveryConstant.N_D_ZONE_FAILOVER, routeZoneFailover); + } + String routeAddressFailover = strategyContextHolder.getHeader(DiscoveryConstant.N_D_ADDRESS_FAILOVER); + if (StringUtils.isNotEmpty(routeAddressFailover)) { + outputSpan(span, DiscoveryConstant.N_D_ADDRESS_FAILOVER, routeAddressFailover); + } + String routeIdBlacklist = strategyContextHolder.getHeader(DiscoveryConstant.N_D_ID_BLACKLIST); + if (StringUtils.isNotEmpty(routeIdBlacklist)) { + outputSpan(span, DiscoveryConstant.N_D_ID_BLACKLIST, routeIdBlacklist); + } + String routeAddressBlacklist = strategyContextHolder.getHeader(DiscoveryConstant.N_D_ADDRESS_BLACKLIST); + if (StringUtils.isNotEmpty(routeAddressBlacklist)) { + outputSpan(span, DiscoveryConstant.N_D_ADDRESS_BLACKLIST, routeAddressBlacklist); + } + } + + if (MapUtils.isNotEmpty(contextMap)) { + for (Map.Entry entry : contextMap.entrySet()) { + String key = entry.getKey(); + String value = entry.getValue(); + if (StringUtils.isNotEmpty(value)) { + outputSpan(span, key, value); + } + } + } + + List tracerInjectorHeaderNameList = strategyMonitorContext.getTracerInjectorHeaderNameList(); + if (CollectionUtils.isNotEmpty(tracerInjectorHeaderNameList)) { + for (String tracerInjectorHeaderName : tracerInjectorHeaderNameList) { + String tracerInjectorHeaderValue = strategyContextHolder.getHeader(tracerInjectorHeaderName); + if (StringUtils.isNotEmpty(tracerInjectorHeaderValue)) { + outputSpan(span, tracerInjectorHeaderName, tracerInjectorHeaderValue); + } + } + } + + Map tracerCustomizationMap = strategyMonitorContext.getTracerCustomizationMap(); + if (MapUtils.isNotEmpty(tracerCustomizationMap)) { + for (Map.Entry entry : tracerCustomizationMap.entrySet()) { + String key = entry.getKey(); + String value = entry.getValue(); + if (StringUtils.isNotEmpty(value)) { + outputSpan(span, key, value); + } + } + } + } + + @Override + public void spanError(Throwable e) { + if (!tracerEnabled) { + return; + } + + if (!tracerSeparateSpanEnabled) { + return; + } + + S span = getCurrentSpan(); + if (span == null) { + // LOG.error("Span not found in context to trace error"); + + return; + } + + errorSpan(span, e); + } + + @Override + public void spanFinish() { + if (!tracerEnabled) { + return; + } + + if (!tracerSeparateSpanEnabled) { + return; + } + + S span = getCurrentSpan(); + if (span != null) { + finishSpan(span); + } else { + // LOG.error("Span not found in context to trace clear"); + } + + StrategyTracerContext.clearCurrentContext(); + } + + @SuppressWarnings("unchecked") + private S getCurrentSpan() { + return tracerSeparateSpanEnabled ? (S) StrategyTracerContext.getCurrentContext().getSpan() : getActiveSpan(); + } + + @Override + public String getTraceId() { + if (!tracerEnabled) { + return null; + } + + S span = getCurrentSpan(); + if (span != null) { + return toTraceId(span); + } + + return null; + } + + public String getSpanId() { + if (!tracerEnabled) { + return null; + } + + S span = getCurrentSpan(); + if (span != null) { + return toSpanId(span); + } + + return null; + } + + protected abstract S buildSpan(); + + protected abstract void outputSpan(S span, String key, String value); + + protected abstract void errorSpan(S span, Throwable e); + + protected abstract void finishSpan(S span); + + protected abstract S getActiveSpan(); + + protected abstract String toTraceId(S span); + + protected abstract String toSpanId(S span); +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/monitor/DefaultStrategyAlarm.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/monitor/DefaultStrategyAlarm.java new file mode 100644 index 0000000000..a7df8c0495 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/monitor/DefaultStrategyAlarm.java @@ -0,0 +1,183 @@ +package com.nepxion.discovery.plugin.strategy.monitor; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import org.apache.commons.collections4.CollectionUtils; +import org.apache.commons.collections4.MapUtils; +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; + +import com.nepxion.discovery.common.constant.DiscoveryConstant; +import com.nepxion.discovery.plugin.framework.adapter.PluginAdapter; +import com.nepxion.discovery.plugin.framework.event.PluginPublisher; +import com.nepxion.discovery.plugin.strategy.constant.StrategyConstant; +import com.nepxion.discovery.plugin.strategy.context.StrategyContextHolder; +import com.nepxion.discovery.plugin.strategy.event.StrategyAlarmEvent; + +public class DefaultStrategyAlarm implements StrategyAlarm { + @Autowired + protected PluginAdapter pluginAdapter; + + @Autowired + protected StrategyContextHolder strategyContextHolder; + + @Autowired + protected StrategyMonitorContext strategyMonitorContext; + + @Autowired + protected PluginPublisher pluginPublisher; + + @Value("${" + StrategyConstant.SPRING_APPLICATION_STRATEGY_ALARM_ENABLED + ":false}") + protected Boolean alarmEnabled; + + @Override + public void alarm(Map contextMap) { + if (!alarmEnabled) { + return; + } + + Map alarmMap = new LinkedHashMap(); + String traceId = strategyMonitorContext.getTraceId(); + String spanId = strategyMonitorContext.getSpanId(); + if (StringUtils.isNotEmpty(traceId)) { + alarmMap.put(DiscoveryConstant.TRACE_ID, traceId); + } + if (StringUtils.isNotEmpty(spanId)) { + alarmMap.put(DiscoveryConstant.SPAN_ID, spanId); + } + alarmMap.put(DiscoveryConstant.N_D_SERVICE_GROUP, pluginAdapter.getGroup()); + alarmMap.put(DiscoveryConstant.N_D_SERVICE_TYPE, pluginAdapter.getServiceType()); + String serviceAppId = pluginAdapter.getServiceAppId(); + if (StringUtils.isNotEmpty(serviceAppId)) { + alarmMap.put(DiscoveryConstant.N_D_SERVICE_APP_ID, serviceAppId); + } + alarmMap.put(DiscoveryConstant.N_D_SERVICE_ID, pluginAdapter.getServiceId()); + alarmMap.put(DiscoveryConstant.N_D_SERVICE_ADDRESS, pluginAdapter.getHost() + ":" + pluginAdapter.getPort()); + String version = pluginAdapter.getVersion(); + if (StringUtils.isNotEmpty(version) && !StringUtils.equals(version, DiscoveryConstant.DEFAULT)) { + alarmMap.put(DiscoveryConstant.N_D_SERVICE_VERSION, version); + } + String region = pluginAdapter.getRegion(); + if (StringUtils.isNotEmpty(region) && !StringUtils.equals(region, DiscoveryConstant.DEFAULT)) { + alarmMap.put(DiscoveryConstant.N_D_SERVICE_REGION, region); + } + String environment = pluginAdapter.getEnvironment(); + if (StringUtils.isNotEmpty(environment) && !StringUtils.equals(environment, DiscoveryConstant.DEFAULT)) { + alarmMap.put(DiscoveryConstant.N_D_SERVICE_ENVIRONMENT, environment); + } + String zone = pluginAdapter.getZone(); + if (StringUtils.isNotEmpty(zone) && !StringUtils.equals(zone, DiscoveryConstant.DEFAULT)) { + alarmMap.put(DiscoveryConstant.N_D_SERVICE_ZONE, zone); + } + + String routeVersion = strategyContextHolder.getHeader(DiscoveryConstant.N_D_VERSION); + if (StringUtils.isNotEmpty(routeVersion)) { + alarmMap.put(DiscoveryConstant.N_D_VERSION, routeVersion); + } + String routeRegion = strategyContextHolder.getHeader(DiscoveryConstant.N_D_REGION); + if (StringUtils.isNotEmpty(routeRegion)) { + alarmMap.put(DiscoveryConstant.N_D_REGION, routeRegion); + } + String routeEnvironment = strategyContextHolder.getHeader(DiscoveryConstant.N_D_ENVIRONMENT); + if (StringUtils.isNotEmpty(routeEnvironment)) { + alarmMap.put(DiscoveryConstant.N_D_ENVIRONMENT, routeEnvironment); + } + String routeAddress = strategyContextHolder.getHeader(DiscoveryConstant.N_D_ADDRESS); + if (StringUtils.isNotEmpty(routeAddress)) { + alarmMap.put(DiscoveryConstant.N_D_ADDRESS, routeAddress); + } + String routeVersionWeight = strategyContextHolder.getHeader(DiscoveryConstant.N_D_VERSION_WEIGHT); + if (StringUtils.isNotEmpty(routeVersionWeight)) { + alarmMap.put(DiscoveryConstant.N_D_VERSION_WEIGHT, routeVersionWeight); + } + String routeRegionWeight = strategyContextHolder.getHeader(DiscoveryConstant.N_D_REGION_WEIGHT); + if (StringUtils.isNotEmpty(routeRegionWeight)) { + alarmMap.put(DiscoveryConstant.N_D_REGION_WEIGHT, routeRegionWeight); + } + String routeVersionPrefer = strategyContextHolder.getHeader(DiscoveryConstant.N_D_VERSION_PREFER); + if (StringUtils.isNotEmpty(routeVersionPrefer)) { + alarmMap.put(DiscoveryConstant.N_D_VERSION_PREFER, routeVersionPrefer); + } + String routeVersionFailover = strategyContextHolder.getHeader(DiscoveryConstant.N_D_VERSION_FAILOVER); + if (StringUtils.isNotEmpty(routeVersionFailover)) { + alarmMap.put(DiscoveryConstant.N_D_VERSION_FAILOVER, routeVersionFailover); + } + String routeRegionTransfer = strategyContextHolder.getHeader(DiscoveryConstant.N_D_REGION_TRANSFER); + if (StringUtils.isNotEmpty(routeRegionTransfer)) { + alarmMap.put(DiscoveryConstant.N_D_REGION_TRANSFER, routeRegionTransfer); + } + String routeRegionFailover = strategyContextHolder.getHeader(DiscoveryConstant.N_D_REGION_FAILOVER); + if (StringUtils.isNotEmpty(routeRegionFailover)) { + alarmMap.put(DiscoveryConstant.N_D_REGION_FAILOVER, routeRegionFailover); + } + String routeEnvironmentFailover = strategyContextHolder.getHeader(DiscoveryConstant.N_D_ENVIRONMENT_FAILOVER); + if (StringUtils.isNotEmpty(routeEnvironmentFailover)) { + alarmMap.put(DiscoveryConstant.N_D_ENVIRONMENT_FAILOVER, routeEnvironmentFailover); + } + String routeZoneFailover = strategyContextHolder.getHeader(DiscoveryConstant.N_D_ZONE_FAILOVER); + if (StringUtils.isNotEmpty(routeZoneFailover)) { + alarmMap.put(DiscoveryConstant.N_D_ZONE_FAILOVER, routeZoneFailover); + } + String routeAddressFailover = strategyContextHolder.getHeader(DiscoveryConstant.N_D_ADDRESS_FAILOVER); + if (StringUtils.isNotEmpty(routeAddressFailover)) { + alarmMap.put(DiscoveryConstant.N_D_ADDRESS_FAILOVER, routeAddressFailover); + } + String routeIdBlacklist = strategyContextHolder.getHeader(DiscoveryConstant.N_D_ID_BLACKLIST); + if (StringUtils.isNotEmpty(routeIdBlacklist)) { + alarmMap.put(DiscoveryConstant.N_D_ID_BLACKLIST, routeIdBlacklist); + } + String routeAddressBlacklist = strategyContextHolder.getHeader(DiscoveryConstant.N_D_ADDRESS_BLACKLIST); + if (StringUtils.isNotEmpty(routeAddressBlacklist)) { + alarmMap.put(DiscoveryConstant.N_D_ADDRESS_BLACKLIST, routeAddressBlacklist); + } + + if (MapUtils.isNotEmpty(contextMap)) { + for (Map.Entry entry : contextMap.entrySet()) { + String key = entry.getKey(); + String value = entry.getValue(); + if (StringUtils.isNotEmpty(value)) { + alarmMap.put(key, value); + } + } + } + + List tracerInjectorHeaderNameList = strategyMonitorContext.getTracerInjectorHeaderNameList(); + if (CollectionUtils.isNotEmpty(tracerInjectorHeaderNameList)) { + for (String tracerInjectorHeaderName : tracerInjectorHeaderNameList) { + String tracerInjectorHeaderValue = strategyContextHolder.getHeader(tracerInjectorHeaderName); + if (StringUtils.isNotEmpty(tracerInjectorHeaderValue)) { + alarmMap.put(tracerInjectorHeaderName, tracerInjectorHeaderValue); + } + } + } + + Map tracerCustomizationMap = strategyMonitorContext.getTracerCustomizationMap(); + if (MapUtils.isNotEmpty(tracerCustomizationMap)) { + for (Map.Entry entry : tracerCustomizationMap.entrySet()) { + String key = entry.getKey(); + String value = entry.getValue(); + if (StringUtils.isNotEmpty(value)) { + alarmMap.put(key, value); + } + } + } + + onAlarm(alarmMap); + } + + private void onAlarm(Map alarmMap) { + pluginPublisher.asyncPublish(new StrategyAlarmEvent(StrategyConstant.STRATEGY_CONTEXT_ALARM, alarmMap)); + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/monitor/DefaultStrategyLogger.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/monitor/DefaultStrategyLogger.java new file mode 100644 index 0000000000..68b8647132 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/monitor/DefaultStrategyLogger.java @@ -0,0 +1,216 @@ +package com.nepxion.discovery.plugin.strategy.monitor; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.List; + +import org.apache.commons.collections4.CollectionUtils; +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.MDC; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; + +import com.nepxion.discovery.common.constant.DiscoveryConstant; +import com.nepxion.discovery.plugin.framework.adapter.PluginAdapter; +import com.nepxion.discovery.plugin.strategy.constant.StrategyConstant; +import com.nepxion.discovery.plugin.strategy.context.StrategyContextHolder; +import com.nepxion.discovery.plugin.strategy.context.StrategyHeaderContext; + +public class DefaultStrategyLogger implements StrategyLogger { + private static final Logger LOG = LoggerFactory.getLogger(DefaultStrategyLogger.class); + + @Autowired + protected PluginAdapter pluginAdapter; + + @Autowired + protected StrategyContextHolder strategyContextHolder; + + @Autowired + protected StrategyMonitorContext strategyMonitorContext; + + @Autowired + protected StrategyHeaderContext strategyHeaderContext; + + @Value("${" + StrategyConstant.SPRING_APPLICATION_STRATEGY_LOGGER_ENABLED + ":false}") + protected Boolean loggerEnabled; + + @Value("${" + StrategyConstant.SPRING_APPLICATION_STRATEGY_LOGGER_MDC_KEY_SHOWN + ":true}") + protected Boolean loggerMdcKeyShown; + + @Value("${" + StrategyConstant.SPRING_APPLICATION_STRATEGY_LOGGER_DEBUG_ENABLED + ":false}") + protected Boolean loggerDebugEnabled; + + @Override + public void loggerOutput() { + if (!loggerEnabled) { + return; + } + + String traceId = strategyMonitorContext.getTraceId(); + String spanId = strategyMonitorContext.getSpanId(); + if (StringUtils.isNotEmpty(traceId)) { + MDC.put(DiscoveryConstant.TRACE_ID, (loggerMdcKeyShown ? DiscoveryConstant.TRACE_ID + "=" : StringUtils.EMPTY) + traceId); + } + if (StringUtils.isNotEmpty(spanId)) { + MDC.put(DiscoveryConstant.SPAN_ID, (loggerMdcKeyShown ? DiscoveryConstant.SPAN_ID + "=" : StringUtils.EMPTY) + spanId); + } + MDC.put(DiscoveryConstant.N_D_SERVICE_GROUP, (loggerMdcKeyShown ? DiscoveryConstant.N_D_SERVICE_GROUP + "=" : StringUtils.EMPTY) + pluginAdapter.getGroup()); + MDC.put(DiscoveryConstant.N_D_SERVICE_TYPE, (loggerMdcKeyShown ? DiscoveryConstant.N_D_SERVICE_TYPE + "=" : StringUtils.EMPTY) + pluginAdapter.getServiceType()); + String serviceAppId = pluginAdapter.getServiceAppId(); + if (StringUtils.isNotEmpty(serviceAppId)) { + MDC.put(DiscoveryConstant.N_D_SERVICE_APP_ID, (loggerMdcKeyShown ? DiscoveryConstant.N_D_SERVICE_APP_ID + "=" : StringUtils.EMPTY) + serviceAppId); + } + MDC.put(DiscoveryConstant.N_D_SERVICE_ID, (loggerMdcKeyShown ? DiscoveryConstant.N_D_SERVICE_ID + "=" : StringUtils.EMPTY) + pluginAdapter.getServiceId()); + MDC.put(DiscoveryConstant.N_D_SERVICE_ADDRESS, (loggerMdcKeyShown ? DiscoveryConstant.N_D_SERVICE_ADDRESS + "=" : StringUtils.EMPTY) + pluginAdapter.getHost() + ":" + pluginAdapter.getPort()); + String version = pluginAdapter.getVersion(); + if (StringUtils.isNotEmpty(version) && !StringUtils.equals(version, DiscoveryConstant.DEFAULT)) { + MDC.put(DiscoveryConstant.N_D_SERVICE_VERSION, (loggerMdcKeyShown ? DiscoveryConstant.N_D_SERVICE_VERSION + "=" : StringUtils.EMPTY) + version); + } + String region = pluginAdapter.getRegion(); + if (StringUtils.isNotEmpty(region) && !StringUtils.equals(region, DiscoveryConstant.DEFAULT)) { + MDC.put(DiscoveryConstant.N_D_SERVICE_REGION, (loggerMdcKeyShown ? DiscoveryConstant.N_D_SERVICE_REGION + "=" : StringUtils.EMPTY) + region); + } + String environment = pluginAdapter.getEnvironment(); + if (StringUtils.isNotEmpty(environment) && !StringUtils.equals(environment, DiscoveryConstant.DEFAULT)) { + MDC.put(DiscoveryConstant.N_D_SERVICE_ENVIRONMENT, (loggerMdcKeyShown ? DiscoveryConstant.N_D_SERVICE_ENVIRONMENT + "=" : StringUtils.EMPTY) + environment); + } + String zone = pluginAdapter.getZone(); + if (StringUtils.isNotEmpty(zone) && !StringUtils.equals(zone, DiscoveryConstant.DEFAULT)) { + MDC.put(DiscoveryConstant.N_D_SERVICE_ZONE, (loggerMdcKeyShown ? DiscoveryConstant.N_D_SERVICE_ZONE + "=" : StringUtils.EMPTY) + zone); + } + } + + @Override + public void loggerClear() { + if (!loggerEnabled) { + return; + } + + MDC.clear(); + } + + @Override + public void loggerDebug() { + if (!loggerDebugEnabled) { + return; + } + + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.append("\n"); + stringBuilder.append("--------------- Strategy Logger Information ----------------").append("\n"); + String traceId = strategyMonitorContext.getTraceId(); + String spanId = strategyMonitorContext.getSpanId(); + if (StringUtils.isNotEmpty(traceId)) { + stringBuilder.append(DiscoveryConstant.TRACE_ID + "=" + traceId).append("\n"); + } + if (StringUtils.isNotEmpty(spanId)) { + stringBuilder.append(DiscoveryConstant.SPAN_ID + "=" + spanId).append("\n"); + } + stringBuilder.append(DiscoveryConstant.N_D_SERVICE_GROUP + "=" + pluginAdapter.getGroup()).append("\n"); + stringBuilder.append(DiscoveryConstant.N_D_SERVICE_TYPE + "=" + pluginAdapter.getServiceType()).append("\n"); + String serviceAppId = pluginAdapter.getServiceAppId(); + if (StringUtils.isNotEmpty(serviceAppId)) { + stringBuilder.append(DiscoveryConstant.N_D_SERVICE_APP_ID + "=" + serviceAppId).append("\n"); + } + stringBuilder.append(DiscoveryConstant.N_D_SERVICE_ID + "=" + pluginAdapter.getServiceId()).append("\n"); + stringBuilder.append(DiscoveryConstant.N_D_SERVICE_ADDRESS + "=" + pluginAdapter.getHost() + ":" + pluginAdapter.getPort()).append("\n"); + String version = pluginAdapter.getVersion(); + if (StringUtils.isNotEmpty(version) && !StringUtils.equals(version, DiscoveryConstant.DEFAULT)) { + stringBuilder.append(DiscoveryConstant.N_D_SERVICE_VERSION + "=" + version).append("\n"); + } + String region = pluginAdapter.getRegion(); + if (StringUtils.isNotEmpty(region) && !StringUtils.equals(region, DiscoveryConstant.DEFAULT)) { + stringBuilder.append(DiscoveryConstant.N_D_SERVICE_REGION + "=" + region).append("\n"); + } + String environment = pluginAdapter.getEnvironment(); + if (StringUtils.isNotEmpty(environment) && !StringUtils.equals(environment, DiscoveryConstant.DEFAULT)) { + stringBuilder.append(DiscoveryConstant.N_D_SERVICE_ENVIRONMENT + "=" + environment).append("\n"); + } + String zone = pluginAdapter.getZone(); + if (StringUtils.isNotEmpty(zone) && !StringUtils.equals(zone, DiscoveryConstant.DEFAULT)) { + stringBuilder.append(DiscoveryConstant.N_D_SERVICE_ZONE + "=" + zone).append("\n"); + } + + String routeVersion = strategyContextHolder.getHeader(DiscoveryConstant.N_D_VERSION); + if (StringUtils.isNotEmpty(routeVersion)) { + stringBuilder.append(DiscoveryConstant.N_D_VERSION + "=" + routeVersion).append("\n"); + } + String routeRegion = strategyContextHolder.getHeader(DiscoveryConstant.N_D_REGION); + if (StringUtils.isNotEmpty(routeRegion)) { + stringBuilder.append(DiscoveryConstant.N_D_REGION + "=" + routeRegion).append("\n"); + } + String routeEnvironment = strategyContextHolder.getHeader(DiscoveryConstant.N_D_ENVIRONMENT); + if (StringUtils.isNotEmpty(routeEnvironment)) { + stringBuilder.append(DiscoveryConstant.N_D_ENVIRONMENT + "=" + routeEnvironment).append("\n"); + } + String routeAddress = strategyContextHolder.getHeader(DiscoveryConstant.N_D_ADDRESS); + if (StringUtils.isNotEmpty(routeAddress)) { + stringBuilder.append(DiscoveryConstant.N_D_ADDRESS + "=" + routeAddress).append("\n"); + } + String routeVersionWeight = strategyContextHolder.getHeader(DiscoveryConstant.N_D_VERSION_WEIGHT); + if (StringUtils.isNotEmpty(routeVersionWeight)) { + stringBuilder.append(DiscoveryConstant.N_D_VERSION_WEIGHT + "=" + routeVersionWeight).append("\n"); + } + String routeRegionWeight = strategyContextHolder.getHeader(DiscoveryConstant.N_D_REGION_WEIGHT); + if (StringUtils.isNotEmpty(routeRegionWeight)) { + stringBuilder.append(DiscoveryConstant.N_D_REGION_WEIGHT + "=" + routeRegionWeight).append("\n"); + } + String routeVersionPrefer = strategyContextHolder.getHeader(DiscoveryConstant.N_D_VERSION_PREFER); + if (StringUtils.isNotEmpty(routeVersionPrefer)) { + stringBuilder.append(DiscoveryConstant.N_D_VERSION_PREFER + "=" + routeVersionPrefer).append("\n"); + } + String routeVersionFailover = strategyContextHolder.getHeader(DiscoveryConstant.N_D_VERSION_FAILOVER); + if (StringUtils.isNotEmpty(routeVersionFailover)) { + stringBuilder.append(DiscoveryConstant.N_D_VERSION_FAILOVER + "=" + routeVersionFailover).append("\n"); + } + String routeRegionTransfer = strategyContextHolder.getHeader(DiscoveryConstant.N_D_REGION_TRANSFER); + if (StringUtils.isNotEmpty(routeRegionTransfer)) { + stringBuilder.append(DiscoveryConstant.N_D_REGION_TRANSFER + "=" + routeRegionTransfer).append("\n"); + } + String routeRegionFailover = strategyContextHolder.getHeader(DiscoveryConstant.N_D_REGION_FAILOVER); + if (StringUtils.isNotEmpty(routeRegionFailover)) { + stringBuilder.append(DiscoveryConstant.N_D_REGION_FAILOVER + "=" + routeRegionFailover).append("\n"); + } + String routeEnvironmentFailover = strategyContextHolder.getHeader(DiscoveryConstant.N_D_ENVIRONMENT_FAILOVER); + if (StringUtils.isNotEmpty(routeEnvironmentFailover)) { + stringBuilder.append(DiscoveryConstant.N_D_ENVIRONMENT_FAILOVER + "=" + routeEnvironmentFailover).append("\n"); + } + String routeZoneFailover = strategyContextHolder.getHeader(DiscoveryConstant.N_D_ZONE_FAILOVER); + if (StringUtils.isNotEmpty(routeZoneFailover)) { + stringBuilder.append(DiscoveryConstant.N_D_ZONE_FAILOVER + "=" + routeZoneFailover).append("\n"); + } + String routeAddressFailover = strategyContextHolder.getHeader(DiscoveryConstant.N_D_ADDRESS_FAILOVER); + if (StringUtils.isNotEmpty(routeAddressFailover)) { + stringBuilder.append(DiscoveryConstant.N_D_ADDRESS_FAILOVER + "=" + routeAddressFailover).append("\n"); + } + String routeIdBlacklist = strategyContextHolder.getHeader(DiscoveryConstant.N_D_ID_BLACKLIST); + if (StringUtils.isNotEmpty(routeIdBlacklist)) { + stringBuilder.append(DiscoveryConstant.N_D_ID_BLACKLIST + "=" + routeIdBlacklist).append("\n"); + } + String routeAddressBlacklist = strategyContextHolder.getHeader(DiscoveryConstant.N_D_ADDRESS_BLACKLIST); + if (StringUtils.isNotEmpty(routeAddressBlacklist)) { + stringBuilder.append(DiscoveryConstant.N_D_ADDRESS_BLACKLIST + "=" + routeAddressBlacklist).append("\n"); + } + + List requestHeaderNameList = strategyHeaderContext.getRequestHeaderNameList(); + if (CollectionUtils.isNotEmpty(requestHeaderNameList)) { + for (String requestHeaderName : requestHeaderNameList) { + String requestHeaderValue = strategyContextHolder.getHeader(requestHeaderName); + if (StringUtils.isNotEmpty(requestHeaderValue)) { + stringBuilder.append(requestHeaderName + "=" + requestHeaderValue).append("\n"); + } + } + } + stringBuilder.append("------------------------------------------------------------"); + LOG.info(stringBuilder.toString()); + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/monitor/StrategyAlarm.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/monitor/StrategyAlarm.java new file mode 100644 index 0000000000..c58930dfcd --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/monitor/StrategyAlarm.java @@ -0,0 +1,16 @@ +package com.nepxion.discovery.plugin.strategy.monitor; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.Map; + +public interface StrategyAlarm { + void alarm(Map contextMap); +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/monitor/StrategyLogger.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/monitor/StrategyLogger.java new file mode 100644 index 0000000000..a685fe8dfd --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/monitor/StrategyLogger.java @@ -0,0 +1,18 @@ +package com.nepxion.discovery.plugin.strategy.monitor; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +public interface StrategyLogger { + void loggerOutput(); + + void loggerClear(); + + void loggerDebug(); +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/monitor/StrategyMonitor.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/monitor/StrategyMonitor.java new file mode 100644 index 0000000000..0ca5dd083d --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/monitor/StrategyMonitor.java @@ -0,0 +1,85 @@ +package com.nepxion.discovery.plugin.strategy.monitor; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.Map; + +import org.springframework.beans.factory.annotation.Autowired; + +public class StrategyMonitor { + @Autowired(required = false) + protected StrategyLogger strategyLogger; + + @Autowired(required = false) + protected StrategyTracer strategyTracer; + + @Autowired(required = false) + protected StrategyAlarm strategyAlarm; + + public void loggerOutput() { + if (strategyLogger != null) { + strategyLogger.loggerOutput(); + } + } + + public void loggerClear() { + if (strategyLogger != null) { + strategyLogger.loggerClear(); + } + } + + public void loggerDebug() { + if (strategyLogger != null) { + strategyLogger.loggerDebug(); + } + } + + public void spanBuild() { + if (strategyTracer != null) { + strategyTracer.spanBuild(); + } + } + + public void spanOutput(Map contextMap) { + if (strategyTracer != null) { + strategyTracer.spanOutput(contextMap); + } + } + + public void spanError(Throwable e) { + if (strategyTracer != null) { + strategyTracer.spanError(e); + } + } + + public void spanFinish() { + if (strategyTracer != null) { + strategyTracer.spanFinish(); + } + } + + public void alarm(Map contextMap) { + if (strategyAlarm != null) { + strategyAlarm.alarm(contextMap); + } + } + + public StrategyLogger getStrategyLogger() { + return strategyLogger; + } + + public StrategyTracer getStrategyTracer() { + return strategyTracer; + } + + public StrategyAlarm getStrategyAlarm() { + return strategyAlarm; + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/monitor/StrategyMonitorContext.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/monitor/StrategyMonitorContext.java new file mode 100644 index 0000000000..7040436157 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/monitor/StrategyMonitorContext.java @@ -0,0 +1,76 @@ +package com.nepxion.discovery.plugin.strategy.monitor; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.List; +import java.util.Map; + +import javax.annotation.PostConstruct; + +import org.springframework.beans.factory.annotation.Autowired; + +import com.nepxion.discovery.common.entity.HeadersInjectorType; +import com.nepxion.discovery.plugin.strategy.adapter.StrategyTracerAdapter; +import com.nepxion.discovery.plugin.strategy.injector.StrategyHeadersResolver; +import com.nepxion.discovery.plugin.strategy.injector.StrategyHeadersInjector; + +public class StrategyMonitorContext { + @Autowired(required = false) + protected StrategyTracer strategyTracer; + + @Autowired(required = false) + protected StrategyTracerAdapter strategyTracerAdapter; + + @Autowired(required = false) + protected List strategyHeadersInjectorList; + + protected List tracerInjectorHeaderNameList; + + @PostConstruct + public void initialize() { + tracerInjectorHeaderNameList = StrategyHeadersResolver.getInjectedHeaders(strategyHeadersInjectorList, HeadersInjectorType.TRACER); + } + + public String getTraceId() { + if (strategyTracer != null) { + return strategyTracer.getTraceId(); + } + + if (strategyTracerAdapter != null) { + return strategyTracerAdapter.getTraceId(); + } + + return null; + } + + public String getSpanId() { + if (strategyTracer != null) { + return strategyTracer.getSpanId(); + } + + if (strategyTracerAdapter != null) { + return strategyTracerAdapter.getSpanId(); + } + + return null; + } + + public List getTracerInjectorHeaderNameList() { + return tracerInjectorHeaderNameList; + } + + public Map getTracerCustomizationMap() { + if (strategyTracerAdapter != null) { + return strategyTracerAdapter.getCustomizationMap(); + } + + return null; + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/monitor/StrategySpan.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/monitor/StrategySpan.java new file mode 100644 index 0000000000..0527558004 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/monitor/StrategySpan.java @@ -0,0 +1,55 @@ +package com.nepxion.discovery.plugin.strategy.monitor; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.io.Serializable; + +import org.apache.commons.lang3.builder.EqualsBuilder; +import org.apache.commons.lang3.builder.HashCodeBuilder; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; + +public class StrategySpan implements Serializable { + private static final long serialVersionUID = 8189198890172152392L; + + private String traceId; + private String spanId; + + public String getTraceId() { + return traceId; + } + + public void setTraceId(String traceId) { + this.traceId = traceId; + } + + public String getSpanId() { + return spanId; + } + + public void setSpanId(String spanId) { + this.spanId = spanId; + } + + @Override + public int hashCode() { + return HashCodeBuilder.reflectionHashCode(this); + } + + @Override + public boolean equals(Object object) { + return EqualsBuilder.reflectionEquals(this, object); + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/monitor/StrategyTracer.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/monitor/StrategyTracer.java new file mode 100644 index 0000000000..0b4653d5be --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/monitor/StrategyTracer.java @@ -0,0 +1,26 @@ +package com.nepxion.discovery.plugin.strategy.monitor; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.Map; + +public interface StrategyTracer { + void spanBuild(); + + void spanOutput(Map contextMap); + + void spanError(Throwable e); + + void spanFinish(); + + String getTraceId(); + + String getSpanId(); +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/monitor/StrategyTracerContext.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/monitor/StrategyTracerContext.java new file mode 100644 index 0000000000..562b14a9fe --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/monitor/StrategyTracerContext.java @@ -0,0 +1,80 @@ +package com.nepxion.discovery.plugin.strategy.monitor; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @author zifeihan + * @version 1.0 + */ + +import java.util.LinkedList; + +import org.apache.commons.lang3.builder.EqualsBuilder; +import org.apache.commons.lang3.builder.HashCodeBuilder; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; + +public class StrategyTracerContext { + private static final ThreadLocal THREAD_LOCAL = new ThreadLocal() { + @Override + protected StrategyTracerContext initialValue() { + return new StrategyTracerContext(); + } + }; + + private LinkedList spanList = new LinkedList(); + + public static StrategyTracerContext getCurrentContext() { + return THREAD_LOCAL.get(); + } + + public static void clearCurrentContext() { + StrategyTracerContext strategyTracerContext = THREAD_LOCAL.get(); + if (strategyTracerContext == null) { + return; + } + + LinkedList spanList = strategyTracerContext.getSpanList(); + if (!spanList.isEmpty()) { + spanList.removeLast(); + } + + if (spanList.isEmpty()) { + THREAD_LOCAL.remove(); + } + } + + public Object getSpan() { + if (spanList.isEmpty()) { + return null; + } + + return spanList.getLast(); + } + + public void setSpan(Object span) { + spanList.addLast(span); + } + + private LinkedList getSpanList() { + return spanList; + } + + @Override + public int hashCode() { + return HashCodeBuilder.reflectionHashCode(this); + } + + @Override + public boolean equals(Object object) { + return EqualsBuilder.reflectionEquals(this, object); + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/monitor/StrategyTracerContextListener.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/monitor/StrategyTracerContextListener.java new file mode 100644 index 0000000000..c63e014d1a --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/monitor/StrategyTracerContextListener.java @@ -0,0 +1,26 @@ +package com.nepxion.discovery.plugin.strategy.monitor; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.context.ApplicationListener; +import org.springframework.context.event.ContextRefreshedEvent; + +public class StrategyTracerContextListener implements ApplicationListener { + private static final Logger LOG = LoggerFactory.getLogger(StrategyTracerContextListener.class); + + @Override + public void onApplicationEvent(ContextRefreshedEvent event) { + // 异步调用下,第一次启动在某些情况下可能存在丢失上下文的问题 + LOG.info("Initialize Strategy Tracer Context after Application started..."); + StrategyTracerContext.getCurrentContext(); + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/src/main/java/com/nepxion/discovery/plugin/strategy/rule/DiscoveryEnabledBasePredicate.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/rule/DiscoveryEnabledBasePredicate.java similarity index 100% rename from discovery-plugin-strategy/src/main/java/com/nepxion/discovery/plugin/strategy/rule/DiscoveryEnabledBasePredicate.java rename to discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/rule/DiscoveryEnabledBasePredicate.java diff --git a/discovery-plugin-strategy/src/main/java/com/nepxion/discovery/plugin/strategy/rule/DiscoveryEnabledBaseRule.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/rule/DiscoveryEnabledBaseRule.java similarity index 100% rename from discovery-plugin-strategy/src/main/java/com/nepxion/discovery/plugin/strategy/rule/DiscoveryEnabledBaseRule.java rename to discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/rule/DiscoveryEnabledBaseRule.java diff --git a/discovery-plugin-strategy/src/main/java/com/nepxion/discovery/plugin/strategy/rule/DiscoveryEnabledZoneAvoidancePredicate.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/rule/DiscoveryEnabledZoneAvoidancePredicate.java similarity index 100% rename from discovery-plugin-strategy/src/main/java/com/nepxion/discovery/plugin/strategy/rule/DiscoveryEnabledZoneAvoidancePredicate.java rename to discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/rule/DiscoveryEnabledZoneAvoidancePredicate.java diff --git a/discovery-plugin-strategy/src/main/java/com/nepxion/discovery/plugin/strategy/rule/DiscoveryEnabledZoneAvoidanceRule.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/rule/DiscoveryEnabledZoneAvoidanceRule.java similarity index 100% rename from discovery-plugin-strategy/src/main/java/com/nepxion/discovery/plugin/strategy/rule/DiscoveryEnabledZoneAvoidanceRule.java rename to discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/rule/DiscoveryEnabledZoneAvoidanceRule.java diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/util/StrategyUtil.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/util/StrategyUtil.java new file mode 100644 index 0000000000..7eacf5f694 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/util/StrategyUtil.java @@ -0,0 +1,45 @@ +package com.nepxion.discovery.plugin.strategy.util; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.apache.commons.lang3.StringUtils; + +import com.nepxion.discovery.common.constant.DiscoveryConstant; + +public class StrategyUtil { + public static boolean isCoreHeaderContains(String headerName) { + return StringUtils.equals(headerName, DiscoveryConstant.N_D_VERSION) || + StringUtils.equals(headerName, DiscoveryConstant.N_D_REGION) || + StringUtils.equals(headerName, DiscoveryConstant.N_D_ADDRESS) || + StringUtils.equals(headerName, DiscoveryConstant.N_D_VERSION_WEIGHT) || + StringUtils.equals(headerName, DiscoveryConstant.N_D_REGION_WEIGHT) || + StringUtils.equals(headerName, DiscoveryConstant.N_D_VERSION_PREFER) || + StringUtils.equals(headerName, DiscoveryConstant.N_D_VERSION_FAILOVER) || + StringUtils.equals(headerName, DiscoveryConstant.N_D_REGION_TRANSFER) || + StringUtils.equals(headerName, DiscoveryConstant.N_D_REGION_FAILOVER) || + StringUtils.equals(headerName, DiscoveryConstant.N_D_ENVIRONMENT_FAILOVER) || + StringUtils.equals(headerName, DiscoveryConstant.N_D_ZONE_FAILOVER) || + StringUtils.equals(headerName, DiscoveryConstant.N_D_ADDRESS_FAILOVER) || + StringUtils.equals(headerName, DiscoveryConstant.N_D_ID_BLACKLIST) || + StringUtils.equals(headerName, DiscoveryConstant.N_D_ADDRESS_BLACKLIST); + } + + public static boolean isInnerHeaderContains(String headerName) { + return StringUtils.equals(headerName, DiscoveryConstant.N_D_SERVICE_GROUP) || + StringUtils.equals(headerName, DiscoveryConstant.N_D_SERVICE_TYPE) || + StringUtils.equals(headerName, DiscoveryConstant.N_D_SERVICE_APP_ID) || + StringUtils.equals(headerName, DiscoveryConstant.N_D_SERVICE_ID) || + StringUtils.equals(headerName, DiscoveryConstant.N_D_SERVICE_ADDRESS) || + StringUtils.equals(headerName, DiscoveryConstant.N_D_SERVICE_VERSION) || + StringUtils.equals(headerName, DiscoveryConstant.N_D_SERVICE_REGION) || + StringUtils.equals(headerName, DiscoveryConstant.N_D_SERVICE_ENVIRONMENT) || + StringUtils.equals(headerName, DiscoveryConstant.N_D_SERVICE_ZONE); + } +} diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/wrapper/StrategyCallableWrapper.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/wrapper/StrategyCallableWrapper.java new file mode 100644 index 0000000000..6c441a85e9 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/wrapper/StrategyCallableWrapper.java @@ -0,0 +1,17 @@ +package com.nepxion.discovery.plugin.strategy.wrapper; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @author Hao Huang + * @version 1.0 + */ + +import java.util.concurrent.Callable; + +public interface StrategyCallableWrapper { + Callable wrapCallable(Callable callable); +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/wrapper/StrategyWrapper.java b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/wrapper/StrategyWrapper.java new file mode 100644 index 0000000000..d8bcde1954 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/wrapper/StrategyWrapper.java @@ -0,0 +1,712 @@ +package com.nepxion.discovery.plugin.strategy.wrapper; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import org.apache.commons.collections4.CollectionUtils; +import org.apache.commons.collections4.MapUtils; +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.apache.commons.lang3.tuple.Pair; +import org.springframework.beans.factory.annotation.Autowired; + +import com.nepxion.discovery.common.entity.AddressWeightEntity; +import com.nepxion.discovery.common.entity.MapWeightEntity; +import com.nepxion.discovery.common.entity.RegionWeightEntity; +import com.nepxion.discovery.common.entity.RuleEntity; +import com.nepxion.discovery.common.entity.StrategyBlacklistEntity; +import com.nepxion.discovery.common.entity.StrategyConditionBlueGreenEntity; +import com.nepxion.discovery.common.entity.StrategyConditionGrayEntity; +import com.nepxion.discovery.common.entity.StrategyEntity; +import com.nepxion.discovery.common.entity.StrategyFailoverEntity; +import com.nepxion.discovery.common.entity.StrategyHeaderEntity; +import com.nepxion.discovery.common.entity.StrategyReleaseEntity; +import com.nepxion.discovery.common.entity.StrategyRouteEntity; +import com.nepxion.discovery.common.entity.StrategyRouteType; +import com.nepxion.discovery.common.entity.VersionWeightEntity; +import com.nepxion.discovery.plugin.framework.adapter.PluginAdapter; +import com.nepxion.discovery.plugin.framework.loadbalance.weight.WeightRandomProcessor; +import com.nepxion.discovery.plugin.strategy.condition.StrategyCondition; + +public class StrategyWrapper { + @Autowired + protected PluginAdapter pluginAdapter; + + @Autowired + protected StrategyCondition strategyCondition; + + @Autowired + protected WeightRandomProcessor strategyWeightRandomProcessor; + + // 从远程配置中心或者本地配置文件获取版本匹配路由配置。如果是远程配置中心,则值会动态改变 + // 返回格式允许如下一种 + // 1. Json格式,内容:服务名 -> 单个或者逗号分隔多个版本号(例如:{"a-service":"1.0", "b-service":"1.1;1.2"}) + // 2. 纯字符串格式,内容:单个或者逗号分隔多个版本号(例如:1.0;1.1;1.2) + public String getRouteVersion() { + return getRouteVersion(null); + } + + // 从远程配置中心或者本地配置文件获取区域匹配路由配置。如果是远程配置中心,则值会动态改变 + // 返回格式允许如下一种 + // 1. Json格式,内容:服务名 -> 单个或者逗号分隔多个区域值(例如:{"a-service":"dev", "b-service":"dev;qa"}) + // 2. 纯字符串格式,内容:单个或者逗号分隔多个区域值(例如:dev;qa) + public String getRouteRegion() { + return getRouteRegion(null); + } + + // 从远程配置中心或者本地配置文件获取IP地址和端口匹配路由配置。如果是远程配置中心,则值会动态改变 + // 返回格式允许如下一种 + // 1. Json格式,内容:服务名 -> 单个或者逗号分隔多个IP地址和端口(例如:{"a-service":"127.0.0.1:3001", "b-service":"4002"}) + // 2. 纯字符串格式,内容:单个或者逗号分隔多个IP地址和端口(例如:127.0.0.1:3001;4002) + public String getRouteAddress() { + return getRouteAddress(null); + } + + // 从远程配置中心或者本地配置文件获取版本权重配置。如果是远程配置中心,则值会动态改变 + // 返回格式允许如下一种 + // 1. Json格式,内容:服务名 -> 单个或者逗号分隔多个版本百分比(例如:1.0=90;1.1=10) + // 2. 纯字符串格式,内容:单个或者逗号分隔多个版本百分比(例如:1.0=90;1.1=10) + public String getRouteVersionWeight() { + return getRouteVersionWeight(null); + } + + // 从远程配置中心或者本地配置文件获取区域权重配置。如果是远程配置中心,则值会动态改变 + // 返回格式允许如下一种 + // 1. Json格式,内容:服务名 -> 单个或者逗号分隔多个区域百分比(例如:dev=85;qa=15) + // 2. 纯字符串格式,内容:单个或者逗号分隔多个区域百分比(例如:dev=85;qa=15) + public String getRouteRegionWeight() { + return getRouteRegionWeight(null); + } + + // 从远程配置中心或者本地配置文件获取版本偏好配置。如果是远程配置中心,则值会动态改变 + // 返回格式允许如下一种 + // 1. Json格式,内容:服务名 -> 单个或者逗号分隔多个版本 + // 2. 纯字符串格式,内容:单个或者逗号分隔多个版本 + public String getRouteVersionPrefer() { + RuleEntity ruleEntity = pluginAdapter.getRule(); + if (ruleEntity != null) { + StrategyFailoverEntity strategyFailoverEntity = ruleEntity.getStrategyFailoverEntity(); + if (strategyFailoverEntity != null) { + return strategyFailoverEntity.getVersionPreferValue(); + } + } + + return null; + } + + // 从远程配置中心或者本地配置文件获取版本故障转移配置。如果是远程配置中心,则值会动态改变 + // 返回格式允许如下一种 + // 1. Json格式,内容:服务名 -> 单个或者逗号分隔多个版本 + // 2. 纯字符串格式,内容:单个或者逗号分隔多个版本 + public String getRouteVersionFailover() { + RuleEntity ruleEntity = pluginAdapter.getRule(); + if (ruleEntity != null) { + StrategyFailoverEntity strategyFailoverEntity = ruleEntity.getStrategyFailoverEntity(); + if (strategyFailoverEntity != null) { + return strategyFailoverEntity.getVersionFailoverValue(); + } + } + + return null; + } + + // 从远程配置中心或者本地配置文件获取区域调试转移配置。如果是远程配置中心,则值会动态改变 + // 返回格式允许如下一种 + // 1. Json格式,内容:服务名 -> 单个或者逗号分隔多个区域 + // 2. 纯字符串格式,内容:单个或者逗号分隔多个区域 + public String getRouteRegionTransfer() { + RuleEntity ruleEntity = pluginAdapter.getRule(); + if (ruleEntity != null) { + StrategyFailoverEntity strategyFailoverEntity = ruleEntity.getStrategyFailoverEntity(); + if (strategyFailoverEntity != null) { + return strategyFailoverEntity.getRegionTransferValue(); + } + } + + return null; + } + + // 从远程配置中心或者本地配置文件获取区域故障转移配置。如果是远程配置中心,则值会动态改变 + // 返回格式允许如下一种 + // 1. Json格式,内容:服务名 -> 单个或者逗号分隔多个区域 + // 2. 纯字符串格式,内容:单个或者逗号分隔多个区域 + public String getRouteRegionFailover() { + RuleEntity ruleEntity = pluginAdapter.getRule(); + if (ruleEntity != null) { + StrategyFailoverEntity strategyFailoverEntity = ruleEntity.getStrategyFailoverEntity(); + if (strategyFailoverEntity != null) { + return strategyFailoverEntity.getRegionFailoverValue(); + } + } + + return null; + } + + // 从远程配置中心或者本地配置文件获取环境故障转移配置。如果是远程配置中心,则值会动态改变 + // 返回格式允许如下一种 + // 1. Json格式,内容:服务名 -> 单个或者逗号分隔多个环境 + // 2. 纯字符串格式,内容:单个或者逗号分隔多个环境 + public String getRouteEnvironmentFailover() { + RuleEntity ruleEntity = pluginAdapter.getRule(); + if (ruleEntity != null) { + StrategyFailoverEntity strategyFailoverEntity = ruleEntity.getStrategyFailoverEntity(); + if (strategyFailoverEntity != null) { + return strategyFailoverEntity.getEnvironmentFailoverValue(); + } + } + + return null; + } + + // 从远程配置中心或者本地配置文件获取可用区故障转移配置。如果是远程配置中心,则值会动态改变 + // 返回格式允许如下一种 + // 1. Json格式,内容:服务名 -> 单个或者逗号分隔多个可用区 + // 2. 纯字符串格式,内容:单个或者逗号分隔多个可用区 + public String getRouteZoneFailover() { + RuleEntity ruleEntity = pluginAdapter.getRule(); + if (ruleEntity != null) { + StrategyFailoverEntity strategyFailoverEntity = ruleEntity.getStrategyFailoverEntity(); + if (strategyFailoverEntity != null) { + return strategyFailoverEntity.getZoneFailoverValue(); + } + } + + return null; + } + + // 从远程配置中心或者本地配置文件获取IP地址和端口故障转移配置。如果是远程配置中心,则值会动态改变 + // 返回格式允许如下一种 + // 1. Json格式,内容:服务名 -> 单个或者逗号分隔多个IP地址和端口(例如:{"a-service":"127.0.0.1:3001", "b-service":"4002"}) + // 2. 纯字符串格式,内容:单个或者逗号分隔多个IP地址和端口(例如:127.0.0.1:3001;4002) + public String getRouteAddressFailover() { + RuleEntity ruleEntity = pluginAdapter.getRule(); + if (ruleEntity != null) { + StrategyFailoverEntity strategyFailoverEntity = ruleEntity.getStrategyFailoverEntity(); + if (strategyFailoverEntity != null) { + return strategyFailoverEntity.getAddressFailoverValue(); + } + } + + return null; + } + + // 从远程配置中心或者本地配置文件获取全局唯一ID黑名单屏蔽配置。如果是远程配置中心,则值会动态改变 + // 返回格式允许如下一种 + // 1. Json格式,内容:服务名 -> 单个或者逗号分隔多个全局唯一ID + // 2. 纯字符串格式,内容:单个或者逗号分隔多个全局唯一ID + public String getRouteIdBlacklist() { + RuleEntity ruleEntity = pluginAdapter.getRule(); + if (ruleEntity != null) { + StrategyBlacklistEntity strategyBlacklistEntity = ruleEntity.getStrategyBlacklistEntity(); + if (strategyBlacklistEntity != null) { + return strategyBlacklistEntity.getIdValue(); + } + } + + return null; + } + + // 从远程配置中心或者本地配置文件获取IP地址和端口黑名单屏蔽配置。如果是远程配置中心,则值会动态改变 + // 返回格式允许如下一种 + // 1. Json格式,内容:服务名 -> 单个或者逗号分隔多个IP地址和端口 + // 2. 纯字符串格式,内容:单个或者逗号分隔多个IP地址和端口 + public String getRouteAddressBlacklist() { + RuleEntity ruleEntity = pluginAdapter.getRule(); + if (ruleEntity != null) { + StrategyBlacklistEntity strategyBlacklistEntity = ruleEntity.getStrategyBlacklistEntity(); + if (strategyBlacklistEntity != null) { + return strategyBlacklistEntity.getAddressValue(); + } + } + + return null; + } + + // 从远程配置中心或者本地配置文件获取版本匹配路由配置。如果是远程配置中心,则值会动态改变 + // Map值为如下一种 + // 1. Header + // 2. Parameter + // 3. Cookie + // 执行优先级为 + // 1. 蓝绿路由配置 + // 2. 灰度路由配置 + // 3. 全局兜底路由配置 + public String getRouteVersion(Map map) { + String routeVersion = getConditionBlueGreenRouteVersion(map); + if (StringUtils.isEmpty(routeVersion)) { + routeVersion = getConditionGrayRouteVersion(map); + if (StringUtils.isEmpty(routeVersion)) { + routeVersion = getGlobalRouteVersion(); + } + } + + return routeVersion; + } + + // 从远程配置中心或者本地配置文件获取区域匹配路由配置。如果是远程配置中心,则值会动态改变 + // Map值为如下一种 + // 1. Header + // 2. Parameter + // 3. Cookie + // 执行优先级为 + // 1. 蓝绿路由配置 + // 2. 灰度路由配置 + // 3. 全局缺省路由配置 + public String getRouteRegion(Map map) { + String routeRegion = getConditionBlueGreenRouteRegion(map); + if (StringUtils.isEmpty(routeRegion)) { + routeRegion = getConditionGrayRouteRegion(map); + if (StringUtils.isEmpty(routeRegion)) { + routeRegion = getGlobalRouteRegion(); + } + } + + return routeRegion; + } + + // 从远程配置中心或者本地配置文件获取IP地址和端口匹配路由配置。如果是远程配置中心,则值会动态改变 + // Map值为如下一种 + // 1. Header + // 2. Parameter + // 3. Cookie + // 执行优先级为 + // 1. 蓝绿路由配置 + // 2. 灰度路由配置 + // 3. 全局缺省路由配置 + public String getRouteAddress(Map map) { + String routeAddress = getConditionBlueGreenRouteAddress(map); + if (StringUtils.isEmpty(routeAddress)) { + routeAddress = getConditionGrayRouteAddress(map); + if (StringUtils.isEmpty(routeAddress)) { + routeAddress = getGlobalRouteAddress(); + } + } + + return routeAddress; + } + + // 从远程配置中心或者本地配置文件获取版本权重路由配置。如果是远程配置中心,则值会动态改变 + // Map值为如下一种 + // 1. Header + // 2. Parameter + // 3. Cookie + // 执行优先级为 + // 1. 蓝绿路由配置 + // 2. 全局缺省路由配置 + public String getRouteVersionWeight(Map map) { + String routeVersionWeight = getConditionBlueGreenRouteVersionWeight(map); + if (StringUtils.isEmpty(routeVersionWeight)) { + routeVersionWeight = getGlobalRouteVersionWeight(); + } + + return routeVersionWeight; + } + + // 从远程配置中心或者本地配置文件获取区域权重路由配置。如果是远程配置中心,则值会动态改变 + // Map值为如下一种 + // 1. Header + // 2. Parameter + // 3. Cookie + // 执行优先级为 + // 1. 蓝绿路由配置 + // 2. 全局缺省路由配置 + public String getRouteRegionWeight(Map map) { + String routeRegionWeight = getConditionBlueGreenRouteRegionWeight(map); + if (StringUtils.isEmpty(routeRegionWeight)) { + routeRegionWeight = getGlobalRouteRegionWeight(); + } + + return routeRegionWeight; + } + + // 获取全局版本匹配路由配置 + public String getGlobalRouteVersion() { + RuleEntity ruleEntity = pluginAdapter.getRule(); + if (ruleEntity != null) { + StrategyEntity strategyEntity = ruleEntity.getStrategyEntity(); + if (strategyEntity != null) { + return strategyEntity.getVersionValue(); + } + } + + return null; + } + + // 获取全局区域匹配路由配置 + public String getGlobalRouteRegion() { + RuleEntity ruleEntity = pluginAdapter.getRule(); + if (ruleEntity != null) { + StrategyEntity strategyEntity = ruleEntity.getStrategyEntity(); + if (strategyEntity != null) { + return strategyEntity.getRegionValue(); + } + } + + return null; + } + + // 获取全局IP地址和端口匹配路由配置 + public String getGlobalRouteAddress() { + RuleEntity ruleEntity = pluginAdapter.getRule(); + if (ruleEntity != null) { + StrategyEntity strategyEntity = ruleEntity.getStrategyEntity(); + if (strategyEntity != null) { + return strategyEntity.getAddressValue(); + } + } + + return null; + } + + // 获取全局版本权重路由配置 + public String getGlobalRouteVersionWeight() { + RuleEntity ruleEntity = pluginAdapter.getRule(); + if (ruleEntity != null) { + StrategyEntity strategyEntity = ruleEntity.getStrategyEntity(); + if (strategyEntity != null) { + return strategyEntity.getVersionWeightValue(); + } + } + + return null; + } + + // 获取全局区域权重路由配置 + public String getGlobalRouteRegionWeight() { + RuleEntity ruleEntity = pluginAdapter.getRule(); + if (ruleEntity != null) { + StrategyEntity strategyEntity = ruleEntity.getStrategyEntity(); + if (strategyEntity != null) { + return strategyEntity.getRegionWeightValue(); + } + } + + return null; + } + + // 获取条件驱动下,版本匹配路由的蓝绿配置 + public String getConditionBlueGreenRouteVersion(Map map) { + StrategyConditionBlueGreenEntity strategyConditionBlueGreenEntity = getTriggeredStrategyConditionBlueGreenEntity(StrategyRouteType.VERSION, map); + if (strategyConditionBlueGreenEntity != null) { + String versionId = strategyConditionBlueGreenEntity.getVersionId(); + StrategyRouteEntity strategyRouteEntity = getTriggeredStrategyRouteEntity(versionId, StrategyRouteType.VERSION); + if (strategyRouteEntity != null) { + return strategyRouteEntity.getValue(); + } + } + + return null; + } + + // 获取条件驱动下,区域匹配路由的蓝绿配置 + public String getConditionBlueGreenRouteRegion(Map map) { + StrategyConditionBlueGreenEntity strategyConditionBlueGreenEntity = getTriggeredStrategyConditionBlueGreenEntity(StrategyRouteType.REGION, map); + if (strategyConditionBlueGreenEntity != null) { + String regionId = strategyConditionBlueGreenEntity.getRegionId(); + StrategyRouteEntity strategyRouteEntity = getTriggeredStrategyRouteEntity(regionId, StrategyRouteType.REGION); + if (strategyRouteEntity != null) { + return strategyRouteEntity.getValue(); + } + } + + return null; + } + + // 获取条件驱动下,IP地址和端口匹配路由的蓝绿配置 + public String getConditionBlueGreenRouteAddress(Map map) { + StrategyConditionBlueGreenEntity strategyConditionBlueGreenEntity = getTriggeredStrategyConditionBlueGreenEntity(StrategyRouteType.ADDRESS, map); + if (strategyConditionBlueGreenEntity != null) { + String addressId = strategyConditionBlueGreenEntity.getAddressId(); + StrategyRouteEntity strategyRouteEntity = getTriggeredStrategyRouteEntity(addressId, StrategyRouteType.ADDRESS); + if (strategyRouteEntity != null) { + return strategyRouteEntity.getValue(); + } + } + + return null; + } + + // 获取条件驱动下,版本权重路由的蓝绿配置 + public String getConditionBlueGreenRouteVersionWeight(Map map) { + StrategyConditionBlueGreenEntity strategyConditionBlueGreenEntity = getTriggeredStrategyConditionBlueGreenEntity(StrategyRouteType.VERSION_WEIGHT, map); + if (strategyConditionBlueGreenEntity != null) { + String versionWeightId = strategyConditionBlueGreenEntity.getVersionWeightId(); + StrategyRouteEntity strategyRouteEntity = getTriggeredStrategyRouteEntity(versionWeightId, StrategyRouteType.VERSION_WEIGHT); + if (strategyRouteEntity != null) { + return strategyRouteEntity.getValue(); + } + } + + return null; + } + + // 获取条件驱动下,区域权重路由的蓝绿配置 + public String getConditionBlueGreenRouteRegionWeight(Map map) { + StrategyConditionBlueGreenEntity strategyConditionBlueGreenEntity = getTriggeredStrategyConditionBlueGreenEntity(StrategyRouteType.REGION_WEIGHT, map); + if (strategyConditionBlueGreenEntity != null) { + String regionWeightId = strategyConditionBlueGreenEntity.getRegionWeightId(); + StrategyRouteEntity strategyRouteEntity = getTriggeredStrategyRouteEntity(regionWeightId, StrategyRouteType.REGION_WEIGHT); + if (strategyRouteEntity != null) { + return strategyRouteEntity.getValue(); + } + } + + return null; + } + + // 获取被条件命中的蓝绿条件对象 + private StrategyConditionBlueGreenEntity getTriggeredStrategyConditionBlueGreenEntity(StrategyRouteType strategyRouteType, Map map) { + RuleEntity ruleEntity = pluginAdapter.getRule(); + if (ruleEntity != null) { + StrategyReleaseEntity strategyReleaseEntity = ruleEntity.getStrategyReleaseEntity(); + if (strategyReleaseEntity != null) { + List strategyConditionBlueGreenEntityList = strategyReleaseEntity.getStrategyConditionBlueGreenEntityList(); + if (CollectionUtils.isNotEmpty(strategyConditionBlueGreenEntityList)) { + StrategyConditionBlueGreenEntity expressionStrategyConditionBlueGreenEntity = getTriggeredExpressionStrategyConditionBlueGreenEntity(strategyConditionBlueGreenEntityList, strategyRouteType, map); + if (expressionStrategyConditionBlueGreenEntity != null) { + return expressionStrategyConditionBlueGreenEntity; + } else { + StrategyConditionBlueGreenEntity globalStrategyConditionBlueGreenEntity = getTriggeredGlobalStrategyConditionBlueGreenyEntity(strategyConditionBlueGreenEntityList, strategyRouteType); + if (globalStrategyConditionBlueGreenEntity != null) { + return globalStrategyConditionBlueGreenEntity; + } + } + } + } + } + + return null; + } + + // 获取被条件命中的蓝绿条件对象 + private StrategyConditionBlueGreenEntity getTriggeredExpressionStrategyConditionBlueGreenEntity(List strategyConditionBlueGreenEntityList, StrategyRouteType strategyRouteType, Map map) { + for (StrategyConditionBlueGreenEntity strategyConditionBlueGreenEntity : strategyConditionBlueGreenEntityList) { + boolean isValidated = validateBlueGreenStrategyType(strategyConditionBlueGreenEntity, strategyRouteType); + if (isValidated) { + boolean isTriggered = false; + if (map == null) { + isTriggered = strategyCondition.isTriggered(strategyConditionBlueGreenEntity); + } else { + isTriggered = strategyCondition.isTriggered(strategyConditionBlueGreenEntity, map); + } + if (isTriggered) { + return strategyConditionBlueGreenEntity; + } + } + } + + return null; + } + + // 获取不带有条件设置的蓝绿条件对象 + // 蓝绿条件驱动允许缺省 + private StrategyConditionBlueGreenEntity getTriggeredGlobalStrategyConditionBlueGreenyEntity(List strategyConditionBlueGreenEntityList, StrategyRouteType strategyRouteType) { + for (StrategyConditionBlueGreenEntity strategyConditionBlueGreenEntity : strategyConditionBlueGreenEntityList) { + boolean isValidated = validateBlueGreenStrategyType(strategyConditionBlueGreenEntity, strategyRouteType); + if (isValidated) { + String expression = strategyConditionBlueGreenEntity.getExpression(); + if (StringUtils.isEmpty(expression)) { + return strategyConditionBlueGreenEntity; + } + } + } + + return null; + } + + // 校验蓝绿路由的类型 + private boolean validateBlueGreenStrategyType(StrategyConditionBlueGreenEntity strategyConditionBlueGreenEntity, StrategyRouteType strategyRouteType) { + switch (strategyRouteType) { + case VERSION: + return StringUtils.isNotEmpty(strategyConditionBlueGreenEntity.getVersionId()); + case REGION: + return StringUtils.isNotEmpty(strategyConditionBlueGreenEntity.getRegionId()); + case ADDRESS: + return StringUtils.isNotEmpty(strategyConditionBlueGreenEntity.getAddressId()); + case VERSION_WEIGHT: + return StringUtils.isNotEmpty(strategyConditionBlueGreenEntity.getVersionWeightId()); + case REGION_WEIGHT: + return StringUtils.isNotEmpty(strategyConditionBlueGreenEntity.getRegionWeightId()); + case ID_BLACKLIST: + break; + case ADDRESS_BLACKLIST: + break; + } + + return false; + } + + // 获取条件驱动下,版本权重路由的灰度配置 + public String getConditionGrayRouteVersion(Map map) { + StrategyConditionGrayEntity strategyConditionGrayEntity = getTriggeredStrategyConditionGrayEntity(map); + if (strategyConditionGrayEntity != null) { + VersionWeightEntity versionWeightEntity = strategyConditionGrayEntity.getVersionWeightEntity(); + if (versionWeightEntity != null) { + return getTriggeredStrategyGrayRoute(versionWeightEntity, StrategyRouteType.VERSION); + } + } + + return null; + } + + // 获取条件驱动下,区域权重路由的灰度配置 + public String getConditionGrayRouteRegion(Map map) { + StrategyConditionGrayEntity strategyConditionGrayEntity = getTriggeredStrategyConditionGrayEntity(map); + if (strategyConditionGrayEntity != null) { + RegionWeightEntity regionWeightEntity = strategyConditionGrayEntity.getRegionWeightEntity(); + if (regionWeightEntity != null) { + return getTriggeredStrategyGrayRoute(regionWeightEntity, StrategyRouteType.REGION); + } + } + + return null; + } + + // 获取条件驱动下,IP地址和端口权重路由的灰度配置 + public String getConditionGrayRouteAddress(Map map) { + StrategyConditionGrayEntity strategyConditionGrayEntity = getTriggeredStrategyConditionGrayEntity(map); + if (strategyConditionGrayEntity != null) { + AddressWeightEntity addressWeightEntity = strategyConditionGrayEntity.getAddressWeightEntity(); + if (addressWeightEntity != null) { + return getTriggeredStrategyGrayRoute(addressWeightEntity, StrategyRouteType.ADDRESS); + } + } + + return null; + } + + // 命中灰度条件 + private StrategyConditionGrayEntity getTriggeredStrategyConditionGrayEntity(Map map) { + RuleEntity ruleEntity = pluginAdapter.getRule(); + if (ruleEntity != null) { + StrategyReleaseEntity strategyReleaseEntity = ruleEntity.getStrategyReleaseEntity(); + if (strategyReleaseEntity != null) { + List strategyConditionGrayEntityList = strategyReleaseEntity.getStrategyConditionGrayEntityList(); + if (CollectionUtils.isNotEmpty(strategyConditionGrayEntityList)) { + StrategyConditionGrayEntity expressionStrategyConditionGrayEntity = getTriggeredExpressionStrategyConditionGrayEntity(strategyConditionGrayEntityList, map); + if (expressionStrategyConditionGrayEntity != null) { + return expressionStrategyConditionGrayEntity; + } else { + StrategyConditionGrayEntity globalStrategyConditionGrayEntity = getTriggeredGlobalStrategyConditionGrayEntity(strategyConditionGrayEntityList); + if (globalStrategyConditionGrayEntity != null) { + return globalStrategyConditionGrayEntity; + } + } + } + } + } + + return null; + } + + // 获取被条件命中的灰度条件对象 + private StrategyConditionGrayEntity getTriggeredExpressionStrategyConditionGrayEntity(List strategyConditionGrayEntityList, Map map) { + for (StrategyConditionGrayEntity strategyConditionGrayEntity : strategyConditionGrayEntityList) { + boolean isTriggered = false; + if (map == null) { + isTriggered = strategyCondition.isTriggered(strategyConditionGrayEntity); + } else { + isTriggered = strategyCondition.isTriggered(strategyConditionGrayEntity, map); + } + if (isTriggered) { + return strategyConditionGrayEntity; + } + } + + return null; + } + + // 获取不带有条件设置的灰度条件对象 + // 灰度条件驱动允许缺省 + private StrategyConditionGrayEntity getTriggeredGlobalStrategyConditionGrayEntity(List strategyConditionGrayEntityList) { + for (StrategyConditionGrayEntity strategyConditionGrayEntity : strategyConditionGrayEntityList) { + String expression = strategyConditionGrayEntity.getExpression(); + if (StringUtils.isEmpty(expression)) { + return strategyConditionGrayEntity; + } + } + + return null; + } + + // 获取被条件命中的灰度路由 + private String getTriggeredStrategyGrayRoute(MapWeightEntity mapWeightEntity, StrategyRouteType strategyRouteType) { + Map weightMap = mapWeightEntity.getWeightMap(); + if (MapUtils.isEmpty(weightMap)) { + return null; + } + + List> weightList = new ArrayList>(); + for (Map.Entry entry : weightMap.entrySet()) { + String id = entry.getKey(); + StrategyRouteEntity strategyRouteEntity = getTriggeredStrategyRouteEntity(id, strategyRouteType); + if (strategyRouteEntity != null) { + String strategyRoute = strategyRouteEntity.getValue(); + Integer weight = Integer.valueOf(entry.getValue()); + weightList.add(new ImmutablePair(strategyRoute, weight)); + } + } + + return strategyWeightRandomProcessor.random(weightList); + } + + // 根据路由ID和路由类型查询相关的路由对象 + private StrategyRouteEntity getTriggeredStrategyRouteEntity(String id, StrategyRouteType strategyRouteType) { + if (StringUtils.isEmpty(id)) { + return null; + } + + RuleEntity ruleEntity = pluginAdapter.getRule(); + if (ruleEntity != null) { + StrategyReleaseEntity strategyReleaseEntity = ruleEntity.getStrategyReleaseEntity(); + if (strategyReleaseEntity != null) { + List strategyRouteEntityList = strategyReleaseEntity.getStrategyRouteEntityList(); + if (CollectionUtils.isNotEmpty(strategyRouteEntityList)) { + for (StrategyRouteEntity strategyRouteEntity : strategyRouteEntityList) { + if (StringUtils.equals(strategyRouteEntity.getId(), id) && strategyRouteEntity.getType() == strategyRouteType) { + return strategyRouteEntity; + } + } + } + } + } + + return null; + } + + // 获取内置Header Map + public Map getHeaderMap() { + RuleEntity ruleEntity = pluginAdapter.getRule(); + if (ruleEntity != null) { + StrategyReleaseEntity strategyReleaseEntity = ruleEntity.getStrategyReleaseEntity(); + if (strategyReleaseEntity != null) { + StrategyHeaderEntity strategyHeaderEntity = strategyReleaseEntity.getStrategyHeaderEntity(); + if (strategyHeaderEntity != null) { + return strategyHeaderEntity.getHeaderMap(); + } + } + } + + return null; + } + + // 获取内置Header + public String getHeader(String name) { + Map headerMap = getHeaderMap(); + if (MapUtils.isNotEmpty(headerMap)) { + return headerMap.get(name); + } + + return null; + } +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/resources/META-INF/additional-spring-configuration-metadata.json b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/resources/META-INF/additional-spring-configuration-metadata.json new file mode 100644 index 0000000000..9d3aa2db57 --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/resources/META-INF/additional-spring-configuration-metadata.json @@ -0,0 +1,212 @@ +{ + "properties": [ + { + "name": "spring.application.strategy.zone.avoidance.rule.enabled", + "type": "java.lang.Boolean", + "defaultValue": true, + "description": "Whether strategy zone avoidance rul is enabled." + }, + { + "name": "spring.application.strategy.hystrix.threadlocal.supported", + "type": "java.lang.Boolean", + "defaultValue": false, + "description": "Whether strategy hystrix threadlocal supported is enabled." + }, + { + "name": "spring.application.strategy.consumer.isolation.enabled", + "type": "java.lang.Boolean", + "defaultValue": false, + "description": "Whether strategy consumer isolation is enabled." + }, + { + "name": "spring.application.strategy.provider.isolation.enabled", + "type": "java.lang.Boolean", + "defaultValue": false, + "description": "Whether strategy provider isolation is enabled." + }, + { + "name": "spring.application.strategy.address.failover.enabled", + "type": "java.lang.Boolean", + "defaultValue": false, + "description": "Whether strategy address failover is enabled." + }, + { + "name": "spring.application.strategy.environment.failover.enabled", + "type": "java.lang.Boolean", + "defaultValue": false, + "description": "Whether strategy environment failover is enabled." + }, + { + "name": "spring.application.strategy.zone.affinity.enabled", + "type": "java.lang.Boolean", + "defaultValue": false, + "description": "Whether strategy zone affinity is enabled." + }, + { + "name": "spring.application.strategy.zone.failover.enabled", + "type": "java.lang.Boolean", + "defaultValue": false, + "description": "Whether strategy zone failover is enabled." + }, + { + "name": "spring.application.strategy.region.transfer.enabled", + "type": "java.lang.Boolean", + "defaultValue": false, + "description": "Whether strategy region transfer is enabled." + }, + { + "name": "spring.application.strategy.region.failover.enabled", + "type": "java.lang.Boolean", + "defaultValue": false, + "description": "Whether strategy region failover is enabled." + }, + { + "name": "spring.application.strategy.version.failover.enabled", + "type": "java.lang.Boolean", + "defaultValue": false, + "description": "Whether strategy version failover is enabled." + }, + { + "name": "spring.application.strategy.version.failover.stable.enabled", + "type": "java.lang.Boolean", + "defaultValue": false, + "description": "Whether strategy version failover for stable instances is enabled." + }, + { + "name": "spring.application.strategy.version.prefer.enabled", + "type": "java.lang.Boolean", + "defaultValue": false, + "description": "Whether strategy version prefer is enabled." + }, + { + "name": "spring.application.strategy.version.sort.type", + "type": "java.lang.String", + "defaultValue": "version", + "description": "Strategy version sort type, it can be version or time." + }, + { + "name": "spring.application.strategy.rest.intercept.enabled", + "type": "java.lang.Boolean", + "defaultValue": true, + "description": "Whether strategy rest intercept is enabled." + }, + { + "name": "spring.application.strategy.rest.intercept.debug.enabled", + "type": "java.lang.Boolean", + "defaultValue": false, + "description": "Whether strategy rest intercept debug is enabled." + }, + { + "name": "spring.application.strategy.feign.core.header.transmission.enabled", + "type": "java.lang.Boolean", + "defaultValue": true, + "description": "Whether strategy feign core header transmission is enabled." + }, + { + "name": "spring.application.strategy.rest.template.core.header.transmission.enabled", + "type": "java.lang.Boolean", + "defaultValue": true, + "description": "Whether strategy rest template core header transmission is enabled." + }, + { + "name": "spring.application.strategy.web.client.core.header.transmission.enabled", + "type": "java.lang.Boolean", + "defaultValue": true, + "description": "Whether strategy web client core header transmission is enabled." + }, + { + "name": "spring.application.strategy.context.request.headers", + "type": "java.lang.String", + "description": "Strategy context request headers." + }, + { + "name": "spring.application.strategy.business.request.headers", + "type": "java.lang.String", + "description": "Strategy business request headers." + }, + { + "name": "spring.application.strategy.monitor.enabled", + "type": "java.lang.Boolean", + "defaultValue": false, + "description": "Whether strategy monitor is enabled. If disabled, tracer and logger are all disabled" + }, + { + "name": "spring.application.strategy.logger.enabled", + "type": "java.lang.Boolean", + "defaultValue": false, + "description": "Whether strategy logger is enabled." + }, + { + "name": "spring.application.strategy.logger.mdc.key.shown", + "type": "java.lang.Boolean", + "defaultValue": true, + "description": "Whether strategy logger mdc key is shown." + }, + { + "name": "spring.application.strategy.logger.debug.enabled", + "type": "java.lang.Boolean", + "defaultValue": false, + "description": "Whether strategy logger debug is enabled." + }, + { + "name": "spring.application.strategy.tracer.enabled", + "type": "java.lang.Boolean", + "defaultValue": false, + "description": "Whether strategy tracer is enabled." + }, + { + "name": "spring.application.strategy.tracer.separate.span.enabled", + "type": "java.lang.Boolean", + "defaultValue": true, + "description": "Whether strategy tracer separate span is enabled." + }, + { + "name": "spring.application.strategy.tracer.rule.output.enabled", + "type": "java.lang.Boolean", + "defaultValue": true, + "description": "Whether strategy tracer rule output is enabled." + }, + { + "name": "spring.application.strategy.tracer.exception.detail.output.enabled", + "type": "java.lang.Boolean", + "defaultValue": false, + "description": "Whether strategy tracer exception detail output is enabled." + }, + { + "name": "spring.application.strategy.tracer.method.context.output.enabled", + "type": "java.lang.Boolean", + "defaultValue": false, + "description": "Whether strategy tracer method context output is enabled." + }, + { + "name": "spring.application.strategy.tracer.span.value", + "type": "java.lang.String", + "defaultValue": "NEPXION", + "description": "Strategy tracer span value." + }, + { + "name": "spring.application.strategy.tracer.span.tag.plugin.value", + "type": "java.lang.String", + "defaultValue": "Nepxion Discovery", + "description": "Strategy tracer span tag plugin value." + }, + { + "name": "spring.application.strategy.alarm.enabled", + "type": "java.lang.Boolean", + "defaultValue": false, + "description": "Whether strategy alarm is enabled." + }, + { + "name": "spring.application.strategy.auto.scan.packages.enabled", + "type": "java.lang.Boolean", + "defaultValue": true, + "description": "Whether strategy auto scan packages is enabled." + }, + { + "name": "spring.application.strategy.auto.scan.recursion.enabled", + "type": "java.lang.Boolean", + "defaultValue": false, + "description": "Whether strategy auto scan recursion is enabled." + } + ] +} \ No newline at end of file diff --git a/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/resources/META-INF/spring.factories b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/resources/META-INF/spring.factories new file mode 100644 index 0000000000..3a4fbaacaf --- /dev/null +++ b/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/resources/META-INF/spring.factories @@ -0,0 +1,5 @@ +org.springframework.boot.env.EnvironmentPostProcessor=\ +com.nepxion.discovery.plugin.strategy.context.StrategyEnvironmentPostProcessor + +org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ +com.nepxion.discovery.plugin.strategy.configuration.StrategyAutoConfiguration \ No newline at end of file diff --git a/discovery-plugin-strategy/pom.xml b/discovery-plugin-strategy/pom.xml index a208228439..6c370041dc 100644 --- a/discovery-plugin-strategy/pom.xml +++ b/discovery-plugin-strategy/pom.xml @@ -3,21 +3,32 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> discovery-plugin-strategy Nepxion Discovery Plugin Strategy - jar + pom 4.0.0 - Nepxion Discovery is an enhancement for Spring Cloud Discovery + Nepxion Discovery is a solution for Spring Cloud with blue green, gray, weight, limitation, circuit breaker, degrade, isolation, monitor, tracing, dye, failover, async agent http://www.nepxion.com com.nepxion discovery - 5.2.0-SNAPSHOT + 6.23.0 - - - ${project.groupId} - discovery-plugin-framework - - + + discovery-plugin-strategy-starter + discovery-plugin-strategy-starter-service + discovery-plugin-strategy-starter-zuul + discovery-plugin-strategy-starter-gateway + discovery-plugin-strategy-starter-hystrix + discovery-plugin-strategy-starter-opentelemetry + discovery-plugin-strategy-starter-opentracing + discovery-plugin-strategy-starter-skywalking + discovery-plugin-strategy-starter-sentinel-datasource + discovery-plugin-strategy-starter-sentinel-limiter + discovery-plugin-strategy-starter-sentinel-monitor + discovery-plugin-strategy-starter-sentinel-opentelemetry + discovery-plugin-strategy-starter-sentinel-opentracing + discovery-plugin-strategy-starter-sentinel-skywalking + discovery-plugin-strategy-starter-sentinel-micrometer + \ No newline at end of file diff --git a/discovery-plugin-strategy/src/main/java/com/nepxion/discovery/plugin/strategy/adapter/DefaultDiscoveryEnabledAdapter.java b/discovery-plugin-strategy/src/main/java/com/nepxion/discovery/plugin/strategy/adapter/DefaultDiscoveryEnabledAdapter.java deleted file mode 100644 index 0fcc9675d5..0000000000 --- a/discovery-plugin-strategy/src/main/java/com/nepxion/discovery/plugin/strategy/adapter/DefaultDiscoveryEnabledAdapter.java +++ /dev/null @@ -1,228 +0,0 @@ -package com.nepxion.discovery.plugin.strategy.adapter; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import java.util.List; -import java.util.Map; - -import javax.annotation.PostConstruct; - -import org.apache.commons.lang3.StringUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.ApplicationContext; - -import com.nepxion.discovery.common.constant.DiscoveryConstant; -import com.nepxion.discovery.common.entity.RuleEntity; -import com.nepxion.discovery.common.entity.StrategyEntity; -import com.nepxion.discovery.common.util.JsonUtil; -import com.nepxion.discovery.common.util.StringUtil; -import com.nepxion.discovery.plugin.framework.adapter.PluginAdapter; -import com.nepxion.discovery.plugin.strategy.context.StrategyContextHolder; -import com.nepxion.discovery.plugin.strategy.matcher.DiscoveryMatcherStrategy; -import com.netflix.loadbalancer.Server; - -public class DefaultDiscoveryEnabledAdapter implements DiscoveryEnabledAdapter { - @Autowired - private ApplicationContext applicationContext; - - @Autowired(required = false) - private DiscoveryEnabledStrategy discoveryEnabledStrategy; - - @Autowired - private DiscoveryMatcherStrategy discoveryMatcherStrategy; - - @Autowired - protected PluginAdapter pluginAdapter; - - protected StrategyContextHolder strategyContextHolder; - - @PostConstruct - private void initialize() { - strategyContextHolder = applicationContext.getBean(StrategyContextHolder.class); - } - - @Override - public boolean apply(Server server) { - boolean enabled = applyVersion(server); - if (!enabled) { - return false; - } - - enabled = applyRegion(server); - if (!enabled) { - return false; - } - - enabled = applyAddress(server); - if (!enabled) { - return false; - } - - return applyStrategy(server); - } - - @SuppressWarnings("unchecked") - private boolean applyVersion(Server server) { - String versionValue = strategyContextHolder.getHeader(DiscoveryConstant.N_D_VERSION); - if (StringUtils.isEmpty(versionValue)) { - RuleEntity ruleEntity = pluginAdapter.getRule(); - if (ruleEntity != null) { - StrategyEntity strategyEntity = ruleEntity.getStrategyEntity(); - if (strategyEntity != null) { - versionValue = strategyEntity.getVersionValue(); - } - } - } - - if (StringUtils.isEmpty(versionValue)) { - return true; - } - - String version = pluginAdapter.getServerVersion(server); - if (StringUtils.isEmpty(version)) { - return false; - } - - String versions = null; - try { - Map versionMap = JsonUtil.fromJson(versionValue, Map.class); - String serviceId = pluginAdapter.getServerServiceId(server); - versions = versionMap.get(serviceId); - } catch (Exception e) { - versions = versionValue; - } - - if (StringUtils.isEmpty(versions)) { - return true; - } - - // 如果精确匹配不满足,尝试用通配符匹配 - List versionList = StringUtil.splitToList(versions, DiscoveryConstant.SEPARATE); - if (versionList.contains(version)) { - return true; - } - - // 通配符匹配。前者是通配表达式,后者是具体值 - for (String versionPattern : versionList) { - if (discoveryMatcherStrategy.match(versionPattern, version)) { - return true; - } - } - - return false; - } - - @SuppressWarnings("unchecked") - private boolean applyRegion(Server server) { - String regionValue = strategyContextHolder.getHeader(DiscoveryConstant.N_D_REGION); - if (StringUtils.isEmpty(regionValue)) { - RuleEntity ruleEntity = pluginAdapter.getRule(); - if (ruleEntity != null) { - StrategyEntity strategyEntity = ruleEntity.getStrategyEntity(); - if (strategyEntity != null) { - regionValue = strategyEntity.getRegionValue(); - } - } - } - - if (StringUtils.isEmpty(regionValue)) { - return true; - } - - String region = pluginAdapter.getServerRegion(server); - if (StringUtils.isEmpty(region)) { - return false; - } - - String regions = null; - try { - Map regionMap = JsonUtil.fromJson(regionValue, Map.class); - String serviceId = pluginAdapter.getServerServiceId(server); - regions = regionMap.get(serviceId); - } catch (Exception e) { - regions = regionValue; - } - - if (StringUtils.isEmpty(regions)) { - return true; - } - - // 如果精确匹配不满足,尝试用通配符匹配 - List regionList = StringUtil.splitToList(regions, DiscoveryConstant.SEPARATE); - if (regionList.contains(region)) { - return true; - } - - // 通配符匹配。前者是通配表达式,后者是具体值 - for (String regionPattern : regionList) { - if (discoveryMatcherStrategy.match(regionPattern, region)) { - return true; - } - } - - return false; - } - - @SuppressWarnings("unchecked") - private boolean applyAddress(Server server) { - String addressValue = strategyContextHolder.getHeader(DiscoveryConstant.N_D_ADDRESS); - if (StringUtils.isEmpty(addressValue)) { - RuleEntity ruleEntity = pluginAdapter.getRule(); - if (ruleEntity != null) { - StrategyEntity strategyEntity = ruleEntity.getStrategyEntity(); - if (strategyEntity != null) { - addressValue = strategyEntity.getAddressValue(); - } - } - } - - if (StringUtils.isEmpty(addressValue)) { - return true; - } - - Map addressMap = JsonUtil.fromJson(addressValue, Map.class); - String serviceId = pluginAdapter.getServerServiceId(server); - String addresses = addressMap.get(serviceId); - if (StringUtils.isEmpty(addresses)) { - return true; - } - - // 如果精确匹配不满足,尝试用通配符匹配 - List addressList = StringUtil.splitToList(addresses, DiscoveryConstant.SEPARATE); - if (addressList.contains(server.getHostPort()) || addressList.contains(server.getHost())) { - return true; - } - - // 通配符匹配。前者是通配表达式,后者是具体值 - for (String addressPattern : addressList) { - if (discoveryMatcherStrategy.match(addressPattern, server.getHostPort()) || discoveryMatcherStrategy.match(addressPattern, server.getHost())) { - return true; - } - } - - return false; - } - - private boolean applyStrategy(Server server) { - if (discoveryEnabledStrategy == null) { - return true; - } - - return discoveryEnabledStrategy.apply(server); - } - - public PluginAdapter getPluginAdapter() { - return pluginAdapter; - } - - public StrategyContextHolder getStrategyContextHolder() { - return strategyContextHolder; - } -} \ No newline at end of file diff --git a/discovery-plugin-strategy/src/main/java/com/nepxion/discovery/plugin/strategy/adapter/DefaultDiscoveryEnabledStrategy.java b/discovery-plugin-strategy/src/main/java/com/nepxion/discovery/plugin/strategy/adapter/DefaultDiscoveryEnabledStrategy.java deleted file mode 100644 index 1e7ed6062b..0000000000 --- a/discovery-plugin-strategy/src/main/java/com/nepxion/discovery/plugin/strategy/adapter/DefaultDiscoveryEnabledStrategy.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.nepxion.discovery.plugin.strategy.adapter; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import javax.annotation.PostConstruct; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.ApplicationContext; - -import com.nepxion.discovery.plugin.framework.adapter.PluginAdapter; -import com.nepxion.discovery.plugin.strategy.context.StrategyContextHolder; - -public abstract class DefaultDiscoveryEnabledStrategy implements DiscoveryEnabledStrategy { - @Autowired - private ApplicationContext applicationContext; - - @Autowired - protected PluginAdapter pluginAdapter; - - protected StrategyContextHolder strategyContextHolder; - - @PostConstruct - private void initialize() { - strategyContextHolder = applicationContext.getBean(StrategyContextHolder.class); - } - - public PluginAdapter getPluginAdapter() { - return pluginAdapter; - } - - public StrategyContextHolder getStrategyContextHolder() { - return strategyContextHolder; - } -} \ No newline at end of file diff --git a/discovery-plugin-strategy/src/main/java/com/nepxion/discovery/plugin/strategy/adapter/DiscoveryEnabledAdapter.java b/discovery-plugin-strategy/src/main/java/com/nepxion/discovery/plugin/strategy/adapter/DiscoveryEnabledAdapter.java deleted file mode 100644 index 50de7d5111..0000000000 --- a/discovery-plugin-strategy/src/main/java/com/nepxion/discovery/plugin/strategy/adapter/DiscoveryEnabledAdapter.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.nepxion.discovery.plugin.strategy.adapter; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import com.netflix.loadbalancer.Server; - -public interface DiscoveryEnabledAdapter { - boolean apply(Server server); -} \ No newline at end of file diff --git a/discovery-plugin-strategy/src/main/java/com/nepxion/discovery/plugin/strategy/configuration/StrategyAutoConfiguration.java b/discovery-plugin-strategy/src/main/java/com/nepxion/discovery/plugin/strategy/configuration/StrategyAutoConfiguration.java deleted file mode 100644 index b10eb46491..0000000000 --- a/discovery-plugin-strategy/src/main/java/com/nepxion/discovery/plugin/strategy/configuration/StrategyAutoConfiguration.java +++ /dev/null @@ -1,55 +0,0 @@ -package com.nepxion.discovery.plugin.strategy.configuration; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.cloud.netflix.ribbon.RibbonClients; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -import com.nepxion.discovery.plugin.strategy.constant.StrategyConstant; -import com.nepxion.discovery.plugin.strategy.isolation.ConsumerIsolationDiscoveryStrategy; -import com.nepxion.discovery.plugin.strategy.isolation.ConsumerIsolationLoadBalanceStrategy; -import com.nepxion.discovery.plugin.strategy.isolation.ConsumerIsolationRegisterStrategy; -import com.nepxion.discovery.plugin.strategy.matcher.DiscoveryAntPathMatcherStrategy; -import com.nepxion.discovery.plugin.strategy.matcher.DiscoveryMatcherStrategy; - -@Configuration -@RibbonClients(defaultConfiguration = { StrategyLoadBalanceConfiguration.class }) -@ConditionalOnProperty(value = StrategyConstant.SPRING_APPLICATION_STRATEGY_CONTROL_ENABLED, matchIfMissing = true) -public class StrategyAutoConfiguration { - @Bean - @ConditionalOnMissingBean - public DiscoveryMatcherStrategy discoveryMatcherStrategy() { - return new DiscoveryAntPathMatcherStrategy(); - } - - @Bean - @ConditionalOnMissingBean - @ConditionalOnProperty(value = StrategyConstant.SPRING_APPLICATION_STRATEGY_REGISTER_ISOLATION_ENABLED, matchIfMissing = false) - public ConsumerIsolationRegisterStrategy consumerIsolationRegisterStrategy() { - return new ConsumerIsolationRegisterStrategy(); - } - - @Bean - @ConditionalOnMissingBean - @ConditionalOnProperty(value = StrategyConstant.SPRING_APPLICATION_STRATEGY_CONSUMER_ISOLATION_ENABLED, matchIfMissing = false) - public ConsumerIsolationDiscoveryStrategy consumerIsolationDiscoveryStrategy() { - return new ConsumerIsolationDiscoveryStrategy(); - } - - @Bean - @ConditionalOnMissingBean - @ConditionalOnProperty(value = StrategyConstant.SPRING_APPLICATION_STRATEGY_CONSUMER_ISOLATION_ENABLED, matchIfMissing = false) - public ConsumerIsolationLoadBalanceStrategy consumerIsolationLoadBalanceStrategy() { - return new ConsumerIsolationLoadBalanceStrategy(); - } -} \ No newline at end of file diff --git a/discovery-plugin-strategy/src/main/java/com/nepxion/discovery/plugin/strategy/constant/StrategyConstant.java b/discovery-plugin-strategy/src/main/java/com/nepxion/discovery/plugin/strategy/constant/StrategyConstant.java deleted file mode 100644 index af80cfefc7..0000000000 --- a/discovery-plugin-strategy/src/main/java/com/nepxion/discovery/plugin/strategy/constant/StrategyConstant.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.nepxion.discovery.plugin.strategy.constant; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -public class StrategyConstant { - public static final String SPRING_APPLICATION_STRATEGY_CONTROL_ENABLED = "spring.application.strategy.control.enabled"; - public static final String SPRING_APPLICATION_STRATEGY_ZONE_AVOIDANCE_RULE_ENABLED = "spring.application.strategy.zone.avoidance.rule.enabled"; - public static final String SPRING_APPLICATION_STRATEGY_HYSTRIX_THREADLOCAL_SUPPORTED = "spring.application.strategy.hystrix.threadlocal.supported"; - public static final String SPRING_APPLICATION_STRATEGY_REGISTER_ISOLATION_GROUP_BLACKLIST = "spring.application.strategy.register.isolation.group.blacklist"; - public static final String SPRING_APPLICATION_STRATEGY_REGISTER_ISOLATION_GROUP_WHITELIST = "spring.application.strategy.register.isolation.group.whitelist"; - public static final String SPRING_APPLICATION_STRATEGY_REGISTER_ISOLATION_ENABLED = "spring.application.strategy.register.isolation.enabled"; - public static final String SPRING_APPLICATION_STRATEGY_CONSUMER_ISOLATION_ENABLED = "spring.application.strategy.consumer.isolation.enabled"; - public static final String SPRING_APPLICATION_STRATEGY_PROVIDER_ISOLATION_ENABLED = "spring.application.strategy.provider.isolation.enabled"; - public static final String SPRING_APPLICATION_STRATEGY_INTERCEPT_LOG_PRINT = "spring.application.strategy.intercept.log.print"; -} \ No newline at end of file diff --git a/discovery-plugin-strategy/src/main/java/com/nepxion/discovery/plugin/strategy/context/AbstractStrategyContextHolder.java b/discovery-plugin-strategy/src/main/java/com/nepxion/discovery/plugin/strategy/context/AbstractStrategyContextHolder.java deleted file mode 100644 index 5377b8f52e..0000000000 --- a/discovery-plugin-strategy/src/main/java/com/nepxion/discovery/plugin/strategy/context/AbstractStrategyContextHolder.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.nepxion.discovery.plugin.strategy.context; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import com.nepxion.discovery.plugin.framework.context.PluginContextHolder; - -public abstract class AbstractStrategyContextHolder implements PluginContextHolder, StrategyContextHolder { - @Override - public String getContext(String name) { - return getHeader(name); - } -} \ No newline at end of file diff --git a/discovery-plugin-strategy/src/main/java/com/nepxion/discovery/plugin/strategy/context/StrategyContextHolder.java b/discovery-plugin-strategy/src/main/java/com/nepxion/discovery/plugin/strategy/context/StrategyContextHolder.java deleted file mode 100644 index 29e10f765a..0000000000 --- a/discovery-plugin-strategy/src/main/java/com/nepxion/discovery/plugin/strategy/context/StrategyContextHolder.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.nepxion.discovery.plugin.strategy.context; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -public interface StrategyContextHolder { - String getHeader(String name); -} \ No newline at end of file diff --git a/discovery-plugin-strategy/src/main/java/com/nepxion/discovery/plugin/strategy/isolation/ConsumerIsolationDiscoveryStrategy.java b/discovery-plugin-strategy/src/main/java/com/nepxion/discovery/plugin/strategy/isolation/ConsumerIsolationDiscoveryStrategy.java deleted file mode 100644 index c34100c732..0000000000 --- a/discovery-plugin-strategy/src/main/java/com/nepxion/discovery/plugin/strategy/isolation/ConsumerIsolationDiscoveryStrategy.java +++ /dev/null @@ -1,56 +0,0 @@ -package com.nepxion.discovery.plugin.strategy.isolation; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import java.util.Iterator; -import java.util.List; - -import org.apache.commons.lang3.StringUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.cloud.client.ServiceInstance; - -import com.nepxion.discovery.common.constant.DiscoveryConstant; -import com.nepxion.discovery.plugin.framework.adapter.PluginAdapter; -import com.nepxion.discovery.plugin.framework.listener.discovery.AbstractDiscoveryListener; - -// 当目标服务的元数据中的Group和本服务不相等,禁止被本服务发现(只用于DiscoveryClient.getInstances接口方法用)。如果是网关,则不做处理 -public class ConsumerIsolationDiscoveryStrategy extends AbstractDiscoveryListener { - @Autowired - private PluginAdapter pluginAdapter; - - @Override - public void onGetInstances(String serviceId, List instances) { - Iterator iterator = instances.iterator(); - while (iterator.hasNext()) { - ServiceInstance serviceInstance = iterator.next(); - - String instanceServiceType = pluginAdapter.getInstanceServiceType(serviceInstance); - if (StringUtils.equals(instanceServiceType, DiscoveryConstant.GATEWAY_TYPE)) { - continue; - } - - String instanceGroup = pluginAdapter.getInstanceGroup(serviceInstance); - String group = pluginAdapter.getGroup(); - if (!StringUtils.equals(instanceGroup, group)) { - iterator.remove(); - } - } - } - - @Override - public void onGetServices(List services) { - - } - - @Override - public int getOrder() { - return HIGHEST_PRECEDENCE; - } -} \ No newline at end of file diff --git a/discovery-plugin-strategy/src/main/java/com/nepxion/discovery/plugin/strategy/isolation/ConsumerIsolationLoadBalanceStrategy.java b/discovery-plugin-strategy/src/main/java/com/nepxion/discovery/plugin/strategy/isolation/ConsumerIsolationLoadBalanceStrategy.java deleted file mode 100644 index 651cd67e7b..0000000000 --- a/discovery-plugin-strategy/src/main/java/com/nepxion/discovery/plugin/strategy/isolation/ConsumerIsolationLoadBalanceStrategy.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.nepxion.discovery.plugin.strategy.isolation; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import java.util.Iterator; -import java.util.List; - -import org.apache.commons.lang3.StringUtils; -import org.springframework.beans.factory.annotation.Autowired; - -import com.nepxion.discovery.common.constant.DiscoveryConstant; -import com.nepxion.discovery.plugin.framework.adapter.PluginAdapter; -import com.nepxion.discovery.plugin.framework.listener.loadbalance.AbstractLoadBalanceListener; -import com.netflix.loadbalancer.Server; - -// 当目标服务的元数据中的Group和本服务不相等,禁止被本服务负载均衡。如果是网关,则不做处理 -public class ConsumerIsolationLoadBalanceStrategy extends AbstractLoadBalanceListener { - @Autowired - private PluginAdapter pluginAdapter; - - @Override - public void onGetServers(String serviceId, List servers) { - Iterator iterator = servers.iterator(); - while (iterator.hasNext()) { - Server server = iterator.next(); - - String serverServiceType = pluginAdapter.getServerServiceType(server); - if (StringUtils.equals(serverServiceType, DiscoveryConstant.GATEWAY_TYPE)) { - continue; - } - - String serverGroup = pluginAdapter.getServerGroup(server); - String group = pluginAdapter.getGroup(); - if (!StringUtils.equals(serverGroup, group)) { - iterator.remove(); - } - } - } - - @Override - public int getOrder() { - return HIGHEST_PRECEDENCE; - } -} \ No newline at end of file diff --git a/discovery-plugin-strategy/src/main/java/com/nepxion/discovery/plugin/strategy/isolation/ConsumerIsolationRegisterStrategy.java b/discovery-plugin-strategy/src/main/java/com/nepxion/discovery/plugin/strategy/isolation/ConsumerIsolationRegisterStrategy.java deleted file mode 100644 index 231bfc7303..0000000000 --- a/discovery-plugin-strategy/src/main/java/com/nepxion/discovery/plugin/strategy/isolation/ConsumerIsolationRegisterStrategy.java +++ /dev/null @@ -1,100 +0,0 @@ -package com.nepxion.discovery.plugin.strategy.isolation; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import java.util.List; - -import org.apache.commons.collections4.CollectionUtils; -import org.apache.commons.lang3.StringUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.cloud.client.serviceregistry.Registration; -import org.springframework.core.env.ConfigurableEnvironment; - -import com.nepxion.discovery.common.constant.DiscoveryConstant; -import com.nepxion.discovery.common.exception.DiscoveryException; -import com.nepxion.discovery.common.util.StringUtil; -import com.nepxion.discovery.plugin.framework.event.RegisterFailureEvent; -import com.nepxion.discovery.plugin.framework.listener.register.AbstractRegisterListener; -import com.nepxion.discovery.plugin.strategy.constant.StrategyConstant; - -// 当本服务的元数据中的Group在黑名单里或者不在白名单里,禁止被注册到注册中心 -public class ConsumerIsolationRegisterStrategy extends AbstractRegisterListener { - @Autowired - private ConfigurableEnvironment environment; - - @Override - public void onRegister(Registration registration) { - String serviceId = registration.getServiceId().toLowerCase(); - String host = registration.getHost(); - int port = registration.getPort(); - String group = registration.getMetadata().get(DiscoveryConstant.GROUP); - - List groupBlacklist = getGroupBlacklist(); - if (CollectionUtils.isNotEmpty(groupBlacklist) && groupBlacklist.contains(group)) { - onRegisterFailure(group, serviceId, host, port, true); - } - - List groupWhitelist = getGroupWhitelist(); - if (CollectionUtils.isNotEmpty(groupWhitelist) && !groupWhitelist.contains(group)) { - onRegisterFailure(group, serviceId, host, port, false); - } - } - - protected List getGroupBlacklist() { - String groupBlacklistText = environment.getProperty(StrategyConstant.SPRING_APPLICATION_STRATEGY_REGISTER_ISOLATION_GROUP_BLACKLIST, String.class, null); - if (StringUtils.isEmpty(groupBlacklistText)) { - return null; - } - - return StringUtil.splitToList(groupBlacklistText, DiscoveryConstant.SEPARATE); - } - - protected List getGroupWhitelist() { - String groupWhitelistText = environment.getProperty(StrategyConstant.SPRING_APPLICATION_STRATEGY_REGISTER_ISOLATION_GROUP_WHITELIST, String.class, null); - if (StringUtils.isEmpty(groupWhitelistText)) { - return null; - } - - return StringUtil.splitToList(groupWhitelistText, DiscoveryConstant.SEPARATE); - } - - private void onRegisterFailure(String group, String serviceId, String host, int port, boolean isBlacklist) { - String description = serviceId + " for " + host + ":" + port + " is rejected to register to Register server, it's group=" + group; - if (isBlacklist) { - description += " is in isolation blacklist"; - } else { - description += " isn't in isolation whitelist"; - } - - pluginEventWapper.fireRegisterFailure(new RegisterFailureEvent(DiscoveryConstant.REGISTER_ISOLATION, description, serviceId, host, port)); - - throw new DiscoveryException(description); - } - - @Override - public void onDeregister(Registration registration) { - - } - - @Override - public void onSetStatus(Registration registration, String status) { - - } - - @Override - public void onClose() { - - } - - @Override - public int getOrder() { - return HIGHEST_PRECEDENCE; - } -} \ No newline at end of file diff --git a/discovery-plugin-strategy/src/main/java/com/nepxion/discovery/plugin/strategy/wrapper/CallableWrapper.java b/discovery-plugin-strategy/src/main/java/com/nepxion/discovery/plugin/strategy/wrapper/CallableWrapper.java deleted file mode 100644 index 2797f1a984..0000000000 --- a/discovery-plugin-strategy/src/main/java/com/nepxion/discovery/plugin/strategy/wrapper/CallableWrapper.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.nepxion.discovery.plugin.strategy.wrapper; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @author Hao Huang - * @version 1.0 - */ - -import java.util.concurrent.Callable; - -public interface CallableWrapper { - Callable wrapCallable(Callable delegate); -} \ No newline at end of file diff --git a/discovery-plugin-test/discovery-plugin-test-starter-automation/pom.xml b/discovery-plugin-test/discovery-plugin-test-starter-automation/pom.xml new file mode 100644 index 0000000000..f68dd7b458 --- /dev/null +++ b/discovery-plugin-test/discovery-plugin-test-starter-automation/pom.xml @@ -0,0 +1,33 @@ + + + discovery-plugin-test-starter-automation + Nepxion Discovery Plugin Test Starter Automation + jar + 4.0.0 + Nepxion Discovery is a solution for Spring Cloud with blue green, gray, weight, limitation, circuit breaker, degrade, isolation, monitor, tracing, dye, failover, async agent + http://www.nepxion.com + + + com.nepxion + discovery-plugin-test + 6.23.0 + + + + + ${project.groupId} + discovery-common + + + + ${project.groupId} + matrix-aop-starter + + + + org.springframework.boot + spring-boot-starter-test + + + \ No newline at end of file diff --git a/discovery-plugin-test/discovery-plugin-test-starter-automation/src/main/java/com/nepxion/discovery/plugin/test/automation/annotation/DTest.java b/discovery-plugin-test/discovery-plugin-test-starter-automation/src/main/java/com/nepxion/discovery/plugin/test/automation/annotation/DTest.java new file mode 100644 index 0000000000..e1ebc86608 --- /dev/null +++ b/discovery-plugin-test/discovery-plugin-test-starter-automation/src/main/java/com/nepxion/discovery/plugin/test/automation/annotation/DTest.java @@ -0,0 +1,25 @@ +package com.nepxion.discovery.plugin.test.automation.annotation; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Inherited; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Target({ ElementType.METHOD, ElementType.TYPE }) +@Retention(RetentionPolicy.RUNTIME) +@Inherited +@Documented +public @interface DTest { + +} \ No newline at end of file diff --git a/discovery-plugin-test/discovery-plugin-test-starter-automation/src/main/java/com/nepxion/discovery/plugin/test/automation/annotation/DTestConfig.java b/discovery-plugin-test/discovery-plugin-test-starter-automation/src/main/java/com/nepxion/discovery/plugin/test/automation/annotation/DTestConfig.java new file mode 100644 index 0000000000..7f2e2144a4 --- /dev/null +++ b/discovery-plugin-test/discovery-plugin-test-starter-automation/src/main/java/com/nepxion/discovery/plugin/test/automation/annotation/DTestConfig.java @@ -0,0 +1,49 @@ +package com.nepxion.discovery.plugin.test.automation.annotation; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Inherited; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +import org.apache.commons.lang3.StringUtils; + +import com.nepxion.discovery.common.entity.FormatType; + +@Target({ ElementType.METHOD, ElementType.TYPE }) +@Retention(RetentionPolicy.RUNTIME) +@Inherited +@Documented +public @interface DTestConfig { + // 组名 + String group(); + + // 服务名 + String serviceId(); + + // 配置类型 + FormatType formatType() default FormatType.TEXT_FORMAT; + + // 组名-服务名组合键值的前缀 + String prefix() default StringUtils.EMPTY; + + // 组名-服务名组合键值的后缀 + String suffix() default StringUtils.EMPTY; + + // 执行配置的文件路径。测试用例运行前,会把该文件里的内容推送到远程配置中心或者服务 + String executePath(); + + // 重置配置的文件路径。测试用例运行后,会把该文件里的内容推送到远程配置中心或者服务。该文件内容是最初的默认配置 + // 如果该注解属性为空,则直接删除从配置中心删除组名-服务名组合键值 + String resetPath() default StringUtils.EMPTY; +} \ No newline at end of file diff --git a/discovery-plugin-test/discovery-plugin-test-starter-automation/src/main/java/com/nepxion/discovery/plugin/test/automation/aop/TestAutoScanProxy.java b/discovery-plugin-test/discovery-plugin-test-starter-automation/src/main/java/com/nepxion/discovery/plugin/test/automation/aop/TestAutoScanProxy.java new file mode 100644 index 0000000000..c8e07888c2 --- /dev/null +++ b/discovery-plugin-test/discovery-plugin-test-starter-automation/src/main/java/com/nepxion/discovery/plugin/test/automation/aop/TestAutoScanProxy.java @@ -0,0 +1,50 @@ +package com.nepxion.discovery.plugin.test.automation.aop; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.lang.annotation.Annotation; + +import com.nepxion.discovery.plugin.test.automation.annotation.DTest; +import com.nepxion.discovery.plugin.test.automation.annotation.DTestConfig; +import com.nepxion.matrix.proxy.aop.DefaultAutoScanProxy; +import com.nepxion.matrix.proxy.mode.ProxyMode; +import com.nepxion.matrix.proxy.mode.ScanMode; + +public class TestAutoScanProxy extends DefaultAutoScanProxy { + private static final long serialVersionUID = -4129026721568940949L; + + private String[] commonInterceptorNames; + + @SuppressWarnings("rawtypes") + private Class[] methodAnnotations; + + public TestAutoScanProxy(String scanPackages) { + super(scanPackages, ProxyMode.BY_METHOD_ANNOTATION_ONLY, ScanMode.FOR_METHOD_ANNOTATION_ONLY); + } + + @Override + protected String[] getCommonInterceptorNames() { + if (commonInterceptorNames == null) { + commonInterceptorNames = new String[] { "testInterceptor" }; + } + + return commonInterceptorNames; + } + + @SuppressWarnings("unchecked") + @Override + protected Class[] getMethodAnnotations() { + if (methodAnnotations == null) { + methodAnnotations = new Class[] { DTest.class, DTestConfig.class }; + } + + return methodAnnotations; + } +} \ No newline at end of file diff --git a/discovery-plugin-test/discovery-plugin-test-starter-automation/src/main/java/com/nepxion/discovery/plugin/test/automation/aop/TestInterceptor.java b/discovery-plugin-test/discovery-plugin-test-starter-automation/src/main/java/com/nepxion/discovery/plugin/test/automation/aop/TestInterceptor.java new file mode 100644 index 0000000000..c81daba7e1 --- /dev/null +++ b/discovery-plugin-test/discovery-plugin-test-starter-automation/src/main/java/com/nepxion/discovery/plugin/test/automation/aop/TestInterceptor.java @@ -0,0 +1,110 @@ +package com.nepxion.discovery.plugin.test.automation.aop; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.lang.reflect.Method; + +import org.aopalliance.intercept.MethodInvocation; +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; + +import com.nepxion.discovery.common.entity.FormatType; +import com.nepxion.discovery.plugin.test.automation.annotation.DTest; +import com.nepxion.discovery.plugin.test.automation.annotation.DTestConfig; +import com.nepxion.discovery.plugin.test.automation.constant.TestConstant; +import com.nepxion.discovery.plugin.test.automation.operation.TestOperation; +import com.nepxion.matrix.proxy.aop.AbstractInterceptor; + +public class TestInterceptor extends AbstractInterceptor { + private static final Logger LOG = LoggerFactory.getLogger(TestInterceptor.class); + + @Autowired + private TestOperation testOperation; + + @Value("${" + TestConstant.SPRING_APPLICATION_TEST_CONFIG_OPERATION_AWAIT_TIME + ":3000}") + private Integer configOperationAwaitTime; + + @Override + public Object invoke(MethodInvocation invocation) throws Throwable { + Method method = invocation.getMethod(); + boolean isTestAnnotationPresent = method.isAnnotationPresent(DTest.class); + boolean isTestConfigAnnotationPresent = method.isAnnotationPresent(DTestConfig.class); + if (isTestAnnotationPresent || isTestConfigAnnotationPresent) { + String methodName = getMethodName(invocation); + LOG.info("---------- Run automation testcase :: {}() ----------", methodName); + + Object object = null; + if (isTestAnnotationPresent) { + object = invocation.proceed(); + } else { + DTestConfig testConfigAnnotation = method.getAnnotation(DTestConfig.class); + String group = convertSpel(invocation, testConfigAnnotation.group()); + String serviceId = convertSpel(invocation, testConfigAnnotation.serviceId()); + FormatType formatType = testConfigAnnotation.formatType(); + String prefix = convertSpel(invocation, testConfigAnnotation.prefix()); + String suffix = convertSpel(invocation, testConfigAnnotation.suffix()); + String executePath = convertSpel(invocation, testConfigAnnotation.executePath()); + String resetPath = convertSpel(invocation, testConfigAnnotation.resetPath()); + + if (formatType == FormatType.TEXT_FORMAT) { + try { + String type = executePath.substring(executePath.lastIndexOf(".") + 1); + formatType = FormatType.fromString(type); + } catch (Exception e) { + + } + } + + if (StringUtils.isNotEmpty(prefix)) { + group = prefix + "-" + group; + } + if (StringUtils.isNotEmpty(suffix)) { + serviceId = serviceId + "-" + suffix; + } + + testOperation.update(group, serviceId, formatType, executePath); + + Thread.sleep(configOperationAwaitTime); + + try { + object = invocation.proceed(); + } finally { + if (StringUtils.isNotEmpty(resetPath)) { + testOperation.update(group, serviceId, formatType, resetPath); + } else { + testOperation.clear(group, serviceId); + } + + Thread.sleep(configOperationAwaitTime); + } + } + + LOG.info("* Passed"); + + return object; + } + + return invocation.proceed(); + } + + private String convertSpel(MethodInvocation invocation, String key) { + String spelKey = null; + try { + spelKey = getSpelKey(invocation, key); + } catch (Exception e) { + spelKey = key; + } + + return spelKey; + } +} \ No newline at end of file diff --git a/discovery-plugin-test/discovery-plugin-test-starter-automation/src/main/java/com/nepxion/discovery/plugin/test/automation/application/TestApplication.java b/discovery-plugin-test/discovery-plugin-test-starter-automation/src/main/java/com/nepxion/discovery/plugin/test/automation/application/TestApplication.java new file mode 100644 index 0000000000..3533b919d1 --- /dev/null +++ b/discovery-plugin-test/discovery-plugin-test-starter-automation/src/main/java/com/nepxion/discovery/plugin/test/automation/application/TestApplication.java @@ -0,0 +1,20 @@ +package com.nepxion.discovery.plugin.test.automation.application; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.builder.SpringApplicationBuilder; + +@SpringBootApplication +public class TestApplication { + public static void main(String[] args) { + new SpringApplicationBuilder(TestApplication.class).run(args); + } +} \ No newline at end of file diff --git a/discovery-plugin-test/discovery-plugin-test-starter-automation/src/main/java/com/nepxion/discovery/plugin/test/automation/configuration/TestAutoConfiguration.java b/discovery-plugin-test/discovery-plugin-test-starter-automation/src/main/java/com/nepxion/discovery/plugin/test/automation/configuration/TestAutoConfiguration.java new file mode 100644 index 0000000000..a84d9f2a2b --- /dev/null +++ b/discovery-plugin-test/discovery-plugin-test-starter-automation/src/main/java/com/nepxion/discovery/plugin/test/automation/configuration/TestAutoConfiguration.java @@ -0,0 +1,53 @@ +package com.nepxion.discovery.plugin.test.automation.configuration; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.env.ConfigurableEnvironment; + +import com.nepxion.discovery.common.exception.DiscoveryException; +import com.nepxion.discovery.plugin.test.automation.aop.TestAutoScanProxy; +import com.nepxion.discovery.plugin.test.automation.aop.TestInterceptor; +import com.nepxion.discovery.plugin.test.automation.constant.TestConstant; +import com.nepxion.discovery.plugin.test.automation.operation.TestOperation; + +@Configuration +public class TestAutoConfiguration { + @Autowired + private ConfigurableEnvironment environment; + + @Bean + public TestAutoScanProxy testAutoScanProxy() { + String scanPackages = environment.getProperty(TestConstant.SPRING_APPLICATION_TEST_SCAN_PACKAGES); + if (StringUtils.isEmpty(scanPackages)) { + throw new DiscoveryException(TestConstant.SPRING_APPLICATION_TEST_SCAN_PACKAGES + "'s value can't be empty"); + } + + return new TestAutoScanProxy(scanPackages); + } + + @Bean + public TestInterceptor testInterceptor() { + String scanPackages = environment.getProperty(TestConstant.SPRING_APPLICATION_TEST_SCAN_PACKAGES); + if (StringUtils.isEmpty(scanPackages)) { + throw new DiscoveryException(TestConstant.SPRING_APPLICATION_TEST_SCAN_PACKAGES + "'s value can't be empty"); + } + + return new TestInterceptor(); + } + + @Bean + public TestOperation testOperation() { + return new TestOperation(); + } +} \ No newline at end of file diff --git a/discovery-plugin-test/discovery-plugin-test-starter-automation/src/main/java/com/nepxion/discovery/plugin/test/automation/constant/TestConstant.java b/discovery-plugin-test/discovery-plugin-test-starter-automation/src/main/java/com/nepxion/discovery/plugin/test/automation/constant/TestConstant.java new file mode 100644 index 0000000000..c3eaf04ee3 --- /dev/null +++ b/discovery-plugin-test/discovery-plugin-test-starter-automation/src/main/java/com/nepxion/discovery/plugin/test/automation/constant/TestConstant.java @@ -0,0 +1,20 @@ +package com.nepxion.discovery.plugin.test.automation.constant; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +public class TestConstant { + public static final String SPRING_APPLICATION_TEST_SCAN_PACKAGES = "spring.application.test.scan.packages"; + public static final String SPRING_APPLICATION_TEST_CONFIG_PRINT_ENABLED = "spring.application.test.config.print.enabled"; + public static final String SPRING_APPLICATION_TEST_CONFIG_OPERATION_AWAIT_TIME = "spring.application.test.config.operation.await.time"; + public static final String SPRING_APPLICATION_TEST_CONSOLE_URL = "spring.application.test.console.url"; + + public static final String REMOTE_UPDATE_URL = "config/remote/update"; + public static final String REMOTE_CLEAR_URL = "config/remote/clear"; +} \ No newline at end of file diff --git a/discovery-plugin-test/discovery-plugin-test-starter-automation/src/main/java/com/nepxion/discovery/plugin/test/automation/context/TestApplicationContextInitializer.java b/discovery-plugin-test/discovery-plugin-test-starter-automation/src/main/java/com/nepxion/discovery/plugin/test/automation/context/TestApplicationContextInitializer.java new file mode 100644 index 0000000000..5660338a02 --- /dev/null +++ b/discovery-plugin-test/discovery-plugin-test-starter-automation/src/main/java/com/nepxion/discovery/plugin/test/automation/context/TestApplicationContextInitializer.java @@ -0,0 +1,47 @@ +package com.nepxion.discovery.plugin.test.automation.context; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.springframework.context.ApplicationContextInitializer; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; + +import com.nepxion.banner.BannerConstant; +import com.nepxion.banner.Description; +import com.nepxion.banner.LogoBanner; +import com.nepxion.banner.NepxionBanner; +import com.nepxion.discovery.common.constant.DiscoveryConstant; +import com.taobao.text.Color; + +public class TestApplicationContextInitializer implements ApplicationContextInitializer { + @Override + public void initialize(ConfigurableApplicationContext applicationContext) { + if (!(applicationContext instanceof AnnotationConfigApplicationContext)) { + /*String bannerShown = System.getProperty(BannerConstant.BANNER_SHOWN, "true"); + if (Boolean.valueOf(bannerShown)) { + System.out.println(""); + System.out.println("╔═══╗"); + System.out.println("╚╗╔╗║"); + System.out.println(" ║║║╠╦══╦══╦══╦╗╔╦══╦═╦╗ ╔╗"); + System.out.println(" ║║║╠╣══╣╔═╣╔╗║╚╝║║═╣╔╣║ ║║"); + System.out.println("╔╝╚╝║╠══║╚═╣╚╝╠╗╔╣║═╣║║╚═╝║"); + System.out.println("╚═══╩╩══╩══╩══╝╚╝╚══╩╝╚═╗╔╝"); + System.out.println(" ╔═╝║"); + System.out.println(" ╚══╝"); + System.out.println("Nepxion Discovery v" + DiscoveryConstant.DISCOVERY_VERSION); + System.out.println(""); + }*/ + + LogoBanner logoBanner = new LogoBanner(TestApplicationContextInitializer.class, "/com/nepxion/discovery/resource/logo.txt", "Welcome to Nepxion", 9, 5, new Color[] { Color.red, Color.green, Color.cyan, Color.blue, Color.yellow, Color.magenta, Color.red, Color.green, Color.cyan }, true); + + NepxionBanner.show(logoBanner, new Description(BannerConstant.VERSION + ":", DiscoveryConstant.DISCOVERY_VERSION, 0, 1), new Description(BannerConstant.GITHUB + ":", BannerConstant.NEPXION_GITHUB + "/Discovery", 0, 1)); + } + } +} \ No newline at end of file diff --git a/discovery-plugin-test/discovery-plugin-test-starter-automation/src/main/java/com/nepxion/discovery/plugin/test/automation/context/TestEnvironmentPostProcessor.java b/discovery-plugin-test/discovery-plugin-test-starter-automation/src/main/java/com/nepxion/discovery/plugin/test/automation/context/TestEnvironmentPostProcessor.java new file mode 100644 index 0000000000..9eaa231971 --- /dev/null +++ b/discovery-plugin-test/discovery-plugin-test-starter-automation/src/main/java/com/nepxion/discovery/plugin/test/automation/context/TestEnvironmentPostProcessor.java @@ -0,0 +1,33 @@ +package com.nepxion.discovery.plugin.test.automation.context; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.env.EnvironmentPostProcessor; +import org.springframework.core.Ordered; +import org.springframework.core.env.ConfigurableEnvironment; + +import com.nepxion.discovery.common.constant.DiscoveryConstant; +import com.nepxion.discovery.common.entity.ServiceType; +import com.nepxion.discovery.common.util.EnvironmentUtil; + +public class TestEnvironmentPostProcessor implements EnvironmentPostProcessor, Ordered { + @Override + public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { + if (EnvironmentUtil.isStandardEnvironment(environment)) { + System.setProperty(DiscoveryConstant.SPRING_APPLICATION_TYPE, ServiceType.TEST.toString()); + } + } + + @Override + public int getOrder() { + return Ordered.HIGHEST_PRECEDENCE; + } +} \ No newline at end of file diff --git a/discovery-plugin-test/discovery-plugin-test-starter-automation/src/main/java/com/nepxion/discovery/plugin/test/automation/operation/TestOperation.java b/discovery-plugin-test/discovery-plugin-test-starter-automation/src/main/java/com/nepxion/discovery/plugin/test/automation/operation/TestOperation.java new file mode 100644 index 0000000000..da2e66812e --- /dev/null +++ b/discovery-plugin-test/discovery-plugin-test-starter-automation/src/main/java/com/nepxion/discovery/plugin/test/automation/operation/TestOperation.java @@ -0,0 +1,66 @@ +package com.nepxion.discovery.plugin.test.automation.operation; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.io.IOException; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.test.web.client.TestRestTemplate; + +import com.nepxion.discovery.common.constant.DiscoveryConstant; +import com.nepxion.discovery.common.entity.FormatType; +import com.nepxion.discovery.common.exception.DiscoveryException; +import com.nepxion.discovery.common.property.DiscoveryContent; +import com.nepxion.discovery.common.util.UrlUtil; +import com.nepxion.discovery.plugin.test.automation.constant.TestConstant; + +public class TestOperation { + private static final Logger LOG = LoggerFactory.getLogger(TestOperation.class); + + @Value("${" + TestConstant.SPRING_APPLICATION_TEST_CONSOLE_URL + "}") + private String consoleUrl; + + @Value("${" + TestConstant.SPRING_APPLICATION_TEST_CONFIG_PRINT_ENABLED + ":true}") + private Boolean configPrintEnabled; + + @Autowired + private TestRestTemplate testRestTemplate; + + public String update(String group, String serviceId, FormatType formatType, String path) { + String content = null; + try { + DiscoveryContent discoveryContent = new DiscoveryContent(path, DiscoveryConstant.ENCODING_UTF_8); + content = discoveryContent.getContent(); + } catch (IOException e) { + throw new DiscoveryException(e); + } + + if (configPrintEnabled) { + LOG.info("Update config, group={}, serviceId={}, formatType={}, path={}, content=\n{}", group, serviceId, formatType, path, content); + } + + String url = consoleUrl + UrlUtil.formatContextPath(TestConstant.REMOTE_UPDATE_URL) + group + "/" + serviceId + "/" + formatType; + + return testRestTemplate.postForEntity(url, content, String.class).getBody(); + } + + public String clear(String group, String serviceId) { + if (configPrintEnabled) { + LOG.info("Clear config, group={}, serviceId={}", group, serviceId); + } + + String url = consoleUrl + UrlUtil.formatContextPath(TestConstant.REMOTE_CLEAR_URL) + group + "/" + serviceId; + + return testRestTemplate.postForEntity(url, null, String.class).getBody(); + } +} \ No newline at end of file diff --git a/discovery-plugin-test/discovery-plugin-test-starter-automation/src/main/resources/META-INF/additional-spring-configuration-metadata.json b/discovery-plugin-test/discovery-plugin-test-starter-automation/src/main/resources/META-INF/additional-spring-configuration-metadata.json new file mode 100644 index 0000000000..bff647be6f --- /dev/null +++ b/discovery-plugin-test/discovery-plugin-test-starter-automation/src/main/resources/META-INF/additional-spring-configuration-metadata.json @@ -0,0 +1,32 @@ +{ + "properties": [ + { + "name": "spring.application.test.scan.packages", + "type": "java.lang.String", + "description": "Test scan packages." + }, + { + "name": "spring.application.test.configcenter.enabled", + "type": "java.lang.Boolean", + "defaultValue": true, + "description": "Whether test configcenter is enabled." + }, + { + "name": "spring.application.test.config.print.enabled", + "type": "java.lang.Boolean", + "defaultValue": true, + "description": "Whether test config print is enabled." + }, + { + "name": "spring.application.test.config.operation.await.time", + "type": "java.lang.Integer", + "defaultValue": 3000, + "description": "Test config operation await time." + }, + { + "name": "spring.application.test.console.url", + "type": "java.lang.String", + "description": "Test console url." + } + ] +} \ No newline at end of file diff --git a/discovery-plugin-test/discovery-plugin-test-starter-automation/src/main/resources/META-INF/spring.factories b/discovery-plugin-test/discovery-plugin-test-starter-automation/src/main/resources/META-INF/spring.factories new file mode 100644 index 0000000000..e01cd6336c --- /dev/null +++ b/discovery-plugin-test/discovery-plugin-test-starter-automation/src/main/resources/META-INF/spring.factories @@ -0,0 +1,8 @@ +org.springframework.boot.env.EnvironmentPostProcessor=\ +com.nepxion.discovery.plugin.test.automation.context.TestEnvironmentPostProcessor + +org.springframework.context.ApplicationContextInitializer=\ +com.nepxion.discovery.plugin.test.automation.context.TestApplicationContextInitializer + +org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ +com.nepxion.discovery.plugin.test.automation.configuration.TestAutoConfiguration \ No newline at end of file diff --git a/discovery-plugin-test/pom.xml b/discovery-plugin-test/pom.xml new file mode 100644 index 0000000000..d77595b462 --- /dev/null +++ b/discovery-plugin-test/pom.xml @@ -0,0 +1,20 @@ + + + discovery-plugin-test + Nepxion Discovery Plugin Test + pom + 4.0.0 + Nepxion Discovery is a solution for Spring Cloud with blue green, gray, weight, limitation, circuit breaker, degrade, isolation, monitor, tracing, dye, failover, async agent + http://www.nepxion.com + + + com.nepxion + discovery + 6.23.0 + + + + discovery-plugin-test-starter-automation + + \ No newline at end of file diff --git a/discovery-springcloud-example-admin/pom.xml b/discovery-springcloud-example-admin/pom.xml deleted file mode 100644 index 03e73d8cdc..0000000000 --- a/discovery-springcloud-example-admin/pom.xml +++ /dev/null @@ -1,89 +0,0 @@ - - - com.nepxion - discovery-springcloud-example-admin - Nepxion Discovery Spring Cloud Example Admin - jar - 4.0.0 - 1.0.0 - Nepxion Discovery is an enhancement for Spring Cloud Discovery - http://www.nepxion.com - - - Greenwich.SR2 - 0.9.0.RELEASE - 2.1.6.RELEASE - 2.1.4 - 1.8 - UTF-8 - - - - - - org.springframework.cloud - spring-cloud-dependencies - ${spring.cloud.version} - pom - import - - - - org.springframework.cloud - spring-cloud-alibaba-dependencies - ${spring.cloud.alibaba.version} - pom - import - - - - org.springframework.boot - spring-boot-dependencies - ${spring.boot.version} - pom - import - - - - de.codecentric - spring-boot-admin-dependencies - ${spring.boot.admin.version} - pom - import - - - - - - - org.springframework.cloud - - - - spring-cloud-starter-alibaba-nacos-discovery - - - - de.codecentric - spring-boot-admin-starter-server - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - - - -parameters - - ${project.build.sourceEncoding} - ${java.version} - ${java.version} - - - - - \ No newline at end of file diff --git a/discovery-springcloud-example-admin/src/main/resources/application.properties b/discovery-springcloud-example-admin/src/main/resources/application.properties deleted file mode 100644 index 565cb5d62e..0000000000 --- a/discovery-springcloud-example-admin/src/main/resources/application.properties +++ /dev/null @@ -1,18 +0,0 @@ -# Spring cloud config -spring.application.name=discovery-springcloud-example-admin -server.port=5555 - -# Eureka config for discovery -eureka.instance.metadataMap.group=example-admin-group -eureka.instance.metadataMap.version=1.0 - -# Consul config for discovery -spring.cloud.consul.discovery.tags=group=example-admin-group,version=1.0 - -# Zookeeper config for discovery -spring.cloud.zookeeper.discovery.metadata.group=example-admin-group -spring.cloud.zookeeper.discovery.metadata.version=1.0 - -# Nacos config for discovery -spring.cloud.nacos.discovery.metadata.group=example-admin-group -spring.cloud.nacos.discovery.metadata.version=1.0 \ No newline at end of file diff --git a/discovery-springcloud-example-admin/src/main/resources/bootstrap.properties b/discovery-springcloud-example-admin/src/main/resources/bootstrap.properties deleted file mode 100644 index 790520b2ea..0000000000 --- a/discovery-springcloud-example-admin/src/main/resources/bootstrap.properties +++ /dev/null @@ -1,20 +0,0 @@ -# Spring cloud config - -# Eureka config for discovery -eureka.client.serviceUrl.defaultZone=http://localhost:9528/eureka/ -eureka.instance.preferIpAddress=true - -# Consul config for discovery -spring.cloud.consul.host=localhost -spring.cloud.consul.port=8500 -spring.cloud.consul.discovery.preferIpAddress=true - -# Zookeeper config for discovery -spring.cloud.zookeeper.connectString=localhost:2181 -spring.cloud.zookeeper.discovery.instancePort=${server.port} -spring.cloud.zookeeper.discovery.root=/spring-cloud-service -spring.cloud.zookeeper.discovery.preferIpAddress=true - -# Nacos config for discovery -spring.cloud.nacos.discovery.server-addr=localhost:8848 -# spring.cloud.nacos.discovery.namespace=discovery \ No newline at end of file diff --git a/discovery-springcloud-example-admin/src/main/resources/logback.xml b/discovery-springcloud-example-admin/src/main/resources/logback.xml deleted file mode 100644 index 239583856c..0000000000 --- a/discovery-springcloud-example-admin/src/main/resources/logback.xml +++ /dev/null @@ -1,49 +0,0 @@ - - - - - - - discovery %date %level [%thread] %logger{10} [%file:%line] - %msg%n - UTF-8 - - - log/discovery-%d{yyyy-MM-dd}.%i.log - 50MB - - - INFO - - - true - - - - 0 - 512 - - - - - - - - discovery %date %level [%thread] %logger{10} [%file:%line] - %msg%n - UTF-8 - - - - INFO - - - - - - - - - - - - - diff --git a/discovery-springcloud-example-console/pom.xml b/discovery-springcloud-example-console/pom.xml deleted file mode 100644 index c2e14df9f6..0000000000 --- a/discovery-springcloud-example-console/pom.xml +++ /dev/null @@ -1,98 +0,0 @@ - - - com.nepxion - discovery-springcloud-example-console - Nepxion Discovery Spring Cloud Example Console - jar - 4.0.0 - 1.0.0 - Nepxion Discovery is an enhancement for Spring Cloud Discovery - http://www.nepxion.com - - - 5.2.0-SNAPSHOT - Greenwich.SR2 - 0.9.0.RELEASE - 2.1.6.RELEASE - 2.1.4 - 1.8 - UTF-8 - - - - - - org.springframework.cloud - spring-cloud-dependencies - ${spring.cloud.version} - pom - import - - - - org.springframework.cloud - spring-cloud-alibaba-dependencies - ${spring.cloud.alibaba.version} - pom - import - - - - org.springframework.boot - spring-boot-dependencies - ${spring.boot.version} - pom - import - - - - de.codecentric - spring-boot-admin-dependencies - ${spring.boot.admin.version} - pom - import - - - - - - - com.nepxion - - discovery-console-starter-nacos - - ${discovery.version} - - - - org.springframework.cloud - - - - spring-cloud-starter-alibaba-nacos-discovery - - - - de.codecentric - spring-boot-admin-starter-client - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - - - -parameters - - ${project.build.sourceEncoding} - ${java.version} - ${java.version} - - - - - \ No newline at end of file diff --git a/discovery-springcloud-example-console/src/main/resources/application.properties b/discovery-springcloud-example-console/src/main/resources/application.properties deleted file mode 100644 index 8e1d8ef849..0000000000 --- a/discovery-springcloud-example-console/src/main/resources/application.properties +++ /dev/null @@ -1,21 +0,0 @@ -# Spring cloud config -spring.application.name=discovery-springcloud-example-console -server.port=2222 - -# Eureka config for discovery -eureka.instance.metadataMap.group=example-console-group -eureka.instance.metadataMap.version=1.0 - -# Consul config for discovery -spring.cloud.consul.discovery.tags=group=example-console-group,version=1.0 - -# Zookeeper config for discovery -spring.cloud.zookeeper.discovery.metadata.group=example-console-group -spring.cloud.zookeeper.discovery.metadata.version=1.0 - -# Nacos config for discovery -spring.cloud.nacos.discovery.metadata.group=example-console-group -spring.cloud.nacos.discovery.metadata.version=1.0 - -# Admin config -management.server.port=3333 \ No newline at end of file diff --git a/discovery-springcloud-example-console/src/main/resources/bootstrap.properties b/discovery-springcloud-example-console/src/main/resources/bootstrap.properties deleted file mode 100644 index c9c018201e..0000000000 --- a/discovery-springcloud-example-console/src/main/resources/bootstrap.properties +++ /dev/null @@ -1,79 +0,0 @@ -# Spring cloud config - -# Eureka config for discovery -eureka.client.serviceUrl.defaultZone=http://localhost:9528/eureka/ -eureka.instance.preferIpAddress=true - -# Consul config for discovery -spring.cloud.consul.host=localhost -spring.cloud.consul.port=8500 -spring.cloud.consul.discovery.preferIpAddress=true - -# Zookeeper config for discovery -spring.cloud.zookeeper.connectString=localhost:2181 -spring.cloud.zookeeper.discovery.instancePort=${server.port} -spring.cloud.zookeeper.discovery.root=/spring-cloud-service -spring.cloud.zookeeper.discovery.preferIpAddress=true - -# Nacos config for discovery -spring.cloud.nacos.discovery.server-addr=localhost:8848 -# spring.cloud.nacos.discovery.namespace=discovery - -# Ribbon config -ribbon.ConnectTimeout=60000 -ribbon.ReadTimeout=60000 - -# Apollo config for rule -apollo.portal-url=http://localhost:8088 -apollo.token=b26d851c635fd51ae21981443d7aa75f14d99e4e -apollo.operator=apollo -# apollo.connect-timeout=1000 -# apollo.read-timeout=5000 -apollo.plugin.app.id=discovery -apollo.plugin.env=DEV -# apollo.plugin.cluster=default -# apollo.plugin.namespace=application - -# Nacos config for rule -nacos.server-addr=localhost:8848 -# nacos.access-key= -# nacos.secret-key= -# nacos.plugin.namespace=application -# nacos.plugin.cluster-name= -# nacos.plugin.context-path= -# nacos.plugin.config-long-poll-timeout= -# nacos.plugin.config-retry-time= -# nacos.plugin.max-retry= -# nacos.plugin.endpoint= -# nacos.plugin.endpoint-port= -# nacos.plugin.is-use-endpoint-parsing-rule= -# nacos.plugin.is-use-cloud-namespace-parsing= -# nacos.plugin.encode= -# nacos.plugin.naming-load-cache-at-start= -# nacos.plugin.naming-client-beat-thread-count= -# nacos.plugin.naming-polling-thread-count= -# nacos.plugin.ram-role-name= -# nacos.plugin.timout= - -# Redis config for rule -spring.redis.host=localhost -spring.redis.port=6379 -spring.redis.password= -spring.redis.database=0 -spring.redis.pool.max-active=8 -spring.redis.pool.max-wait=-1 -spring.redis.pool.max-idle=8 -spring.redis.pool.min-idle=0 - -# Admin config -# 该项只对Consul有效,而且必须配置在bootstrap.properties里,配置在application.properties无效 -# management.health.consul.enabled=true -management.endpoints.web.exposure.include=* -management.endpoints.jmx.exposure.include=* -management.endpoint.health.show-details=ALWAYS -spring.boot.admin.client.instance.prefer-ip=true -spring.boot.admin.client.url=http://localhost:5555 - -# User config -admin=admin -nepxion=nepxion \ No newline at end of file diff --git a/discovery-springcloud-example-console/src/main/resources/logback.xml b/discovery-springcloud-example-console/src/main/resources/logback.xml deleted file mode 100644 index 239583856c..0000000000 --- a/discovery-springcloud-example-console/src/main/resources/logback.xml +++ /dev/null @@ -1,49 +0,0 @@ - - - - - - - discovery %date %level [%thread] %logger{10} [%file:%line] - %msg%n - UTF-8 - - - log/discovery-%d{yyyy-MM-dd}.%i.log - 50MB - - - INFO - - - true - - - - 0 - 512 - - - - - - - - discovery %date %level [%thread] %logger{10} [%file:%line] - %msg%n - UTF-8 - - - - INFO - - - - - - - - - - - - - diff --git a/discovery-springcloud-example-eureka/pom.xml b/discovery-springcloud-example-eureka/pom.xml deleted file mode 100644 index 43175bc6a1..0000000000 --- a/discovery-springcloud-example-eureka/pom.xml +++ /dev/null @@ -1,63 +0,0 @@ - - - com.nepxion - discovery-springcloud-example-eureka - Nepxion Discovery Spring Cloud Example Eureka - jar - 4.0.0 - 1.0.0 - Nepxion Discovery is an enhancement for Spring Cloud Discovery - http://www.nepxion.com - - - Greenwich.SR2 - 2.1.6.RELEASE - 1.8 - UTF-8 - - - - - - org.springframework.cloud - spring-cloud-dependencies - ${spring.cloud.version} - pom - import - - - - org.springframework.boot - spring-boot-dependencies - ${spring.boot.version} - pom - import - - - - - - - org.springframework.cloud - spring-cloud-starter-netflix-eureka-server - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - - - -parameters - - ${project.build.sourceEncoding} - ${java.version} - ${java.version} - - - - - \ No newline at end of file diff --git a/discovery-springcloud-example-eureka/src/main/resources/logback.xml b/discovery-springcloud-example-eureka/src/main/resources/logback.xml deleted file mode 100644 index 239583856c..0000000000 --- a/discovery-springcloud-example-eureka/src/main/resources/logback.xml +++ /dev/null @@ -1,49 +0,0 @@ - - - - - - - discovery %date %level [%thread] %logger{10} [%file:%line] - %msg%n - UTF-8 - - - log/discovery-%d{yyyy-MM-dd}.%i.log - 50MB - - - INFO - - - true - - - - 0 - 512 - - - - - - - - discovery %date %level [%thread] %logger{10} [%file:%line] - %msg%n - UTF-8 - - - - INFO - - - - - - - - - - - - - diff --git a/discovery-springcloud-example-gateway/pom.xml b/discovery-springcloud-example-gateway/pom.xml deleted file mode 100644 index e979a38f45..0000000000 --- a/discovery-springcloud-example-gateway/pom.xml +++ /dev/null @@ -1,112 +0,0 @@ - - - com.nepxion - discovery-springcloud-example-gateway - Nepxion Discovery Spring Cloud Example Gateway - jar - 4.0.0 - 1.0.0 - Nepxion Discovery is an enhancement for Spring Cloud Discovery - http://www.nepxion.com - - - 5.2.0-SNAPSHOT - Greenwich.SR2 - 0.9.0.RELEASE - 2.1.6.RELEASE - 2.1.4 - 1.8 - UTF-8 - - - - - - org.springframework.cloud - spring-cloud-dependencies - ${spring.cloud.version} - pom - import - - - - org.springframework.cloud - spring-cloud-alibaba-dependencies - ${spring.cloud.alibaba.version} - pom - import - - - - org.springframework.boot - spring-boot-dependencies - ${spring.boot.version} - pom - import - - - - de.codecentric - spring-boot-admin-dependencies - ${spring.boot.admin.version} - pom - import - - - - - - - com.nepxion - - - - discovery-plugin-starter-nacos - ${discovery.version} - - - - com.nepxion - - discovery-plugin-config-center-starter-nacos - - ${discovery.version} - - - - com.nepxion - discovery-plugin-strategy-starter-gateway - ${discovery.version} - - - - - - - de.codecentric - spring-boot-admin-starter-client - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - - - -parameters - - ${project.build.sourceEncoding} - ${java.version} - ${java.version} - - - - - \ No newline at end of file diff --git a/discovery-springcloud-example-gateway/src/main/java/com/nepxion/discovery/plugin/example/gateway/impl/MyDiscoveryEnabledStrategy.java b/discovery-springcloud-example-gateway/src/main/java/com/nepxion/discovery/plugin/example/gateway/impl/MyDiscoveryEnabledStrategy.java deleted file mode 100644 index f7790ee6e3..0000000000 --- a/discovery-springcloud-example-gateway/src/main/java/com/nepxion/discovery/plugin/example/gateway/impl/MyDiscoveryEnabledStrategy.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.nepxion.discovery.plugin.example.gateway.impl; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; - -import com.nepxion.discovery.plugin.framework.adapter.PluginAdapter; -import com.nepxion.discovery.plugin.strategy.adapter.DiscoveryEnabledStrategy; -import com.nepxion.discovery.plugin.strategy.gateway.context.GatewayStrategyContextHolder; -import com.netflix.loadbalancer.Server; - -// 实现了组合策略,版本路由策略+区域路由策略+IP和端口路由策略+自定义策略 -public class MyDiscoveryEnabledStrategy implements DiscoveryEnabledStrategy { - private static final Logger LOG = LoggerFactory.getLogger(MyDiscoveryEnabledStrategy.class); - - @Autowired - private GatewayStrategyContextHolder gatewayStrategyContextHolder; - - @Autowired - private PluginAdapter pluginAdapter; - - @Override - public boolean apply(Server server) { - // 对Rest调用传来的Header参数(例如:mobile)做策略 - return applyFromHeader(server); - } - - // 根据Rest调用传来的Header参数(例如:mobile),选取执行调用请求的服务实例 - private boolean applyFromHeader(Server server) { - String mobile = gatewayStrategyContextHolder.getHeader("mobile"); - String serviceId = pluginAdapter.getServerServiceId(server); - String version = pluginAdapter.getServerVersion(server); - String region = pluginAdapter.getServerRegion(server); - - LOG.info("负载均衡用户定制触发:mobile={}, serviceId={}, version={}, region={}", mobile, serviceId, version, region); - - if (StringUtils.isNotEmpty(mobile)) { - // 手机号以移动138开头,路由到1.0版本的服务上 - if (mobile.startsWith("138") && StringUtils.equals(version, "1.0")) { - return true; - // 手机号以联通133开头,路由到2.0版本的服务上 - } else if (mobile.startsWith("133") && StringUtils.equals(version, "1.1")) { - return true; - } else { - // 其它情况,直接拒绝请求 - return false; - } - } - - return true; - } -} \ No newline at end of file diff --git a/discovery-springcloud-example-gateway/src/main/java/com/nepxion/discovery/plugin/example/gateway/impl/MyDiscoveryListener.java b/discovery-springcloud-example-gateway/src/main/java/com/nepxion/discovery/plugin/example/gateway/impl/MyDiscoveryListener.java deleted file mode 100644 index 02a4ae3c24..0000000000 --- a/discovery-springcloud-example-gateway/src/main/java/com/nepxion/discovery/plugin/example/gateway/impl/MyDiscoveryListener.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.nepxion.discovery.plugin.example.gateway.impl; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import java.util.Iterator; -import java.util.List; - -import org.apache.commons.lang3.StringUtils; -import org.springframework.cloud.client.ServiceInstance; - -import com.nepxion.discovery.plugin.framework.listener.discovery.AbstractDiscoveryListener; - -// 当目标服务的元数据中的Group为mygroup2,禁止被本服务发现(只用于DiscoveryClient.getInstances接口方法用) -public class MyDiscoveryListener extends AbstractDiscoveryListener { - @Override - public void onGetInstances(String serviceId, List instances) { - Iterator iterator = instances.iterator(); - while (iterator.hasNext()) { - ServiceInstance serviceInstance = iterator.next(); - String group = pluginAdapter.getInstanceGroup(serviceInstance); - if (StringUtils.equals(group, "mygroup2")) { - iterator.remove(); - - System.out.println("********** 服务名=" + serviceId + ",组名=" + group + "的服务禁止被本服务发现"); - } - } - } - - @Override - public void onGetServices(List services) { - - } - - @Override - public int getOrder() { - return LOWEST_PRECEDENCE - 500; - } -} \ No newline at end of file diff --git a/discovery-springcloud-example-gateway/src/main/java/com/nepxion/discovery/plugin/example/gateway/impl/MyLoadBalanceListener.java b/discovery-springcloud-example-gateway/src/main/java/com/nepxion/discovery/plugin/example/gateway/impl/MyLoadBalanceListener.java deleted file mode 100644 index e2eb553066..0000000000 --- a/discovery-springcloud-example-gateway/src/main/java/com/nepxion/discovery/plugin/example/gateway/impl/MyLoadBalanceListener.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.nepxion.discovery.plugin.example.gateway.impl; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import java.util.Iterator; -import java.util.List; - -import org.apache.commons.lang3.StringUtils; - -import com.nepxion.discovery.plugin.framework.listener.loadbalance.AbstractLoadBalanceListener; -import com.netflix.loadbalancer.Server; - -// 当目标服务的元数据中的Group为mygroup2,禁止被本服务负载均衡 -public class MyLoadBalanceListener extends AbstractLoadBalanceListener { - @Override - public void onGetServers(String serviceId, List servers) { - Iterator iterator = servers.iterator(); - while (iterator.hasNext()) { - Server server = iterator.next(); - String group = pluginAdapter.getServerGroup(server); - if (StringUtils.equals(group, "mygroup3")) { - iterator.remove(); - - System.out.println("********** 服务名=" + serviceId + ",组名=" + group + "的服务禁止被本服务负载均衡"); - } - } - } - - @Override - public int getOrder() { - return LOWEST_PRECEDENCE - 500; - } -} \ No newline at end of file diff --git a/discovery-springcloud-example-gateway/src/main/java/com/nepxion/discovery/plugin/example/gateway/impl/MyRegisterListener.java b/discovery-springcloud-example-gateway/src/main/java/com/nepxion/discovery/plugin/example/gateway/impl/MyRegisterListener.java deleted file mode 100644 index b85fb76ed3..0000000000 --- a/discovery-springcloud-example-gateway/src/main/java/com/nepxion/discovery/plugin/example/gateway/impl/MyRegisterListener.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.nepxion.discovery.plugin.example.gateway.impl; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import org.apache.commons.lang3.StringUtils; -import org.springframework.cloud.client.serviceregistry.Registration; - -import com.nepxion.discovery.common.constant.DiscoveryConstant; -import com.nepxion.discovery.common.exception.DiscoveryException; -import com.nepxion.discovery.plugin.framework.listener.register.AbstractRegisterListener; - -// 当本服务的元数据中的Group为mygroup1,禁止被注册到注册中心 -public class MyRegisterListener extends AbstractRegisterListener { - @Override - public void onRegister(Registration registration) { - String serviceId = registration.getServiceId().toLowerCase(); - String group = registration.getMetadata().get(DiscoveryConstant.GROUP); - if (StringUtils.equals(group, "mygroup1")) { - throw new DiscoveryException("服务名=" + serviceId + ",组名=" + group + "的服务禁止被注册到注册中心"); - } - } - - @Override - public void onDeregister(Registration registration) { - - } - - @Override - public void onSetStatus(Registration registration, String status) { - - } - - @Override - public void onClose() { - - } - - @Override - public int getOrder() { - return LOWEST_PRECEDENCE - 500; - } -} \ No newline at end of file diff --git a/discovery-springcloud-example-gateway/src/main/java/com/nepxion/discovery/plugin/example/gateway/impl/MyRouteFilter.java b/discovery-springcloud-example-gateway/src/main/java/com/nepxion/discovery/plugin/example/gateway/impl/MyRouteFilter.java deleted file mode 100644 index b43fc0ee7d..0000000000 --- a/discovery-springcloud-example-gateway/src/main/java/com/nepxion/discovery/plugin/example/gateway/impl/MyRouteFilter.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.nepxion.discovery.plugin.example.gateway.impl; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import org.apache.commons.lang3.StringUtils; -import org.springframework.beans.factory.annotation.Value; - -import com.nepxion.discovery.plugin.strategy.gateway.filter.DefaultGatewayStrategyRouteFilter; - -// 适用于A/B Testing或者更根据某业务参数决定灰度路由路径。可以结合配置中心分别配置A/B两条路径,可以动态改变并通知 -// 当Header中传来的用户为张三,执行一条路由路径;为李四,执行另一条路由路径 -public class MyRouteFilter extends DefaultGatewayStrategyRouteFilter { - private static final String DEFAULT_A_ROUTE_VERSION = "{\"discovery-springcloud-example-a\":\"1.0\", \"discovery-springcloud-example-b\":\"1.0\", \"discovery-springcloud-example-c\":\"1.0\"}"; - private static final String DEFAULT_B_ROUTE_VERSION = "{\"discovery-springcloud-example-a\":\"1.1\", \"discovery-springcloud-example-b\":\"1.1\", \"discovery-springcloud-example-c\":\"1.1\"}"; - - @Value("${a.route.version:" + DEFAULT_A_ROUTE_VERSION + "}") - private String aRouteVersion; - - @Value("${b.route.version:" + DEFAULT_B_ROUTE_VERSION + "}") - private String bRouteVersion; - - @Override - public String getRouteVersion() { - String user = strategyContextHolder.getHeader("user"); - - if (StringUtils.equals(user, "zhangsan")) { - return aRouteVersion; - } else if (StringUtils.equals(user, "lisi")) { - return bRouteVersion; - } - - return super.getRouteVersion(); - } -} \ No newline at end of file diff --git a/discovery-springcloud-example-gateway/src/main/resources/application.properties b/discovery-springcloud-example-gateway/src/main/resources/application.properties deleted file mode 100644 index 1ece098924..0000000000 --- a/discovery-springcloud-example-gateway/src/main/resources/application.properties +++ /dev/null @@ -1,21 +0,0 @@ -# Spring cloud config -spring.application.name=discovery-springcloud-example-gateway -server.port=1500 - -# Eureka config for discovery -eureka.instance.metadataMap.group=example-service-group -eureka.instance.metadataMap.version=1.0 - -# Consul config for discovery -spring.cloud.consul.discovery.tags=group=example-service-group,version=1.0 - -# Zookeeper config for discovery -spring.cloud.zookeeper.discovery.metadata.group=example-service-group -spring.cloud.zookeeper.discovery.metadata.version=1.0 - -# Nacos config for discovery -spring.cloud.nacos.discovery.metadata.group=example-service-group -spring.cloud.nacos.discovery.metadata.version=1.0 - -# Admin config -management.server.port=5500 \ No newline at end of file diff --git a/discovery-springcloud-example-gateway/src/main/resources/bootstrap.properties b/discovery-springcloud-example-gateway/src/main/resources/bootstrap.properties deleted file mode 100644 index f40053b9f2..0000000000 --- a/discovery-springcloud-example-gateway/src/main/resources/bootstrap.properties +++ /dev/null @@ -1,128 +0,0 @@ -# Spring cloud config - -# Eureka config for discovery -eureka.client.serviceUrl.defaultZone=http://localhost:9528/eureka/ -eureka.instance.preferIpAddress=true - -# Consul config for discovery -spring.cloud.consul.host=localhost -spring.cloud.consul.port=8500 -spring.cloud.consul.discovery.preferIpAddress=true - -# Zookeeper config for discovery -spring.cloud.zookeeper.connectString=localhost:2181 -spring.cloud.zookeeper.discovery.instancePort=${server.port} -spring.cloud.zookeeper.discovery.root=/spring-cloud-service -spring.cloud.zookeeper.discovery.preferIpAddress=true - -# Nacos config for discovery -spring.cloud.nacos.discovery.server-addr=localhost:8848 -# spring.cloud.nacos.discovery.namespace=discovery - -# Ribbon config -ribbon.ConnectTimeout=60000 -ribbon.ReadTimeout=60000 - -# Apollo config for rule -app.id=discovery -apollo.meta=http://localhost:8080 -# apollo.plugin.namespace=application - -# Nacos config for rule -nacos.server-addr=localhost:8848 -# nacos.access-key= -# nacos.secret-key= -# nacos.plugin.namespace=application -# nacos.plugin.cluster-name= -# nacos.plugin.context-path= -# nacos.plugin.config-long-poll-timeout= -# nacos.plugin.config-retry-time= -# nacos.plugin.max-retry= -# nacos.plugin.endpoint= -# nacos.plugin.endpoint-port= -# nacos.plugin.is-use-endpoint-parsing-rule= -# nacos.plugin.is-use-cloud-namespace-parsing= -# nacos.plugin.encode= -# nacos.plugin.naming-load-cache-at-start= -# nacos.plugin.naming-client-beat-thread-count= -# nacos.plugin.naming-polling-thread-count= -# nacos.plugin.ram-role-name= -# nacos.plugin.timout= - -# Redis config for rule -spring.redis.host=localhost -spring.redis.port=6379 -spring.redis.password= -spring.redis.database=0 -spring.redis.pool.max-active=8 -spring.redis.pool.max-wait=-1 -spring.redis.pool.max-idle=8 -spring.redis.pool.min-idle=0 - -# Admin config -# 该项只对Consul有效,而且必须配置在bootstrap.properties里,配置在application.properties无效 -# management.health.consul.enabled=true -management.endpoints.web.exposure.include=* -management.endpoints.jmx.exposure.include=* -management.endpoint.health.show-details=ALWAYS -spring.boot.admin.client.instance.prefer-ip=true -spring.boot.admin.client.url=http://localhost:5555 - -# Plugin core config -# 开启和关闭服务注册层面的控制。一旦关闭,服务注册的黑/白名单过滤功能将失效,最大注册数的限制过滤功能将失效。缺失则默认为true -# spring.application.register.control.enabled=true -# 开启和关闭服务发现层面的控制。一旦关闭,服务多版本调用的控制功能将失效,动态屏蔽指定IP地址的服务实例被发现的功能将失效。缺失则默认为true -# spring.application.discovery.control.enabled=true -# 开启和关闭通过Rest方式对规则配置的控制和推送。一旦关闭,只能通过远程配置中心来控制和推送。缺失则默认为true -# spring.application.config.rest.control.enabled=true -# 规则文件的格式,支持xml和json。缺失则默认为xml -# spring.application.config.format=xml -# spring.application.config.format=json -# 本地规则文件的路径,支持两种方式:classpath:rule.xml(rule.json) - 规则文件放在resources目录下,便于打包进jar;file:rule.xml(rule.json) - 规则文件放在工程根目录下,放置在外部便于修改。缺失则默认为不装载本地规则 -# spring.application.config.path=classpath:rule.xml -# spring.application.config.path=classpath:rule.json -# 为微服务归类的Key,一般通过group字段来归类,例如eureka.instance.metadataMap.group=xxx-group或者eureka.instance.metadataMap.application=xxx-application。缺失则默认为group -# spring.application.group.key=group -# spring.application.group.key=application -# 由于服务未注册,或者被过滤,或者被隔离,导致消费端拿不到服务实例的时候,通过日志方式通知。缺失则默认为false -# spring.application.no.server.found.notification.enabled=false - -# Plugin strategy config -# 开启和关闭策略扩展功能的控制。一旦关闭,用户自定义和编程灰度路由策略功能将失效。缺失则默认为true -# spring.application.strategy.control.enabled=true -# 开启和关闭Ribbon默认的ZoneAvoidanceRule负载均衡策略。一旦关闭,则使用RoundRobin简单轮询负载均衡策略。缺失则默认为true -# spring.application.strategy.zone.avoidance.rule.enabled=true -# 开启和关闭内置的路由策略过滤器。一旦关闭,基于配置中心(或自定义)的路由策略Header传递方式将失效,只能通过前端的路由策略Header传递方式。缺失则默认为true -# spring.application.strategy.gateway.route.filter.enabled=true -# 路由策略过滤器的执行顺序(Order)。缺失则默认为9000 -# spring.application.strategy.gateway.route.filter.order=9000 -# 当外界传值Header的时候,网关也设置并传递同名的Header,需要决定哪个Header传递到后边的服务去。如果下面开关为true,以网关设置为优先,否则以外界传值为优先。缺失则默认为true -spring.application.strategy.gateway.header.priority=false -# 启动和关闭注册的服务隔离(基于Group黑/白名单的策略)。缺失则默认为false -spring.application.strategy.register.isolation.enabled=true -# 启动和关闭消费端的服务隔离(基于Group是否相同的策略)。缺失则默认为false -spring.application.strategy.consumer.isolation.enabled=true -# 启动和关闭提供端的服务隔离(基于Group是否相同的策略)。缺失则默认为false -spring.application.strategy.provider.isolation.enabled=true -# 启动和关闭Header传递的日志打印,注意每调用一次都会打印一次,会对性能有所影响,建议压测环境和生产环境关闭。缺失则默认为false -spring.application.strategy.intercept.log.print=true -# 开启Spring Cloud Gateway网关上实现Hystrix线程隔离模式做服务隔离时,必须把spring.application.strategy.hystrix.threadlocal.supported设置为true,同时要引入discovery-plugin-strategy-starter-hystrix包,否则线程切换时会发生ThreadLocal上下文对象丢失 -# spring.application.strategy.hystrix.threadlocal.supported=true - -# Spring cloud gateway config -# 跟Hystrix会冲突。开启Hystrix后,下面项必须注释掉 -# spring.cloud.gateway.discovery.locator.enabled=true -spring.cloud.gateway.discovery.locator.lowerCaseServiceId=true -spring.cloud.gateway.routes[0].id=discovery-springcloud-example-a -spring.cloud.gateway.routes[0].predicates[0]=Path=/discovery-springcloud-example-a/** -# spring.cloud.gateway.routes[0].filters[0]=SetPath=/discovery-springcloud-example-a/** -# Gateway如果用Consul做服务注册发现中心,必须配置StripPrefix=1,其他配置中心配不配无所谓,但建议都配 -spring.cloud.gateway.routes[0].filters[0]=StripPrefix=1 -spring.cloud.gateway.routes[0].uri=lb://discovery-springcloud-example-a - -# Hystrix配置 -# spring.cloud.gateway.routes[0].filters[1].name=Hystrix -# spring.cloud.gateway.routes[0].filters[1].args.name=default -# spring.cloud.gateway.routes[0].filters[1].args.fallbackUri=forward:/fallback -# hystrix.command.default.execution.isolation.strategy=THREAD -# hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds=3000 \ No newline at end of file diff --git a/discovery-springcloud-example-gateway/src/main/resources/logback.xml b/discovery-springcloud-example-gateway/src/main/resources/logback.xml deleted file mode 100644 index 239583856c..0000000000 --- a/discovery-springcloud-example-gateway/src/main/resources/logback.xml +++ /dev/null @@ -1,49 +0,0 @@ - - - - - - - discovery %date %level [%thread] %logger{10} [%file:%line] - %msg%n - UTF-8 - - - log/discovery-%d{yyyy-MM-dd}.%i.log - 50MB - - - INFO - - - true - - - - 0 - 512 - - - - - - - - discovery %date %level [%thread] %logger{10} [%file:%line] - %msg%n - UTF-8 - - - - INFO - - - - - - - - - - - - - diff --git a/discovery-springcloud-example-service/pom.xml b/discovery-springcloud-example-service/pom.xml deleted file mode 100644 index 85854a2b49..0000000000 --- a/discovery-springcloud-example-service/pom.xml +++ /dev/null @@ -1,117 +0,0 @@ - - - com.nepxion - discovery-springcloud-example-service - Nepxion Discovery Spring Cloud Example Service - jar - 4.0.0 - 1.0.0 - Nepxion Discovery is an enhancement for Spring Cloud Discovery - http://www.nepxion.com - - - 5.2.0-SNAPSHOT - Greenwich.SR2 - 0.9.0.RELEASE - 2.1.6.RELEASE - 2.1.4 - 1.8 - UTF-8 - - - - - - org.springframework.cloud - spring-cloud-dependencies - ${spring.cloud.version} - pom - import - - - - org.springframework.cloud - spring-cloud-alibaba-dependencies - ${spring.cloud.alibaba.version} - pom - import - - - - org.springframework.boot - spring-boot-dependencies - ${spring.boot.version} - pom - import - - - - de.codecentric - spring-boot-admin-dependencies - ${spring.boot.admin.version} - pom - import - - - - - - - com.nepxion - - - - discovery-plugin-starter-nacos - ${discovery.version} - - - - com.nepxion - - discovery-plugin-config-center-starter-nacos - - ${discovery.version} - - - - com.nepxion - discovery-plugin-strategy-starter-service - ${discovery.version} - - - - - - - org.springframework.cloud - spring-cloud-starter-alibaba-sentinel - - - - de.codecentric - spring-boot-admin-starter-client - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - - - -parameters - - ${project.build.sourceEncoding} - ${java.version} - ${java.version} - - - - - \ No newline at end of file diff --git a/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/context/MyApplicationContextInitializer.java b/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/context/MyApplicationContextInitializer.java deleted file mode 100644 index 9511df5efa..0000000000 --- a/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/context/MyApplicationContextInitializer.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.nepxion.discovery.plugin.example.service.context; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext; -import org.springframework.context.ApplicationContextInitializer; -import org.springframework.context.ConfigurableApplicationContext; - -// 通过如下方式,可以代替在配置文件里面配置元数据,格式为ext.xxx。例如,如果version希望通过git插件获取到最后一次提交编号,可以动态在这里进行解析并放入 -public class MyApplicationContextInitializer implements ApplicationContextInitializer { - @Override - public void initialize(ConfigurableApplicationContext applicationContext) { - if (applicationContext instanceof AnnotationConfigServletWebServerApplicationContext) { - // System.setProperty("ext.group", "myGroup"); - // System.setProperty("ext.version", "8888"); - // System.setProperty("ext.region", "myRegion"); - } - } -} \ No newline at end of file diff --git a/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/feign/AFeignImpl.java b/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/feign/AFeignImpl.java deleted file mode 100644 index 96b8f863be..0000000000 --- a/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/feign/AFeignImpl.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.nepxion.discovery.plugin.example.service.feign; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RestController; - -import com.nepxion.discovery.common.constant.DiscoveryConstant; - -@RestController -@ConditionalOnProperty(name = DiscoveryConstant.SPRING_APPLICATION_NAME, havingValue = "discovery-springcloud-example-a") -public class AFeignImpl extends AbstractFeignImpl implements AFeign { - private static final Logger LOG = LoggerFactory.getLogger(AFeignImpl.class); - - @Autowired - private BFeign bFeign; - - // Hystrix测试 - // @Autowired - // private HystrixService hystrixService; - - @Override - public String invoke(@RequestBody String value) { - // LOG.info("---------- 主方法里获取上下文 RequestContextHolder.getRequestAttributes():{}", RequestContextHolder.getRequestAttributes()); - // LOG.info("---------- 主方法里获取上下文 RestStrategyContext.getCurrentContext().getRequestAttributes():{}", RestStrategyContext.getCurrentContext().getRequestAttributes()); - // LOG.info("---------- 主方法里获取Token:{}", ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader("token")); - - // hystrixService.invokeHystrix(value); - - value = doInvoke(value); - value = bFeign.invoke(value); - - LOG.info("调用路径:{}", value); - - return value; - } -} \ No newline at end of file diff --git a/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/feign/AbstractFeignImpl.java b/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/feign/AbstractFeignImpl.java deleted file mode 100644 index 39f4910afe..0000000000 --- a/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/feign/AbstractFeignImpl.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.nepxion.discovery.plugin.example.service.feign; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import org.apache.commons.lang3.StringUtils; -import org.springframework.beans.factory.annotation.Autowired; - -import com.nepxion.discovery.plugin.framework.adapter.PluginAdapter; - -public class AbstractFeignImpl { - @Autowired - private PluginAdapter pluginAdapter; - - public String doInvoke(String value) { - String serviceId = pluginAdapter.getServiceId(); - String host = pluginAdapter.getHost(); - int port = pluginAdapter.getPort(); - String version = pluginAdapter.getVersion(); - String region = pluginAdapter.getRegion(); - - StringBuilder stringBuilder = new StringBuilder(); - stringBuilder.append(value + " -> " + serviceId); - stringBuilder.append("[" + host + ":" + port + "]"); - if (StringUtils.isNotEmpty(version)) { - stringBuilder.append("[V" + version + "]"); - } - if (StringUtils.isNotEmpty(region)) { - stringBuilder.append("[Region=" + region + "]"); - } - - return stringBuilder.toString(); - } -} \ No newline at end of file diff --git a/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/hystrix/HystrixService.java b/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/hystrix/HystrixService.java deleted file mode 100644 index 681e6b9d3d..0000000000 --- a/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/hystrix/HystrixService.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.nepxion.discovery.plugin.example.service.hystrix; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Service; -import org.springframework.web.context.request.ServletRequestAttributes; - -import com.nepxion.discovery.plugin.strategy.service.context.RestStrategyContext; - -@Service -public class HystrixService { - private static final Logger LOG = LoggerFactory.getLogger(HystrixService.class); - - // Hystrix测试 - // @HystrixCommand(fallbackMethod = "invokeFallback", commandProperties = { @HystrixProperty(name = "execution.isolation.strategy", value = "THREAD") }) - public String invokeHystrix(String value) { - LOG.info("---------- 熔断方法里获取上下文 RestStrategyContext.getCurrentContext().getRequestAttributes():{}", RestStrategyContext.getCurrentContext().getRequestAttributes()); - LOG.info("---------- 熔断方法里获取Token:{}", ((ServletRequestAttributes) RestStrategyContext.getCurrentContext().getRequestAttributes()).getRequest().getHeader("token")); - - return "Invoke Hystrix"; - } - - public String invokeFallback(String value, Throwable e) { - LOG.info("---------- 快速失败方法里获取上下文 RestStrategyContext.getCurrentContext().getRequestAttributes():{}", RestStrategyContext.getCurrentContext().getRequestAttributes()); - - if (e != null) { - LOG.error("Fallback error", e); - } - - return "Fallback by Hystrix"; - } -} \ No newline at end of file diff --git a/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/impl/MyDiscoveryEnabledStrategy.java b/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/impl/MyDiscoveryEnabledStrategy.java deleted file mode 100644 index 2b068d46c6..0000000000 --- a/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/impl/MyDiscoveryEnabledStrategy.java +++ /dev/null @@ -1,94 +0,0 @@ -package com.nepxion.discovery.plugin.example.service.impl; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import java.util.Map; - -import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; - -import com.nepxion.discovery.plugin.framework.adapter.PluginAdapter; -import com.nepxion.discovery.plugin.strategy.adapter.DiscoveryEnabledStrategy; -import com.nepxion.discovery.plugin.strategy.service.constant.ServiceStrategyConstant; -import com.nepxion.discovery.plugin.strategy.service.context.ServiceStrategyContextHolder; -import com.netflix.loadbalancer.Server; - -// 实现了组合策略,版本路由策略+区域路由策略+IP和端口路由策略+自定义策略 -public class MyDiscoveryEnabledStrategy implements DiscoveryEnabledStrategy { - private static final Logger LOG = LoggerFactory.getLogger(MyDiscoveryEnabledStrategy.class); - - @Autowired - private ServiceStrategyContextHolder serviceStrategyContextHolder; - - @Autowired - private PluginAdapter pluginAdapter; - - @Override - public boolean apply(Server server) { - // 对Rest调用传来的Header参数(例如:token)做策略 - boolean enabled = applyFromHeader(server); - if (!enabled) { - return false; - } - - // 对RPC调用传来的方法参数做策略 - return applyFromMethod(server); - } - - // 根据Rest调用传来的Header参数(例如:token),选取执行调用请求的服务实例 - private boolean applyFromHeader(Server server) { - String token = serviceStrategyContextHolder.getHeader("token"); - String serviceId = pluginAdapter.getServerServiceId(server); - String version = pluginAdapter.getServerVersion(server); - String region = pluginAdapter.getServerRegion(server); - - LOG.info("负载均衡用户定制触发:token={}, serviceId={}, version={}, region={}", token, serviceId, version, region); - - String filterServiceId = "discovery-springcloud-example-c"; - String filterToken = "123"; - if (StringUtils.equals(serviceId, filterServiceId) && StringUtils.isNotEmpty(token) && token.contains(filterToken)) { - LOG.info("过滤条件:当serviceId={} && Token含有'{}'的时候,不能被Ribbon负载均衡到", filterServiceId, filterToken); - - return false; - } - - return true; - } - - // 根据RPC调用传来的方法参数(例如接口名、方法名、参数名或参数值等),选取执行调用请求的服务实例 - @SuppressWarnings("unchecked") - private boolean applyFromMethod(Server server) { - Map attributes = serviceStrategyContextHolder.getRpcAttributes(); - String serviceId = pluginAdapter.getServerServiceId(server); - String version = pluginAdapter.getServerVersion(server); - String region = pluginAdapter.getServerRegion(server); - - LOG.info("负载均衡用户定制触发:attributes={}, serviceId={}, version={}, region={}", attributes, serviceId, version, region); - - String filterServiceId = "discovery-springcloud-example-b"; - String filterVersion = "1.0"; - String filterBusinessValue = "abc"; - if (StringUtils.equals(serviceId, filterServiceId) && StringUtils.equals(version, filterVersion)) { - if (attributes.containsKey(ServiceStrategyConstant.PARAMETER_MAP)) { - Map parameterMap = (Map) attributes.get(ServiceStrategyConstant.PARAMETER_MAP); - String value = parameterMap.get("value").toString(); - if (StringUtils.isNotEmpty(value) && value.contains(filterBusinessValue)) { - LOG.info("过滤条件:当serviceId={} && version={} && 业务参数含有'{}'的时候,不能被Ribbon负载均衡到", filterServiceId, filterVersion, filterBusinessValue); - - return false; - } - } - } - - return true; - } -} \ No newline at end of file diff --git a/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/impl/MyDiscoveryListener.java b/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/impl/MyDiscoveryListener.java deleted file mode 100644 index 48b8f53b3b..0000000000 --- a/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/impl/MyDiscoveryListener.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.nepxion.discovery.plugin.example.service.impl; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import java.util.Iterator; -import java.util.List; - -import org.apache.commons.lang3.StringUtils; -import org.springframework.cloud.client.ServiceInstance; - -import com.nepxion.discovery.plugin.framework.listener.discovery.AbstractDiscoveryListener; - -// 当目标服务的元数据中的Group为mygroup2,禁止被本服务发现(只用于DiscoveryClient.getInstances接口方法用) -public class MyDiscoveryListener extends AbstractDiscoveryListener { - @Override - public void onGetInstances(String serviceId, List instances) { - Iterator iterator = instances.iterator(); - while (iterator.hasNext()) { - ServiceInstance serviceInstance = iterator.next(); - String group = pluginAdapter.getInstanceGroup(serviceInstance); - if (StringUtils.equals(group, "mygroup2")) { - iterator.remove(); - - System.out.println("********** 服务名=" + serviceId + ",组名=" + group + "的服务禁止被本服务发现"); - } - } - } - - @Override - public void onGetServices(List services) { - - } - - @Override - public int getOrder() { - return LOWEST_PRECEDENCE - 500; - } -} \ No newline at end of file diff --git a/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/impl/MyLoadBalanceListener.java b/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/impl/MyLoadBalanceListener.java deleted file mode 100644 index 7daa51d0b4..0000000000 --- a/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/impl/MyLoadBalanceListener.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.nepxion.discovery.plugin.example.service.impl; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import java.util.Iterator; -import java.util.List; - -import org.apache.commons.lang3.StringUtils; - -import com.nepxion.discovery.plugin.framework.listener.loadbalance.AbstractLoadBalanceListener; -import com.netflix.loadbalancer.Server; - -// 当目标服务的元数据中的Group为mygroup2,禁止被本服务负载均衡 -public class MyLoadBalanceListener extends AbstractLoadBalanceListener { - @Override - public void onGetServers(String serviceId, List servers) { - Iterator iterator = servers.iterator(); - while (iterator.hasNext()) { - Server server = iterator.next(); - String group = pluginAdapter.getServerGroup(server); - if (StringUtils.equals(group, "mygroup3")) { - iterator.remove(); - - System.out.println("********** 服务名=" + serviceId + ",组名=" + group + "的服务禁止被本服务负载均衡"); - } - } - } - - @Override - public int getOrder() { - return LOWEST_PRECEDENCE - 500; - } -} \ No newline at end of file diff --git a/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/impl/MyRegisterListener.java b/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/impl/MyRegisterListener.java deleted file mode 100644 index 4865aacab8..0000000000 --- a/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/impl/MyRegisterListener.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.nepxion.discovery.plugin.example.service.impl; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import org.apache.commons.lang3.StringUtils; -import org.springframework.cloud.client.serviceregistry.Registration; - -import com.nepxion.discovery.common.constant.DiscoveryConstant; -import com.nepxion.discovery.common.exception.DiscoveryException; -import com.nepxion.discovery.plugin.framework.listener.register.AbstractRegisterListener; - -// 当本服务的元数据中的Group为mygroup1,禁止被注册到注册中心 -public class MyRegisterListener extends AbstractRegisterListener { - @Override - public void onRegister(Registration registration) { - String serviceId = registration.getServiceId().toLowerCase(); - String group = registration.getMetadata().get(DiscoveryConstant.GROUP); - if (StringUtils.equals(group, "mygroup1")) { - throw new DiscoveryException("服务名=" + serviceId + ",组名=" + group + "的服务禁止被注册到注册中心"); - } - } - - @Override - public void onDeregister(Registration registration) { - - } - - @Override - public void onSetStatus(Registration registration, String status) { - - } - - @Override - public void onClose() { - - } - - @Override - public int getOrder() { - return LOWEST_PRECEDENCE - 500; - } -} \ No newline at end of file diff --git a/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/impl/MySubscriber.java b/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/impl/MySubscriber.java deleted file mode 100644 index 19f296a860..0000000000 --- a/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/impl/MySubscriber.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.nepxion.discovery.plugin.example.service.impl; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import java.util.Map; - -import org.springframework.beans.factory.annotation.Autowired; - -import com.google.common.eventbus.Subscribe; -import com.nepxion.discovery.common.entity.CustomizationEntity; -import com.nepxion.discovery.plugin.framework.adapter.PluginAdapter; -import com.nepxion.discovery.plugin.framework.event.CustomizationEvent; -import com.nepxion.discovery.plugin.framework.event.RegisterFailureEvent; -import com.nepxion.eventbus.annotation.EventBus; - -@EventBus -public class MySubscriber { - @Autowired - private PluginAdapter pluginAdapter; - - @Subscribe - public void onCustomization(CustomizationEvent customizationEvent) { - CustomizationEntity customizationEntity = customizationEvent.getCustomizationEntity(); - String serviceId = pluginAdapter.getServiceId(); - if (customizationEntity != null) { - Map> customizationMap = customizationEntity.getCustomizationMap(); - Map customizationParameter = customizationMap.get(serviceId); - System.out.println("========== 获取客户化对象, serviceId=" + serviceId + ", customizationParameter=" + customizationParameter); - // 根据customizationParameter的参数动态切换数据源 - } else { - System.out.println("========== 获取客户化对象, serviceId=" + serviceId + ", customizationEntity=" + customizationEntity); - // 根据customizationParameter的参数动态切换数据源 - } - } - - @Subscribe - public void onRegisterFailure(RegisterFailureEvent registerFailureEvent) { - System.out.println("========== 注册失败, eventType=" + registerFailureEvent.getEventType() + ", eventDescription=" + registerFailureEvent.getEventDescription() + ", serviceId=" + registerFailureEvent.getServiceId() + ", host=" + registerFailureEvent.getHost() + ", port=" + registerFailureEvent.getPort()); - } -} \ No newline at end of file diff --git a/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/rest/AbstractRestImpl.java b/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/rest/AbstractRestImpl.java deleted file mode 100644 index b86abd5a9e..0000000000 --- a/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/rest/AbstractRestImpl.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.nepxion.discovery.plugin.example.service.rest; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import org.apache.commons.lang3.StringUtils; -import org.springframework.beans.factory.annotation.Autowired; - -import com.nepxion.discovery.plugin.framework.adapter.PluginAdapter; - -public class AbstractRestImpl { - @Autowired - private PluginAdapter pluginAdapter; - - public String doRest(String value) { - String serviceId = pluginAdapter.getServiceId(); - String host = pluginAdapter.getHost(); - int port = pluginAdapter.getPort(); - String version = pluginAdapter.getVersion(); - String region = pluginAdapter.getRegion(); - - StringBuilder stringBuilder = new StringBuilder(); - stringBuilder.append(value + " -> " + serviceId); - stringBuilder.append("[" + host + ":" + port + "]"); - if (StringUtils.isNotEmpty(version)) { - stringBuilder.append("[V" + version + "]"); - } - if (StringUtils.isNotEmpty(region)) { - stringBuilder.append("[Region=" + region + "]"); - } - - return stringBuilder.toString(); - } -} \ No newline at end of file diff --git a/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/sentinel/MyAFeignFallbackHandler.java b/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/sentinel/MyAFeignFallbackHandler.java deleted file mode 100644 index 532901e514..0000000000 --- a/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/sentinel/MyAFeignFallbackHandler.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.nepxion.discovery.plugin.example.service.sentinel; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Component; - -import com.nepxion.discovery.plugin.example.service.feign.AFeign; - -@Component -public class MyAFeignFallbackHandler implements AFeign { - private static final Logger LOG = LoggerFactory.getLogger(MyAFeignFallbackHandler.class); - - @Override - public String invoke(String value) { - LOG.info("Value={}", value); - - return "Sentinel AFeign Client Fallback Causes"; - } -} \ No newline at end of file diff --git a/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/sentinel/MyBFeignFallbackHandler.java b/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/sentinel/MyBFeignFallbackHandler.java deleted file mode 100644 index e41f67e2b8..0000000000 --- a/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/sentinel/MyBFeignFallbackHandler.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.nepxion.discovery.plugin.example.service.sentinel; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Component; - -import com.nepxion.discovery.plugin.example.service.feign.BFeign; - -@Component -public class MyBFeignFallbackHandler implements BFeign { - private static final Logger LOG = LoggerFactory.getLogger(MyBFeignFallbackHandler.class); - - @Override - public String invoke(String value) { - LOG.info("Value={}", value); - - return "Sentinel BFeign Client Fallback Causes"; - } -} \ No newline at end of file diff --git a/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/sentinel/MyCFeignFallbackHandler.java b/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/sentinel/MyCFeignFallbackHandler.java deleted file mode 100644 index ef7d444b23..0000000000 --- a/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/sentinel/MyCFeignFallbackHandler.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.nepxion.discovery.plugin.example.service.sentinel; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Component; - -import com.nepxion.discovery.plugin.example.service.feign.CFeign; - -@Component -public class MyCFeignFallbackHandler implements CFeign { - private static final Logger LOG = LoggerFactory.getLogger(MyCFeignFallbackHandler.class); - - @Override - public String invoke(String value) { - LOG.info("Value={}", value); - - return "Sentinel CFeign Client Fallback Causes"; - } -} \ No newline at end of file diff --git a/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/sentinel/MyRestTemplateBlockHandler.java b/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/sentinel/MyRestTemplateBlockHandler.java deleted file mode 100644 index 48d6491a4b..0000000000 --- a/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/sentinel/MyRestTemplateBlockHandler.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.nepxion.discovery.plugin.example.service.sentinel; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.cloud.alibaba.sentinel.rest.SentinelClientHttpResponse; -import org.springframework.http.HttpRequest; -import org.springframework.http.client.ClientHttpRequestExecution; - -import com.alibaba.csp.sentinel.slots.block.BlockException; - -public class MyRestTemplateBlockHandler { - private static final Logger LOG = LoggerFactory.getLogger(MyRestTemplateBlockHandler.class); - - public static SentinelClientHttpResponse handleBlock(HttpRequest request, byte[] body, ClientHttpRequestExecution execution, BlockException e) { - LOG.info("Sentinel RestTemplate Client Block Causes"); - LOG.error("Sentinel RestTemplate Client Block Exception", e); - LOG.info("Sentinel Rule Limit App={}", e.getRuleLimitApp()); - LOG.info("Sentinel Exception Name={}", e.getClass().getCanonicalName()); - - return new SentinelClientHttpResponse("Sentinel RestTemplate Client Block Causes"); - } -} \ No newline at end of file diff --git a/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/sentinel/MyRestTemplateFallbackHandler.java b/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/sentinel/MyRestTemplateFallbackHandler.java deleted file mode 100644 index 568a3d11e9..0000000000 --- a/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/sentinel/MyRestTemplateFallbackHandler.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.nepxion.discovery.plugin.example.service.sentinel; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.cloud.alibaba.sentinel.rest.SentinelClientHttpResponse; -import org.springframework.http.HttpRequest; -import org.springframework.http.client.ClientHttpRequestExecution; - -import com.alibaba.csp.sentinel.slots.block.BlockException; - -public class MyRestTemplateFallbackHandler { - private static final Logger LOG = LoggerFactory.getLogger(MyRestTemplateFallbackHandler.class); - - public static SentinelClientHttpResponse handleFallback(HttpRequest request, byte[] body, ClientHttpRequestExecution execution, BlockException e) { - LOG.info("Sentinel RestTemplate Client Fallback Causes"); - LOG.error("Sentinel RestTemplate Client Fallback Exception", e); - LOG.info("Sentinel Rule Limit App={}", e.getRuleLimitApp()); - LOG.info("Sentinel Exception Name={}", e.getClass().getCanonicalName()); - - return new SentinelClientHttpResponse("Sentinel RestTemplate Client Fallback Causes"); - } -} \ No newline at end of file diff --git a/discovery-springcloud-example-service/src/main/resources/application-a1.properties b/discovery-springcloud-example-service/src/main/resources/application-a1.properties deleted file mode 100644 index 60e0cb654c..0000000000 --- a/discovery-springcloud-example-service/src/main/resources/application-a1.properties +++ /dev/null @@ -1,24 +0,0 @@ -# Spring cloud config -spring.application.name=discovery-springcloud-example-a -server.port=1100 - -# Eureka config for discovery -eureka.instance.metadataMap.group=example-service-group -eureka.instance.metadataMap.version=1.0 -eureka.instance.metadataMap.region=dev - -# Consul config for discovery -spring.cloud.consul.discovery.tags=group=example-service-group,version=1.0,region=dev - -# Zookeeper config for discovery -spring.cloud.zookeeper.discovery.metadata.group=example-service-group -spring.cloud.zookeeper.discovery.metadata.version=1.0 -spring.cloud.zookeeper.discovery.metadata.region=dev - -# Nacos config for discovery -spring.cloud.nacos.discovery.metadata.group=example-service-group -spring.cloud.nacos.discovery.metadata.version=1.0 -spring.cloud.nacos.discovery.metadata.region=dev - -# Admin config -management.server.port=5100 \ No newline at end of file diff --git a/discovery-springcloud-example-service/src/main/resources/application-a2.properties b/discovery-springcloud-example-service/src/main/resources/application-a2.properties deleted file mode 100644 index 6a00e535bd..0000000000 --- a/discovery-springcloud-example-service/src/main/resources/application-a2.properties +++ /dev/null @@ -1,24 +0,0 @@ -# Spring cloud config -spring.application.name=discovery-springcloud-example-a -server.port=1101 - -# Eureka config for discovery -eureka.instance.metadataMap.group=example-service-group -eureka.instance.metadataMap.version=1.1 -eureka.instance.metadataMap.region=qa - -# Consul config for discovery -spring.cloud.consul.discovery.tags=group=example-service-group,version=1.1,region=qa - -# Zookeeper config for discovery -spring.cloud.zookeeper.discovery.metadata.group=example-service-group -spring.cloud.zookeeper.discovery.metadata.version=1.1 -spring.cloud.zookeeper.discovery.metadata.region=qa - -# Nacos config for discovery -spring.cloud.nacos.discovery.metadata.group=example-service-group -spring.cloud.nacos.discovery.metadata.version=1.1 -spring.cloud.nacos.discovery.metadata.region=qa - -# Admin config -management.server.port=5101 \ No newline at end of file diff --git a/discovery-springcloud-example-service/src/main/resources/application-b1.properties b/discovery-springcloud-example-service/src/main/resources/application-b1.properties deleted file mode 100644 index 23ebe411cc..0000000000 --- a/discovery-springcloud-example-service/src/main/resources/application-b1.properties +++ /dev/null @@ -1,24 +0,0 @@ -# Spring cloud config -spring.application.name=discovery-springcloud-example-b -server.port=1200 - -# Eureka config for discovery -eureka.instance.metadataMap.group=example-service-group -eureka.instance.metadataMap.version=1.0 -eureka.instance.metadataMap.region=dev - -# Consul config for discovery -spring.cloud.consul.discovery.tags=group=example-service-group,version=1.0,region=dev - -# Zookeeper config for discovery -spring.cloud.zookeeper.discovery.metadata.group=example-service-group -spring.cloud.zookeeper.discovery.metadata.version=1.0 -spring.cloud.zookeeper.discovery.metadata.region=dev - -# Nacos config for discovery -spring.cloud.nacos.discovery.metadata.group=example-service-group -spring.cloud.nacos.discovery.metadata.version=1.0 -spring.cloud.nacos.discovery.metadata.region=dev - -# Admin config -management.server.port=5200 \ No newline at end of file diff --git a/discovery-springcloud-example-service/src/main/resources/application-b2.properties b/discovery-springcloud-example-service/src/main/resources/application-b2.properties deleted file mode 100644 index 60a18e8139..0000000000 --- a/discovery-springcloud-example-service/src/main/resources/application-b2.properties +++ /dev/null @@ -1,24 +0,0 @@ -# Spring cloud config -spring.application.name=discovery-springcloud-example-b -server.port=1201 - -# Eureka config for discovery -eureka.instance.metadataMap.group=example-service-group -eureka.instance.metadataMap.version=1.1 -eureka.instance.metadataMap.region=qa - -# Consul config for discovery -spring.cloud.consul.discovery.tags=group=example-service-group,version=1.1,region=qa - -# Zookeeper config for discovery -spring.cloud.zookeeper.discovery.metadata.group=example-service-group -spring.cloud.zookeeper.discovery.metadata.version=1.1 -spring.cloud.zookeeper.discovery.metadata.region=qa - -# Nacos config for discovery -spring.cloud.nacos.discovery.metadata.group=example-service-group -spring.cloud.nacos.discovery.metadata.version=1.1 -spring.cloud.nacos.discovery.metadata.region=qa - -# Admin config -management.server.port=5201 \ No newline at end of file diff --git a/discovery-springcloud-example-service/src/main/resources/application-c1.properties b/discovery-springcloud-example-service/src/main/resources/application-c1.properties deleted file mode 100644 index 3d55bb73d0..0000000000 --- a/discovery-springcloud-example-service/src/main/resources/application-c1.properties +++ /dev/null @@ -1,24 +0,0 @@ -# Spring cloud config -spring.application.name=discovery-springcloud-example-c -server.port=1300 - -# Eureka config for discovery -eureka.instance.metadataMap.group=example-service-group -eureka.instance.metadataMap.version=1.0 -eureka.instance.metadataMap.region=dev - -# Consul config for discovery -spring.cloud.consul.discovery.tags=group=example-service-group,version=1.0,region=dev - -# Zookeeper config for discovery -spring.cloud.zookeeper.discovery.metadata.group=example-service-group -spring.cloud.zookeeper.discovery.metadata.version=1.0 -spring.cloud.zookeeper.discovery.metadata.region=dev - -# Nacos config for discovery -spring.cloud.nacos.discovery.metadata.group=example-service-group -spring.cloud.nacos.discovery.metadata.version=1.0 -spring.cloud.nacos.discovery.metadata.region=dev - -# Admin config -management.server.port=5300 \ No newline at end of file diff --git a/discovery-springcloud-example-service/src/main/resources/application-c2.properties b/discovery-springcloud-example-service/src/main/resources/application-c2.properties deleted file mode 100644 index 8e5b78841c..0000000000 --- a/discovery-springcloud-example-service/src/main/resources/application-c2.properties +++ /dev/null @@ -1,24 +0,0 @@ -# Spring cloud config -spring.application.name=discovery-springcloud-example-c -server.port=1301 - -# Eureka config for discovery -eureka.instance.metadataMap.group=example-service-group -eureka.instance.metadataMap.version=1.1 -eureka.instance.metadataMap.region=qa - -# Consul config for discovery -spring.cloud.consul.discovery.tags=group=example-service-group,version=1.1,region=qa - -# Zookeeper config for discovery -spring.cloud.zookeeper.discovery.metadata.group=example-service-group -spring.cloud.zookeeper.discovery.metadata.version=1.1 -spring.cloud.zookeeper.discovery.metadata.region=qa - -# Nacos config for discovery -spring.cloud.nacos.discovery.metadata.group=example-service-group -spring.cloud.nacos.discovery.metadata.version=1.1 -spring.cloud.nacos.discovery.metadata.region=qa - -# Admin config -management.server.port=5301 \ No newline at end of file diff --git a/discovery-springcloud-example-service/src/main/resources/application-c3.properties b/discovery-springcloud-example-service/src/main/resources/application-c3.properties deleted file mode 100644 index 3aa3ae93ec..0000000000 --- a/discovery-springcloud-example-service/src/main/resources/application-c3.properties +++ /dev/null @@ -1,24 +0,0 @@ -# Spring cloud config -spring.application.name=discovery-springcloud-example-c -server.port=1302 - -# Eureka config for discovery -eureka.instance.metadataMap.group=example-service-group -eureka.instance.metadataMap.version=1.2 -eureka.instance.metadataMap.region=qa - -# Consul config for discovery -spring.cloud.consul.discovery.tags=group=example-service-group,version=1.2,region=qa - -# Zookeeper config for discovery -spring.cloud.zookeeper.discovery.metadata.group=example-service-group -spring.cloud.zookeeper.discovery.metadata.version=1.2 -spring.cloud.zookeeper.discovery.metadata.region=qa - -# Nacos config for discovery -spring.cloud.nacos.discovery.metadata.group=example-service-group -spring.cloud.nacos.discovery.metadata.version=1.2 -spring.cloud.nacos.discovery.metadata.region=qa - -# Admin config -management.server.port=5302 \ No newline at end of file diff --git a/discovery-springcloud-example-service/src/main/resources/bootstrap.properties b/discovery-springcloud-example-service/src/main/resources/bootstrap.properties deleted file mode 100644 index 2515064049..0000000000 --- a/discovery-springcloud-example-service/src/main/resources/bootstrap.properties +++ /dev/null @@ -1,133 +0,0 @@ -# Spring cloud config -# server.servlet.context-path=/nepxion - -# Eureka config for discovery -eureka.client.serviceUrl.defaultZone=http://localhost:9528/eureka/ -eureka.instance.preferIpAddress=true - -# Consul config for discovery -spring.cloud.consul.host=localhost -spring.cloud.consul.port=8500 -spring.cloud.consul.discovery.preferIpAddress=true - -# Zookeeper config for discovery -spring.cloud.zookeeper.connectString=localhost:2181 -spring.cloud.zookeeper.discovery.instancePort=${server.port} -spring.cloud.zookeeper.discovery.root=/spring-cloud-service -spring.cloud.zookeeper.discovery.preferIpAddress=true - -# Nacos config for discovery -spring.cloud.nacos.discovery.server-addr=localhost:8848 -# spring.cloud.nacos.discovery.namespace=discovery - -# Ribbon config -ribbon.ConnectTimeout=60000 -ribbon.ReadTimeout=60000 - -# Feign Config -# G版或更高版本,解决FeignClientSpecification的问题。F版不需要该行配置 -spring.main.allow-bean-definition-overriding=true - -# Apollo config for rule -app.id=discovery -apollo.meta=http://localhost:8080 -# apollo.plugin.namespace=application - -# Nacos config for rule -nacos.server-addr=localhost:8848 -# nacos.access-key= -# nacos.secret-key= -# nacos.plugin.namespace=application -# nacos.plugin.cluster-name= -# nacos.plugin.context-path= -# nacos.plugin.config-long-poll-timeout= -# nacos.plugin.config-retry-time= -# nacos.plugin.max-retry= -# nacos.plugin.endpoint= -# nacos.plugin.endpoint-port= -# nacos.plugin.is-use-endpoint-parsing-rule= -# nacos.plugin.is-use-cloud-namespace-parsing= -# nacos.plugin.encode= -# nacos.plugin.naming-load-cache-at-start= -# nacos.plugin.naming-client-beat-thread-count= -# nacos.plugin.naming-polling-thread-count= -# nacos.plugin.ram-role-name= -# nacos.plugin.timout= - -# Redis config for rule -spring.redis.host=localhost -spring.redis.port=6379 -spring.redis.password= -spring.redis.database=0 -spring.redis.pool.max-active=8 -spring.redis.pool.max-wait=-1 -spring.redis.pool.max-idle=8 -spring.redis.pool.min-idle=0 - -# Sentinel config -spring.cloud.sentinel.transport.dashboard=localhost:8075 -spring.cloud.sentinel.eager=true -# 本地规则方式和远程规则方式不能同时并存,必须两选一。使用时候必须注释掉其中之一,生成环境必须使用远程规则方式 -# 本地规则方式配置 -spring.cloud.sentinel.datasource.ds1.file.file=classpath:sentinel.json -spring.cloud.sentinel.datasource.ds1.file.data-type=json -spring.cloud.sentinel.datasource.ds1.file.rule-type=flow -# 远程规则方式配置 -# spring.cloud.sentinel.datasource.ds2.apollo.namespace-name=application -# spring.cloud.sentinel.datasource.ds2.apollo.flow-rules-key=example-service-group-${spring.application.name}-sentinel-flow -# spring.cloud.sentinel.datasource.ds2.apollo.rule-type=flow -# Feign和RestTemplate熔断降级限流开关 -feign.sentinel.enabled=true -resttemplate.sentinel.enabled=true - -# Admin config -# 该项只对Consul有效,而且必须配置在bootstrap.properties里,配置在application.properties无效 -# management.health.consul.enabled=true -management.endpoints.web.exposure.include=* -management.endpoints.jmx.exposure.include=* -management.endpoint.health.show-details=ALWAYS -spring.boot.admin.client.instance.prefer-ip=true -spring.boot.admin.client.url=http://localhost:5555 - -# Plugin core config -# 开启和关闭服务注册层面的控制。一旦关闭,服务注册的黑/白名单过滤功能将失效,最大注册数的限制过滤功能将失效。缺失则默认为true -# spring.application.register.control.enabled=true -# 开启和关闭服务发现层面的控制。一旦关闭,服务多版本调用的控制功能将失效,动态屏蔽指定IP地址的服务实例被发现的功能将失效。缺失则默认为true -# spring.application.discovery.control.enabled=true -# 开启和关闭通过Rest方式对规则配置的控制和推送。一旦关闭,只能通过远程配置中心来控制和推送。缺失则默认为true -# spring.application.config.rest.control.enabled=true -# 规则文件的格式,支持xml和json。缺失则默认为xml -# spring.application.config.format=xml -# spring.application.config.format=json -# 本地规则文件的路径,支持两种方式:classpath:rule.xml(rule.json) - 规则文件放在resources目录下,便于打包进jar;file:rule.xml(rule.json) - 规则文件放在工程根目录下,放置在外部便于修改。缺失则默认为不装载本地规则 -# spring.application.config.path=classpath:rule.xml -# spring.application.config.path=classpath:rule.json -# 为微服务归类的Key,一般通过group字段来归类,例如eureka.instance.metadataMap.group=xxx-group或者eureka.instance.metadataMap.application=xxx-application。缺失则默认为group -# spring.application.group.key=group -# spring.application.group.key=application -# 由于服务未注册,或者被过滤,或者被隔离,导致消费端拿不到服务实例的时候,通过日志方式通知。缺失则默认为false -# spring.application.no.server.found.notification.enabled=false - -# Plugin strategy config -# 开启和关闭策略扩展功能的控制。一旦关闭,用户自定义和编程灰度路由策略功能将失效。缺失则默认为true -# spring.application.strategy.control.enabled=true -# 开启和关闭Ribbon默认的ZoneAvoidanceRule负载均衡策略。一旦关闭,则使用RoundRobin简单轮询负载均衡策略。缺失则默认为true -# spring.application.strategy.zone.avoidance.rule.enabled=true -# 启动和关闭用户自定义和编程灰度路由策略的时候,对REST方式的调用拦截。缺失则默认为true -# spring.application.strategy.rest.intercept.enabled=true -# 用户自定义和编程灰度路由策略的时候,对REST方式调用拦截的时候(支持Feign或者RestTemplate调用),希望把来自外部自定义的Header参数传递到服务里,那么配置如下值。如果多个用“;”分隔,不允许出现空格 -spring.application.strategy.request.headers=token -# 启动和关闭用户自定义和编程灰度路由策略的时候,对RPC方式的调用拦截。缺失则默认为false -spring.application.strategy.rpc.intercept.enabled=true -# 用户自定义和编程灰度路由策略的时候,需要指定对业务RestController类的扫描路径。此项配置作用于RPC方式的调用拦截和消费端的服务隔离两项功能 -spring.application.strategy.scan.packages=com.nepxion.discovery.plugin.example.service.feign -# 启动和关闭注册的服务隔离(基于Group黑/白名单的策略)。缺失则默认为false -spring.application.strategy.register.isolation.enabled=true -# 启动和关闭消费端的服务隔离(基于Group是否相同的策略)。缺失则默认为false -spring.application.strategy.consumer.isolation.enabled=true -# 启动和关闭提供端的服务隔离(基于Group是否相同的策略)。缺失则默认为false -spring.application.strategy.provider.isolation.enabled=true -# 启动和关闭Header传递的日志打印,注意每调用一次都会打印一次,会对性能有所影响,建议压测环境和生产环境关闭。缺失则默认为false -spring.application.strategy.intercept.log.print=true -# 开启服务端实现Hystrix线程隔离模式做服务隔离时,必须把spring.application.strategy.hystrix.threadlocal.supported设置为true,同时要引入discovery-plugin-strategy-starter-hystrix包,否则线程切换时会发生ThreadLocal上下文对象丢失 -# spring.application.strategy.hystrix.threadlocal.supported=true \ No newline at end of file diff --git a/discovery-springcloud-example-service/src/main/resources/logback.xml b/discovery-springcloud-example-service/src/main/resources/logback.xml deleted file mode 100644 index 239583856c..0000000000 --- a/discovery-springcloud-example-service/src/main/resources/logback.xml +++ /dev/null @@ -1,49 +0,0 @@ - - - - - - - discovery %date %level [%thread] %logger{10} [%file:%line] - %msg%n - UTF-8 - - - log/discovery-%d{yyyy-MM-dd}.%i.log - 50MB - - - INFO - - - true - - - - 0 - 512 - - - - - - - - discovery %date %level [%thread] %logger{10} [%file:%line] - %msg%n - UTF-8 - - - - INFO - - - - - - - - - - - - - diff --git a/discovery-springcloud-example-service/src/main/resources/rule.json b/discovery-springcloud-example-service/src/main/resources/rule.json deleted file mode 100644 index 46afb75a7c..0000000000 --- a/discovery-springcloud-example-service/src/main/resources/rule.json +++ /dev/null @@ -1,218 +0,0 @@ -{ - "registerEntity": { - "hostFilterEntity": { - "filterType": "BLACKLIST", - "filterValueList": [ - "10.10", - "11.11" - ], - "filterMap": { - "discovery-springcloud-example-a": [ - "172.16" - ] - } - }, - "countFilterEntity": { - "filterValue": 10000, - "filterMap": { - "discovery-springcloud-example-a": 5000 - } - } - }, - "discoveryEntity": { - "hostFilterEntity": { - "filterType": "BLACKLIST", - "filterValueList": [ - "10.10", - "11.11" - ], - "filterMap": { - "discovery-springcloud-example-b": [ - "172.16" - ] - } - }, - "versionFilterEntity": { - "versionEntityMap": { - "discovery-springcloud-example-a": [ - { - "consumerServiceName": "discovery-springcloud-example-a", - "providerServiceName": "discovery-springcloud-example-b", - "consumerVersionValueList": [ - "1.0" - ], - "providerVersionValueList": [ - "1.0" - ] - }, - { - "consumerServiceName": "discovery-springcloud-example-a", - "providerServiceName": "discovery-springcloud-example-b", - "consumerVersionValueList": [ - "1.1" - ], - "providerVersionValueList": [ - "1.1" - ] - } - ], - "discovery-springcloud-example-b": [ - { - "consumerServiceName": "discovery-springcloud-example-b", - "providerServiceName": "discovery-springcloud-example-c", - "consumerVersionValueList": [ - "1.0" - ], - "providerVersionValueList": [ - "1.0", - "1.1" - ] - }, - { - "consumerServiceName": "discovery-springcloud-example-b", - "providerServiceName": "discovery-springcloud-example-c", - "consumerVersionValueList": [ - "1.1" - ], - "providerVersionValueList": [ - "1.2" - ] - } - ] - } - }, - "weightFilterEntity": { - "versionWeightEntityMap": { - "discovery-springcloud-example-b": [ - { - "weightMap": { - "1.0": 90, - "1.1": 10 - }, - "consumerServiceName": "discovery-springcloud-example-b", - "providerServiceName": "discovery-springcloud-example-c", - "type": "VERSION" - } - ] - }, - "versionWeightEntityList": [ - { - "weightMap": { - "1.0": 90, - "1.1": 10 - }, - "consumerServiceName": null, - "providerServiceName": "discovery-springcloud-example-c", - "type": "VERSION" - } - ], - "versionWeightEntity": { - "weightMap": { - "1.0": 90, - "1.1": 10 - } - }, - "regionWeightEntityMap": { - "discovery-springcloud-example-b": [ - { - "weightMap": { - "dev": 85, - "qa": 15 - }, - "consumerServiceName": "discovery-springcloud-example-b", - "providerServiceName": "discovery-springcloud-example-c", - "type": "REGION" - } - ] - }, - "regionWeightEntityList": [ - { - "weightMap": { - "dev": 85, - "qa": 15 - }, - "consumerServiceName": null, - "providerServiceName": "discovery-springcloud-example-c", - "type": "REGION" - } - ], - "regionWeightEntity": { - "weightMap": { - "dev": 85, - "qa": 15 - } - } - } - }, - "strategyEntity": { - "versionValue": "{\"discovery-springcloud-example-a\":\"1.0\", \"discovery-springcloud-example-b\":\"1.0\", \"discovery-springcloud-example-c\":\"1.0;1.2\"}", - "regionValue": "{\"discovery-springcloud-example-a\":\"qa;dev\", \"discovery-springcloud-example-b\":\"dev\", \"discovery-springcloud-example-c\":\"qa\"}", - "addressValue": "{\"discovery-springcloud-example-a\":\"192.168.43.101:1100\", \"discovery-springcloud-example-b\":\"192.168.43.101:1201\", \"discovery-springcloud-example-c\":\"192.168.43.101:1300\"}", - "versionWeightValue": "{\"discovery-springcloud-example-a\":\"1.0=90;1.1=10\", \"discovery-springcloud-example-b\":\"1.0=90;1.1=10\", \"discovery-springcloud-example-c\":\"1.0=90;1.1=10\"}", - "regionWeightValue": "{\"discovery-springcloud-example-a\":\"dev=85;qa=15\", \"discovery-springcloud-example-b\":\"dev=85;qa=15\", \"discovery-springcloud-example-c\":\"dev=85;qa=15\"}" - }, - "customizationEntity": { - "customizationMap": { - "discovery-springcloud-example-a": { - "database": "qa" - }, - "discovery-springcloud-example-c": { - "database": "prod" - } - } - }, - "strategyCustomizationEntity": { - "strategyConditionEntityList": [ - { - "id": "1", - "headerMap": { - "a": "1", - "b": "2" - }, - "versionId": "a", - "regionId": "b", - "addressId": "c", - "versionWeightId": "d", - "regionWeightId": "e" - }, - { - "id": "2", - "headerMap": { - "c": "3" - }, - "versionId": "a", - "regionId": "b", - "addressId": null, - "versionWeightId": null, - "regionWeightId": null - } - ], - "strategyRouteEntityList": [ - { - "id": "a", - "type": "VERSION", - "value": "{\"discovery-springcloud-example-a\":\"1.0\", \"discovery-springcloud-example-b\":\"1.0\", \"discovery-springcloud-example-c\":\"1.0;1.2\"}" - }, - { - "id": "b", - "type": "REGION", - "value": "{\"discovery-springcloud-example-a\":\"qa;dev\", \"discovery-springcloud-example-b\":\"dev\", \"discovery-springcloud-example-c\":\"qa\"}" - }, - { - "id": "c", - "type": "ADDRESS", - "value": "{\"discovery-springcloud-example-a\":\"192.168.43.101:1100\", \"discovery-springcloud-example-b\":\"192.168.43.101:1201\", \"discovery-springcloud-example-c\":\"192.168.43.101:1300\"}" - }, - { - "id": "d", - "type": "VERSION_WEIGHT", - "value": "{\"discovery-springcloud-example-a\":\"1.0=90;1.1=10\", \"discovery-springcloud-example-b\":\"1.0=90;1.1=10\", \"discovery-springcloud-example-c\":\"1.0=90;1.1=10\"}" - }, - { - "id": "e", - "type": "REGION_WEIGHT", - "value": "{\"discovery-springcloud-example-a\":\"dev=85;qa=15\", \"discovery-springcloud-example-b\":\"dev=85;qa=15\", \"discovery-springcloud-example-c\":\"dev=85;qa=15\"}" - } - ] - } -} \ No newline at end of file diff --git a/discovery-springcloud-example-service/src/main/resources/rule.xml b/discovery-springcloud-example-service/src/main/resources/rule.xml deleted file mode 100644 index 51068600a0..0000000000 --- a/discovery-springcloud-example-service/src/main/resources/rule.xml +++ /dev/null @@ -1,140 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - {"discovery-springcloud-example-a":"1.0", "discovery-springcloud-example-b":"1.0", "discovery-springcloud-example-c":"1.0;1.2"} - - - {"discovery-springcloud-example-a":"qa;dev", "discovery-springcloud-example-b":"dev", "discovery-springcloud-example-c":"qa"} - - -
{"discovery-springcloud-example-a":"192.168.43.101:1100", "discovery-springcloud-example-b":"192.168.43.101:1201", "discovery-springcloud-example-c":"192.168.43.101:1300"}
- - - {"discovery-springcloud-example-a":"1.0=90;1.1=10", "discovery-springcloud-example-b":"1.0=90;1.1=10", "discovery-springcloud-example-c":"1.0=90;1.1=10"} - - - {"discovery-springcloud-example-a":"dev=85;qa=15", "discovery-springcloud-example-b":"dev=85;qa=15", "discovery-springcloud-example-c":"dev=85;qa=15"} - -
- - - - - - - - - - {"discovery-springcloud-example-a":"1.0", "discovery-springcloud-example-b":"1.0", "discovery-springcloud-example-c":"1.0;1.2"} - {"discovery-springcloud-example-a":"qa;dev", "discovery-springcloud-example-b":"dev", "discovery-springcloud-example-c":"qa"} - {"discovery-springcloud-example-a":"192.168.43.101:1100", "discovery-springcloud-example-b":"192.168.43.101:1201", "discovery-springcloud-example-c":"192.168.43.101:1300"} - {"discovery-springcloud-example-a":"1.0=90;1.1=10", "discovery-springcloud-example-b":"1.0=90;1.1=10", "discovery-springcloud-example-c":"1.0=90;1.1=10"} - {"discovery-springcloud-example-a":"dev=85;qa=15", "discovery-springcloud-example-b":"dev=85;qa=15", "discovery-springcloud-example-c":"dev=85;qa=15"} - - - - - - - - - - -
\ No newline at end of file diff --git a/discovery-springcloud-example-zuul/pom.xml b/discovery-springcloud-example-zuul/pom.xml deleted file mode 100644 index 7d0988041f..0000000000 --- a/discovery-springcloud-example-zuul/pom.xml +++ /dev/null @@ -1,112 +0,0 @@ - - - com.nepxion - discovery-springcloud-example-zuul - Nepxion Discovery Spring Cloud Example Zuul - jar - 4.0.0 - 1.0.0 - Nepxion Discovery is an enhancement for Spring Cloud Discovery - http://www.nepxion.com - - - 5.2.0-SNAPSHOT - Greenwich.SR2 - 0.9.0.RELEASE - 2.1.6.RELEASE - 2.1.4 - 1.8 - UTF-8 - - - - - - org.springframework.cloud - spring-cloud-dependencies - ${spring.cloud.version} - pom - import - - - - org.springframework.cloud - spring-cloud-alibaba-dependencies - ${spring.cloud.alibaba.version} - pom - import - - - - org.springframework.boot - spring-boot-dependencies - ${spring.boot.version} - pom - import - - - - de.codecentric - spring-boot-admin-dependencies - ${spring.boot.admin.version} - pom - import - - - - - - - com.nepxion - - - - discovery-plugin-starter-nacos - ${discovery.version} - - - - com.nepxion - - discovery-plugin-config-center-starter-nacos - - ${discovery.version} - - - - com.nepxion - discovery-plugin-strategy-starter-zuul - ${discovery.version} - - - - - - - de.codecentric - spring-boot-admin-starter-client - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - - - -parameters - - ${project.build.sourceEncoding} - ${java.version} - ${java.version} - - - - - \ No newline at end of file diff --git a/discovery-springcloud-example-zuul/src/main/java/com/nepxion/discovery/plugin/example/zuul/impl/MyDiscoveryEnabledStrategy.java b/discovery-springcloud-example-zuul/src/main/java/com/nepxion/discovery/plugin/example/zuul/impl/MyDiscoveryEnabledStrategy.java deleted file mode 100644 index d23978d362..0000000000 --- a/discovery-springcloud-example-zuul/src/main/java/com/nepxion/discovery/plugin/example/zuul/impl/MyDiscoveryEnabledStrategy.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.nepxion.discovery.plugin.example.zuul.impl; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; - -import com.nepxion.discovery.plugin.framework.adapter.PluginAdapter; -import com.nepxion.discovery.plugin.strategy.adapter.DiscoveryEnabledStrategy; -import com.nepxion.discovery.plugin.strategy.zuul.context.ZuulStrategyContextHolder; -import com.netflix.loadbalancer.Server; - -// 实现了组合策略,版本路由策略+区域路由策略+IP和端口路由策略+自定义策略 -public class MyDiscoveryEnabledStrategy implements DiscoveryEnabledStrategy { - private static final Logger LOG = LoggerFactory.getLogger(MyDiscoveryEnabledStrategy.class); - - @Autowired - private ZuulStrategyContextHolder zuulStrategyContextHolder; - - @Autowired - private PluginAdapter pluginAdapter; - - @Override - public boolean apply(Server server) { - // 对Rest调用传来的Header参数(例如:mobile)做策略 - return applyFromHeader(server); - } - - // 根据Rest调用传来的Header参数(例如:mobile),选取执行调用请求的服务实例 - private boolean applyFromHeader(Server server) { - String mobile = zuulStrategyContextHolder.getHeader("mobile"); - String serviceId = pluginAdapter.getServerServiceId(server); - String version = pluginAdapter.getServerVersion(server); - String region = pluginAdapter.getServerRegion(server); - - LOG.info("负载均衡用户定制触发:mobile={}, serviceId={}, version={}, region={}", mobile, serviceId, version, region); - - if (StringUtils.isNotEmpty(mobile)) { - // 手机号以移动138开头,路由到1.0版本的服务上 - if (mobile.startsWith("138") && StringUtils.equals(version, "1.0")) { - return true; - // 手机号以联通133开头,路由到2.0版本的服务上 - } else if (mobile.startsWith("133") && StringUtils.equals(version, "1.1")) { - return true; - } else { - // 其它情况,直接拒绝请求 - return false; - } - } - - return true; - } -} \ No newline at end of file diff --git a/discovery-springcloud-example-zuul/src/main/java/com/nepxion/discovery/plugin/example/zuul/impl/MyDiscoveryListener.java b/discovery-springcloud-example-zuul/src/main/java/com/nepxion/discovery/plugin/example/zuul/impl/MyDiscoveryListener.java deleted file mode 100644 index f1ad3c806e..0000000000 --- a/discovery-springcloud-example-zuul/src/main/java/com/nepxion/discovery/plugin/example/zuul/impl/MyDiscoveryListener.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.nepxion.discovery.plugin.example.zuul.impl; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import java.util.Iterator; -import java.util.List; - -import org.apache.commons.lang3.StringUtils; -import org.springframework.cloud.client.ServiceInstance; - -import com.nepxion.discovery.plugin.framework.listener.discovery.AbstractDiscoveryListener; - -// 当目标服务的元数据中的Group为mygroup2,禁止被本服务发现(只用于DiscoveryClient.getInstances接口方法用) -public class MyDiscoveryListener extends AbstractDiscoveryListener { - @Override - public void onGetInstances(String serviceId, List instances) { - Iterator iterator = instances.iterator(); - while (iterator.hasNext()) { - ServiceInstance serviceInstance = iterator.next(); - String group = pluginAdapter.getInstanceGroup(serviceInstance); - if (StringUtils.equals(group, "mygroup2")) { - iterator.remove(); - - System.out.println("********** 服务名=" + serviceId + ",组名=" + group + "的服务禁止被本服务发现"); - } - } - } - - @Override - public void onGetServices(List services) { - - } - - @Override - public int getOrder() { - return LOWEST_PRECEDENCE - 500; - } -} \ No newline at end of file diff --git a/discovery-springcloud-example-zuul/src/main/java/com/nepxion/discovery/plugin/example/zuul/impl/MyLoadBalanceListener.java b/discovery-springcloud-example-zuul/src/main/java/com/nepxion/discovery/plugin/example/zuul/impl/MyLoadBalanceListener.java deleted file mode 100644 index 3f1ef67936..0000000000 --- a/discovery-springcloud-example-zuul/src/main/java/com/nepxion/discovery/plugin/example/zuul/impl/MyLoadBalanceListener.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.nepxion.discovery.plugin.example.zuul.impl; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import java.util.Iterator; -import java.util.List; - -import org.apache.commons.lang3.StringUtils; - -import com.nepxion.discovery.plugin.framework.listener.loadbalance.AbstractLoadBalanceListener; -import com.netflix.loadbalancer.Server; - -// 当目标服务的元数据中的Group为mygroup2,禁止被本服务负载均衡 -public class MyLoadBalanceListener extends AbstractLoadBalanceListener { - @Override - public void onGetServers(String serviceId, List servers) { - Iterator iterator = servers.iterator(); - while (iterator.hasNext()) { - Server server = iterator.next(); - String group = pluginAdapter.getServerGroup(server); - if (StringUtils.equals(group, "mygroup3")) { - iterator.remove(); - - System.out.println("********** 服务名=" + serviceId + ",组名=" + group + "的服务禁止被本服务负载均衡"); - } - } - } - - @Override - public int getOrder() { - return LOWEST_PRECEDENCE - 500; - } -} \ No newline at end of file diff --git a/discovery-springcloud-example-zuul/src/main/java/com/nepxion/discovery/plugin/example/zuul/impl/MyRegisterListener.java b/discovery-springcloud-example-zuul/src/main/java/com/nepxion/discovery/plugin/example/zuul/impl/MyRegisterListener.java deleted file mode 100644 index 8966d4ad64..0000000000 --- a/discovery-springcloud-example-zuul/src/main/java/com/nepxion/discovery/plugin/example/zuul/impl/MyRegisterListener.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.nepxion.discovery.plugin.example.zuul.impl; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import org.apache.commons.lang3.StringUtils; -import org.springframework.cloud.client.serviceregistry.Registration; - -import com.nepxion.discovery.common.constant.DiscoveryConstant; -import com.nepxion.discovery.common.exception.DiscoveryException; -import com.nepxion.discovery.plugin.framework.listener.register.AbstractRegisterListener; - -// 当本服务的元数据中的Group为mygroup1,禁止被注册到注册中心 -public class MyRegisterListener extends AbstractRegisterListener { - @Override - public void onRegister(Registration registration) { - String serviceId = registration.getServiceId().toLowerCase(); - String group = registration.getMetadata().get(DiscoveryConstant.GROUP); - if (StringUtils.equals(group, "mygroup1")) { - throw new DiscoveryException("服务名=" + serviceId + ",组名=" + group + "的服务禁止被注册到注册中心"); - } - } - - @Override - public void onDeregister(Registration registration) { - - } - - @Override - public void onSetStatus(Registration registration, String status) { - - } - - @Override - public void onClose() { - - } - - @Override - public int getOrder() { - return LOWEST_PRECEDENCE - 500; - } -} \ No newline at end of file diff --git a/discovery-springcloud-example-zuul/src/main/java/com/nepxion/discovery/plugin/example/zuul/impl/MyRouteFilter.java b/discovery-springcloud-example-zuul/src/main/java/com/nepxion/discovery/plugin/example/zuul/impl/MyRouteFilter.java deleted file mode 100644 index 08f539affc..0000000000 --- a/discovery-springcloud-example-zuul/src/main/java/com/nepxion/discovery/plugin/example/zuul/impl/MyRouteFilter.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.nepxion.discovery.plugin.example.zuul.impl; - -/** - *

Title: Nepxion Discovery

- *

Description: Nepxion Discovery

- *

Copyright: Copyright (c) 2017-2050

- *

Company: Nepxion

- * @author Haojun Ren - * @version 1.0 - */ - -import org.apache.commons.lang3.StringUtils; -import org.springframework.beans.factory.annotation.Value; - -import com.nepxion.discovery.plugin.strategy.zuul.filter.DefaultZuulStrategyRouteFilter; - -// 适用于A/B Testing或者更根据某业务参数决定灰度路由路径。可以结合配置中心分别配置A/B两条路径,可以动态改变并通知 -// 当Header中传来的用户为张三,执行一条路由路径;为李四,执行另一条路由路径 -public class MyRouteFilter extends DefaultZuulStrategyRouteFilter { - private static final String DEFAULT_A_ROUTE_VERSION = "{\"discovery-springcloud-example-a\":\"1.0\", \"discovery-springcloud-example-b\":\"1.0\", \"discovery-springcloud-example-c\":\"1.0\"}"; - private static final String DEFAULT_B_ROUTE_VERSION = "{\"discovery-springcloud-example-a\":\"1.1\", \"discovery-springcloud-example-b\":\"1.1\", \"discovery-springcloud-example-c\":\"1.1\"}"; - - @Value("${a.route.version:" + DEFAULT_A_ROUTE_VERSION + "}") - private String aRouteVersion; - - @Value("${b.route.version:" + DEFAULT_B_ROUTE_VERSION + "}") - private String bRouteVersion; - - @Override - public String getRouteVersion() { - String user = strategyContextHolder.getHeader("user"); - - if (StringUtils.equals(user, "zhangsan")) { - return aRouteVersion; - } else if (StringUtils.equals(user, "lisi")) { - return bRouteVersion; - } - - return super.getRouteVersion(); - } -} \ No newline at end of file diff --git a/discovery-springcloud-example-zuul/src/main/resources/application.properties b/discovery-springcloud-example-zuul/src/main/resources/application.properties deleted file mode 100644 index 6c025f959a..0000000000 --- a/discovery-springcloud-example-zuul/src/main/resources/application.properties +++ /dev/null @@ -1,21 +0,0 @@ -# Spring cloud config -spring.application.name=discovery-springcloud-example-zuul -server.port=1400 - -# Eureka config for discovery -eureka.instance.metadataMap.group=example-service-group -eureka.instance.metadataMap.version=1.0 - -# Consul config for discovery -spring.cloud.consul.discovery.tags=group=example-service-group,version=1.0 - -# Zookeeper config for discovery -spring.cloud.zookeeper.discovery.metadata.group=example-service-group -spring.cloud.zookeeper.discovery.metadata.version=1.0 - -# Nacos config for discovery -spring.cloud.nacos.discovery.metadata.group=example-service-group -spring.cloud.nacos.discovery.metadata.version=1.0 - -# Admin config -management.server.port=5400 \ No newline at end of file diff --git a/discovery-springcloud-example-zuul/src/main/resources/bootstrap.properties b/discovery-springcloud-example-zuul/src/main/resources/bootstrap.properties deleted file mode 100644 index fae54d3ea3..0000000000 --- a/discovery-springcloud-example-zuul/src/main/resources/bootstrap.properties +++ /dev/null @@ -1,115 +0,0 @@ -# Spring cloud config - -# Eureka config for discovery -eureka.client.serviceUrl.defaultZone=http://localhost:9528/eureka/ -eureka.instance.preferIpAddress=true - -# Consul config for discovery -spring.cloud.consul.host=localhost -spring.cloud.consul.port=8500 -spring.cloud.consul.discovery.preferIpAddress=true - -# Zookeeper config for discovery -spring.cloud.zookeeper.connectString=localhost:2181 -spring.cloud.zookeeper.discovery.instancePort=${server.port} -spring.cloud.zookeeper.discovery.root=/spring-cloud-service -spring.cloud.zookeeper.discovery.preferIpAddress=true - -# Nacos config for discovery -spring.cloud.nacos.discovery.server-addr=localhost:8848 -# spring.cloud.nacos.discovery.namespace=discovery - -# Ribbon config -ribbon.ConnectTimeout=60000 -ribbon.ReadTimeout=60000 - -# Apollo config for rule -app.id=discovery -apollo.meta=http://localhost:8080 -# apollo.plugin.namespace=application - -# Nacos config for rule -nacos.server-addr=localhost:8848 -# nacos.access-key= -# nacos.secret-key= -# nacos.plugin.namespace=application -# nacos.plugin.cluster-name= -# nacos.plugin.context-path= -# nacos.plugin.config-long-poll-timeout= -# nacos.plugin.config-retry-time= -# nacos.plugin.max-retry= -# nacos.plugin.endpoint= -# nacos.plugin.endpoint-port= -# nacos.plugin.is-use-endpoint-parsing-rule= -# nacos.plugin.is-use-cloud-namespace-parsing= -# nacos.plugin.encode= -# nacos.plugin.naming-load-cache-at-start= -# nacos.plugin.naming-client-beat-thread-count= -# nacos.plugin.naming-polling-thread-count= -# nacos.plugin.ram-role-name= -# nacos.plugin.timout= - -# Redis config for rule -spring.redis.host=localhost -spring.redis.port=6379 -spring.redis.password= -spring.redis.database=0 -spring.redis.pool.max-active=8 -spring.redis.pool.max-wait=-1 -spring.redis.pool.max-idle=8 -spring.redis.pool.min-idle=0 - -# Admin config -# 该项只对Consul有效,而且必须配置在bootstrap.properties里,配置在application.properties无效 -# management.health.consul.enabled=true -management.endpoints.web.exposure.include=* -management.endpoints.jmx.exposure.include=* -management.endpoint.health.show-details=ALWAYS -spring.boot.admin.client.instance.prefer-ip=true -spring.boot.admin.client.url=http://localhost:5555 - -# Plugin core config -# 开启和关闭服务注册层面的控制。一旦关闭,服务注册的黑/白名单过滤功能将失效,最大注册数的限制过滤功能将失效。缺失则默认为true -# spring.application.register.control.enabled=true -# 开启和关闭服务发现层面的控制。一旦关闭,服务多版本调用的控制功能将失效,动态屏蔽指定IP地址的服务实例被发现的功能将失效。缺失则默认为true -# spring.application.discovery.control.enabled=true -# 开启和关闭通过Rest方式对规则配置的控制和推送。一旦关闭,只能通过远程配置中心来控制和推送。缺失则默认为true -# spring.application.config.rest.control.enabled=true -# 规则文件的格式,支持xml和json。缺失则默认为xml -# spring.application.config.format=xml -# spring.application.config.format=json -# 本地规则文件的路径,支持两种方式:classpath:rule.xml(rule.json) - 规则文件放在resources目录下,便于打包进jar;file:rule.xml(rule.json) - 规则文件放在工程根目录下,放置在外部便于修改。缺失则默认为不装载本地规则 -# spring.application.config.path=classpath:rule.xml -# spring.application.config.path=classpath:rule.json -# 为微服务归类的Key,一般通过group字段来归类,例如eureka.instance.metadataMap.group=xxx-group或者eureka.instance.metadataMap.application=xxx-application。缺失则默认为group -# spring.application.group.key=group -# spring.application.group.key=application -# 由于服务未注册,或者被过滤,或者被隔离,导致消费端拿不到服务实例的时候,通过日志方式通知。缺失则默认为false -# spring.application.no.server.found.notification.enabled=false - -# Plugin strategy config -# 开启和关闭策略扩展功能的控制。一旦关闭,用户自定义和编程灰度路由策略功能将失效。缺失则默认为true -# spring.application.strategy.control.enabled=true -# 开启和关闭Ribbon默认的ZoneAvoidanceRule负载均衡策略。一旦关闭,则使用RoundRobin简单轮询负载均衡策略。缺失则默认为true -# spring.application.strategy.zone.avoidance.rule.enabled=true -# 开启和关闭内置的路由策略过滤器。一旦关闭,基于配置中心(或自定义)的路由策略Header传递方式将失效,只能通过前端的路由策略Header传递方式。缺失则默认为true -# spring.application.strategy.zuul.route.filter.enabled=true -# 路由策略过滤器的执行顺序(Order)。缺失则默认为0 -# spring.application.strategy.zuul.route.filter.order=0 -# 当外界传值Header的时候,网关也设置并传递同名的Header,需要决定哪个Header传递到后边的服务去。如果下面开关为true,以网关设置为优先,否则以外界传值为优先。缺失则默认为true -spring.application.strategy.zuul.header.priority=false -# 启动和关闭注册的服务隔离(基于Group黑/白名单的策略)。缺失则默认为false -spring.application.strategy.register.isolation.enabled=true -# 启动和关闭消费端的服务隔离(基于Group是否相同的策略)。缺失则默认为false -spring.application.strategy.consumer.isolation.enabled=true -# 启动和关闭提供端的服务隔离(基于Group是否相同的策略)。缺失则默认为false -spring.application.strategy.provider.isolation.enabled=true -# 启动和关闭Header传递的日志打印,注意每调用一次都会打印一次,会对性能有所影响,建议压测环境和生产环境关闭。缺失则默认为false -spring.application.strategy.intercept.log.print=true -# 开启Zuul网关上实现Hystrix线程隔离模式做服务隔离时,必须把spring.application.strategy.hystrix.threadlocal.supported设置为true,同时要引入discovery-plugin-strategy-starter-hystrix包,否则线程切换时会发生ThreadLocal上下文对象丢失 -# spring.application.strategy.hystrix.threadlocal.supported=true - -# Zuul config -zuul.routes.discovery-springcloud-example-a.path=/discovery-springcloud-example-a/** -zuul.routes.discovery-springcloud-example-a.serviceId=discovery-springcloud-example-a -# zuul.ribbon-isolation-strategy=THREAD \ No newline at end of file diff --git a/discovery-springcloud-example-zuul/src/main/resources/logback.xml b/discovery-springcloud-example-zuul/src/main/resources/logback.xml deleted file mode 100644 index 239583856c..0000000000 --- a/discovery-springcloud-example-zuul/src/main/resources/logback.xml +++ /dev/null @@ -1,49 +0,0 @@ - - - - - - - discovery %date %level [%thread] %logger{10} [%file:%line] - %msg%n - UTF-8 - - - log/discovery-%d{yyyy-MM-dd}.%i.log - 50MB - - - INFO - - - true - - - - 0 - 512 - - - - - - - - discovery %date %level [%thread] %logger{10} [%file:%line] - %msg%n - UTF-8 - - - - INFO - - - - - - - - - - - - - diff --git a/discovery-springcloud-examples/discovery-springcloud-example-admin/pom.xml b/discovery-springcloud-examples/discovery-springcloud-example-admin/pom.xml new file mode 100644 index 0000000000..eb58fc7b3a --- /dev/null +++ b/discovery-springcloud-examples/discovery-springcloud-example-admin/pom.xml @@ -0,0 +1,33 @@ + + + discovery-springcloud-example-admin + Nepxion Discovery Spring Cloud Example Admin + jar + 4.0.0 + Nepxion Discovery is a solution for Spring Cloud with blue green, gray, weight, limitation, circuit breaker, degrade, isolation, monitor, tracing, dye, failover, async agent + http://www.nepxion.com + + + com.nepxion + discovery-springcloud-examples + 6.23.0 + + + + + + + + + + com.alibaba.cloud + spring-cloud-starter-alibaba-nacos-discovery + + + + de.codecentric + spring-boot-admin-starter-server + + + \ No newline at end of file diff --git a/discovery-springcloud-example-admin/src/main/java/com/nepxion/discovery/admin/example/AdminApplication.java b/discovery-springcloud-examples/discovery-springcloud-example-admin/src/main/java/com/nepxion/discovery/admin/example/AdminApplication.java similarity index 100% rename from discovery-springcloud-example-admin/src/main/java/com/nepxion/discovery/admin/example/AdminApplication.java rename to discovery-springcloud-examples/discovery-springcloud-example-admin/src/main/java/com/nepxion/discovery/admin/example/AdminApplication.java diff --git a/discovery-springcloud-examples/discovery-springcloud-example-admin/src/main/resources/application.properties b/discovery-springcloud-examples/discovery-springcloud-example-admin/src/main/resources/application.properties new file mode 100644 index 0000000000..c6b7977a3c --- /dev/null +++ b/discovery-springcloud-examples/discovery-springcloud-example-admin/src/main/resources/application.properties @@ -0,0 +1,18 @@ +# Spring cloud config +spring.application.name=discovery-springcloud-example-admin +server.port=9728 + +# Eureka config for discovery +eureka.instance.metadataMap.group=example-admin-group +eureka.instance.metadataMap.version=1.0 + +# Consul config for discovery +spring.cloud.consul.discovery.tags=group=example-admin-group,version=1.0 + +# Zookeeper config for discovery +spring.cloud.zookeeper.discovery.metadata.group=example-admin-group +spring.cloud.zookeeper.discovery.metadata.version=1.0 + +# Nacos config for discovery +spring.cloud.nacos.discovery.metadata.group=example-admin-group +spring.cloud.nacos.discovery.metadata.version=1.0 \ No newline at end of file diff --git a/discovery-springcloud-examples/discovery-springcloud-example-admin/src/main/resources/bootstrap.properties b/discovery-springcloud-examples/discovery-springcloud-example-admin/src/main/resources/bootstrap.properties new file mode 100644 index 0000000000..5a706e1477 --- /dev/null +++ b/discovery-springcloud-examples/discovery-springcloud-example-admin/src/main/resources/bootstrap.properties @@ -0,0 +1,28 @@ +# Spring cloud config + +# Eureka config for discovery +eureka.client.serviceUrl.defaultZone=http://localhost:9528/eureka/ +eureka.instance.preferIpAddress=true + +# Consul config for discovery +spring.cloud.consul.host=localhost +spring.cloud.consul.port=8500 +spring.cloud.consul.discovery.preferIpAddress=true + +# Zookeeper config for discovery +spring.cloud.zookeeper.connectString=localhost:2181 +spring.cloud.zookeeper.discovery.instancePort=${server.port} +spring.cloud.zookeeper.discovery.root=/spring-cloud +spring.cloud.zookeeper.discovery.preferIpAddress=true + +# Nacos config for discovery +spring.cloud.nacos.discovery.server-addr=localhost:8848 +# spring.cloud.nacos.discovery.namespace=discovery + +# Ribbon config +ribbon.ServerListRefreshInterval=5000 +ribbon.ConnectTimeout=60000 +ribbon.ReadTimeout=60000 +ribbon.maxAutoRetries=3 +ribbon.maxAutoRetriesNextServer=3 +ribbon.okToRetryOnAllOperations=true \ No newline at end of file diff --git a/discovery-springcloud-examples/discovery-springcloud-example-admin/src/main/resources/logback.xml b/discovery-springcloud-examples/discovery-springcloud-example-admin/src/main/resources/logback.xml new file mode 100644 index 0000000000..c37b63f8e2 --- /dev/null +++ b/discovery-springcloud-examples/discovery-springcloud-example-admin/src/main/resources/logback.xml @@ -0,0 +1,50 @@ + + + + + + + %d{yyyy-MM-dd HH:mm:ss.SSS} %5p ${PID:- } --- [%15.15t] %-40.40logger{39} : %msg%n + + UTF-8 + + + log/discovery-%d{yyyy-MM-dd}.%i.log + 50MB + + + INFO + + + true + + + + 0 + 512 + + + + + + + + + %d{yyyy-MM-dd HH:mm:ss.SSS} %levelColor(%5p) %magenta(${PID:- }) --- [%15.15t] %cyan(%-40.40logger{39}) : %msg%n + + + + INFO + + + + + + + + + + + + + \ No newline at end of file diff --git a/discovery-springcloud-examples/discovery-springcloud-example-console/pom.xml b/discovery-springcloud-examples/discovery-springcloud-example-console/pom.xml new file mode 100644 index 0000000000..2405d2f82a --- /dev/null +++ b/discovery-springcloud-examples/discovery-springcloud-example-console/pom.xml @@ -0,0 +1,43 @@ + + + discovery-springcloud-example-console + Nepxion Discovery Spring Cloud Example Console + jar + 4.0.0 + Nepxion Discovery is a solution for Spring Cloud with blue green, gray, weight, limitation, circuit breaker, degrade, isolation, monitor, tracing, dye, failover, async agent + http://www.nepxion.com + + + com.nepxion + discovery-springcloud-examples + 6.23.0 + + + + + + + + + + com.alibaba.cloud + spring-cloud-starter-alibaba-nacos-discovery + + + + com.nepxion + + discovery-console-starter-nacos + + + + + + + + de.codecentric + spring-boot-admin-starter-client + + + \ No newline at end of file diff --git a/discovery-springcloud-example-console/src/main/java/com/nepxion/discovery/console/example/ConsoleApplication.java b/discovery-springcloud-examples/discovery-springcloud-example-console/src/main/java/com/nepxion/discovery/console/example/ConsoleApplication.java similarity index 100% rename from discovery-springcloud-example-console/src/main/java/com/nepxion/discovery/console/example/ConsoleApplication.java rename to discovery-springcloud-examples/discovery-springcloud-example-console/src/main/java/com/nepxion/discovery/console/example/ConsoleApplication.java diff --git a/discovery-springcloud-examples/discovery-springcloud-example-console/src/main/resources/application.properties b/discovery-springcloud-examples/discovery-springcloud-example-console/src/main/resources/application.properties new file mode 100644 index 0000000000..fa66f48be0 --- /dev/null +++ b/discovery-springcloud-examples/discovery-springcloud-example-console/src/main/resources/application.properties @@ -0,0 +1,21 @@ +# Spring cloud config +spring.application.name=discovery-springcloud-example-console +server.port=9628 + +# Eureka config for discovery +eureka.instance.metadataMap.group=example-console-group +eureka.instance.metadataMap.version=1.0 + +# Consul config for discovery +spring.cloud.consul.discovery.tags=group=example-console-group,version=1.0 + +# Zookeeper config for discovery +spring.cloud.zookeeper.discovery.metadata.group=example-console-group +spring.cloud.zookeeper.discovery.metadata.version=1.0 + +# Nacos config for discovery +spring.cloud.nacos.discovery.metadata.group=example-console-group +spring.cloud.nacos.discovery.metadata.version=1.0 + +# Management config +management.server.port=9629 \ No newline at end of file diff --git a/discovery-springcloud-examples/discovery-springcloud-example-console/src/main/resources/bootstrap.properties b/discovery-springcloud-examples/discovery-springcloud-example-console/src/main/resources/bootstrap.properties new file mode 100644 index 0000000000..2e6f04487f --- /dev/null +++ b/discovery-springcloud-examples/discovery-springcloud-example-console/src/main/resources/bootstrap.properties @@ -0,0 +1,149 @@ +# Spring cloud config + +# Eureka config for discovery +eureka.client.serviceUrl.defaultZone=http://localhost:9528/eureka/ +eureka.instance.preferIpAddress=true + +# Consul config for discovery +spring.cloud.consul.host=localhost +spring.cloud.consul.port=8500 +spring.cloud.consul.discovery.preferIpAddress=true + +# Zookeeper config for discovery +spring.cloud.zookeeper.connectString=localhost:2181 +spring.cloud.zookeeper.discovery.instancePort=${server.port} +spring.cloud.zookeeper.discovery.root=/spring-cloud +spring.cloud.zookeeper.discovery.preferIpAddress=true + +# Nacos config for discovery +spring.cloud.nacos.discovery.server-addr=localhost:8848 +# spring.cloud.nacos.discovery.namespace=discovery + +# Ribbon config +ribbon.ServerListRefreshInterval=5000 +ribbon.ConnectTimeout=60000 +ribbon.ReadTimeout=60000 +ribbon.maxAutoRetries=3 +ribbon.maxAutoRetriesNextServer=3 +ribbon.okToRetryOnAllOperations=true + +# Apollo config for rule +apollo.portal-url=http://106.54.227.205:80 +apollo.token=93af480ee2dd57af856c972ce55a42cbe08c2f12 +apollo.operator=apollo +# apollo.connect-timeout=1000 +# apollo.read-timeout=5000 +apollo.app.id=discovery +apollo.env=DEV +# apollo.cluster=default +# apollo.namespace=application + +# Nacos config for rule +nacos.server-addr=localhost:8848 +# nacos.access-key= +# nacos.secret-key= +# nacos.username= +# nacos.password= +# nacos.namespace=application +# nacos.cluster-name= +# nacos.context-path= +# nacos.config-long-poll-timeout= +# nacos.config-retry-time= +# nacos.max-retry= +# nacos.endpoint= +# nacos.endpoint-port= +# nacos.is-use-endpoint-parsing-rule= +# nacos.is-use-cloud-namespace-parsing= +# nacos.encode= +# nacos.naming-load-cache-at-start= +# nacos.naming-client-beat-thread-count= +# nacos.naming-polling-thread-count= +# nacos.naming-request-domain-max-retry-count= +# nacos.naming-push-empty-protection= +# nacos.ram-role-name= +# nacos.timout= + +# Redis config for rule +spring.redis.host=localhost +spring.redis.port=6379 +spring.redis.password= +spring.redis.database=0 + +# Zookeeper config for rule +zookeeper.connect-string=localhost:2181 +zookeeper.retry-count=3 +zookeeper.sleep-time=3000 + +# Consul config for rule +consul.host=localhost +consul.port=8500 +consul.timeout=1 +consul.token= + +# Etcd config for rule +etcd.server.addr=http://localhost:2379 +etcd.username= +etcd.password= + +# Management config +# 该项只对Consul有效,而且必须配置在bootstrap.properties里,配置在application.properties无效 +# management.health.consul.enabled=true +management.endpoints.web.exposure.include=* +management.endpoints.jmx.exposure.include=* +management.endpoint.health.show-details=ALWAYS + +# Spring boot admin config +spring.boot.admin.client.instance.prefer-ip=true +spring.boot.admin.client.url=http://localhost:9728 + +# User config +admin=admin +nepxion=nepxion + +# 启动和关闭服务相关操作端点。缺失则默认为true +# spring.application.console.service.endpoint.enabled=true +# 启动和关闭配置相关操作端点。缺失则默认为true +# spring.application.console.config.endpoint.enabled=true +# 启动和关闭版本相关操作端点。缺失则默认为true +# spring.application.console.version.endpoint.enabled=true +# 启动和关闭侦测相关操作端点。缺失则默认为true +# spring.application.console.inspector.endpoint.enabled=true +# 启动和关闭网关路由相关操作端点。缺失则默认为true +# spring.application.console.route.endpoint.enabled=true +# 启动和关闭策略相关操作端点。缺失则默认为true +# spring.application.console.strategy.endpoint.enabled=true +# 启动和关闭Sentinel相关操作端点。缺失则默认为true +# spring.application.console.sentinel.endpoint.enabled=true +# 启动和关闭无损下线黑名单相关操作端点。缺失则默认为true +# spring.application.console.blacklist.endpoint.enabled=true +# 启动和关闭故障转移相关操作端点。缺失则默认为true +# spring.application.console.failover.endpoint.enabled=true +# 启动和关闭认证相关操作端点。缺失则默认为true +# spring.application.console.authentication.endpoint.enabled=true +# 启动和关闭策略操作端点的验证SPEL表达式方法。缺失则默认为true +# 该端点方法使用Spring StandardEvaluationContext类,StandardEvaluationContext支持全部的Spel语法且功能齐全,但GitHub Security报告其存在一定的注入风险,推荐使用SimpleEvaluationContext,而SimpleEvaluationContext并不能满足当前框架的需求 +# 如果未使用验证SPEL表达式方法,可以通过下面开关关闭在方法在策略端点上的暴露,规避风险 +# spring.application.console.strategy.endpoint.validate-expression.enabled=true + +# 启动和关闭Swagger。缺失则默认为true +# swagger.enabled=true +# 业务服务Swagger Docket组名 +# swagger.service.group=Your group +# 业务服务Swagger扫描目录 +# swagger.service.packages=your-package1;your-package2 +# 业务服务Swagger描述 +# swagger.service.description=Your service Restful APIs +# 业务服务Swagger版本 +# swagger.service.version=1.0.0 +# 业务服务Swagger License名称 +# swagger.service.license.name=Apache License 2.0 +# 业务服务Swagger License链接 +# swagger.service.license.url=http://www.apache.org/licenses/LICENSE-2.0 +# 业务服务Swagger联系人名称 +# swagger.service.contact.name=Nepxion +# 业务服务Swagger联系人网址 +# swagger.service.contact.url=https://github.com/Nepxion/Discovery +# 业务服务Swagger联系人邮件 +# swagger.service.contact.email=1394997@qq.com +# 业务服务Swagger服务条件网址 +# swagger.service.termsOfService.url=http://nepxion.com/discovery \ No newline at end of file diff --git a/discovery-springcloud-examples/discovery-springcloud-example-console/src/main/resources/logback.xml b/discovery-springcloud-examples/discovery-springcloud-example-console/src/main/resources/logback.xml new file mode 100644 index 0000000000..c37b63f8e2 --- /dev/null +++ b/discovery-springcloud-examples/discovery-springcloud-example-console/src/main/resources/logback.xml @@ -0,0 +1,50 @@ + + + + + + + %d{yyyy-MM-dd HH:mm:ss.SSS} %5p ${PID:- } --- [%15.15t] %-40.40logger{39} : %msg%n + + UTF-8 + + + log/discovery-%d{yyyy-MM-dd}.%i.log + 50MB + + + INFO + + + true + + + + 0 + 512 + + + + + + + + + %d{yyyy-MM-dd HH:mm:ss.SSS} %levelColor(%5p) %magenta(${PID:- }) --- [%15.15t] %cyan(%-40.40logger{39}) : %msg%n + + + + INFO + + + + + + + + + + + + + \ No newline at end of file diff --git a/discovery-springcloud-examples/discovery-springcloud-example-eureka/pom.xml b/discovery-springcloud-examples/discovery-springcloud-example-eureka/pom.xml new file mode 100644 index 0000000000..ed8016397c --- /dev/null +++ b/discovery-springcloud-examples/discovery-springcloud-example-eureka/pom.xml @@ -0,0 +1,23 @@ + + + discovery-springcloud-example-eureka + Nepxion Discovery Spring Cloud Example Eureka + jar + 4.0.0 + Nepxion Discovery is a solution for Spring Cloud with blue green, gray, weight, limitation, circuit breaker, degrade, isolation, monitor, tracing, dye, failover, async agent + http://www.nepxion.com + + + com.nepxion + discovery-springcloud-examples + 6.23.0 + + + + + org.springframework.cloud + spring-cloud-starter-netflix-eureka-server + + + \ No newline at end of file diff --git a/discovery-springcloud-example-eureka/src/main/java/com/nepxion/discovery/eureka/example/EurekaApplication.java b/discovery-springcloud-examples/discovery-springcloud-example-eureka/src/main/java/com/nepxion/discovery/eureka/example/EurekaApplication.java similarity index 100% rename from discovery-springcloud-example-eureka/src/main/java/com/nepxion/discovery/eureka/example/EurekaApplication.java rename to discovery-springcloud-examples/discovery-springcloud-example-eureka/src/main/java/com/nepxion/discovery/eureka/example/EurekaApplication.java diff --git a/discovery-springcloud-example-eureka/src/main/resources/application.properties b/discovery-springcloud-examples/discovery-springcloud-example-eureka/src/main/resources/application.properties similarity index 100% rename from discovery-springcloud-example-eureka/src/main/resources/application.properties rename to discovery-springcloud-examples/discovery-springcloud-example-eureka/src/main/resources/application.properties diff --git a/discovery-springcloud-examples/discovery-springcloud-example-eureka/src/main/resources/logback.xml b/discovery-springcloud-examples/discovery-springcloud-example-eureka/src/main/resources/logback.xml new file mode 100644 index 0000000000..c37b63f8e2 --- /dev/null +++ b/discovery-springcloud-examples/discovery-springcloud-example-eureka/src/main/resources/logback.xml @@ -0,0 +1,50 @@ + + + + + + + %d{yyyy-MM-dd HH:mm:ss.SSS} %5p ${PID:- } --- [%15.15t] %-40.40logger{39} : %msg%n + + UTF-8 + + + log/discovery-%d{yyyy-MM-dd}.%i.log + 50MB + + + INFO + + + true + + + + 0 + 512 + + + + + + + + + %d{yyyy-MM-dd HH:mm:ss.SSS} %levelColor(%5p) %magenta(${PID:- }) --- [%15.15t] %cyan(%-40.40logger{39}) : %msg%n + + + + INFO + + + + + + + + + + + + + \ No newline at end of file diff --git a/discovery-springcloud-examples/discovery-springcloud-example-gateway/pom.xml b/discovery-springcloud-examples/discovery-springcloud-example-gateway/pom.xml new file mode 100644 index 0000000000..67d4ef4746 --- /dev/null +++ b/discovery-springcloud-examples/discovery-springcloud-example-gateway/pom.xml @@ -0,0 +1,57 @@ + + + discovery-springcloud-example-gateway + Nepxion Discovery Spring Cloud Example Gateway + jar + 4.0.0 + Nepxion Discovery is a solution for Spring Cloud with blue green, gray, weight, limitation, circuit breaker, degrade, isolation, monitor, tracing, dye, failover, async agent + http://www.nepxion.com + + + com.nepxion + discovery-springcloud-examples + 6.23.0 + + + + + com.nepxion + + + + discovery-plugin-register-center-starter-nacos + + + + com.nepxion + + discovery-plugin-config-center-starter-nacos + + + + + + + + com.nepxion + discovery-plugin-admin-center-starter + + + + com.nepxion + discovery-plugin-strategy-starter-gateway + + + + + + + de.codecentric + spring-boot-admin-starter-client + + + \ No newline at end of file diff --git a/discovery-springcloud-example-gateway/src/main/java/com/nepxion/discovery/plugin/example/gateway/DiscoveryApplicationGateway.java b/discovery-springcloud-examples/discovery-springcloud-example-gateway/src/main/java/com/nepxion/discovery/plugin/example/gateway/DiscoveryApplicationGateway.java similarity index 85% rename from discovery-springcloud-example-gateway/src/main/java/com/nepxion/discovery/plugin/example/gateway/DiscoveryApplicationGateway.java rename to discovery-springcloud-examples/discovery-springcloud-example-gateway/src/main/java/com/nepxion/discovery/plugin/example/gateway/DiscoveryApplicationGateway.java index 79e83777b6..40c61008be 100644 --- a/discovery-springcloud-example-gateway/src/main/java/com/nepxion/discovery/plugin/example/gateway/DiscoveryApplicationGateway.java +++ b/discovery-springcloud-examples/discovery-springcloud-example-gateway/src/main/java/com/nepxion/discovery/plugin/example/gateway/DiscoveryApplicationGateway.java @@ -11,7 +11,6 @@ */ import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.context.annotation.Bean; @@ -21,7 +20,7 @@ import com.nepxion.discovery.plugin.example.gateway.impl.MyLoadBalanceListener; import com.nepxion.discovery.plugin.example.gateway.impl.MyRegisterListener; import com.nepxion.discovery.plugin.example.gateway.impl.MyRouteFilter; -import com.nepxion.discovery.plugin.strategy.gateway.constant.GatewayStrategyConstant; +import com.nepxion.discovery.plugin.example.gateway.impl.MySubscriber; import com.nepxion.discovery.plugin.strategy.gateway.filter.GatewayStrategyRouteFilter; @SpringBootApplication @@ -32,10 +31,8 @@ public static void main(String[] args) { } @Bean - @ConditionalOnProperty(value = GatewayStrategyConstant.SPRING_APPLICATION_STRATEGY_GATEWAY_ROUTE_FILTER_ENABLED, matchIfMissing = true) public GatewayStrategyRouteFilter gatewayStrategyRouteFilter() { return new MyRouteFilter(); - // return new CustomizationGatewayStrategyRouteFilter(); } @Bean @@ -58,6 +55,11 @@ public MyLoadBalanceListener myLoadBalanceListener() { return new MyLoadBalanceListener(); } + @Bean + public MySubscriber mySubscriber() { + return new MySubscriber(); + } + /*@Bean public RouteLocator routeLocator(RouteLocatorBuilder builder) { return builder diff --git a/discovery-springcloud-examples/discovery-springcloud-example-gateway/src/main/java/com/nepxion/discovery/plugin/example/gateway/impl/MyDiscoveryEnabledStrategy.java b/discovery-springcloud-examples/discovery-springcloud-example-gateway/src/main/java/com/nepxion/discovery/plugin/example/gateway/impl/MyDiscoveryEnabledStrategy.java new file mode 100644 index 0000000000..7c499299da --- /dev/null +++ b/discovery-springcloud-examples/discovery-springcloud-example-gateway/src/main/java/com/nepxion/discovery/plugin/example/gateway/impl/MyDiscoveryEnabledStrategy.java @@ -0,0 +1,65 @@ +package com.nepxion.discovery.plugin.example.gateway.impl; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; + +import com.nepxion.discovery.plugin.framework.adapter.PluginAdapter; +import com.nepxion.discovery.plugin.strategy.adapter.DiscoveryEnabledStrategy; +import com.nepxion.discovery.plugin.strategy.gateway.context.GatewayStrategyContextHolder; +import com.netflix.loadbalancer.Server; + +// 实现了组合策略,版本路由策略+区域路由策略+IP地址和端口路由策略+自定义策略 +public class MyDiscoveryEnabledStrategy implements DiscoveryEnabledStrategy { + private static final Logger LOG = LoggerFactory.getLogger(MyDiscoveryEnabledStrategy.class); + + @Autowired + private GatewayStrategyContextHolder gatewayStrategyContextHolder; + + @Autowired + private PluginAdapter pluginAdapter; + + @Override + public boolean apply(Server server) { + // 对Rest调用传来的Header参数(例如:mobile)做策略 + return applyFromHeader(server); + } + + // 根据REST调用传来的Header参数(例如:mobile),选取执行调用请求的服务实例 + private boolean applyFromHeader(Server server) { + String mobile = gatewayStrategyContextHolder.getHeader("mobile"); + String serviceId = pluginAdapter.getServerServiceId(server); + String version = pluginAdapter.getServerVersion(server); + String region = pluginAdapter.getServerRegion(server); + String environment = pluginAdapter.getServerEnvironment(server); + String address = server.getHost() + ":" + server.getPort(); + + LOG.info("负载均衡用户定制触发:mobile={}, serviceId={}, version={}, region={}, env={}, address={}", mobile, serviceId, version, region, environment, address); + + if (StringUtils.isNotEmpty(mobile)) { + // 手机号以移动138开头,路由到1.0版本的服务上 + if (mobile.startsWith("138") && StringUtils.equals(version, "1.0")) { + return true; + // 手机号以联通133开头,路由到1.1版本的服务上 + } else if (mobile.startsWith("133") && StringUtils.equals(version, "1.1")) { + return true; + } else { + // 其它情况,实例被过滤掉 + return false; + } + } + + // 无手机号,实例不被过滤掉 + return true; + } +} \ No newline at end of file diff --git a/discovery-springcloud-examples/discovery-springcloud-example-gateway/src/main/java/com/nepxion/discovery/plugin/example/gateway/impl/MyDiscoveryListener.java b/discovery-springcloud-examples/discovery-springcloud-example-gateway/src/main/java/com/nepxion/discovery/plugin/example/gateway/impl/MyDiscoveryListener.java new file mode 100644 index 0000000000..6a475d9379 --- /dev/null +++ b/discovery-springcloud-examples/discovery-springcloud-example-gateway/src/main/java/com/nepxion/discovery/plugin/example/gateway/impl/MyDiscoveryListener.java @@ -0,0 +1,49 @@ +package com.nepxion.discovery.plugin.example.gateway.impl; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.Iterator; +import java.util.List; + +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.cloud.client.ServiceInstance; + +import com.nepxion.discovery.plugin.framework.listener.discovery.AbstractDiscoveryListener; + +// 当目标服务的元数据中的Group为mygroup2,禁止被本服务发现(只用于DiscoveryClient.getInstances接口方法用) +public class MyDiscoveryListener extends AbstractDiscoveryListener { + private static final Logger LOG = LoggerFactory.getLogger(MyDiscoveryListener.class); + + @Override + public void onGetInstances(String serviceId, List instances) { + Iterator iterator = instances.iterator(); + while (iterator.hasNext()) { + ServiceInstance instance = iterator.next(); + String group = pluginAdapter.getInstanceGroup(instance); + if (StringUtils.equals(group, "mygroup2")) { + iterator.remove(); + + LOG.info("服务名=" + serviceId + ",组名=" + group + "的服务禁止被本服务发现"); + } + } + } + + @Override + public void onGetServices(List services) { + + } + + @Override + public int getOrder() { + return LOWEST_PRECEDENCE - 500; + } +} \ No newline at end of file diff --git a/discovery-springcloud-example-gateway/src/main/java/com/nepxion/discovery/plugin/example/gateway/impl/MyFallback.java b/discovery-springcloud-examples/discovery-springcloud-example-gateway/src/main/java/com/nepxion/discovery/plugin/example/gateway/impl/MyFallback.java similarity index 100% rename from discovery-springcloud-example-gateway/src/main/java/com/nepxion/discovery/plugin/example/gateway/impl/MyFallback.java rename to discovery-springcloud-examples/discovery-springcloud-example-gateway/src/main/java/com/nepxion/discovery/plugin/example/gateway/impl/MyFallback.java diff --git a/discovery-springcloud-examples/discovery-springcloud-example-gateway/src/main/java/com/nepxion/discovery/plugin/example/gateway/impl/MyLoadBalanceListener.java b/discovery-springcloud-examples/discovery-springcloud-example-gateway/src/main/java/com/nepxion/discovery/plugin/example/gateway/impl/MyLoadBalanceListener.java new file mode 100644 index 0000000000..2dbb6126e6 --- /dev/null +++ b/discovery-springcloud-examples/discovery-springcloud-example-gateway/src/main/java/com/nepxion/discovery/plugin/example/gateway/impl/MyLoadBalanceListener.java @@ -0,0 +1,44 @@ +package com.nepxion.discovery.plugin.example.gateway.impl; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.Iterator; +import java.util.List; + +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.nepxion.discovery.plugin.framework.listener.loadbalance.AbstractLoadBalanceListener; +import com.netflix.loadbalancer.Server; + +// 当目标服务的元数据中的Group为mygroup2,禁止被本服务负载均衡 +public class MyLoadBalanceListener extends AbstractLoadBalanceListener { + private static final Logger LOG = LoggerFactory.getLogger(MyLoadBalanceListener.class); + + @Override + public void onGetServers(String serviceId, List servers) { + Iterator iterator = servers.iterator(); + while (iterator.hasNext()) { + Server server = iterator.next(); + String group = pluginAdapter.getServerGroup(server); + if (StringUtils.equals(group, "mygroup3")) { + iterator.remove(); + + LOG.info("服务名=" + serviceId + ",组名=" + group + "的服务禁止被本服务负载均衡"); + } + } + } + + @Override + public int getOrder() { + return LOWEST_PRECEDENCE - 500; + } +} \ No newline at end of file diff --git a/discovery-springcloud-examples/discovery-springcloud-example-gateway/src/main/java/com/nepxion/discovery/plugin/example/gateway/impl/MyRegisterListener.java b/discovery-springcloud-examples/discovery-springcloud-example-gateway/src/main/java/com/nepxion/discovery/plugin/example/gateway/impl/MyRegisterListener.java new file mode 100644 index 0000000000..41d7f8f929 --- /dev/null +++ b/discovery-springcloud-examples/discovery-springcloud-example-gateway/src/main/java/com/nepxion/discovery/plugin/example/gateway/impl/MyRegisterListener.java @@ -0,0 +1,48 @@ +package com.nepxion.discovery.plugin.example.gateway.impl; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.apache.commons.lang3.StringUtils; +import org.springframework.cloud.client.serviceregistry.Registration; + +import com.nepxion.discovery.common.exception.DiscoveryException; +import com.nepxion.discovery.plugin.framework.listener.register.AbstractRegisterListener; + +// 当本服务的元数据中的Group为mygroup1,禁止被注册到注册中心 +public class MyRegisterListener extends AbstractRegisterListener { + @Override + public void onRegister(Registration registration) { + String serviceId = pluginAdapter.getServiceId(); + String group = pluginAdapter.getGroup(); + if (StringUtils.equals(group, "mygroup1")) { + throw new DiscoveryException("服务名=" + serviceId + ",组名=" + group + "的服务禁止被注册到注册中心"); + } + } + + @Override + public void onDeregister(Registration registration) { + + } + + @Override + public void onSetStatus(Registration registration, String status) { + + } + + @Override + public void onClose() { + + } + + @Override + public int getOrder() { + return LOWEST_PRECEDENCE - 500; + } +} \ No newline at end of file diff --git a/discovery-springcloud-examples/discovery-springcloud-example-gateway/src/main/java/com/nepxion/discovery/plugin/example/gateway/impl/MyRouteFilter.java b/discovery-springcloud-examples/discovery-springcloud-example-gateway/src/main/java/com/nepxion/discovery/plugin/example/gateway/impl/MyRouteFilter.java new file mode 100644 index 0000000000..b6cc5699c8 --- /dev/null +++ b/discovery-springcloud-examples/discovery-springcloud-example-gateway/src/main/java/com/nepxion/discovery/plugin/example/gateway/impl/MyRouteFilter.java @@ -0,0 +1,41 @@ +package com.nepxion.discovery.plugin.example.gateway.impl; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Value; + +import com.nepxion.discovery.plugin.strategy.gateway.filter.DefaultGatewayStrategyRouteFilter; + +// 适用于A/B Testing或者更根据某业务参数决定蓝绿灰度路由路径。可以结合配置中心分别配置A/B两条路径,可以动态改变并通知 +// 当Header中传来的用户为张三,执行一条路由路径;为李四,执行另一条路由路径 +public class MyRouteFilter extends DefaultGatewayStrategyRouteFilter { + private static final String DEFAULT_A_ROUTE_VERSION = "{\"discovery-springcloud-example-a\":\"1.0\", \"discovery-springcloud-example-b\":\"1.0\", \"discovery-springcloud-example-c\":\"1.0\"}"; + private static final String DEFAULT_B_ROUTE_VERSION = "{\"discovery-springcloud-example-a\":\"1.1\", \"discovery-springcloud-example-b\":\"1.1\", \"discovery-springcloud-example-c\":\"1.1\"}"; + + @Value("${a.route.version:" + DEFAULT_A_ROUTE_VERSION + "}") + private String aRouteVersion; + + @Value("${b.route.version:" + DEFAULT_B_ROUTE_VERSION + "}") + private String bRouteVersion; + + @Override + public String getRouteVersion() { + String user = strategyContextHolder.getHeader("user"); + + if (StringUtils.equals(user, "zhangsan")) { + return aRouteVersion; + } else if (StringUtils.equals(user, "lisi")) { + return bRouteVersion; + } + + return super.getRouteVersion(); + } +} \ No newline at end of file diff --git a/discovery-springcloud-examples/discovery-springcloud-example-gateway/src/main/java/com/nepxion/discovery/plugin/example/gateway/impl/MySubscriber.java b/discovery-springcloud-examples/discovery-springcloud-example-gateway/src/main/java/com/nepxion/discovery/plugin/example/gateway/impl/MySubscriber.java new file mode 100644 index 0000000000..5b4bb2d9f7 --- /dev/null +++ b/discovery-springcloud-examples/discovery-springcloud-example-gateway/src/main/java/com/nepxion/discovery/plugin/example/gateway/impl/MySubscriber.java @@ -0,0 +1,75 @@ +package com.nepxion.discovery.plugin.example.gateway.impl; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.List; +import java.util.Map; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; + +import com.google.common.eventbus.Subscribe; +import com.nepxion.discovery.common.entity.ParameterEntity; +import com.nepxion.discovery.common.entity.ParameterServiceEntity; +import com.nepxion.discovery.plugin.framework.adapter.PluginAdapter; +import com.nepxion.discovery.plugin.framework.event.ParameterChangedEvent; +import com.nepxion.discovery.plugin.framework.event.RegisterFailureEvent; +import com.nepxion.discovery.plugin.framework.event.RuleClearedEvent; +import com.nepxion.discovery.plugin.framework.event.RuleFailureEvent; +import com.nepxion.discovery.plugin.framework.event.RuleUpdatedEvent; +import com.nepxion.discovery.plugin.strategy.event.StrategyAlarmEvent; +import com.nepxion.eventbus.annotation.EventBus; + +@EventBus +public class MySubscriber { + private static final Logger LOG = LoggerFactory.getLogger(MySubscriber.class); + + @Autowired + private PluginAdapter pluginAdapter; + + @Subscribe + public void onRuleUpdated(RuleUpdatedEvent ruleUpdatedEvent) { + LOG.info("规则执行更新, rule=" + ruleUpdatedEvent.getRule()); + } + + @Subscribe + public void onRuleCleared(RuleClearedEvent ruleClearedEvent) { + LOG.info("规则执行清空"); + } + + @Subscribe + public void onRuleRuleFailure(RuleFailureEvent ruleFailureEvent) { + LOG.info("规则更新失败, rule=" + ruleFailureEvent.getRule() + ", exception=" + ruleFailureEvent.getException()); + } + + @Subscribe + public void onParameterChanged(ParameterChangedEvent parameterChangedEvent) { + ParameterEntity parameterEntity = parameterChangedEvent.getParameterEntity(); + String serviceId = pluginAdapter.getServiceId(); + List parameterServiceEntityList = null; + if (parameterEntity != null) { + Map> parameterServiceMap = parameterEntity.getParameterServiceMap(); + parameterServiceEntityList = parameterServiceMap.get(serviceId); + } + LOG.info("获取动态参数, serviceId=" + serviceId + ", parameterServiceEntityList=" + parameterServiceEntityList); + } + + @Subscribe + public void onRegisterFailure(RegisterFailureEvent registerFailureEvent) { + LOG.info("注册失败, eventType=" + registerFailureEvent.getEventType() + ", eventDescription=" + registerFailureEvent.getEventDescription() + ", serviceId=" + registerFailureEvent.getServiceId() + ", host=" + registerFailureEvent.getHost() + ", port=" + registerFailureEvent.getPort()); + } + + @Subscribe + public void onAlarm(StrategyAlarmEvent strategyAlarmEvent) { + LOG.info("告警类型=" + strategyAlarmEvent.getAlarmType()); + LOG.info("告警内容=" + strategyAlarmEvent.getAlarmMap()); + } +} \ No newline at end of file diff --git a/discovery-springcloud-examples/discovery-springcloud-example-gateway/src/main/resources/application.properties b/discovery-springcloud-examples/discovery-springcloud-example-gateway/src/main/resources/application.properties new file mode 100644 index 0000000000..ffd039564b --- /dev/null +++ b/discovery-springcloud-examples/discovery-springcloud-example-gateway/src/main/resources/application.properties @@ -0,0 +1,21 @@ +# Spring cloud config +spring.application.name=discovery-springcloud-example-gateway +server.port=1500 + +# Eureka config for discovery +eureka.instance.metadataMap.group=example-service-group +eureka.instance.metadataMap.version=1.0 + +# Consul config for discovery +spring.cloud.consul.discovery.tags=group=example-service-group,version=1.0 + +# Zookeeper config for discovery +spring.cloud.zookeeper.discovery.metadata.group=example-service-group +spring.cloud.zookeeper.discovery.metadata.version=1.0 + +# Nacos config for discovery +spring.cloud.nacos.discovery.metadata.group=example-service-group +spring.cloud.nacos.discovery.metadata.version=1.0 + +# Management config +management.server.port=5500 \ No newline at end of file diff --git a/discovery-springcloud-examples/discovery-springcloud-example-gateway/src/main/resources/bootstrap.properties b/discovery-springcloud-examples/discovery-springcloud-example-gateway/src/main/resources/bootstrap.properties new file mode 100644 index 0000000000..5312660dc3 --- /dev/null +++ b/discovery-springcloud-examples/discovery-springcloud-example-gateway/src/main/resources/bootstrap.properties @@ -0,0 +1,335 @@ +# Spring cloud config + +# Eureka config for discovery +eureka.client.serviceUrl.defaultZone=http://localhost:9528/eureka/ +eureka.instance.preferIpAddress=true + +# Consul config for discovery +spring.cloud.consul.host=localhost +spring.cloud.consul.port=8500 +spring.cloud.consul.discovery.preferIpAddress=true + +# Zookeeper config for discovery +spring.cloud.zookeeper.connectString=localhost:2181 +spring.cloud.zookeeper.discovery.instancePort=${server.port} +spring.cloud.zookeeper.discovery.root=/spring-cloud +spring.cloud.zookeeper.discovery.preferIpAddress=true + +# Nacos config for discovery +spring.cloud.nacos.discovery.server-addr=localhost:8848 +# spring.cloud.nacos.discovery.namespace=discovery + +# Ribbon config +ribbon.ServerListRefreshInterval=5000 +ribbon.ConnectTimeout=60000 +ribbon.ReadTimeout=60000 +ribbon.maxAutoRetries=3 +ribbon.maxAutoRetriesNextServer=3 +ribbon.okToRetryOnAllOperations=true + +# Apollo config for rule +app.id=discovery +apollo.meta=http://106.54.227.205:8080 +# apollo.namespace=application + +# Nacos config for rule +nacos.server-addr=localhost:8848 +# nacos.access-key= +# nacos.secret-key= +# nacos.username= +# nacos.password= +# nacos.namespace=application +# nacos.cluster-name= +# nacos.context-path= +# nacos.config-long-poll-timeout= +# nacos.config-retry-time= +# nacos.max-retry= +# nacos.endpoint= +# nacos.endpoint-port= +# nacos.is-use-endpoint-parsing-rule= +# nacos.is-use-cloud-namespace-parsing= +# nacos.encode= +# nacos.naming-load-cache-at-start= +# nacos.naming-client-beat-thread-count= +# nacos.naming-polling-thread-count= +# nacos.naming-request-domain-max-retry-count= +# nacos.naming-push-empty-protection= +# nacos.ram-role-name= +# nacos.timout= + +# Redis config for rule +spring.redis.host=localhost +spring.redis.port=6379 +spring.redis.password= +spring.redis.database=0 + +# Zookeeper config for rule +zookeeper.connect-string=localhost:2181 +zookeeper.retry-count=3 +zookeeper.sleep-time=3000 + +# Consul config for rule +consul.host=localhost +consul.port=8500 +consul.timeout=1 +consul.token= + +# Etcd config for rule +etcd.server.addr=http://localhost:2379 +etcd.username= +etcd.password= + +# Management config +# 该项只对Consul有效,而且必须配置在bootstrap.properties里,配置在application.properties无效 +# management.health.consul.enabled=true +management.endpoints.web.exposure.include=* +management.endpoints.jmx.exposure.include=* +management.endpoint.health.show-details=ALWAYS + +# Spring boot admin config +spring.boot.admin.client.instance.prefer-ip=true +spring.boot.admin.client.url=http://localhost:9728 + +# Plugin core config +# 随机权重算法。缺失则默认为MapWeightRandom +# spring.application.weight.random.type=MapWeightRandom +# 规则文件的格式,支持xml和json。缺失则默认为xml +# spring.application.config.format=xml +# spring.application.config.format=json +# 本地规则文件的路径,支持两种方式:classpath:rule.xml(rule.json) - 规则文件放在resources目录下,便于打包进jar;file:rule.xml(rule.json) - 规则文件放在工程根目录下,放置在外部便于修改。缺失则默认为不装载本地规则 +# spring.application.config.path=classpath:rule.xml +# spring.application.config.path=classpath:rule.json +# 为微服务归类的Key,一般通过group字段来归类,例如eureka.instance.metadataMap.group=xxx-group或者eureka.instance.metadataMap.application=xxx-application。缺失则默认为group +# spring.application.group.key=group +# spring.application.group.key=application +# 业务系统希望大多数时候Spring、SpringBoot或者SpringCloud的基本配置、调优参数(非业务系统配置参数),不配置在业务端,集成到基础框架里。但特殊情况下,业务系统有时候也希望能把基础框架里配置的参数给覆盖掉,用他们自己的配置 +# 对于此类型的配置需求,可以配置在下面的配置文件里。该文件一般放在resource目录下。缺失则默认为spring-application-default.properties +# spring.application.default.properties.path=spring-application-default.properties +# 负载均衡下,消费端尝试获取对应提供端服务实例列表为空的时候,通过日志方式通知。缺失则默认为false +# spring.application.no.servers.notify.enabled=false +# 由于Nacos注册中心会自动把服务名处理成GROUP@@SERVICE_ID的格式,导致根据服务名去获取元数据的时候会找不到。通过如下开关开启是否要过滤掉GROUP前缀。缺失则默认为true +# spring.application.nacos.service.id.filter.enabled=true +# 启动和关闭在服务启动的时候参数订阅事件发送。缺失则默认为true +# spring.application.parameter.event.onstart.enabled=true + +# Plugin strategy config +# 开启和关闭Ribbon默认的ZoneAvoidanceRule负载均衡策略。一旦关闭,则使用RoundRobin简单轮询负载均衡策略。缺失则默认为true +# spring.application.strategy.zone.avoidance.rule.enabled=true +# 路由策略过滤器的执行顺序(Order)。缺失则默认为9000 +# spring.application.strategy.gateway.route.filter.order=9000 +# 当外界传值Header的时候,网关也设置并传递同名的Header,需要决定哪个Header传递到后边的服务去。如果下面开关为true,以网关设置为优先,否则以外界传值为优先。缺失则默认为true +spring.application.strategy.gateway.header.priority=false +# 当以网关设置为优先的时候,网关未配置Header,而外界配置了Header,仍旧忽略外界的Header。缺失则默认为true +# spring.application.strategy.gateway.original.header.ignored=true +# 开启和关闭网关订阅配置中心的动态路由策略。缺失则默认为false +spring.application.strategy.gateway.dynamic.route.enabled=true +# 启动和关闭网关上核心策略Header传递,缺失则默认为true。当全局订阅启动时,可以关闭核心策略Header传递,这样可以节省传递数据的大小,一定程度上可以提升性能 +# 核心策略Header指n-d-开头的Header(不包括n-d-env,因为环境路由隔离,必须传递该Header),不包括n-d-service开头的Header +# spring.application.strategy.gateway.core.header.transmission.enabled=true + +# 启动和关闭监控,一旦关闭,调用链和日志输出都将关闭。缺失则默认为false +spring.application.strategy.monitor.enabled=true +# 启动和关闭告警,一旦关闭,蓝绿灰度上下文输出都将关闭。缺失则默认为false +spring.application.strategy.alarm.enabled=true +# 启动和关闭日志输出。缺失则默认为false +spring.application.strategy.logger.enabled=true +# 日志输出中,是否显示MDC前面的Key。缺失则默认为true +# spring.application.strategy.logger.mdc.key.shown=true +# 启动和关闭Debug日志打印,注意:每调用一次都会打印一次,会对性能有所影响,建议压测环境和生产环境关闭。缺失则默认为false +spring.application.strategy.logger.debug.enabled=true +# 启动和关闭调用链输出。缺失则默认为false +spring.application.strategy.tracer.enabled=true +# 启动和关闭调用链的蓝绿灰度信息以独立的Span节点输出,如果关闭,则蓝绿灰度信息输出到原生的Span节点中(SkyWalking不支持原生模式)。缺失则默认为true +# spring.application.strategy.tracer.separate.span.enabled=true +# 启动和关闭调用链的蓝绿灰度规则策略信息输出。缺失则默认为true +# spring.application.strategy.tracer.rule.output.enabled=true +# 启动和关闭调用链的异常信息是否以详细格式输出。缺失则默认为false +# spring.application.strategy.tracer.exception.detail.output.enabled=false +# 显示在调用链界面上蓝绿灰度Span的名称,建议改成具有公司特色的框架产品名称。缺失则默认为NEPXION +# spring.application.strategy.tracer.span.value=NEPXION +# 显示在调用链界面上蓝绿灰度Span Tag的插件名称,建议改成具有公司特色的框架产品的描述。缺失则默认为Nepxion Discovery +# spring.application.strategy.tracer.span.tag.plugin.value=Nepxion Discovery +# 启动和关闭Sentinel调用链上规则在Span上的输出。缺失则默认为true +# spring.application.strategy.tracer.sentinel.rule.output.enabled=true +# 启动和关闭Sentinel调用链上方法入参在Span上的输出。缺失则默认为false +# spring.application.strategy.tracer.sentinel.args.output.enabled=false + +# 启动和关闭Sentinel Metric通过次数统计输出功能。缺失则默认为true +# spring.application.strategy.metric.sentinel.pass.qps.output.enabled=true +# 启动和关闭Sentinel Metric阻塞次数统计输出功能。缺失则默认为true +# spring.application.strategy.metric.sentinel.block.qps.output.enabled=true +# 启动和关闭Sentinel Metric成功次数统计输出功能。缺失则默认为true +# spring.application.strategy.metric.sentinel.success.qps.output.enabled=true +# 启动和关闭Sentinel Metric异常次数统计输出功能。缺失则默认为true +# spring.application.strategy.metric.sentinel.exception.qps.output.enabled=true + +# 启动和关闭Sentinel限流降级熔断权限等原生功能的数据来源扩展。缺失则默认为false +# spring.application.strategy.sentinel.datasource.enabled=true +# 流控规则文件路径。缺失则默认为classpath:sentinel-flow.json +# spring.application.strategy.sentinel.flow.path=classpath:sentinel-flow.json +# 降级规则文件路径。缺失则默认为classpath:sentinel-degrade.json +# spring.application.strategy.sentinel.degrade.path=classpath:sentinel-degrade.json +# 授权规则文件路径。缺失则默认为classpath:sentinel-authority.json +# spring.application.strategy.sentinel.authority.path=classpath:sentinel-authority.json +# 系统规则文件路径。缺失则默认为classpath:sentinel-system.json +# spring.application.strategy.sentinel.system.path=classpath:sentinel-system.json +# 热点参数流控规则文件路径。缺失则默认为classpath:sentinel-param-flow.json +# spring.application.strategy.sentinel.param.flow.path=classpath:sentinel-param-flow.json + +# 启动和关闭消费端的服务隔离(基于Group是否相同的策略)。缺失则默认为false +spring.application.strategy.consumer.isolation.enabled=true + +# 版本故障转移,即无法找到相应版本的服务实例,路由到老的稳定版本的实例。其作用是防止蓝绿灰度版本发布人为设置错误,或者对应的版本实例发生灾难性的全部下线,导致流量有损 +# 在开启版本故障转移的开关前提下,故障转移有三种策略: +# 1. 如果“version-failover”值已配置,指定版本的故障转移,即找不到实例的时候,直接路由到该版本实例 +# 2. 如果“version-failover”值未配置 +# 2.1 开启“version.failover.stable.enabled”开关,版本列表排序策略的(取最老的稳定版本的实例)故障转移,即找不到实例的时候,直接路由到最老的稳定版本的实例 +# 2.2 关闭“version.failover.stable.enabled”开关,负载均衡策略的故障转移,即找不到实例的时候,执行负载均衡策略 +# 启动和关闭版本故障转移。缺失则默认为false +# spring.application.strategy.version.failover.enabled=true +# 开启和关闭版本列表排序策略下取稳定版本的版本故障转移。缺失则默认为false +# spring.application.strategy.version.failover.stable.enabled=true + +# 版本偏好,即非蓝绿灰度发布场景下,路由到老的稳定版本的实例。其作用是防止多个网关上并行实施蓝绿灰度版本发布产生混乱,对处于非蓝绿灰度状态的服务,调用它的时候,只取它的老的稳定版本的实例;蓝绿灰度状态的服务,还是根据传递的Header版本号进行匹配 +# 在开启版本偏好的开关前提下,偏好有两种策略: +# 1. 如果“version-prefer”值已配置,指定版本的偏好,即不管存在多少版本,直接路由到该版本实例 +# 2. 如果“version-prefer”值未配置,版本列表排序策略的(取最老的稳定版本的实例)偏好,即不管存在多少版本,直接路由到最老的稳定版本的实例 +# 启动和关闭版本偏好。缺失则默认为false +# spring.application.strategy.version.prefer.enabled=true + +# 区域调试转移,即当未对服务指定访问区域的时候,转移到事先指定的区域 +# 使用场景示例: +# 开发环境(个人电脑环境)在测试环境(线上环境)进行联调 +# 访问路径为A服务 -> B服务 -> C服务,A服务和B服务在开发环境上,C服务在测试环境上 +# 调用时候,在B服务上进行如下两个配置,并在最前端传入的Header(n-d-region)指定为B的开发环境区域(用来保证A服务和B服务只在开发环境调用),而B服务会自动转移调用到测试环境上的C服务实例,但不会转移到其它个人电脑的C服务实例 +# 该功能的意义,个人电脑环境可以接入到测试环境联调,当多套个人环境接入时候,可以保护不同的个人环境间不会彼此调用 +# 通过“region-transfer”值进行区域转移值配置,如果缺失,则报错 +# 启动和关闭区域调试转移。缺失则默认为false +# spring.application.strategy.region.transfer.enabled=true + +# 在开启区域故障转移的开关前提下,故障转移有两种策略: +# 1. 如果“region-failover”值已配置,指定区域的故障转移,即找不到实例的时候,直接路由到该区域实例 +# 2. 如果“region-failover”值未配置,负载均衡策略的故障转移,即找不到实例的时候,执行负载均衡策略 +# 启动和关闭区域故障转移。缺失则默认为false +# spring.application.strategy.region.failover.enabled=true + +# 启动和关闭环境故障转移。缺失则默认为false +# 如果“env-failover”值未配置,则默认为common +# spring.application.strategy.environment.failover.enabled=true + +# 启动和关闭可用区亲和性,即同一个可用区的服务才能调用,同一个可用区的条件是调用端实例和提供端实例的元数据Metadata的zone配置值必须相等。缺失则默认为false +# spring.application.strategy.zone.affinity.enabled=true + +# 在开启可用区故障转移的开关前提下,故障转移有两种策略: +# 1. 如果“zone-failover”值已配置,指定可用区的故障转移,即找不到实例的时候,直接路由到该可用区实例 +# 2. 如果“zone-failover”值未配置,负载均衡策略的故障转移,即找不到实例的时候,执行负载均衡策略 +# 启动和关闭可用区故障转移。缺失则默认为false +# spring.application.strategy.zone.failover.enabled=true + +# 在开启IP地址和端口故障转移的开关前提下,故障转移有两种策略: +# 1. 如果“address-failover”值已配置,指定IP地址或者端口的故障转移,即找不到实例的时候,直接路由到该IP地址或者端口实例 +# 2. 如果“address-failover”值未配置,负载均衡策略的故障转移,即找不到实例的时候,执行负载均衡策略 +# 启动和关闭IP地址和端口故障转移。缺失则默认为false +# spring.application.strategy.address.failover.enabled=true + +# 版本号排序类型。缺失则默认为version +# 版本故障转移或者版本偏好启动时,需要寻址旧的稳定版本 +# 1. 当排序类型为version时,适用于版本号采用时间戳或者数字递增的方式。处理逻辑为将排序后版本号列表的第一个值作为旧的稳定版本 +# 2. 当排序类型为time时,不限于版本号的格式。处理逻辑为将根据服务实例全局唯一ID的时间戳前缀进行排序,把上线时间最早的服务实例的版本号作为旧的稳定版本 +# spring.application.strategy.version.sort.type=version +# spring.application.strategy.version.sort.type=time + +# 启动和关闭自动扫描目录,当扫描目录未人工配置的时候,可以通过自动扫描方式决定扫描目录。缺失则默认为true +# spring.application.strategy.auto.scan.packages.enabled=true +# 启动和关闭嵌套扫描,嵌套扫描指扫描非本工程下外部包的目录,可以支持多层嵌套。缺失则默认为false +# spring.application.strategy.auto.scan.recursion.enabled=false + +# 开启和关闭使用服务名前缀来作为服务组名。缺失则默认为false +# spring.application.group.generator.enabled=true +# 服务名前缀的截断长度,必须大于0 +# spring.application.group.generator.length=15 +# 服务名前缀的截断标志。当截断长度配置了,则取截断长度方式,否则取截断标志方式 +# spring.application.group.generator.character=- + +# 开启和关闭使用Git信息中的字段单个或者多个组合来作为服务版本号。缺失则默认为false +# spring.application.git.generator.enabled=true +# 插件git-commit-id-plugin产生git信息文件的输出路径,支持properties和json两种格式,支持classpath:xxx和file:xxx两种路径,这些需要和插件里的配置保持一致。缺失则默认为classpath:git.properties +# spring.application.git.generator.path=classpath:git.properties +# spring.application.git.generator.path=classpath:git.json +# 使用Git信息中的字段单个或者多个组合来作为服务版本号。缺失则默认为{git.commit.time}-{git.total.commit.count} +# 日期 + Git提交次数的版本号格式 +# spring.application.git.version.key={git.commit.time}-{git.total.commit.count} +# POM版本号格式 +# spring.application.git.version.key={git.build.version} + +# 开启和关闭从SkyWalking apm-agent-core里反射获取TraceId并复制。由于SkyWalking对WebFlux上下文Threadlocal处理机制不恰当,导致产生的TraceId在全链路中并不一致,打开这个开关可以保证全链路TraceId都是一致的。缺失则默认为true +# spring.application.strategy.gateway.skywalking.traceid.enabled=true + +# 下面配置只适用于网关里直接进行Feign、RestTemplate或者WebClient调用场景 +# 启动和关闭路由策略的时候,对REST方式的调用拦截。缺失则默认为true +spring.application.strategy.rest.intercept.enabled=true +# 启动和关闭Header传递的Debug日志打印,注意:每调用一次都会打印一次,会对性能有所影响,建议压测环境和生产环境关闭。缺失则默认为false +spring.application.strategy.rest.intercept.debug.enabled=true +# 启动和关闭Feign上核心策略Header传递,缺失则默认为true。当全局订阅启动时,可以关闭核心策略Header传递,这样可以节省传递数据的大小,一定程度上可以提升性能 +# 核心策略Header指n-d-开头的Header(不包括n-d-env,因为环境路由隔离,必须传递该Header),不包括n-d-service开头的Header +# spring.application.strategy.feign.core.header.transmission.enabled=true +# 启动和关闭RestTemplate上核心策略Header传递,缺失则默认为true。当全局订阅启动时,可以关闭核心策略Header传递,这样可以节省传递数据的大小,一定程度上可以提升性能 +# 核心策略Header指n-d-开头的Header(不包括n-d-env,因为环境路由隔离,必须传递该Header),不包括n-d-service开头的Header +# spring.application.strategy.rest.template.core.header.transmission.enabled=true +# 启动和关闭WebClient上核心策略Header传递,缺失则默认为true。当全局订阅启动时,可以关闭核心策略Header传递,这样可以节省传递数据的大小,一定程度上可以提升性能 +# 核心策略Header指n-d-开头的Header(不包括n-d-env,因为环境路由隔离,必须传递该Header),不包括n-d-service开头的Header +# spring.application.strategy.web.client.core.header.transmission.enabled=true +# 路由策略的时候,对REST方式调用拦截的时候(支持Feign、RestTemplate或者WebClient调用),希望把来自外部自定义的Header参数(用于框架内置上下文Header,例如:trace-id, span-id等)传递到服务里,那么配置如下值。如果多个用“;”分隔,不允许出现空格 +spring.application.strategy.context.request.headers=trace-id;span-id +# 路由策略的时候,对REST方式调用拦截的时候(支持Feign、RestTemplate或者WebClient调用),希望把来自外部自定义的Header参数(用于业务系统自定义Header,例如:mobile)传递到服务里,那么配置如下值。如果多个用“;”分隔,不允许出现空格 +spring.application.strategy.business.request.headers=user;mobile;location + +# 开启和关闭Hystrix线程隔离模式做服务隔离时,对线程切换上下文传递的功能。缺失则默认为false +# Hystrix线程隔离模式做服务隔离时,必须把spring.application.strategy.hystrix.threadlocal.supported设置为true,同时要引入discovery-plugin-strategy-starter-hystrix包,否则线程切换时会发生ThreadLocal上下文对象丢失 +# spring.application.strategy.hystrix.threadlocal.supported=true + +# 启动和关闭服务相关操作端点。缺失则默认为true +# spring.application.admin.service.endpoint.enabled=true +# 启动和关闭配置相关操作端点。缺失则默认为true +# spring.application.admin.config.endpoint.enabled=true +# 启动和关闭版本相关操作端点。缺失则默认为true +# spring.application.admin.version.endpoint.enabled=true +# 启动和关闭侦测相关操作端点。缺失则默认为true +# spring.application.admin.inspector.endpoint.enabled=true +# 启动和关闭路由相关操作端点。缺失则默认为true +# spring.application.admin.router.endpoint.enabled=true +# 启动和关闭策略相关操作端点。缺失则默认为true +# spring.application.admin.strategy.endpoint.enabled=true +# 启动和关闭Sentinel相关操作端点。缺失则默认为true +# spring.application.admin.sentinel.endpoint.enabled=true +# 启动和关闭Git相关操作端点。缺失则默认为true +# spring.application.admin.git.endpoint.enabled=true +# 启动和关闭Spring Cloud Gateway相关操作端点。缺失则默认为true +# spring.application.admin.gateway.endpoint.enabled=true +# 启动和关闭Zuul相关操作端点。缺失则默认为true +# spring.application.admin.zuul.endpoint.enabled=true +# 启动和关闭策略操作端点的验证SPEL表达式方法。缺失则默认为true +# 该端点方法使用Spring StandardEvaluationContext类,StandardEvaluationContext支持全部的Spel语法且功能齐全,但GitHub Security报告其存在一定的注入风险,推荐使用SimpleEvaluationContext,而SimpleEvaluationContext并不能满足当前框架的需求 +# 如果未使用验证SPEL表达式方法,可以通过下面开关关闭在方法在策略端点上的暴露,规避风险 +# spring.application.admin.strategy.endpoint.validate-expression.enabled=true + +# Spring cloud gateway config +# 开启和关闭自动路由。缺失则默认关闭自动路由 +# spring.cloud.gateway.discovery.locator.enabled=true +spring.cloud.gateway.discovery.locator.lowerCaseServiceId=true +# 当启动自动路由(locator.enabled=true)时候,必须关闭reactive模式,否则无法执行蓝绿灰度发布。只有H版需要该配置 +spring.cloud.discovery.reactive.enabled=false + +# 手工配置路由。自动路由和手工动态路由不能混合使用 +spring.cloud.gateway.routes[0].id=route0 +spring.cloud.gateway.routes[0].predicates[0]=Path=/discovery-springcloud-example-a/**, /x/**,/y/** +# Gateway如果用Consul做服务注册发现中心,必须配置StripPrefix=1,其他配置中心配不配无所谓,但建议都配 +spring.cloud.gateway.routes[0].filters[0]=StripPrefix=1 +spring.cloud.gateway.routes[0].uri=lb://discovery-springcloud-example-a + +# Hystrix配置 +# spring.cloud.gateway.routes[0].filters[1].name=Hystrix +# spring.cloud.gateway.routes[0].filters[1].args.name=default +# spring.cloud.gateway.routes[0].filters[1].args.fallbackUri=forward:/fallback +# hystrix.command.default.execution.isolation.strategy=THREAD +# hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds=3000 \ No newline at end of file diff --git a/discovery-springcloud-examples/discovery-springcloud-example-gateway/src/main/resources/dynamic-route-complete.json b/discovery-springcloud-examples/discovery-springcloud-example-gateway/src/main/resources/dynamic-route-complete.json new file mode 100644 index 0000000000..534018fcf0 --- /dev/null +++ b/discovery-springcloud-examples/discovery-springcloud-example-gateway/src/main/resources/dynamic-route-complete.json @@ -0,0 +1,14 @@ +[ + { + "id": "route0", + "uri": "lb://discovery-springcloud-example-a", + "predicates": [ + "Path=/discovery-springcloud-example-a/**,/x/**,/y/**" + ], + "filters": [ + "StripPrefix=1" + ], + "order": 0, + "metadata": {} + } +] \ No newline at end of file diff --git a/discovery-springcloud-examples/discovery-springcloud-example-gateway/src/main/resources/dynamic-route-complex.json b/discovery-springcloud-examples/discovery-springcloud-example-gateway/src/main/resources/dynamic-route-complex.json new file mode 100644 index 0000000000..780af53101 --- /dev/null +++ b/discovery-springcloud-examples/discovery-springcloud-example-gateway/src/main/resources/dynamic-route-complex.json @@ -0,0 +1,66 @@ +[ + { + "id": "route0", + "uri": "lb://discovery-springcloud-example-a", + "userPredicates": [ + { + "name": "Path", + "args": { + "_genkey_0": "/discovery-springcloud-example-a/**", + "_genkey_1": "/x/**", + "_genkey_2": "/y/**" + } + }, + { + "name": "Header", + "args": { + "header": "a", + "regexp": "1" + } + }, + { + "name": "Header", + "args": { + "header": "b", + "regexp": "2" + } + }, + { + "name": "Cookie", + "args": { + "name": "c", + "regexp": "3" + } + }, + { + "name": "Cookie", + "args": { + "name": "d", + "regexp": "4" + } + }, + { + "name": "Query", + "args": { + "param": "e", + "regexp": "5" + } + }, + { + "name": "Query", + "args": { + "param": "f", + "regexp": "6" + } + } + ], + "userFilters": [ + { + "name": "StripPrefix", + "args": { + "_genkey_0": "1" + } + } + ] + } +] \ No newline at end of file diff --git a/discovery-springcloud-examples/discovery-springcloud-example-gateway/src/main/resources/dynamic-route-customization.json b/discovery-springcloud-examples/discovery-springcloud-example-gateway/src/main/resources/dynamic-route-customization.json new file mode 100644 index 0000000000..667a3eb96c --- /dev/null +++ b/discovery-springcloud-examples/discovery-springcloud-example-gateway/src/main/resources/dynamic-route-customization.json @@ -0,0 +1,27 @@ +[ + { + "id": "route0", + "uri": "lb://discovery-springcloud-example-a", + "predicates": [ + "Path=/discovery-springcloud-example-a/**,/x/**,/y/**" + ], + "filters": [ + "StripPrefix=1" + ], + "userPredicates": [], + "userFilters": [ + { + "name": "Authentication", + "args": { + "secretKey": "abc", + "whiteList.0": "* swagger-ui.html", + "whiteList.1": "* /swagger-resources/**", + "whiteList.2": "* /doc.html", + "userMap.name": "jason", + "userMap.age": "20", + "authInfoCarryStrategy": "AuthWriteToHeader" + } + } + ] + } +] \ No newline at end of file diff --git a/discovery-springcloud-examples/discovery-springcloud-example-gateway/src/main/resources/dynamic-route-simple.json b/discovery-springcloud-examples/discovery-springcloud-example-gateway/src/main/resources/dynamic-route-simple.json new file mode 100644 index 0000000000..c3e9358668 --- /dev/null +++ b/discovery-springcloud-examples/discovery-springcloud-example-gateway/src/main/resources/dynamic-route-simple.json @@ -0,0 +1,12 @@ +[ + { + "id": "route0", + "uri": "lb://discovery-springcloud-example-a", + "predicates": [ + "Path=/discovery-springcloud-example-a/**,/x/**,/y/**" + ], + "filters": [ + "StripPrefix=1" + ] + } +] \ No newline at end of file diff --git a/discovery-springcloud-examples/discovery-springcloud-example-gateway/src/main/resources/logback.xml b/discovery-springcloud-examples/discovery-springcloud-example-gateway/src/main/resources/logback.xml new file mode 100644 index 0000000000..c37b63f8e2 --- /dev/null +++ b/discovery-springcloud-examples/discovery-springcloud-example-gateway/src/main/resources/logback.xml @@ -0,0 +1,50 @@ + + + + + + + %d{yyyy-MM-dd HH:mm:ss.SSS} %5p ${PID:- } --- [%15.15t] %-40.40logger{39} : %msg%n + + UTF-8 + + + log/discovery-%d{yyyy-MM-dd}.%i.log + 50MB + + + INFO + + + true + + + + 0 + 512 + + + + + + + + + %d{yyyy-MM-dd HH:mm:ss.SSS} %levelColor(%5p) %magenta(${PID:- }) --- [%15.15t] %cyan(%-40.40logger{39}) : %msg%n + + + + INFO + + + + + + + + + + + + + \ No newline at end of file diff --git a/discovery-springcloud-example-gateway/src/main/resources/rule.json b/discovery-springcloud-examples/discovery-springcloud-example-gateway/src/main/resources/rule.json similarity index 100% rename from discovery-springcloud-example-gateway/src/main/resources/rule.json rename to discovery-springcloud-examples/discovery-springcloud-example-gateway/src/main/resources/rule.json diff --git a/discovery-springcloud-example-gateway/src/main/resources/rule.xml b/discovery-springcloud-examples/discovery-springcloud-example-gateway/src/main/resources/rule.xml similarity index 100% rename from discovery-springcloud-example-gateway/src/main/resources/rule.xml rename to discovery-springcloud-examples/discovery-springcloud-example-gateway/src/main/resources/rule.xml diff --git a/discovery-springcloud-examples/discovery-springcloud-example-service/pom.xml b/discovery-springcloud-examples/discovery-springcloud-example-service/pom.xml new file mode 100644 index 0000000000..19df19abe0 --- /dev/null +++ b/discovery-springcloud-examples/discovery-springcloud-example-service/pom.xml @@ -0,0 +1,62 @@ + + + discovery-springcloud-example-service + Nepxion Discovery Spring Cloud Example Service + jar + 4.0.0 + Nepxion Discovery is a solution for Spring Cloud with blue green, gray, weight, limitation, circuit breaker, degrade, isolation, monitor, tracing, dye, failover, async agent + http://www.nepxion.com + + + com.nepxion + discovery-springcloud-examples + 6.23.0 + + + + + com.nepxion + + + + discovery-plugin-register-center-starter-nacos + + + + com.nepxion + + discovery-plugin-config-center-starter-nacos + + + + + + + + ${project.groupId} + discovery-plugin-admin-center-starter + + + + com.nepxion + discovery-plugin-strategy-starter-service + + + + + + + com.alibaba.cloud + spring-cloud-starter-alibaba-sentinel + + + + de.codecentric + spring-boot-admin-starter-client + + + \ No newline at end of file diff --git a/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/DiscoveryApplicationA1.java b/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/DiscoveryApplicationA1.java similarity index 80% rename from discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/DiscoveryApplicationA1.java rename to discovery-springcloud-examples/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/DiscoveryApplicationA1.java index 42240ea85e..f26c435043 100644 --- a/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/DiscoveryApplicationA1.java +++ b/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/DiscoveryApplicationA1.java @@ -9,31 +9,29 @@ * @version 1.0 */ -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; -import org.springframework.cloud.alibaba.sentinel.annotation.SentinelRestTemplate; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.cloud.openfeign.EnableFeignClients; import org.springframework.context.annotation.Bean; import org.springframework.web.client.RestTemplate; +import com.alibaba.cloud.sentinel.annotation.SentinelRestTemplate; import com.nepxion.discovery.plugin.example.service.impl.MyDiscoveryEnabledStrategy; import com.nepxion.discovery.plugin.example.service.impl.MyDiscoveryListener; import com.nepxion.discovery.plugin.example.service.impl.MyLoadBalanceListener; import com.nepxion.discovery.plugin.example.service.impl.MyRegisterListener; +import com.nepxion.discovery.plugin.example.service.impl.MyRouteFilter; import com.nepxion.discovery.plugin.example.service.impl.MySubscriber; import com.nepxion.discovery.plugin.example.service.sentinel.MyRestTemplateBlockHandler; import com.nepxion.discovery.plugin.example.service.sentinel.MyRestTemplateFallbackHandler; import com.nepxion.discovery.plugin.example.service.sentinel.MySentinelFlowRuleParser; -import com.nepxion.discovery.plugin.strategy.service.aop.RestTemplateStrategyInterceptor; +import com.nepxion.discovery.plugin.strategy.service.filter.ServiceStrategyRouteFilter; @SpringBootApplication @EnableDiscoveryClient @EnableFeignClients -// Hystrix测试 -// @EnableCircuitBreaker public class DiscoveryApplicationA1 { public static void main(String[] args) { System.setProperty("spring.profiles.active", "a1"); @@ -44,13 +42,8 @@ public static void main(String[] args) { @Bean @LoadBalanced @SentinelRestTemplate(blockHandler = "handleBlock", blockHandlerClass = MyRestTemplateBlockHandler.class, fallback = "handleFallback", fallbackClass = MyRestTemplateFallbackHandler.class) - public RestTemplate restTemplate(@Autowired(required = false) RestTemplateStrategyInterceptor restTemplateStrategyInterceptor) { - RestTemplate restTemplate = new RestTemplate(); - if (restTemplateStrategyInterceptor != null) { - restTemplate.getInterceptors().add(restTemplateStrategyInterceptor); - } - - return restTemplate; + public RestTemplate restTemplate() { + return new RestTemplate(); } @Bean @@ -58,6 +51,11 @@ public MySentinelFlowRuleParser mySentinelFlowRuleParser() { return new MySentinelFlowRuleParser(); } + @Bean + public ServiceStrategyRouteFilter serviceStrategyRouteFilter() { + return new MyRouteFilter(); + } + @Bean public MyDiscoveryEnabledStrategy myDiscoveryEnabledStrategy() { return new MyDiscoveryEnabledStrategy(); diff --git a/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/DiscoveryApplicationA2.java b/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/DiscoveryApplicationA2.java similarity index 100% rename from discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/DiscoveryApplicationA2.java rename to discovery-springcloud-examples/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/DiscoveryApplicationA2.java diff --git a/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/DiscoveryApplicationB1.java b/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/DiscoveryApplicationB1.java similarity index 100% rename from discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/DiscoveryApplicationB1.java rename to discovery-springcloud-examples/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/DiscoveryApplicationB1.java diff --git a/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/DiscoveryApplicationB2.java b/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/DiscoveryApplicationB2.java similarity index 100% rename from discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/DiscoveryApplicationB2.java rename to discovery-springcloud-examples/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/DiscoveryApplicationB2.java diff --git a/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/DiscoveryApplicationC1.java b/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/DiscoveryApplicationC1.java similarity index 100% rename from discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/DiscoveryApplicationC1.java rename to discovery-springcloud-examples/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/DiscoveryApplicationC1.java diff --git a/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/DiscoveryApplicationC2.java b/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/DiscoveryApplicationC2.java similarity index 100% rename from discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/DiscoveryApplicationC2.java rename to discovery-springcloud-examples/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/DiscoveryApplicationC2.java diff --git a/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/DiscoveryApplicationC3.java b/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/DiscoveryApplicationC3.java similarity index 100% rename from discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/DiscoveryApplicationC3.java rename to discovery-springcloud-examples/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/DiscoveryApplicationC3.java diff --git a/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/context/MyApplicationContextInitializer.java b/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/context/MyApplicationContextInitializer.java new file mode 100644 index 0000000000..f00c56fc28 --- /dev/null +++ b/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/context/MyApplicationContextInitializer.java @@ -0,0 +1,28 @@ +package com.nepxion.discovery.plugin.example.service.context; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.springframework.context.ApplicationContextInitializer; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; + +// 通过如下方式,可以代替在配置文件里面配置元数据,格式为ext.xxx。例如,如果version希望通过git插件获取到最后一次提交编号,可以动态在这里进行解析并放入 +public class MyApplicationContextInitializer implements ApplicationContextInitializer { + @Override + public void initialize(ConfigurableApplicationContext applicationContext) { + if (applicationContext instanceof AnnotationConfigApplicationContext) { + return; + } + + // System.setProperty("ext.group", "myGroup"); + // System.setProperty("ext.version", "8888"); + // System.setProperty("ext.region", "myRegion"); + } +} \ No newline at end of file diff --git a/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/feign/AFeign.java b/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/feign/AFeign.java similarity index 100% rename from discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/feign/AFeign.java rename to discovery-springcloud-examples/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/feign/AFeign.java diff --git a/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/feign/AFeignImpl.java b/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/feign/AFeignImpl.java new file mode 100644 index 0000000000..59895ffe3c --- /dev/null +++ b/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/feign/AFeignImpl.java @@ -0,0 +1,38 @@ +package com.nepxion.discovery.plugin.example.service.feign; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RestController; + +import com.nepxion.discovery.common.constant.DiscoveryConstant; + +@RestController +@ConditionalOnProperty(name = DiscoveryConstant.SPRING_APPLICATION_NAME, havingValue = "discovery-springcloud-example-a") +public class AFeignImpl extends AbstractFeignImpl implements AFeign { + private static final Logger LOG = LoggerFactory.getLogger(AFeignImpl.class); + + @Autowired + private BFeign bFeign; + + @Override + public String invoke(@RequestBody String value) { + value = doInvoke(value); + value = bFeign.invoke(value); + + LOG.info("调用路径:{}", value); + + return value; + } +} \ No newline at end of file diff --git a/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/feign/AbstractFeignImpl.java b/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/feign/AbstractFeignImpl.java new file mode 100644 index 0000000000..7c57f25150 --- /dev/null +++ b/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/feign/AbstractFeignImpl.java @@ -0,0 +1,23 @@ +package com.nepxion.discovery.plugin.example.service.feign; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.springframework.beans.factory.annotation.Autowired; + +import com.nepxion.discovery.plugin.framework.adapter.PluginAdapter; + +public class AbstractFeignImpl { + @Autowired + private PluginAdapter pluginAdapter; + + public String doInvoke(String value) { + return pluginAdapter.getPluginInfo(value); + } +} \ No newline at end of file diff --git a/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/feign/BFeign.java b/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/feign/BFeign.java similarity index 100% rename from discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/feign/BFeign.java rename to discovery-springcloud-examples/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/feign/BFeign.java diff --git a/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/feign/BFeignImpl.java b/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/feign/BFeignImpl.java similarity index 100% rename from discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/feign/BFeignImpl.java rename to discovery-springcloud-examples/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/feign/BFeignImpl.java diff --git a/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/feign/CFeign.java b/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/feign/CFeign.java similarity index 100% rename from discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/feign/CFeign.java rename to discovery-springcloud-examples/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/feign/CFeign.java diff --git a/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/feign/CFeignImpl.java b/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/feign/CFeignImpl.java similarity index 100% rename from discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/feign/CFeignImpl.java rename to discovery-springcloud-examples/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/feign/CFeignImpl.java diff --git a/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/feign/FeignConfiguration.java b/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/feign/FeignConfiguration.java similarity index 100% rename from discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/feign/FeignConfiguration.java rename to discovery-springcloud-examples/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/feign/FeignConfiguration.java diff --git a/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/impl/MyDiscoveryEnabledStrategy.java b/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/impl/MyDiscoveryEnabledStrategy.java new file mode 100644 index 0000000000..19263edf15 --- /dev/null +++ b/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/impl/MyDiscoveryEnabledStrategy.java @@ -0,0 +1,98 @@ +package com.nepxion.discovery.plugin.example.service.impl; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.Map; + +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; + +import com.nepxion.discovery.common.constant.DiscoveryConstant; +import com.nepxion.discovery.plugin.framework.adapter.PluginAdapter; +import com.nepxion.discovery.plugin.strategy.adapter.DiscoveryEnabledStrategy; +import com.nepxion.discovery.plugin.strategy.service.context.ServiceStrategyContextHolder; +import com.netflix.loadbalancer.Server; + +// 实现了组合策略,版本路由策略+区域路由策略+IP地址和端口路由策略+自定义策略 +public class MyDiscoveryEnabledStrategy implements DiscoveryEnabledStrategy { + private static final Logger LOG = LoggerFactory.getLogger(MyDiscoveryEnabledStrategy.class); + + @Autowired + private PluginAdapter pluginAdapter; + + @Autowired + private ServiceStrategyContextHolder serviceStrategyContextHolder; + + @Override + public boolean apply(Server server) { + // 对Rest调用传来的Header参数(例如:token)做策略 + boolean enabled = applyFromHeader(server); + if (!enabled) { + return false; + } + + // 对RPC调用传来的方法参数做策略 + return applyFromMethod(server); + } + + // 根据REST调用传来的Header参数(例如:token),选取执行调用请求的服务实例 + private boolean applyFromHeader(Server server) { + String token = serviceStrategyContextHolder.getHeader("token"); + String serviceId = pluginAdapter.getServerServiceId(server); + String version = pluginAdapter.getServerVersion(server); + String region = pluginAdapter.getServerRegion(server); + String environment = pluginAdapter.getServerEnvironment(server); + String address = server.getHost() + ":" + server.getPort(); + + LOG.info("负载均衡用户定制触发:token={}, serviceId={}, version={}, region={}, env={}, address={}", token, serviceId, version, region, environment, address); + + String filterServiceId = "discovery-springcloud-example-c"; + String filterToken = "123"; + if (StringUtils.equals(serviceId, filterServiceId) && StringUtils.isNotEmpty(token) && token.contains(filterToken)) { + LOG.info("过滤条件:当serviceId={} && Token含有'{}'的时候,不能被负载均衡到", filterServiceId, filterToken); + + return false; + } + + return true; + } + + // 根据RPC调用传来的方法参数(例如接口名、方法名、参数名或参数值等),选取执行调用请求的服务实例 + @SuppressWarnings("unchecked") + private boolean applyFromMethod(Server server) { + Map attributes = serviceStrategyContextHolder.getRpcAttributes(); + String serviceId = pluginAdapter.getServerServiceId(server); + String version = pluginAdapter.getServerVersion(server); + String region = pluginAdapter.getServerRegion(server); + String environment = pluginAdapter.getServerEnvironment(server); + String address = server.getHost() + ":" + server.getPort(); + + LOG.info("负载均衡用户定制触发:attributes={}, serviceId={}, version={}, region={}, env={}, address={}", attributes, serviceId, version, region, environment, address); + + String filterServiceId = "discovery-springcloud-example-b"; + String filterVersion = "1.0"; + String filterBusinessValue = "abc"; + if (StringUtils.equals(serviceId, filterServiceId) && StringUtils.equals(version, filterVersion)) { + if (attributes.containsKey(DiscoveryConstant.PARAMETER_MAP)) { + Map parameterMap = (Map) attributes.get(DiscoveryConstant.PARAMETER_MAP); + String value = parameterMap.get("value").toString(); + if (StringUtils.isNotEmpty(value) && value.contains(filterBusinessValue)) { + LOG.info("过滤条件:当serviceId={} && version={} && 业务参数含有'{}'的时候,不能被负载均衡到", filterServiceId, filterVersion, filterBusinessValue); + + return false; + } + } + } + + return true; + } +} \ No newline at end of file diff --git a/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/impl/MyDiscoveryListener.java b/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/impl/MyDiscoveryListener.java new file mode 100644 index 0000000000..94d2342e49 --- /dev/null +++ b/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/impl/MyDiscoveryListener.java @@ -0,0 +1,49 @@ +package com.nepxion.discovery.plugin.example.service.impl; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.Iterator; +import java.util.List; + +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.cloud.client.ServiceInstance; + +import com.nepxion.discovery.plugin.framework.listener.discovery.AbstractDiscoveryListener; + +// 当目标服务的元数据中的Group为mygroup2,禁止被本服务发现(只用于DiscoveryClient.getInstances接口方法用) +public class MyDiscoveryListener extends AbstractDiscoveryListener { + private static final Logger LOG = LoggerFactory.getLogger(MyDiscoveryListener.class); + + @Override + public void onGetInstances(String serviceId, List instances) { + Iterator iterator = instances.iterator(); + while (iterator.hasNext()) { + ServiceInstance instance = iterator.next(); + String group = pluginAdapter.getInstanceGroup(instance); + if (StringUtils.equals(group, "mygroup2")) { + iterator.remove(); + + LOG.info("服务名=" + serviceId + ",组名=" + group + "的服务禁止被本服务发现"); + } + } + } + + @Override + public void onGetServices(List services) { + + } + + @Override + public int getOrder() { + return LOWEST_PRECEDENCE - 500; + } +} \ No newline at end of file diff --git a/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/impl/MyLoadBalanceListener.java b/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/impl/MyLoadBalanceListener.java new file mode 100644 index 0000000000..f678e46d68 --- /dev/null +++ b/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/impl/MyLoadBalanceListener.java @@ -0,0 +1,44 @@ +package com.nepxion.discovery.plugin.example.service.impl; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.Iterator; +import java.util.List; + +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.nepxion.discovery.plugin.framework.listener.loadbalance.AbstractLoadBalanceListener; +import com.netflix.loadbalancer.Server; + +// 当目标服务的元数据中的Group为mygroup2,禁止被本服务负载均衡 +public class MyLoadBalanceListener extends AbstractLoadBalanceListener { + private static final Logger LOG = LoggerFactory.getLogger(MyLoadBalanceListener.class); + + @Override + public void onGetServers(String serviceId, List servers) { + Iterator iterator = servers.iterator(); + while (iterator.hasNext()) { + Server server = iterator.next(); + String group = pluginAdapter.getServerGroup(server); + if (StringUtils.equals(group, "mygroup3")) { + iterator.remove(); + + LOG.info("服务名=" + serviceId + ",组名=" + group + "的服务禁止被本服务负载均衡"); + } + } + } + + @Override + public int getOrder() { + return LOWEST_PRECEDENCE - 500; + } +} \ No newline at end of file diff --git a/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/impl/MyRegisterListener.java b/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/impl/MyRegisterListener.java new file mode 100644 index 0000000000..6bc9fab1be --- /dev/null +++ b/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/impl/MyRegisterListener.java @@ -0,0 +1,48 @@ +package com.nepxion.discovery.plugin.example.service.impl; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.apache.commons.lang3.StringUtils; +import org.springframework.cloud.client.serviceregistry.Registration; + +import com.nepxion.discovery.common.exception.DiscoveryException; +import com.nepxion.discovery.plugin.framework.listener.register.AbstractRegisterListener; + +// 当本服务的元数据中的Group为mygroup1,禁止被注册到注册中心 +public class MyRegisterListener extends AbstractRegisterListener { + @Override + public void onRegister(Registration registration) { + String serviceId = pluginAdapter.getServiceId(); + String group = pluginAdapter.getGroup(); + if (StringUtils.equals(group, "mygroup1")) { + throw new DiscoveryException("服务名=" + serviceId + ",组名=" + group + "的服务禁止被注册到注册中心"); + } + } + + @Override + public void onDeregister(Registration registration) { + + } + + @Override + public void onSetStatus(Registration registration, String status) { + + } + + @Override + public void onClose() { + + } + + @Override + public int getOrder() { + return LOWEST_PRECEDENCE - 500; + } +} \ No newline at end of file diff --git a/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/impl/MyRouteFilter.java b/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/impl/MyRouteFilter.java new file mode 100644 index 0000000000..08d5cb0407 --- /dev/null +++ b/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/impl/MyRouteFilter.java @@ -0,0 +1,41 @@ +package com.nepxion.discovery.plugin.example.service.impl; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Value; + +import com.nepxion.discovery.plugin.strategy.service.filter.DefaultServiceStrategyRouteFilter; + +// 适用于A/B Testing或者更根据某业务参数决定蓝绿灰度路由路径。可以结合配置中心分别配置A/B两条路径,可以动态改变并通知 +// 当Header中传来的用户为张三,执行一条路由路径;为李四,执行另一条路由路径 +public class MyRouteFilter extends DefaultServiceStrategyRouteFilter { + private static final String DEFAULT_A_ROUTE_VERSION = "{\"discovery-springcloud-example-a\":\"1.0\", \"discovery-springcloud-example-b\":\"1.0\", \"discovery-springcloud-example-c\":\"1.0\"}"; + private static final String DEFAULT_B_ROUTE_VERSION = "{\"discovery-springcloud-example-a\":\"1.1\", \"discovery-springcloud-example-b\":\"1.1\", \"discovery-springcloud-example-c\":\"1.1\"}"; + + @Value("${a.route.version:" + DEFAULT_A_ROUTE_VERSION + "}") + private String aRouteVersion; + + @Value("${b.route.version:" + DEFAULT_B_ROUTE_VERSION + "}") + private String bRouteVersion; + + @Override + public String getRouteVersion() { + String user = strategyContextHolder.getHeader("user"); + + if (StringUtils.equals(user, "zhangsan")) { + return aRouteVersion; + } else if (StringUtils.equals(user, "lisi")) { + return bRouteVersion; + } + + return super.getRouteVersion(); + } +} \ No newline at end of file diff --git a/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/impl/MySubscriber.java b/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/impl/MySubscriber.java new file mode 100644 index 0000000000..24759ed4ae --- /dev/null +++ b/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/impl/MySubscriber.java @@ -0,0 +1,75 @@ +package com.nepxion.discovery.plugin.example.service.impl; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.List; +import java.util.Map; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; + +import com.google.common.eventbus.Subscribe; +import com.nepxion.discovery.common.entity.ParameterEntity; +import com.nepxion.discovery.common.entity.ParameterServiceEntity; +import com.nepxion.discovery.plugin.framework.adapter.PluginAdapter; +import com.nepxion.discovery.plugin.framework.event.ParameterChangedEvent; +import com.nepxion.discovery.plugin.framework.event.RegisterFailureEvent; +import com.nepxion.discovery.plugin.framework.event.RuleClearedEvent; +import com.nepxion.discovery.plugin.framework.event.RuleFailureEvent; +import com.nepxion.discovery.plugin.framework.event.RuleUpdatedEvent; +import com.nepxion.discovery.plugin.strategy.event.StrategyAlarmEvent; +import com.nepxion.eventbus.annotation.EventBus; + +@EventBus +public class MySubscriber { + private static final Logger LOG = LoggerFactory.getLogger(MySubscriber.class); + + @Autowired + private PluginAdapter pluginAdapter; + + @Subscribe + public void onRuleUpdated(RuleUpdatedEvent ruleUpdatedEvent) { + LOG.info("规则执行更新, rule=" + ruleUpdatedEvent.getRule()); + } + + @Subscribe + public void onRuleCleared(RuleClearedEvent ruleClearedEvent) { + LOG.info("规则执行清空"); + } + + @Subscribe + public void onRuleRuleFailure(RuleFailureEvent ruleFailureEvent) { + LOG.info("规则更新失败, rule=" + ruleFailureEvent.getRule() + ", exception=" + ruleFailureEvent.getException()); + } + + @Subscribe + public void onParameterChanged(ParameterChangedEvent parameterChangedEvent) { + ParameterEntity parameterEntity = parameterChangedEvent.getParameterEntity(); + String serviceId = pluginAdapter.getServiceId(); + List parameterServiceEntityList = null; + if (parameterEntity != null) { + Map> parameterServiceMap = parameterEntity.getParameterServiceMap(); + parameterServiceEntityList = parameterServiceMap.get(serviceId); + } + LOG.info("获取动态参数, serviceId=" + serviceId + ", parameterServiceEntityList=" + parameterServiceEntityList); + } + + @Subscribe + public void onRegisterFailure(RegisterFailureEvent registerFailureEvent) { + LOG.info("注册失败, eventType=" + registerFailureEvent.getEventType() + ", eventDescription=" + registerFailureEvent.getEventDescription() + ", serviceId=" + registerFailureEvent.getServiceId() + ", host=" + registerFailureEvent.getHost() + ", port=" + registerFailureEvent.getPort()); + } + + @Subscribe + public void onAlarm(StrategyAlarmEvent strategyAlarmEvent) { + LOG.info("告警类型=" + strategyAlarmEvent.getAlarmType()); + LOG.info("告警内容=" + strategyAlarmEvent.getAlarmMap()); + } +} \ No newline at end of file diff --git a/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/rest/ARestImpl.java b/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/rest/ARestImpl.java similarity index 83% rename from discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/rest/ARestImpl.java rename to discovery-springcloud-examples/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/rest/ARestImpl.java index 14bf695196..e4ab90f7c8 100644 --- a/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/rest/ARestImpl.java +++ b/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/rest/ARestImpl.java @@ -49,16 +49,16 @@ public String rest(@RequestBody String value) { ServletRequestAttributes attributes = serviceStrategyContextHolder.getRestAttributes(); Enumeration headerNames = attributes.getRequest().getHeaderNames(); - System.out.println("Header name list:"); + LOG.info("Header name list:"); while (headerNames.hasMoreElements()) { String headerName = headerNames.nextElement(); - System.out.println("* " + headerName); + LOG.info("* " + headerName); } String token = attributes.getRequest().getHeader("token"); - System.out.println("Old token=" + token); + LOG.info("Old token=" + token); - System.out.println("New token=Token-A"); + LOG.info("New token=Token-A"); HttpHeaders headers = new HttpHeaders(); headers.set("token", "Token-A"); @@ -83,18 +83,10 @@ public String test(@RequestBody String value) { } public String handleBlock(String value, BlockException e) { - LOG.info("Value={}", value); - LOG.info("Sentinel AServer Block Causes"); - LOG.error("Sentinel AServer Block Exception", e); - LOG.info("Sentinel Rule Limit App={}", e.getRuleLimitApp()); - - return "Sentinel AServer Block Causes"; + return "A server sentinel block, cause=" + e.getClass().getName() + ", rule=" + e.getRule() + ", limitApp=" + e.getRuleLimitApp() + ", value=" + value; } public String handleFallback(String value) { - LOG.info("Value={}", value); - LOG.info("Sentinel AServer Fallback Causes"); - - return "Sentinel AServer Fallback Causes"; + return "A server sentinel fallback, value=" + value; } } \ No newline at end of file diff --git a/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/rest/AbstractRestImpl.java b/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/rest/AbstractRestImpl.java new file mode 100644 index 0000000000..1bec47adf0 --- /dev/null +++ b/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/rest/AbstractRestImpl.java @@ -0,0 +1,23 @@ +package com.nepxion.discovery.plugin.example.service.rest; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.springframework.beans.factory.annotation.Autowired; + +import com.nepxion.discovery.plugin.framework.adapter.PluginAdapter; + +public class AbstractRestImpl { + @Autowired + private PluginAdapter pluginAdapter; + + public String doRest(String value) { + return pluginAdapter.getPluginInfo(value); + } +} \ No newline at end of file diff --git a/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/rest/BRestImpl.java b/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/rest/BRestImpl.java similarity index 82% rename from discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/rest/BRestImpl.java rename to discovery-springcloud-examples/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/rest/BRestImpl.java index a6bd41f16f..40b89a5c0a 100644 --- a/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/rest/BRestImpl.java +++ b/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/rest/BRestImpl.java @@ -49,16 +49,16 @@ public String rest(@RequestBody String value) { ServletRequestAttributes attributes = serviceStrategyContextHolder.getRestAttributes(); Enumeration headerNames = attributes.getRequest().getHeaderNames(); - System.out.println("Header name list:"); + LOG.info("Header name list:"); while (headerNames.hasMoreElements()) { String headerName = headerNames.nextElement(); - System.out.println("* " + headerName); + LOG.info("* " + headerName); } String token = attributes.getRequest().getHeader("token"); - System.out.println("Old token=" + token); + LOG.info("Old token=" + token); - System.out.println("New token=Token-B"); + LOG.info("New token=Token-B"); HttpHeaders headers = new HttpHeaders(); headers.set("token", "Token-B"); @@ -77,18 +77,10 @@ public String test(@RequestBody String value) { } public String handleBlock(String value, BlockException e) { - LOG.info("Value={}", value); - LOG.info("Sentinel BServer Block Causes"); - LOG.error("Sentinel BServer Block Exception", e); - LOG.info("Sentinel Rule Limit App={}", e.getRuleLimitApp()); - - return "Sentinel BServer Block Causes"; + return "B server sentinel block, cause=" + e.getClass().getName() + ", rule=" + e.getRule() + ", limitApp=" + e.getRuleLimitApp() + ", value=" + value; } public String handleFallback(String value) { - LOG.info("Value={}", value); - LOG.info("Sentinel BServer Fallback Causes"); - - return "Sentinel BServer Fallback Causes"; + return "B server sentinel fallback, value=" + value; } } \ No newline at end of file diff --git a/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/rest/CRestImpl.java b/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/rest/CRestImpl.java similarity index 81% rename from discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/rest/CRestImpl.java rename to discovery-springcloud-examples/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/rest/CRestImpl.java index 7243f93c46..385450fc85 100644 --- a/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/rest/CRestImpl.java +++ b/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/rest/CRestImpl.java @@ -43,14 +43,14 @@ public String rest(@RequestBody String value) { ServletRequestAttributes attributes = serviceStrategyContextHolder.getRestAttributes(); Enumeration headerNames = attributes.getRequest().getHeaderNames(); - System.out.println("Header name list:"); + LOG.info("Header name list:"); while (headerNames.hasMoreElements()) { String headerName = headerNames.nextElement(); - System.out.println("* " + headerName); + LOG.info("* " + headerName); } String token = attributes.getRequest().getHeader("token"); - System.out.println("Token=" + token); + LOG.info("Token=" + token); LOG.info("调用路径:{}", value); @@ -63,18 +63,10 @@ public String test(@RequestBody String value) { } public String handleBlock(String value, BlockException e) { - LOG.info("Value={}", value); - LOG.info("Sentinel CServer Block Causes"); - LOG.error("Sentinel CServer Block Exception", e); - LOG.info("Sentinel Rule Limit App={}", e.getRuleLimitApp()); - - return "Sentinel CServer Block Causes"; + return "C server sentinel block, cause=" + e.getClass().getName() + ", rule=" + e.getRule() + ", limitApp=" + e.getRuleLimitApp() + ", value=" + value; } public String handleFallback(String value) { - LOG.info("Value={}", value); - LOG.info("Sentinel CServer Fallback Causes"); - - return "Sentinel CServer Fallback Causes"; + return "C server sentinel fallback, value=" + value; } } \ No newline at end of file diff --git a/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/sentinel/MyAFeignFallbackHandler.java b/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/sentinel/MyAFeignFallbackHandler.java new file mode 100644 index 0000000000..bca68ad2f1 --- /dev/null +++ b/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/sentinel/MyAFeignFallbackHandler.java @@ -0,0 +1,22 @@ +package com.nepxion.discovery.plugin.example.service.sentinel; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.springframework.stereotype.Component; + +import com.nepxion.discovery.plugin.example.service.feign.AFeign; + +@Component +public class MyAFeignFallbackHandler implements AFeign { + @Override + public String invoke(String value) { + return value + " -> A Feign client sentinel fallback"; + } +} \ No newline at end of file diff --git a/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/sentinel/MyBFeignFallbackHandler.java b/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/sentinel/MyBFeignFallbackHandler.java new file mode 100644 index 0000000000..288fadaa70 --- /dev/null +++ b/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/sentinel/MyBFeignFallbackHandler.java @@ -0,0 +1,22 @@ +package com.nepxion.discovery.plugin.example.service.sentinel; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.springframework.stereotype.Component; + +import com.nepxion.discovery.plugin.example.service.feign.BFeign; + +@Component +public class MyBFeignFallbackHandler implements BFeign { + @Override + public String invoke(String value) { + return value + " -> B Feign client sentinel fallback"; + } +} \ No newline at end of file diff --git a/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/sentinel/MyCFeignFallbackHandler.java b/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/sentinel/MyCFeignFallbackHandler.java new file mode 100644 index 0000000000..74d4b7c7b8 --- /dev/null +++ b/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/sentinel/MyCFeignFallbackHandler.java @@ -0,0 +1,22 @@ +package com.nepxion.discovery.plugin.example.service.sentinel; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.springframework.stereotype.Component; + +import com.nepxion.discovery.plugin.example.service.feign.CFeign; + +@Component +public class MyCFeignFallbackHandler implements CFeign { + @Override + public String invoke(String value) { + return value + " -> C Feign client sentinel fallback"; + } +} \ No newline at end of file diff --git a/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/sentinel/MyRestTemplateBlockHandler.java b/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/sentinel/MyRestTemplateBlockHandler.java new file mode 100644 index 0000000000..e667b6c8ac --- /dev/null +++ b/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/sentinel/MyRestTemplateBlockHandler.java @@ -0,0 +1,22 @@ +package com.nepxion.discovery.plugin.example.service.sentinel; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.springframework.http.HttpRequest; +import org.springframework.http.client.ClientHttpRequestExecution; + +import com.alibaba.cloud.sentinel.rest.SentinelClientHttpResponse; +import com.alibaba.csp.sentinel.slots.block.BlockException; + +public class MyRestTemplateBlockHandler { + public static SentinelClientHttpResponse handleBlock(HttpRequest request, byte[] body, ClientHttpRequestExecution execution, BlockException e) { + return new SentinelClientHttpResponse("RestTemplate client sentinel block, cause=" + e.getClass().getName() + ", rule=" + e.getRule() + ", limitApp=" + e.getRuleLimitApp()); + } +} \ No newline at end of file diff --git a/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/sentinel/MyRestTemplateFallbackHandler.java b/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/sentinel/MyRestTemplateFallbackHandler.java new file mode 100644 index 0000000000..5c0faf09ff --- /dev/null +++ b/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/sentinel/MyRestTemplateFallbackHandler.java @@ -0,0 +1,22 @@ +package com.nepxion.discovery.plugin.example.service.sentinel; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.springframework.http.HttpRequest; +import org.springframework.http.client.ClientHttpRequestExecution; + +import com.alibaba.cloud.sentinel.rest.SentinelClientHttpResponse; +import com.alibaba.csp.sentinel.slots.block.BlockException; + +public class MyRestTemplateFallbackHandler { + public static SentinelClientHttpResponse handleFallback(HttpRequest request, byte[] body, ClientHttpRequestExecution execution, BlockException e) { + return new SentinelClientHttpResponse("RestTemplate client sentinel fallback, cause=" + e.getClass().getName() + ", rule=" + e.getRule() + ", limitApp=" + e.getRuleLimitApp()); + } +} \ No newline at end of file diff --git a/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/sentinel/MySentinelFlowRuleParser.java b/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/sentinel/MySentinelFlowRuleParser.java similarity index 100% rename from discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/sentinel/MySentinelFlowRuleParser.java rename to discovery-springcloud-examples/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/sentinel/MySentinelFlowRuleParser.java diff --git a/discovery-springcloud-example-service/src/main/resources/META-INF/spring.factories b/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/resources/META-INF/spring.factories similarity index 100% rename from discovery-springcloud-example-service/src/main/resources/META-INF/spring.factories rename to discovery-springcloud-examples/discovery-springcloud-example-service/src/main/resources/META-INF/spring.factories diff --git a/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/resources/application-a1.properties b/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/resources/application-a1.properties new file mode 100644 index 0000000000..cc25cbecf7 --- /dev/null +++ b/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/resources/application-a1.properties @@ -0,0 +1,33 @@ +# Spring cloud config +spring.application.name=discovery-springcloud-example-a +server.port=1100 + +# Eureka config for discovery +eureka.instance.metadataMap.group=example-service-group +eureka.instance.metadataMap.version=1.0 +eureka.instance.metadataMap.region=dev +eureka.instance.metadataMap.env=env1 +eureka.instance.metadataMap.zone=zone1 +eureka.instance.metadataMap.active=true + +# Consul config for discovery +spring.cloud.consul.discovery.tags=group=example-service-group,version=1.0,region=dev,env=env1,zone=zone1,active=true + +# Zookeeper config for discovery +spring.cloud.zookeeper.discovery.metadata.group=example-service-group +spring.cloud.zookeeper.discovery.metadata.version=1.0 +spring.cloud.zookeeper.discovery.metadata.region=dev +spring.cloud.zookeeper.discovery.metadata.env=env1 +spring.cloud.zookeeper.discovery.metadata.zone=zone1 +spring.cloud.zookeeper.discovery.metadata.active=true + +# Nacos config for discovery +spring.cloud.nacos.discovery.metadata.group=example-service-group +spring.cloud.nacos.discovery.metadata.version=1.0 +spring.cloud.nacos.discovery.metadata.region=dev +spring.cloud.nacos.discovery.metadata.env=env1 +spring.cloud.nacos.discovery.metadata.zone=zone1 +spring.cloud.nacos.discovery.metadata.active=true + +# Management config +management.server.port=5100 \ No newline at end of file diff --git a/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/resources/application-a2.properties b/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/resources/application-a2.properties new file mode 100644 index 0000000000..672b4b1b55 --- /dev/null +++ b/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/resources/application-a2.properties @@ -0,0 +1,33 @@ +# Spring cloud config +spring.application.name=discovery-springcloud-example-a +server.port=1101 + +# Eureka config for discovery +eureka.instance.metadataMap.group=example-service-group +eureka.instance.metadataMap.version=1.1 +eureka.instance.metadataMap.region=qa +eureka.instance.metadataMap.env=common +eureka.instance.metadataMap.zone=zone2 +eureka.instance.metadataMap.active=true + +# Consul config for discovery +spring.cloud.consul.discovery.tags=group=example-service-group,version=1.1,region=qa,env=common,zone=zone2,active=true + +# Zookeeper config for discovery +spring.cloud.zookeeper.discovery.metadata.group=example-service-group +spring.cloud.zookeeper.discovery.metadata.version=1.1 +spring.cloud.zookeeper.discovery.metadata.region=qa +spring.cloud.zookeeper.discovery.metadata.env=common +spring.cloud.zookeeper.discovery.metadata.zone=zone2 +spring.cloud.zookeeper.discovery.metadata.active=true + +# Nacos config for discovery +spring.cloud.nacos.discovery.metadata.group=example-service-group +spring.cloud.nacos.discovery.metadata.version=1.1 +spring.cloud.nacos.discovery.metadata.region=qa +spring.cloud.nacos.discovery.metadata.env=common +spring.cloud.nacos.discovery.metadata.zone=zone2 +spring.cloud.nacos.discovery.metadata.active=true + +# Management config +management.server.port=5101 \ No newline at end of file diff --git a/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/resources/application-b1.properties b/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/resources/application-b1.properties new file mode 100644 index 0000000000..cffa7bc309 --- /dev/null +++ b/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/resources/application-b1.properties @@ -0,0 +1,30 @@ +# Spring cloud config +spring.application.name=discovery-springcloud-example-b +server.port=1200 + +# Eureka config for discovery +eureka.instance.metadataMap.group=example-service-group +eureka.instance.metadataMap.version=1.0 +eureka.instance.metadataMap.region=dev +eureka.instance.metadataMap.env=env1 +eureka.instance.metadataMap.zone=zone1 + +# Consul config for discovery +spring.cloud.consul.discovery.tags=group=example-service-group,version=1.0,region=dev,env=env1,zone=zone1 + +# Zookeeper config for discovery +spring.cloud.zookeeper.discovery.metadata.group=example-service-group +spring.cloud.zookeeper.discovery.metadata.version=1.0 +spring.cloud.zookeeper.discovery.metadata.region=dev +spring.cloud.zookeeper.discovery.metadata.env=env1 +spring.cloud.zookeeper.discovery.metadata.zone=zone1 + +# Nacos config for discovery +spring.cloud.nacos.discovery.metadata.group=example-service-group +spring.cloud.nacos.discovery.metadata.version=1.0 +spring.cloud.nacos.discovery.metadata.region=dev +spring.cloud.nacos.discovery.metadata.env=env1 +spring.cloud.nacos.discovery.metadata.zone=zone1 + +# Management config +management.server.port=5200 \ No newline at end of file diff --git a/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/resources/application-b2.properties b/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/resources/application-b2.properties new file mode 100644 index 0000000000..21b746d00e --- /dev/null +++ b/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/resources/application-b2.properties @@ -0,0 +1,30 @@ +# Spring cloud config +spring.application.name=discovery-springcloud-example-b +server.port=1201 + +# Eureka config for discovery +eureka.instance.metadataMap.group=example-service-group +eureka.instance.metadataMap.version=1.1 +eureka.instance.metadataMap.region=qa +eureka.instance.metadataMap.env=common +eureka.instance.metadataMap.zone=zone2 + +# Consul config for discovery +spring.cloud.consul.discovery.tags=group=example-service-group,version=1.1,region=qa,env=common,zone=zone2 + +# Zookeeper config for discovery +spring.cloud.zookeeper.discovery.metadata.group=example-service-group +spring.cloud.zookeeper.discovery.metadata.version=1.1 +spring.cloud.zookeeper.discovery.metadata.region=qa +spring.cloud.zookeeper.discovery.metadata.env=common +spring.cloud.zookeeper.discovery.metadata.zone=zone2 + +# Nacos config for discovery +spring.cloud.nacos.discovery.metadata.group=example-service-group +spring.cloud.nacos.discovery.metadata.version=1.1 +spring.cloud.nacos.discovery.metadata.region=qa +spring.cloud.nacos.discovery.metadata.env=common +spring.cloud.nacos.discovery.metadata.zone=zone2 + +# Management config +management.server.port=5201 \ No newline at end of file diff --git a/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/resources/application-c1.properties b/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/resources/application-c1.properties new file mode 100644 index 0000000000..c398f0242b --- /dev/null +++ b/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/resources/application-c1.properties @@ -0,0 +1,30 @@ +# Spring cloud config +spring.application.name=discovery-springcloud-example-c +server.port=1300 + +# Eureka config for discovery +eureka.instance.metadataMap.group=example-service-group +eureka.instance.metadataMap.version=1.0 +eureka.instance.metadataMap.region=dev +eureka.instance.metadataMap.env=env1 +eureka.instance.metadataMap.zone=zone1 + +# Consul config for discovery +spring.cloud.consul.discovery.tags=group=example-service-group,version=1.0,region=dev,env=env1,zone=zone1 + +# Zookeeper config for discovery +spring.cloud.zookeeper.discovery.metadata.group=example-service-group +spring.cloud.zookeeper.discovery.metadata.version=1.0 +spring.cloud.zookeeper.discovery.metadata.region=dev +spring.cloud.zookeeper.discovery.metadata.env=env1 +spring.cloud.zookeeper.discovery.metadata.zone=zone1 + +# Nacos config for discovery +spring.cloud.nacos.discovery.metadata.group=example-service-group +spring.cloud.nacos.discovery.metadata.version=1.0 +spring.cloud.nacos.discovery.metadata.region=dev +spring.cloud.nacos.discovery.metadata.env=env1 +spring.cloud.nacos.discovery.metadata.zone=zone1 + +# Management config +management.server.port=5300 \ No newline at end of file diff --git a/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/resources/application-c2.properties b/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/resources/application-c2.properties new file mode 100644 index 0000000000..553ac05988 --- /dev/null +++ b/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/resources/application-c2.properties @@ -0,0 +1,30 @@ +# Spring cloud config +spring.application.name=discovery-springcloud-example-c +server.port=1301 + +# Eureka config for discovery +eureka.instance.metadataMap.group=example-service-group +eureka.instance.metadataMap.version=1.1 +eureka.instance.metadataMap.region=qa +eureka.instance.metadataMap.env=common +eureka.instance.metadataMap.zone=zone2 + +# Consul config for discovery +spring.cloud.consul.discovery.tags=group=example-service-group,version=1.1,region=qa,env=common,zone=zone2 + +# Zookeeper config for discovery +spring.cloud.zookeeper.discovery.metadata.group=example-service-group +spring.cloud.zookeeper.discovery.metadata.version=1.1 +spring.cloud.zookeeper.discovery.metadata.region=qa +spring.cloud.zookeeper.discovery.metadata.env=common +spring.cloud.zookeeper.discovery.metadata.zone=zone2 + +# Nacos config for discovery +spring.cloud.nacos.discovery.metadata.group=example-service-group +spring.cloud.nacos.discovery.metadata.version=1.1 +spring.cloud.nacos.discovery.metadata.region=qa +spring.cloud.nacos.discovery.metadata.env=common +spring.cloud.nacos.discovery.metadata.zone=zone2 + +# Management config +management.server.port=5301 \ No newline at end of file diff --git a/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/resources/application-c3.properties b/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/resources/application-c3.properties new file mode 100644 index 0000000000..623c92c786 --- /dev/null +++ b/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/resources/application-c3.properties @@ -0,0 +1,30 @@ +# Spring cloud config +spring.application.name=discovery-springcloud-example-c +server.port=1302 + +# Eureka config for discovery +eureka.instance.metadataMap.group=example-service-group +eureka.instance.metadataMap.version=1.2 +eureka.instance.metadataMap.region=qa +eureka.instance.metadataMap.env=env2 +eureka.instance.metadataMap.zone=zone2 + +# Consul config for discovery +spring.cloud.consul.discovery.tags=group=example-service-group,version=1.2,region=qa,env=env2,zone=zone2 + +# Zookeeper config for discovery +spring.cloud.zookeeper.discovery.metadata.group=example-service-group +spring.cloud.zookeeper.discovery.metadata.version=1.2 +spring.cloud.zookeeper.discovery.metadata.region=qa +spring.cloud.zookeeper.discovery.metadata.env=env2 +spring.cloud.zookeeper.discovery.metadata.zone=zone2 + +# Nacos config for discovery +spring.cloud.nacos.discovery.metadata.group=example-service-group +spring.cloud.nacos.discovery.metadata.version=1.2 +spring.cloud.nacos.discovery.metadata.region=qa +spring.cloud.nacos.discovery.metadata.env=env2 +spring.cloud.nacos.discovery.metadata.zone=zone2 + +# Management config +management.server.port=5302 \ No newline at end of file diff --git a/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/resources/bootstrap.properties b/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/resources/bootstrap.properties new file mode 100644 index 0000000000..3f49a3c144 --- /dev/null +++ b/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/resources/bootstrap.properties @@ -0,0 +1,364 @@ +# Spring cloud config +# server.servlet.context-path=/nepxion + +# Eureka config for discovery +eureka.client.serviceUrl.defaultZone=http://localhost:9528/eureka/ +eureka.instance.preferIpAddress=true + +# Consul config for discovery +spring.cloud.consul.host=localhost +spring.cloud.consul.port=8500 +spring.cloud.consul.discovery.preferIpAddress=true + +# Zookeeper config for discovery +spring.cloud.zookeeper.connectString=localhost:2181 +spring.cloud.zookeeper.discovery.instancePort=${server.port} +spring.cloud.zookeeper.discovery.root=/spring-cloud +spring.cloud.zookeeper.discovery.preferIpAddress=true + +# Nacos config for discovery +spring.cloud.nacos.discovery.server-addr=localhost:8848 +# spring.cloud.nacos.discovery.namespace=discovery + +# Ribbon config +ribbon.ServerListRefreshInterval=5000 +ribbon.ConnectTimeout=60000 +ribbon.ReadTimeout=60000 +ribbon.maxAutoRetries=3 +ribbon.maxAutoRetriesNextServer=3 +ribbon.okToRetryOnAllOperations=true + +# Feign config +# 解决FeignClientSpecification的问题。支持G版或更高版本的配置,其它版本不需要该行配置 +spring.main.allow-bean-definition-overriding=true + +# Apollo config for rule +app.id=discovery +apollo.meta=http://106.54.227.205:8080 +# apollo.namespace=application + +# Nacos config for rule +nacos.server-addr=localhost:8848 +# nacos.access-key= +# nacos.secret-key= +# nacos.username= +# nacos.password= +# nacos.namespace=application +# nacos.cluster-name= +# nacos.context-path= +# nacos.config-long-poll-timeout= +# nacos.config-retry-time= +# nacos.max-retry= +# nacos.endpoint= +# nacos.endpoint-port= +# nacos.is-use-endpoint-parsing-rule= +# nacos.is-use-cloud-namespace-parsing= +# nacos.encode= +# nacos.naming-load-cache-at-start= +# nacos.naming-client-beat-thread-count= +# nacos.naming-polling-thread-count= +# nacos.naming-request-domain-max-retry-count= +# nacos.naming-push-empty-protection= +# nacos.ram-role-name= +# nacos.timout= + +# Redis config for rule +spring.redis.host=localhost +spring.redis.port=6379 +spring.redis.password= +spring.redis.database=0 + +# Zookeeper config for rule +zookeeper.connect-string=localhost:2181 +zookeeper.retry-count=3 +zookeeper.sleep-time=3000 + +# Consul config for rule +consul.host=localhost +consul.port=8500 +consul.timeout=1 +consul.token= + +# Etcd config for rule +etcd.server.addr=http://localhost:2379 +etcd.username= +etcd.password= + +# Sentinel config +spring.cloud.sentinel.transport.dashboard=localhost:8075 +spring.cloud.sentinel.eager=true +# 本地规则方式和远程规则方式不能同时并存,必须两选一。使用时候必须注释掉其中之一,生成环境必须使用远程规则方式 +# 本地规则方式配置 +spring.cloud.sentinel.datasource.ds1.file.file=classpath:sentinel.json +spring.cloud.sentinel.datasource.ds1.file.data-type=json +spring.cloud.sentinel.datasource.ds1.file.rule-type=flow +# 远程规则方式配置 +# spring.cloud.sentinel.datasource.ds2.apollo.namespace-name=application +# spring.cloud.sentinel.datasource.ds2.apollo.flow-rules-key=example-service-group-${spring.application.name}-sentinel-flow +# spring.cloud.sentinel.datasource.ds2.apollo.rule-type=flow +# Feign和RestTemplate熔断降级限流开关 +feign.sentinel.enabled=true +resttemplate.sentinel.enabled=true + +# Management config +# 该项只对Consul有效,而且必须配置在bootstrap.properties里,配置在application.properties无效 +# management.health.consul.enabled=true +management.endpoints.web.exposure.include=* +management.endpoints.jmx.exposure.include=* +management.endpoint.health.show-details=ALWAYS + +# Spring boot admin config +spring.boot.admin.client.instance.prefer-ip=true +spring.boot.admin.client.url=http://localhost:9728 + +# Plugin core config +# 随机权重算法。缺失则默认为MapWeightRandom +# spring.application.weight.random.type=MapWeightRandom +# 规则文件的格式,支持xml和json。缺失则默认为xml +# spring.application.config.format=xml +# spring.application.config.format=json +# 本地规则文件的路径,支持两种方式:classpath:rule.xml(rule.json) - 规则文件放在resources目录下,便于打包进jar;file:rule.xml(rule.json) - 规则文件放在工程根目录下,放置在外部便于修改。缺失则默认为不装载本地规则 +# spring.application.config.path=classpath:rule.xml +# spring.application.config.path=classpath:rule.json +# 为微服务归类的Key,一般通过group字段来归类,例如eureka.instance.metadataMap.group=xxx-group或者eureka.instance.metadataMap.application=xxx-application。缺失则默认为group +# spring.application.group.key=group +# spring.application.group.key=application +# 业务系统希望大多数时候Spring、SpringBoot或者SpringCloud的基本配置、调优参数(非业务系统配置参数),不配置在业务端,集成到基础框架里。但特殊情况下,业务系统有时候也希望能把基础框架里配置的参数给覆盖掉,用他们自己的配置 +# 对于此类型的配置需求,可以配置在下面的配置文件里。该文件一般放在resource目录下。缺失则默认为spring-application-default.properties +# spring.application.default.properties.path=spring-application-default.properties +# 负载均衡下,消费端尝试获取对应提供端服务实例列表为空的时候,通过日志方式通知。缺失则默认为false +# spring.application.no.servers.notify.enabled=false +# 由于Nacos注册中心会自动把服务名处理成GROUP@@SERVICE_ID的格式,导致根据服务名去获取元数据的时候会找不到。通过如下开关开启是否要过滤掉GROUP前缀。缺失则默认为true +# spring.application.nacos.service.id.filter.enabled=true +# 启动和关闭在服务启动的时候参数订阅事件发送。缺失则默认为true +# spring.application.parameter.event.onstart.enabled=true + +# Plugin strategy config +# 开启和关闭Ribbon默认的ZoneAvoidanceRule负载均衡策略。一旦关闭,则使用RoundRobin简单轮询负载均衡策略。缺失则默认为true +# spring.application.strategy.zone.avoidance.rule.enabled=true +# 启动和关闭路由策略的时候,对REST方式的调用拦截。缺失则默认为true +# spring.application.strategy.rest.intercept.enabled=true +# 启动和关闭路由策略的时候,对REST方式在异步调用场景下在服务端的Request请求的装饰,当主线程先于子线程执行完的时候,Request会被Destory,导致Header仍旧拿不到,开启装饰,就可以确保拿到。缺失则默认为true +# spring.application.strategy.rest.request.decorator.enabled=true +# 启动和关闭Header传递的Debug日志打印,注意:每调用一次都会打印一次,会对性能有所影响,建议压测环境和生产环境关闭。缺失则默认为false +spring.application.strategy.rest.intercept.debug.enabled=true +# 路由策略过滤器的执行顺序(Order)。缺失则默认为0 +# spring.application.strategy.service.route.filter.order=0 +# 当外界传值Header的时候,服务也设置并传递同名的Header,需要决定哪个Header传递到后边的服务去。如果下面开关为true,以服务设置为优先,否则以外界传值为优先。缺失则默认为true +# spring.application.strategy.service.header.priority=true +# 启动和关闭Feign上核心策略Header传递,缺失则默认为true。当全局订阅启动时,可以关闭核心策略Header传递,这样可以节省传递数据的大小,一定程度上可以提升性能 +# 核心策略Header指n-d-开头的Header(不包括n-d-env,因为环境路由隔离,必须传递该Header),不包括n-d-service开头的Header +# spring.application.strategy.feign.core.header.transmission.enabled=true +# 启动和关闭RestTemplate上核心策略Header传递,缺失则默认为true。当全局订阅启动时,可以关闭核心策略Header传递,这样可以节省传递数据的大小,一定程度上可以提升性能 +# 核心策略Header指n-d-开头的Header(不包括n-d-env,因为环境路由隔离,必须传递该Header),不包括n-d-service开头的Header +# spring.application.strategy.rest.template.core.header.transmission.enabled=true +# 启动和关闭WebClient上核心策略Header传递,缺失则默认为true。当全局订阅启动时,可以关闭核心策略Header传递,这样可以节省传递数据的大小,一定程度上可以提升性能 +# 核心策略Header指n-d-开头的Header(不包括n-d-env,因为环境路由隔离,必须传递该Header),不包括n-d-service开头的Header +# spring.application.strategy.web.client.core.header.transmission.enabled=true +# 路由策略的时候,对REST方式调用拦截的时候(支持Feign、RestTemplate或者WebClient调用),希望把来自外部自定义的Header参数(用于框架内置上下文Header,例如:trace-id, span-id等)传递到服务里,那么配置如下值。如果多个用“;”分隔,不允许出现空格 +# spring.application.strategy.context.request.headers=trace-id;span-id +# 路由策略的时候,对REST方式调用拦截的时候(支持Feign、RestTemplate或者WebClient调用),希望把来自外部自定义的Header参数(用于业务系统自定义Header,例如:mobile)传递到服务里,那么配置如下值。如果多个用“;”分隔,不允许出现空格 +spring.application.strategy.business.request.headers=token +# 路由策略的时候,执行请求过滤,对指定包含的URI字段进行排除。缺失则默认为/actuator/,如果多个用“;”分隔,不允许出现空格 +# spring.application.strategy.uri.filter.exclusion=/actuator/ +# 启动和关闭路由策略的时候,对RPC方式的调用拦截。缺失则默认为false +spring.application.strategy.rpc.intercept.enabled=true +# 路由策略的时候,需要指定对带有@RestController或者@ServiceStrategy注解的类的扫描路径。此项配置作用于RPC方式的调用拦截、提供端的服务隔离、调用链和告警三项功能 +spring.application.strategy.scan.packages=com.nepxion.discovery.plugin.example.service.feign + +# 启动和关闭监控,一旦关闭,调用链和日志输出都将关闭。缺失则默认为false +spring.application.strategy.monitor.enabled=true +# 启动和关闭告警,一旦关闭,蓝绿灰度上下文输出都将关闭。缺失则默认为false +spring.application.strategy.alarm.enabled=true +# 启动和关闭日志输出。缺失则默认为false +spring.application.strategy.logger.enabled=true +# 日志输出中,是否显示MDC前面的Key。缺失则默认为true +# spring.application.strategy.logger.mdc.key.shown=true +# 启动和关闭Debug日志打印,注意:每调用一次都会打印一次,会对性能有所影响,建议压测环境和生产环境关闭。缺失则默认为false +spring.application.strategy.logger.debug.enabled=true +# 启动和关闭调用链输出。缺失则默认为false +spring.application.strategy.tracer.enabled=true +# 启动和关闭调用链的蓝绿灰度信息以独立的Span节点输出,如果关闭,则蓝绿灰度信息输出到原生的Span节点中(SkyWalking不支持原生模式)。缺失则默认为true +# spring.application.strategy.tracer.separate.span.enabled=true +# 启动和关闭调用链的蓝绿灰度规则策略信息输出。缺失则默认为true +# spring.application.strategy.tracer.rule.output.enabled=true +# 启动和关闭调用链的异常信息是否以详细格式输出。缺失则默认为false +# spring.application.strategy.tracer.exception.detail.output.enabled=false +# 启动和关闭类方法上入参和出参输出到调用链。缺失则默认为false +# spring.application.strategy.tracer.method.context.output.enabled=false +# 显示在调用链界面上蓝绿灰度Span的名称,建议改成具有公司特色的框架产品名称。缺失则默认为NEPXION +# spring.application.strategy.tracer.span.value=NEPXION +# 显示在调用链界面上蓝绿灰度Span Tag的插件名称,建议改成具有公司特色的框架产品的描述。缺失则默认为Nepxion Discovery +# spring.application.strategy.tracer.span.tag.plugin.value=Nepxion Discovery +# 启动和关闭Sentinel调用链上规则在Span上的输出。缺失则默认为true +# spring.application.strategy.tracer.sentinel.rule.output.enabled=true +# 启动和关闭Sentinel调用链上方法入参在Span上的输出。缺失则默认为false +# spring.application.strategy.tracer.sentinel.args.output.enabled=false + +# 启动和关闭Sentinel Metric通过次数统计输出功能。缺失则默认为true +# spring.application.strategy.metric.sentinel.pass.qps.output.enabled=true +# 启动和关闭Sentinel Metric阻塞次数统计输出功能。缺失则默认为true +# spring.application.strategy.metric.sentinel.block.qps.output.enabled=true +# 启动和关闭Sentinel Metric成功次数统计输出功能。缺失则默认为true +# spring.application.strategy.metric.sentinel.success.qps.output.enabled=true +# 启动和关闭Sentinel Metric异常次数统计输出功能。缺失则默认为true +# spring.application.strategy.metric.sentinel.exception.qps.output.enabled=true + +# 启动和关闭Sentinel限流降级熔断权限等原生功能的数据来源扩展。缺失则默认为false +# spring.application.strategy.sentinel.datasource.enabled=true +# 流控规则文件路径。缺失则默认为classpath:sentinel-flow.json +# spring.application.strategy.sentinel.flow.path=classpath:sentinel-flow.json +# 降级规则文件路径。缺失则默认为classpath:sentinel-degrade.json +# spring.application.strategy.sentinel.degrade.path=classpath:sentinel-degrade.json +# 授权规则文件路径。缺失则默认为classpath:sentinel-authority.json +# spring.application.strategy.sentinel.authority.path=classpath:sentinel-authority.json +# 系统规则文件路径。缺失则默认为classpath:sentinel-system.json +# spring.application.strategy.sentinel.system.path=classpath:sentinel-system.json +# 热点参数流控规则文件路径。缺失则默认为classpath:sentinel-param-flow.json +# spring.application.strategy.sentinel.param.flow.path=classpath:sentinel-param-flow.json + +# 启动和关闭Sentinel LimitApp高级限流熔断功能。缺失则默认为false +# spring.application.strategy.sentinel.limit.app.enabled=false +# 执行Sentinel LimitApp高级限流熔断时候,以Http请求中的Header值作为关键Key。缺失则默认为n-d-service-id,即以服务名作为关键Key +# spring.application.strategy.sentinel.request.origin.key=n-d-service-id + +# 版本故障转移,即无法找到相应版本的服务实例,路由到老的稳定版本的实例。其作用是防止蓝绿灰度版本发布人为设置错误,或者对应的版本实例发生灾难性的全部下线,导致流量有损 +# 在开启版本故障转移的开关前提下,故障转移有三种策略: +# 1. 如果“version-failover”值已配置,指定版本的故障转移,即找不到实例的时候,直接路由到该版本实例 +# 2. 如果“version-failover”值未配置 +# 2.1 开启“version.failover.stable.enabled”开关,版本列表排序策略的(取最老的稳定版本的实例)故障转移,即找不到实例的时候,直接路由到最老的稳定版本的实例 +# 2.2 关闭“version.failover.stable.enabled”开关,负载均衡策略的故障转移,即找不到实例的时候,执行负载均衡策略 +# 启动和关闭版本故障转移。缺失则默认为false +# spring.application.strategy.version.failover.enabled=true +# 开启和关闭版本列表排序策略下取稳定版本的版本故障转移。缺失则默认为false +# spring.application.strategy.version.failover.stable.enabled=true + +# 版本偏好,即非蓝绿灰度发布场景下,路由到老的稳定版本的实例。其作用是防止多个网关上并行实施蓝绿灰度版本发布产生混乱,对处于非蓝绿灰度状态的服务,调用它的时候,只取它的老的稳定版本的实例;蓝绿灰度状态的服务,还是根据传递的Header版本号进行匹配 +# 在开启版本偏好的开关前提下,偏好有两种策略: +# 1. 如果“version-prefer”值已配置,指定版本的偏好,即不管存在多少版本,直接路由到该版本实例 +# 2. 如果“version-prefer”值未配置,版本列表排序策略的(取最老的稳定版本的实例)偏好,即不管存在多少版本,直接路由到最老的稳定版本的实例 +# 启动和关闭版本偏好。缺失则默认为false +# spring.application.strategy.version.prefer.enabled=true + +# 区域调试转移,即当未对服务指定访问区域的时候,转移到事先指定的区域 +# 使用场景示例: +# 开发环境(个人电脑环境)在测试环境(线上环境)进行联调 +# 访问路径为A服务 -> B服务 -> C服务,A服务和B服务在开发环境上,C服务在测试环境上 +# 调用时候,在B服务上进行如下两个配置,并在最前端传入的Header(n-d-region)指定为B的开发环境区域(用来保证A服务和B服务只在开发环境调用),而B服务会自动转移调用到测试环境上的C服务实例,但不会转移到其它个人电脑的C服务实例 +# 该功能的意义,个人电脑环境可以接入到测试环境联调,当多套个人环境接入时候,可以保护不同的个人环境间不会彼此调用 +# 通过“region-transfer”值进行区域转移值配置,如果缺失,则报错 +# 启动和关闭区域调试转移。缺失则默认为false +# spring.application.strategy.region.transfer.enabled=true + +# 启动和关闭消费端的服务隔离(基于Group是否相同的策略)。缺失则默认为false +spring.application.strategy.consumer.isolation.enabled=true + +# 启动和关闭提供端的服务隔离(基于Group是否相同的策略)。缺失则默认为false +spring.application.strategy.provider.isolation.enabled=true + +# 在开启区域故障转移的开关前提下,故障转移有两种策略: +# 1. 如果“region-failover”值已配置,指定区域的故障转移,即找不到实例的时候,直接路由到该区域实例 +# 2. 如果“region-failover”值未配置,负载均衡策略的故障转移,即找不到实例的时候,执行负载均衡策略 +# 启动和关闭区域故障转移。缺失则默认为false +# spring.application.strategy.region.failover.enabled=true + +# 启动和关闭环境故障转移。缺失则默认为false +# 如果“env-failover”值未配置,则默认为common +# spring.application.strategy.environment.failover.enabled=true + +# 启动和关闭可用区亲和性,即同一个可用区的服务才能调用,同一个可用区的条件是调用端实例和提供端实例的元数据Metadata的zone配置值必须相等。缺失则默认为false +# spring.application.strategy.zone.affinity.enabled=true + +# 在开启可用区故障转移的开关前提下,故障转移有两种策略: +# 1. 如果“zone-failover”值已配置,指定可用区的故障转移,即找不到实例的时候,直接路由到该可用区实例 +# 2. 如果“zone-failover”值未配置,负载均衡策略的故障转移,即找不到实例的时候,执行负载均衡策略 +# 启动和关闭可用区故障转移。缺失则默认为false +# spring.application.strategy.zone.failover.enabled=true + +# 在开启IP地址和端口故障转移的开关前提下,故障转移有两种策略: +# 1. 如果“address-failover”值已配置,指定IP地址或者端口的故障转移,即找不到实例的时候,直接路由到该IP地址或者端口实例 +# 2. 如果“address-failover”值未配置,负载均衡策略的故障转移,即找不到实例的时候,执行负载均衡策略 +# 启动和关闭IP地址和端口故障转移。缺失则默认为false +# spring.application.strategy.address.failover.enabled=true + +# 版本号排序类型。缺失则默认为version +# 版本故障转移或者版本偏好启动时,需要寻址旧的稳定版本 +# 1. 当排序类型为version时,适用于版本号采用时间戳或者数字递增的方式。处理逻辑为将排序后版本号列表的第一个值作为旧的稳定版本 +# 2. 当排序类型为time时,不限于版本号的格式。处理逻辑为将根据服务实例全局唯一ID的时间戳前缀进行排序,把上线时间最早的服务实例的版本号作为旧的稳定版本 +# spring.application.strategy.version.sort.type=version +# spring.application.strategy.version.sort.type=time + +# 启动和关闭自动扫描目录,当扫描目录未人工配置的时候,可以通过自动扫描方式决定扫描目录。缺失则默认为true +# spring.application.strategy.auto.scan.packages.enabled=true +# 启动和关闭嵌套扫描,嵌套扫描指扫描非本工程下外部包的目录,可以支持多层嵌套。缺失则默认为false +# spring.application.strategy.auto.scan.recursion.enabled=false + +# 开启和关闭使用服务名前缀来作为服务组名。缺失则默认为false +# spring.application.group.generator.enabled=true +# 服务名前缀的截断长度,必须大于0 +# spring.application.group.generator.length=15 +# 服务名前缀的截断标志。当截断长度配置了,则取截断长度方式,否则取截断标志方式 +# spring.application.group.generator.character=- + +# 开启和关闭使用Git信息中的字段单个或者多个组合来作为服务版本号。缺失则默认为false +# spring.application.git.generator.enabled=true +# 插件git-commit-id-plugin产生git信息文件的输出路径,支持properties和json两种格式,支持classpath:xxx和file:xxx两种路径,这些需要和插件里的配置保持一致。缺失则默认为classpath:git.properties +# spring.application.git.generator.path=classpath:git.properties +# spring.application.git.generator.path=classpath:git.json +# 使用Git信息中的字段单个或者多个组合来作为服务版本号。缺失则默认为{git.commit.time}-{git.total.commit.count} +# 日期 + Git提交次数的版本号格式 +# spring.application.git.version.key={git.commit.time}-{git.total.commit.count} +# POM版本号格式 +# spring.application.git.version.key={git.build.version} + +# 开启和关闭Hystrix线程隔离模式做服务隔离时,对线程切换上下文传递的功能。缺失则默认为false +# Hystrix线程隔离模式做服务隔离时,必须把spring.application.strategy.hystrix.threadlocal.supported设置为true,同时要引入discovery-plugin-strategy-starter-hystrix包,否则线程切换时会发生ThreadLocal上下文对象丢失 +# spring.application.strategy.hystrix.threadlocal.supported=true + +# 启动和关闭服务相关操作端点。缺失则默认为true +# spring.application.admin.service.endpoint.enabled=true +# 启动和关闭配置相关操作端点。缺失则默认为true +# spring.application.admin.config.endpoint.enabled=true +# 启动和关闭版本相关操作端点。缺失则默认为true +# spring.application.admin.version.endpoint.enabled=true +# 启动和关闭侦测相关操作端点。缺失则默认为true +# spring.application.admin.inspector.endpoint.enabled=true +# 启动和关闭路由相关操作端点。缺失则默认为true +# spring.application.admin.router.endpoint.enabled=true +# 启动和关闭策略相关操作端点。缺失则默认为true +# spring.application.admin.strategy.endpoint.enabled=true +# 启动和关闭Sentinel相关操作端点。缺失则默认为true +# spring.application.admin.sentinel.endpoint.enabled=true +# 启动和关闭Git相关操作端点。缺失则默认为true +# spring.application.admin.git.endpoint.enabled=true +# 启动和关闭Spring Cloud Gateway相关操作端点。缺失则默认为true +# spring.application.admin.gateway.endpoint.enabled=true +# 启动和关闭Zuul相关操作端点。缺失则默认为true +# spring.application.admin.zuul.endpoint.enabled=true +# 启动和关闭策略操作端点的验证SPEL表达式方法。缺失则默认为true +# 该端点方法使用Spring StandardEvaluationContext类,StandardEvaluationContext支持全部的Spel语法且功能齐全,但GitHub Security报告其存在一定的注入风险,推荐使用SimpleEvaluationContext,而SimpleEvaluationContext并不能满足当前框架的需求 +# 如果未使用验证SPEL表达式方法,可以通过下面开关关闭在方法在策略端点上的暴露,规避风险 +# spring.application.admin.strategy.endpoint.validate-expression.enabled=true + +# 启动和关闭Swagger。缺失则默认为true +# swagger.enabled=true +# 业务服务Swagger Docket组名 +# swagger.service.group=Your group +# 业务服务Swagger扫描目录 +# swagger.service.packages=your-package1;your-package2 +# 业务服务Swagger描述 +# swagger.service.description=Your service Restful APIs +# 业务服务Swagger版本 +# swagger.service.version=1.0.0 +# 业务服务Swagger License名称 +# swagger.service.license.name=Apache License 2.0 +# 业务服务Swagger License链接 +# swagger.service.license.url=http://www.apache.org/licenses/LICENSE-2.0 +# 业务服务Swagger联系人名称 +# swagger.service.contact.name=Nepxion +# 业务服务Swagger联系人网址 +# swagger.service.contact.url=https://github.com/Nepxion/Discovery +# 业务服务Swagger联系人邮件 +# swagger.service.contact.email=1394997@qq.com +# 业务服务Swagger服务条件网址 +# swagger.service.termsOfService.url=http://nepxion.com/discovery \ No newline at end of file diff --git a/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/resources/logback.xml b/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/resources/logback.xml new file mode 100644 index 0000000000..c37b63f8e2 --- /dev/null +++ b/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/resources/logback.xml @@ -0,0 +1,50 @@ + + + + + + + %d{yyyy-MM-dd HH:mm:ss.SSS} %5p ${PID:- } --- [%15.15t] %-40.40logger{39} : %msg%n + + UTF-8 + + + log/discovery-%d{yyyy-MM-dd}.%i.log + 50MB + + + INFO + + + true + + + + 0 + 512 + + + + + + + + + %d{yyyy-MM-dd HH:mm:ss.SSS} %levelColor(%5p) %magenta(${PID:- }) --- [%15.15t] %cyan(%-40.40logger{39}) : %msg%n + + + + INFO + + + + + + + + + + + + + \ No newline at end of file diff --git a/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/resources/rule.json b/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/resources/rule.json new file mode 100644 index 0000000000..dceb2c15c5 --- /dev/null +++ b/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/resources/rule.json @@ -0,0 +1,477 @@ +{ + "registerEntity": { + "hostFilterEntity": { + "filterType": "BLACKLIST", + "filterValueList": [ + "10.10", + "11.11" + ], + "filterMap": { + "discovery-springcloud-example-a": [ + "172.16" + ] + } + }, + "countFilterEntity": { + "filterValue": 10000, + "filterMap": { + "discovery-springcloud-example-a": 5000 + } + } + }, + "discoveryEntity": { + "hostFilterEntity": { + "filterType": "BLACKLIST", + "filterValueList": [ + "10.10", + "11.11" + ], + "filterMap": { + "discovery-springcloud-example-b": [ + "172.16" + ] + } + }, + "versionFilterEntity": { + "versionEntityMap": { + "discovery-springcloud-example-a": [ + { + "consumerServiceName": "discovery-springcloud-example-a", + "providerServiceName": "discovery-springcloud-example-b", + "consumerVersionValueList": [ + "1.0" + ], + "providerVersionValueList": [ + "1.0" + ] + }, + { + "consumerServiceName": "discovery-springcloud-example-a", + "providerServiceName": "discovery-springcloud-example-b", + "consumerVersionValueList": [ + "1.1" + ], + "providerVersionValueList": [ + "1.1" + ] + } + ], + "discovery-springcloud-example-b": [ + { + "consumerServiceName": "discovery-springcloud-example-b", + "providerServiceName": "discovery-springcloud-example-c", + "consumerVersionValueList": [ + "1.0" + ], + "providerVersionValueList": [ + "1.0", + "1.1" + ] + }, + { + "consumerServiceName": "discovery-springcloud-example-b", + "providerServiceName": "discovery-springcloud-example-c", + "consumerVersionValueList": [ + "1.1" + ], + "providerVersionValueList": [ + "1.2" + ] + } + ] + } + }, + "regionFilterEntity": { + "regionEntityMap": { + "discovery-springcloud-example-a": [ + { + "consumerServiceName": "discovery-springcloud-example-a", + "providerServiceName": "discovery-springcloud-example-b", + "consumerRegionValueList": [ + "dev" + ], + "providerRegionValueList": [ + "dev" + ] + }, + { + "consumerServiceName": "discovery-springcloud-example-a", + "providerServiceName": "discovery-springcloud-example-b", + "consumerRegionValueList": [ + "qa" + ], + "providerRegionValueList": [ + "qa" + ] + } + ], + "discovery-springcloud-example-b": [ + { + "consumerServiceName": "discovery-springcloud-example-b", + "providerServiceName": "discovery-springcloud-example-c", + "consumerRegionValueList": [ + "dev" + ], + "providerRegionValueList": [ + "dev" + ] + }, + { + "consumerServiceName": "discovery-springcloud-example-b", + "providerServiceName": "discovery-springcloud-example-c", + "consumerRegionValueList": [ + "qa" + ], + "providerRegionValueList": [ + "qa" + ] + } + ] + } + }, + "weightFilterEntity": { + "versionWeightEntityMap": { + "discovery-springcloud-example-b": [ + { + "weightMap": { + "1.0": 90, + "1.1": 10 + }, + "consumerServiceName": "discovery-springcloud-example-b", + "providerServiceName": "discovery-springcloud-example-c", + "type": "VERSION" + } + ] + }, + "versionWeightEntityList": [ + { + "weightMap": { + "1.0": 90, + "1.1": 10 + }, + "consumerServiceName": null, + "providerServiceName": "discovery-springcloud-example-c", + "type": "VERSION" + } + ], + "versionWeightEntity": { + "weightMap": { + "1.0": 90, + "1.1": 10 + } + }, + "regionWeightEntityMap": { + "discovery-springcloud-example-b": [ + { + "weightMap": { + "dev": 85, + "qa": 15 + }, + "consumerServiceName": "discovery-springcloud-example-b", + "providerServiceName": "discovery-springcloud-example-c", + "type": "REGION" + } + ] + }, + "regionWeightEntityList": [ + { + "weightMap": { + "dev": 85, + "qa": 15 + }, + "consumerServiceName": null, + "providerServiceName": "discovery-springcloud-example-c", + "type": "REGION" + } + ], + "regionWeightEntity": { + "weightMap": { + "dev": 85, + "qa": 15 + } + } + } + }, + "strategyEntity": { + "versionValue": "{\"discovery-springcloud-example-a\":\"1.0\", \"discovery-springcloud-example-b\":\"1.0\", \"discovery-springcloud-example-c\":\"1.0;1.2\"}", + "regionValue": "{\"discovery-springcloud-example-a\":\"qa;dev\", \"discovery-springcloud-example-b\":\"dev\", \"discovery-springcloud-example-c\":\"qa\"}", + "addressValue": "{\"discovery-springcloud-example-a\":\"192.168.43.101:1100\", \"discovery-springcloud-example-b\":\"192.168.43.101:1201\", \"discovery-springcloud-example-c\":\"192.168.43.101:1300\"}", + "versionWeightValue": "{\"discovery-springcloud-example-a\":\"1.0=90;1.1=10\", \"discovery-springcloud-example-b\":\"1.0=90;1.1=10\", \"discovery-springcloud-example-c\":\"1.0=90;1.1=10\"}", + "regionWeightValue": "{\"discovery-springcloud-example-a\":\"dev=85;qa=15\", \"discovery-springcloud-example-b\":\"dev=85;qa=15\", \"discovery-springcloud-example-c\":\"dev=85;qa=15\"}" + }, + "strategyReleaseEntity": { + "strategyConditionBlueGreenEntityList": [ + { + "id": "1", + "expression": "#H['a'] == '1' and #H['b'] == '2'", + "versionId": "a-1", + "regionId": "b-1", + "addressId": "c-1", + "versionWeightId": "d-1", + "regionWeightId": "e-1" + }, + { + "id": "2", + "expression": "#H['c'] == '3'", + "versionId": "a-2", + "regionId": "b-2", + "addressId": "c-2", + "versionWeightId": "d-2", + "regionWeightId": "e-2" + }, + { + "id": "3", + "expression": null, + "versionId": "a-2", + "regionId": "b-2", + "addressId": "c-2", + "versionWeightId": "d-2", + "regionWeightId": "e-2" + } + ], + "strategyConditionGrayEntityList": [ + { + "id": "1", + "expression": "#H['a'] == '1' and #H['b'] == '2'", + "versionWeightEntity": { + "weightMap": { + "a-1": 10, + "a-2": 90 + } + }, + "regionWeightEntity": { + "weightMap": { + "b-1": 20, + "b-2": 80 + } + }, + "addressWeightEntity": { + "weightMap": { + "c-1": 30, + "c-2": 70 + } + } + }, + { + "id": "2", + "expression": "#H['c'] == '3'", + "versionWeightEntity": { + "weightMap": { + "a-1": 90, + "a-2": 10 + } + }, + "regionWeightEntity": { + "weightMap": { + "b-1": 80, + "b-2": 20 + } + }, + "addressWeightEntity": { + "weightMap": { + "c-1": 70, + "c-2": 30 + } + } + }, + { + "id": "3", + "expression": null, + "versionWeightEntity": { + "weightMap": { + "a-1": 5, + "a-2": 95 + } + }, + "regionWeightEntity": { + "weightMap": { + "b-1": 5, + "b-2": 95 + } + }, + "addressWeightEntity": { + "weightMap": { + "c-1": 5, + "c-2": 95 + } + } + } + ], + "strategyRouteEntityList": [ + { + "id": "a-1", + "type": "VERSION", + "value": "{\"discovery-springcloud-example-a\":\"1.0\", \"discovery-springcloud-example-b\":\"1.0\", \"discovery-springcloud-example-c\":\"1.0;1.2\"}" + }, + { + "id": "a-2", + "type": "VERSION", + "value": "{\"discovery-springcloud-example-a\":\"1.1\", \"discovery-springcloud-example-b\":\"1.1\", \"discovery-springcloud-example-c\":\"1.2\"}" + }, + { + "id": "b-1", + "type": "REGION", + "value": "{\"discovery-springcloud-example-a\":\"qa;dev\", \"discovery-springcloud-example-b\":\"dev\", \"discovery-springcloud-example-c\":\"qa\"}" + }, + { + "id": "b-2", + "type": "REGION", + "value": "{\"discovery-springcloud-example-a\":\"qa\", \"discovery-springcloud-example-b\":\"qa\", \"discovery-springcloud-example-c\":\"qa\"}" + }, + { + "id": "c-1", + "type": "ADDRESS", + "value": "{\"discovery-springcloud-example-a\":\"192.168.43.101:1100\", \"discovery-springcloud-example-b\":\"192.168.43.101:1201\", \"discovery-springcloud-example-c\":\"192.168.43.101:1300\"}" + }, + { + "id": "c-2", + "type": "ADDRESS", + "value": "{\"discovery-springcloud-example-a\":\"192.168.43.101:1101\", \"discovery-springcloud-example-b\":\"192.168.43.101:1201\", \"discovery-springcloud-example-c\":\"192.168.43.101:1301\"}" + }, + { + "id": "d-1", + "type": "VERSION_WEIGHT", + "value": "{\"discovery-springcloud-example-a\":\"1.0=90;1.1=10\", \"discovery-springcloud-example-b\":\"1.0=90;1.1=10\", \"discovery-springcloud-example-c\":\"1.0=90;1.1=10\"}" + }, + { + "id": "d-2", + "type": "VERSION_WEIGHT", + "value": "{\"discovery-springcloud-example-a\":\"1.0=10;1.1=90\", \"discovery-springcloud-example-b\":\"1.0=10;1.1=90\", \"discovery-springcloud-example-c\":\"1.0=10;1.1=90\"}" + }, + { + "id": "e-1", + "type": "REGION_WEIGHT", + "value": "{\"discovery-springcloud-example-a\":\"dev=85;qa=15\", \"discovery-springcloud-example-b\":\"dev=85;qa=15\", \"discovery-springcloud-example-c\":\"dev=85;qa=15\"}" + }, + { + "id": "e-2", + "type": "REGION_WEIGHT", + "value": "{\"discovery-springcloud-example-a\":\"dev=15;qa=85\", \"discovery-springcloud-example-b\":\"dev=15;qa=85\", \"discovery-springcloud-example-c\":\"dev=15;qa=85\"}" + } + ], + "strategyHeaderEntity": { + "headerMap": { + "a": "1", + "b": "2", + "c": "3" + } + } + }, + "strategyFailoverEntity": { + "versionPreferValue": "{\"discovery-springcloud-example-a\":\"1.0\", \"discovery-springcloud-example-b\":\"1.0\", \"discovery-springcloud-example-c\":\"1.0\"}", + "versionFailoverValue": "{\"discovery-springcloud-example-a\":\"1.1\", \"discovery-springcloud-example-b\":\"1.1\", \"discovery-springcloud-example-c\":\"1.1\"}", + "regionTransferValue": "qa", + "regionFailoverValue": "dev", + "environmentFailoverValue": "env1;default", + "zoneFailoverValue": "zone1;default", + "addressFailoverValue": "*1" + }, + "strategyBlacklistEntity": { + "idValue": "{\"discovery-springcloud-example-a\":\"20210601-222214-909-1146-372-698\", \"discovery-springcloud-example-b\":\"20210601-222623-277-4978-633-279\", \"discovery-springcloud-example-c\":\"20210601-222728-133-2597-222-609\"}", + "addressValue": "{\"discovery-springcloud-example-a\":\"192.168.43.101:1100\", \"discovery-springcloud-example-b\":\"192.168.43.101:1201\", \"discovery-springcloud-example-c\":\"192.168.43.101:1300\"}" + }, + "parameterEntity": { + "parameterServiceMap": { + "discovery-springcloud-example-a": [ + { + "parameterMap": { + "service-name": "discovery-springcloud-example-a", + "tag-key": "version", + "tag-value": "1.0", + "key": "ShardingSphere", + "value": "db1" + } + }, + { + "parameterMap": { + "service-name": "discovery-springcloud-example-a", + "tag-key": "version", + "tag-value": "1.1", + "key": "ShardingSphere", + "value": "db2" + } + } + ], + "discovery-springcloud-example-b": [ + { + "parameterMap": { + "service-name": "discovery-springcloud-example-b", + "tag-key": "region", + "tag-value": "dev", + "key": "RocketMQ", + "value": "queue1" + } + }, + { + "parameterMap": { + "service-name": "discovery-springcloud-example-b", + "tag-key": "region", + "tag-value": "qa", + "key": "RocketMQ", + "value": "queue2" + } + } + ], + "discovery-springcloud-example-c": [ + { + "parameterMap": { + "service-name": "discovery-springcloud-example-c", + "tag-key": "env", + "tag-value": "env1", + "key": "ShardingSphere", + "value": "db1" + } + }, + { + "parameterMap": { + "service-name": "discovery-springcloud-example-c", + "tag-key": "env", + "tag-value": "env2", + "key": "ShardingSphere", + "value": "db2" + } + } + ], + "discovery-springcloud-example-d": [ + { + "parameterMap": { + "service-name": "discovery-springcloud-example-d", + "tag-key": "zone", + "tag-value": "zone1", + "key": "RocketMQ", + "value": "queue1" + } + }, + { + "parameterMap": { + "service-name": "discovery-springcloud-example-d", + "tag-key": "zone", + "tag-value": "zone2", + "key": "RocketMQ", + "value": "queue2" + } + } + ], + "discovery-springcloud-example-e": [ + { + "parameterMap": { + "service-name": "discovery-springcloud-example-e", + "tag-key": "address", + "tag-value": "192.168.43.101:1201", + "key": "ShardingSphere", + "value": "db1" + } + }, + { + "parameterMap": { + "service-name": "discovery-springcloud-example-e", + "tag-key": "address", + "tag-value": "192.168.43.102:1201", + "key": "ShardingSphere", + "value": "db2" + } + } + ] + } + } +} \ No newline at end of file diff --git a/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/resources/rule.xml b/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/resources/rule.xml new file mode 100644 index 0000000000..a18e7dd98f --- /dev/null +++ b/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/resources/rule.xml @@ -0,0 +1,244 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + {"discovery-springcloud-example-a":"1.0", "discovery-springcloud-example-b":"1.0", "discovery-springcloud-example-c":"1.0;1.2"} + + + {"discovery-springcloud-example-a":"qa;dev", "discovery-springcloud-example-b":"dev", "discovery-springcloud-example-c":"qa"} + + +
{"discovery-springcloud-example-a":"192.168.43.101:1100", "discovery-springcloud-example-b":"192.168.43.101:1201", "discovery-springcloud-example-c":"192.168.43.101:1300"}
+ + + {"discovery-springcloud-example-a":"1.0=90;1.1=10", "discovery-springcloud-example-b":"1.0=90;1.1=10", "discovery-springcloud-example-c":"1.0=90;1.1=10"} + + + {"discovery-springcloud-example-a":"dev=85;qa=15", "discovery-springcloud-example-b":"dev=85;qa=15", "discovery-springcloud-example-c":"dev=85;qa=15"} + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + {"discovery-springcloud-example-a":"1.0", "discovery-springcloud-example-b":"1.0", "discovery-springcloud-example-c":"1.0;1.2"} + {"discovery-springcloud-example-a":"1.1", "discovery-springcloud-example-b":"1.1", "discovery-springcloud-example-c":"1.2"} + {"discovery-springcloud-example-a":"qa;dev", "discovery-springcloud-example-b":"dev", "discovery-springcloud-example-c":"qa"} + {"discovery-springcloud-example-a":"qa", "discovery-springcloud-example-b":"qa", "discovery-springcloud-example-c":"qa"} + {"discovery-springcloud-example-a":"192.168.43.101:1100", "discovery-springcloud-example-b":"192.168.43.101:1201", "discovery-springcloud-example-c":"192.168.43.101:1300"} + {"discovery-springcloud-example-a":"192.168.43.101:1101", "discovery-springcloud-example-b":"192.168.43.101:1201", "discovery-springcloud-example-c":"192.168.43.101:1301"} + {"discovery-springcloud-example-a":"1.0=90;1.1=10", "discovery-springcloud-example-b":"1.0=90;1.1=10", "discovery-springcloud-example-c":"1.0=90;1.1=10"} + {"discovery-springcloud-example-a":"1.0=10;1.1=90", "discovery-springcloud-example-b":"1.0=10;1.1=90", "discovery-springcloud-example-c":"1.0=10;1.1=90"} + {"discovery-springcloud-example-a":"dev=85;qa=15", "discovery-springcloud-example-b":"dev=85;qa=15", "discovery-springcloud-example-c":"dev=85;qa=15"} + {"discovery-springcloud-example-a":"dev=15;qa=85", "discovery-springcloud-example-b":"dev=15;qa=85", "discovery-springcloud-example-c":"dev=15;qa=85"} + + + +
{"a":"1", "b":"2", "c":"3"}
+
+ + + + + {"discovery-springcloud-example-a":"1.0", "discovery-springcloud-example-b":"1.0", "discovery-springcloud-example-c":"1.0"} + + {"discovery-springcloud-example-a":"1.1", "discovery-springcloud-example-b":"1.1", "discovery-springcloud-example-c":"1.1"} + + qa + + dev + + env1;default + + zone1;default + + *1 + + + + + + {"discovery-springcloud-example-a":"20210601-222214-909-1146-372-698", "discovery-springcloud-example-b":"20210601-222623-277-4978-633-279", "discovery-springcloud-example-c":"20210601-222728-133-2597-222-609"} + +
{"discovery-springcloud-example-a":"192.168.43.101:1100", "discovery-springcloud-example-b":"192.168.43.101:1201", "discovery-springcloud-example-c":"192.168.43.101:1300"}
+
+ + + + + + + + + + + + + + + + + + + +
\ No newline at end of file diff --git a/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/resources/sentinel-authority.json b/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/resources/sentinel-authority.json new file mode 100644 index 0000000000..5bac2382d0 --- /dev/null +++ b/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/resources/sentinel-authority.json @@ -0,0 +1,7 @@ +[ + { + "resource": "sentinel-resource", + "limitApp": "1.0&zhangsan", + "strategy": 0 + } +] \ No newline at end of file diff --git a/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/resources/sentinel-degrade.json b/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/resources/sentinel-degrade.json new file mode 100644 index 0000000000..d503a76387 --- /dev/null +++ b/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/resources/sentinel-degrade.json @@ -0,0 +1,10 @@ +[ + { + "resource": "sentinel-resource", + "limitApp": "default", + "count": 2, + "timeWindow": 10, + "grade": 0, + "passCount": 0 + } +] \ No newline at end of file diff --git a/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/resources/sentinel-flow.json b/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/resources/sentinel-flow.json new file mode 100644 index 0000000000..9e2d2d061a --- /dev/null +++ b/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/resources/sentinel-flow.json @@ -0,0 +1,15 @@ +[ + { + "resource": "sentinel-resource", + "limitApp": "default", + "grade": 1, + "count": 1, + "strategy": 0, + "refResource": null, + "controlBehavior": 0, + "warmUpPeriodSec": 10, + "maxQueueingTimeMs": 500, + "clusterMode": false, + "clusterConfig": null + } +] \ No newline at end of file diff --git a/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/resources/sentinel-param-flow.json b/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/resources/sentinel-param-flow.json new file mode 100644 index 0000000000..4c1affa8bc --- /dev/null +++ b/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/resources/sentinel-param-flow.json @@ -0,0 +1,15 @@ +[ + { + "resource": "sentinel-resource", + "limitApp": "default", + "grade": 1, + "paramIdx": 0, + "count": 1, + "controlBehavior": 0, + "maxQueueingTimeMs": 0, + "burstCount": 0, + "durationInSec": 1, + "paramFlowItemList": [], + "clusterMode": false + } +] \ No newline at end of file diff --git a/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/resources/sentinel-system.json b/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/resources/sentinel-system.json new file mode 100644 index 0000000000..4cf844cd7b --- /dev/null +++ b/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/resources/sentinel-system.json @@ -0,0 +1,11 @@ +[ + { + "resource": null, + "limitApp": null, + "highestSystemLoad": -1.0, + "highestCpuUsage": -1.0, + "qps": 200.0, + "avgRt": -1, + "maxThread": -1 + } +] \ No newline at end of file diff --git a/discovery-springcloud-example-service/src/main/resources/sentinel.json b/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/resources/sentinel.json similarity index 100% rename from discovery-springcloud-example-service/src/main/resources/sentinel.json rename to discovery-springcloud-examples/discovery-springcloud-example-service/src/main/resources/sentinel.json diff --git a/discovery-springcloud-examples/discovery-springcloud-example-service/src/test/java/com/nepxion/discovery/plugin/example/service/parser/ConfigParserTest.java b/discovery-springcloud-examples/discovery-springcloud-example-service/src/test/java/com/nepxion/discovery/plugin/example/service/parser/ConfigParserTest.java new file mode 100644 index 0000000000..66841ff967 --- /dev/null +++ b/discovery-springcloud-examples/discovery-springcloud-example-service/src/test/java/com/nepxion/discovery/plugin/example/service/parser/ConfigParserTest.java @@ -0,0 +1,88 @@ +package com.nepxion.discovery.plugin.example.service.parser; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; + +import org.apache.commons.io.IOUtils; + +import com.nepxion.discovery.common.constant.DiscoveryConstant; +import com.nepxion.discovery.common.entity.RuleEntity; +import com.nepxion.discovery.plugin.framework.parser.json.JsonConfigDeparser; +import com.nepxion.discovery.plugin.framework.parser.json.JsonConfigParser; +import com.nepxion.discovery.plugin.framework.parser.xml.XmlConfigDeparser; +import com.nepxion.discovery.plugin.framework.parser.xml.XmlConfigParser; + +public class ConfigParserTest { + public static void main(String[] args) { + testXml(); + // testJson(); + } + + public static void testXml() { + String rule = testFile("rule.xml"); + + RuleEntity ruleEntity = new XmlConfigParser().parse(rule); + + System.out.println("**************************************************"); + System.out.println(ruleEntity); + System.out.println("**************************************************"); + + System.out.println("**************************************************"); + new XmlConfigDeparser().deparse(ruleEntity); + System.out.println("**************************************************"); + + System.out.println("**************************************************"); + new JsonConfigDeparser().deparse(ruleEntity); + System.out.println("**************************************************"); + } + + public static void testJson() { + String rule = testFile("rule.json"); + + RuleEntity ruleEntity = new JsonConfigParser().parse(rule); + + System.out.println("**************************************************"); + System.out.println(ruleEntity); + System.out.println("**************************************************"); + + System.out.println("**************************************************"); + new JsonConfigDeparser().deparse(ruleEntity); + System.out.println("**************************************************"); + + System.out.println("**************************************************"); + new XmlConfigDeparser().deparse(ruleEntity); + System.out.println("**************************************************"); + } + + public static String testFile(String fileName) { + File file = new File("src/main/resources/" + fileName); + InputStream inputStream = null; + String rule = null; + try { + inputStream = new FileInputStream(file); + rule = IOUtils.toString(inputStream, DiscoveryConstant.ENCODING_UTF_8); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } finally { + if (inputStream != null) { + IOUtils.closeQuietly(inputStream); + } + } + + return rule; + } +} \ No newline at end of file diff --git a/discovery-springcloud-examples/discovery-springcloud-example-zuul/pom.xml b/discovery-springcloud-examples/discovery-springcloud-example-zuul/pom.xml new file mode 100644 index 0000000000..6cb4a95a87 --- /dev/null +++ b/discovery-springcloud-examples/discovery-springcloud-example-zuul/pom.xml @@ -0,0 +1,57 @@ + + + discovery-springcloud-example-zuul + Nepxion Discovery Spring Cloud Example Zuul + jar + 4.0.0 + Nepxion Discovery is a solution for Spring Cloud with blue green, gray, weight, limitation, circuit breaker, degrade, isolation, monitor, tracing, dye, failover, async agent + http://www.nepxion.com + + + com.nepxion + discovery-springcloud-examples + 6.23.0 + + + + + com.nepxion + + + + discovery-plugin-register-center-starter-nacos + + + + com.nepxion + + discovery-plugin-config-center-starter-nacos + + + + + + + + ${project.groupId} + discovery-plugin-admin-center-starter + + + + com.nepxion + discovery-plugin-strategy-starter-zuul + + + + + + + de.codecentric + spring-boot-admin-starter-client + + + \ No newline at end of file diff --git a/discovery-springcloud-example-zuul/src/main/java/com/nepxion/discovery/plugin/example/zuul/DiscoveryApplicationZuul.java b/discovery-springcloud-examples/discovery-springcloud-example-zuul/src/main/java/com/nepxion/discovery/plugin/example/zuul/DiscoveryApplicationZuul.java similarity index 83% rename from discovery-springcloud-example-zuul/src/main/java/com/nepxion/discovery/plugin/example/zuul/DiscoveryApplicationZuul.java rename to discovery-springcloud-examples/discovery-springcloud-example-zuul/src/main/java/com/nepxion/discovery/plugin/example/zuul/DiscoveryApplicationZuul.java index db84f7365c..91ea0d31ed 100644 --- a/discovery-springcloud-example-zuul/src/main/java/com/nepxion/discovery/plugin/example/zuul/DiscoveryApplicationZuul.java +++ b/discovery-springcloud-examples/discovery-springcloud-example-zuul/src/main/java/com/nepxion/discovery/plugin/example/zuul/DiscoveryApplicationZuul.java @@ -10,7 +10,6 @@ */ import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.netflix.zuul.EnableZuulProxy; @@ -21,7 +20,7 @@ import com.nepxion.discovery.plugin.example.zuul.impl.MyLoadBalanceListener; import com.nepxion.discovery.plugin.example.zuul.impl.MyRegisterListener; import com.nepxion.discovery.plugin.example.zuul.impl.MyRouteFilter; -import com.nepxion.discovery.plugin.strategy.zuul.constant.ZuulStrategyConstant; +import com.nepxion.discovery.plugin.example.zuul.impl.MySubscriber; import com.nepxion.discovery.plugin.strategy.zuul.filter.ZuulStrategyRouteFilter; @SpringBootApplication @@ -33,10 +32,8 @@ public static void main(String[] args) { } @Bean - @ConditionalOnProperty(value = ZuulStrategyConstant.SPRING_APPLICATION_STRATEGY_ZUUL_ROUTE_FILTER_ENABLED, matchIfMissing = true) public ZuulStrategyRouteFilter zuulStrategyRouteFilter() { return new MyRouteFilter(); - // return new CustomizationZuulStrategyRouteFilter(); } @Bean @@ -58,4 +55,9 @@ public MyDiscoveryListener myDiscoveryListener() { public MyLoadBalanceListener myLoadBalanceListener() { return new MyLoadBalanceListener(); } + + @Bean + public MySubscriber mySubscriber() { + return new MySubscriber(); + } } \ No newline at end of file diff --git a/discovery-springcloud-examples/discovery-springcloud-example-zuul/src/main/java/com/nepxion/discovery/plugin/example/zuul/impl/MyDiscoveryEnabledStrategy.java b/discovery-springcloud-examples/discovery-springcloud-example-zuul/src/main/java/com/nepxion/discovery/plugin/example/zuul/impl/MyDiscoveryEnabledStrategy.java new file mode 100644 index 0000000000..c9e78b34c9 --- /dev/null +++ b/discovery-springcloud-examples/discovery-springcloud-example-zuul/src/main/java/com/nepxion/discovery/plugin/example/zuul/impl/MyDiscoveryEnabledStrategy.java @@ -0,0 +1,65 @@ +package com.nepxion.discovery.plugin.example.zuul.impl; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; + +import com.nepxion.discovery.plugin.framework.adapter.PluginAdapter; +import com.nepxion.discovery.plugin.strategy.adapter.DiscoveryEnabledStrategy; +import com.nepxion.discovery.plugin.strategy.zuul.context.ZuulStrategyContextHolder; +import com.netflix.loadbalancer.Server; + +// 实现了组合策略,版本路由策略+区域路由策略+IP地址和端口路由策略+自定义策略 +public class MyDiscoveryEnabledStrategy implements DiscoveryEnabledStrategy { + private static final Logger LOG = LoggerFactory.getLogger(MyDiscoveryEnabledStrategy.class); + + @Autowired + private ZuulStrategyContextHolder zuulStrategyContextHolder; + + @Autowired + private PluginAdapter pluginAdapter; + + @Override + public boolean apply(Server server) { + // 对Rest调用传来的Header参数(例如:mobile)做策略 + return applyFromHeader(server); + } + + // 根据REST调用传来的Header参数(例如:mobile),选取执行调用请求的服务实例 + private boolean applyFromHeader(Server server) { + String mobile = zuulStrategyContextHolder.getHeader("mobile"); + String serviceId = pluginAdapter.getServerServiceId(server); + String version = pluginAdapter.getServerVersion(server); + String region = pluginAdapter.getServerRegion(server); + String environment = pluginAdapter.getServerEnvironment(server); + String address = server.getHost() + ":" + server.getPort(); + + LOG.info("负载均衡用户定制触发:mobile={}, serviceId={}, version={}, region={}, env={}, address={}", mobile, serviceId, version, region, environment, address); + + if (StringUtils.isNotEmpty(mobile)) { + // 手机号以移动138开头,路由到1.0版本的服务上 + if (mobile.startsWith("138") && StringUtils.equals(version, "1.0")) { + return true; + // 手机号以联通133开头,路由到1.1版本的服务上 + } else if (mobile.startsWith("133") && StringUtils.equals(version, "1.1")) { + return true; + } else { + // 其它情况,实例被过滤掉 + return false; + } + } + + // 无手机号,实例不被过滤掉 + return true; + } +} \ No newline at end of file diff --git a/discovery-springcloud-examples/discovery-springcloud-example-zuul/src/main/java/com/nepxion/discovery/plugin/example/zuul/impl/MyDiscoveryListener.java b/discovery-springcloud-examples/discovery-springcloud-example-zuul/src/main/java/com/nepxion/discovery/plugin/example/zuul/impl/MyDiscoveryListener.java new file mode 100644 index 0000000000..ddc40f989e --- /dev/null +++ b/discovery-springcloud-examples/discovery-springcloud-example-zuul/src/main/java/com/nepxion/discovery/plugin/example/zuul/impl/MyDiscoveryListener.java @@ -0,0 +1,49 @@ +package com.nepxion.discovery.plugin.example.zuul.impl; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.Iterator; +import java.util.List; + +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.cloud.client.ServiceInstance; + +import com.nepxion.discovery.plugin.framework.listener.discovery.AbstractDiscoveryListener; + +// 当目标服务的元数据中的Group为mygroup2,禁止被本服务发现(只用于DiscoveryClient.getInstances接口方法用) +public class MyDiscoveryListener extends AbstractDiscoveryListener { + private static final Logger LOG = LoggerFactory.getLogger(MyDiscoveryListener.class); + + @Override + public void onGetInstances(String serviceId, List instances) { + Iterator iterator = instances.iterator(); + while (iterator.hasNext()) { + ServiceInstance instance = iterator.next(); + String group = pluginAdapter.getInstanceGroup(instance); + if (StringUtils.equals(group, "mygroup2")) { + iterator.remove(); + + LOG.info("服务名=" + serviceId + ",组名=" + group + "的服务禁止被本服务发现"); + } + } + } + + @Override + public void onGetServices(List services) { + + } + + @Override + public int getOrder() { + return LOWEST_PRECEDENCE - 500; + } +} \ No newline at end of file diff --git a/discovery-springcloud-examples/discovery-springcloud-example-zuul/src/main/java/com/nepxion/discovery/plugin/example/zuul/impl/MyLoadBalanceListener.java b/discovery-springcloud-examples/discovery-springcloud-example-zuul/src/main/java/com/nepxion/discovery/plugin/example/zuul/impl/MyLoadBalanceListener.java new file mode 100644 index 0000000000..02e1612c71 --- /dev/null +++ b/discovery-springcloud-examples/discovery-springcloud-example-zuul/src/main/java/com/nepxion/discovery/plugin/example/zuul/impl/MyLoadBalanceListener.java @@ -0,0 +1,44 @@ +package com.nepxion.discovery.plugin.example.zuul.impl; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.Iterator; +import java.util.List; + +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.nepxion.discovery.plugin.framework.listener.loadbalance.AbstractLoadBalanceListener; +import com.netflix.loadbalancer.Server; + +// 当目标服务的元数据中的Group为mygroup2,禁止被本服务负载均衡 +public class MyLoadBalanceListener extends AbstractLoadBalanceListener { + private static final Logger LOG = LoggerFactory.getLogger(MyLoadBalanceListener.class); + + @Override + public void onGetServers(String serviceId, List servers) { + Iterator iterator = servers.iterator(); + while (iterator.hasNext()) { + Server server = iterator.next(); + String group = pluginAdapter.getServerGroup(server); + if (StringUtils.equals(group, "mygroup3")) { + iterator.remove(); + + LOG.info("服务名=" + serviceId + ",组名=" + group + "的服务禁止被本服务负载均衡"); + } + } + } + + @Override + public int getOrder() { + return LOWEST_PRECEDENCE - 500; + } +} \ No newline at end of file diff --git a/discovery-springcloud-examples/discovery-springcloud-example-zuul/src/main/java/com/nepxion/discovery/plugin/example/zuul/impl/MyRegisterListener.java b/discovery-springcloud-examples/discovery-springcloud-example-zuul/src/main/java/com/nepxion/discovery/plugin/example/zuul/impl/MyRegisterListener.java new file mode 100644 index 0000000000..9e51f7357d --- /dev/null +++ b/discovery-springcloud-examples/discovery-springcloud-example-zuul/src/main/java/com/nepxion/discovery/plugin/example/zuul/impl/MyRegisterListener.java @@ -0,0 +1,48 @@ +package com.nepxion.discovery.plugin.example.zuul.impl; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.apache.commons.lang3.StringUtils; +import org.springframework.cloud.client.serviceregistry.Registration; + +import com.nepxion.discovery.common.exception.DiscoveryException; +import com.nepxion.discovery.plugin.framework.listener.register.AbstractRegisterListener; + +// 当本服务的元数据中的Group为mygroup1,禁止被注册到注册中心 +public class MyRegisterListener extends AbstractRegisterListener { + @Override + public void onRegister(Registration registration) { + String serviceId = pluginAdapter.getServiceId(); + String group = pluginAdapter.getGroup(); + if (StringUtils.equals(group, "mygroup1")) { + throw new DiscoveryException("服务名=" + serviceId + ",组名=" + group + "的服务禁止被注册到注册中心"); + } + } + + @Override + public void onDeregister(Registration registration) { + + } + + @Override + public void onSetStatus(Registration registration, String status) { + + } + + @Override + public void onClose() { + + } + + @Override + public int getOrder() { + return LOWEST_PRECEDENCE - 500; + } +} \ No newline at end of file diff --git a/discovery-springcloud-examples/discovery-springcloud-example-zuul/src/main/java/com/nepxion/discovery/plugin/example/zuul/impl/MyRouteFilter.java b/discovery-springcloud-examples/discovery-springcloud-example-zuul/src/main/java/com/nepxion/discovery/plugin/example/zuul/impl/MyRouteFilter.java new file mode 100644 index 0000000000..7e1a196a6b --- /dev/null +++ b/discovery-springcloud-examples/discovery-springcloud-example-zuul/src/main/java/com/nepxion/discovery/plugin/example/zuul/impl/MyRouteFilter.java @@ -0,0 +1,41 @@ +package com.nepxion.discovery.plugin.example.zuul.impl; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Value; + +import com.nepxion.discovery.plugin.strategy.zuul.filter.DefaultZuulStrategyRouteFilter; + +// 适用于A/B Testing或者更根据某业务参数决定蓝绿灰度路由路径。可以结合配置中心分别配置A/B两条路径,可以动态改变并通知 +// 当Header中传来的用户为张三,执行一条路由路径;为李四,执行另一条路由路径 +public class MyRouteFilter extends DefaultZuulStrategyRouteFilter { + private static final String DEFAULT_A_ROUTE_VERSION = "{\"discovery-springcloud-example-a\":\"1.0\", \"discovery-springcloud-example-b\":\"1.0\", \"discovery-springcloud-example-c\":\"1.0\"}"; + private static final String DEFAULT_B_ROUTE_VERSION = "{\"discovery-springcloud-example-a\":\"1.1\", \"discovery-springcloud-example-b\":\"1.1\", \"discovery-springcloud-example-c\":\"1.1\"}"; + + @Value("${a.route.version:" + DEFAULT_A_ROUTE_VERSION + "}") + private String aRouteVersion; + + @Value("${b.route.version:" + DEFAULT_B_ROUTE_VERSION + "}") + private String bRouteVersion; + + @Override + public String getRouteVersion() { + String user = strategyContextHolder.getHeader("user"); + + if (StringUtils.equals(user, "zhangsan")) { + return aRouteVersion; + } else if (StringUtils.equals(user, "lisi")) { + return bRouteVersion; + } + + return super.getRouteVersion(); + } +} \ No newline at end of file diff --git a/discovery-springcloud-examples/discovery-springcloud-example-zuul/src/main/java/com/nepxion/discovery/plugin/example/zuul/impl/MySubscriber.java b/discovery-springcloud-examples/discovery-springcloud-example-zuul/src/main/java/com/nepxion/discovery/plugin/example/zuul/impl/MySubscriber.java new file mode 100644 index 0000000000..84d1bc35fc --- /dev/null +++ b/discovery-springcloud-examples/discovery-springcloud-example-zuul/src/main/java/com/nepxion/discovery/plugin/example/zuul/impl/MySubscriber.java @@ -0,0 +1,75 @@ +package com.nepxion.discovery.plugin.example.zuul.impl; + +/** + *

Title: Nepxion Discovery

+ *

Description: Nepxion Discovery

+ *

Copyright: Copyright (c) 2017-2050

+ *

Company: Nepxion

+ * @author Haojun Ren + * @version 1.0 + */ + +import java.util.List; +import java.util.Map; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; + +import com.google.common.eventbus.Subscribe; +import com.nepxion.discovery.common.entity.ParameterEntity; +import com.nepxion.discovery.common.entity.ParameterServiceEntity; +import com.nepxion.discovery.plugin.framework.adapter.PluginAdapter; +import com.nepxion.discovery.plugin.framework.event.ParameterChangedEvent; +import com.nepxion.discovery.plugin.framework.event.RegisterFailureEvent; +import com.nepxion.discovery.plugin.framework.event.RuleClearedEvent; +import com.nepxion.discovery.plugin.framework.event.RuleFailureEvent; +import com.nepxion.discovery.plugin.framework.event.RuleUpdatedEvent; +import com.nepxion.discovery.plugin.strategy.event.StrategyAlarmEvent; +import com.nepxion.eventbus.annotation.EventBus; + +@EventBus +public class MySubscriber { + private static final Logger LOG = LoggerFactory.getLogger(MySubscriber.class); + + @Autowired + private PluginAdapter pluginAdapter; + + @Subscribe + public void onRuleUpdated(RuleUpdatedEvent ruleUpdatedEvent) { + LOG.info("规则执行更新, rule=" + ruleUpdatedEvent.getRule()); + } + + @Subscribe + public void onRuleCleared(RuleClearedEvent ruleClearedEvent) { + LOG.info("规则执行清空"); + } + + @Subscribe + public void onRuleRuleFailure(RuleFailureEvent ruleFailureEvent) { + LOG.info("规则更新失败, rule=" + ruleFailureEvent.getRule() + ", exception=" + ruleFailureEvent.getException()); + } + + @Subscribe + public void onParameterChanged(ParameterChangedEvent parameterChangedEvent) { + ParameterEntity parameterEntity = parameterChangedEvent.getParameterEntity(); + String serviceId = pluginAdapter.getServiceId(); + List parameterServiceEntityList = null; + if (parameterEntity != null) { + Map> parameterServiceMap = parameterEntity.getParameterServiceMap(); + parameterServiceEntityList = parameterServiceMap.get(serviceId); + } + LOG.info("获取动态参数, serviceId=" + serviceId + ", parameterServiceEntityList=" + parameterServiceEntityList); + } + + @Subscribe + public void onRegisterFailure(RegisterFailureEvent registerFailureEvent) { + LOG.info("注册失败, eventType=" + registerFailureEvent.getEventType() + ", eventDescription=" + registerFailureEvent.getEventDescription() + ", serviceId=" + registerFailureEvent.getServiceId() + ", host=" + registerFailureEvent.getHost() + ", port=" + registerFailureEvent.getPort()); + } + + @Subscribe + public void onAlarm(StrategyAlarmEvent strategyAlarmEvent) { + LOG.info("告警类型=" + strategyAlarmEvent.getAlarmType()); + LOG.info("告警内容=" + strategyAlarmEvent.getAlarmMap()); + } +} \ No newline at end of file diff --git a/discovery-springcloud-examples/discovery-springcloud-example-zuul/src/main/resources/application.properties b/discovery-springcloud-examples/discovery-springcloud-example-zuul/src/main/resources/application.properties new file mode 100644 index 0000000000..9f3d919494 --- /dev/null +++ b/discovery-springcloud-examples/discovery-springcloud-example-zuul/src/main/resources/application.properties @@ -0,0 +1,21 @@ +# Spring cloud config +spring.application.name=discovery-springcloud-example-zuul +server.port=1400 + +# Eureka config for discovery +eureka.instance.metadataMap.group=example-service-group +eureka.instance.metadataMap.version=1.0 + +# Consul config for discovery +spring.cloud.consul.discovery.tags=group=example-service-group,version=1.0 + +# Zookeeper config for discovery +spring.cloud.zookeeper.discovery.metadata.group=example-service-group +spring.cloud.zookeeper.discovery.metadata.version=1.0 + +# Nacos config for discovery +spring.cloud.nacos.discovery.metadata.group=example-service-group +spring.cloud.nacos.discovery.metadata.version=1.0 + +# Management config +management.server.port=5400 \ No newline at end of file diff --git a/discovery-springcloud-examples/discovery-springcloud-example-zuul/src/main/resources/bootstrap.properties b/discovery-springcloud-examples/discovery-springcloud-example-zuul/src/main/resources/bootstrap.properties new file mode 100644 index 0000000000..f7a83b6d8c --- /dev/null +++ b/discovery-springcloud-examples/discovery-springcloud-example-zuul/src/main/resources/bootstrap.properties @@ -0,0 +1,354 @@ +# Spring cloud config + +# Eureka config for discovery +eureka.client.serviceUrl.defaultZone=http://localhost:9528/eureka/ +eureka.instance.preferIpAddress=true + +# Consul config for discovery +spring.cloud.consul.host=localhost +spring.cloud.consul.port=8500 +spring.cloud.consul.discovery.preferIpAddress=true + +# Zookeeper config for discovery +spring.cloud.zookeeper.connectString=localhost:2181 +spring.cloud.zookeeper.discovery.instancePort=${server.port} +spring.cloud.zookeeper.discovery.root=/spring-cloud +spring.cloud.zookeeper.discovery.preferIpAddress=true + +# Nacos config for discovery +spring.cloud.nacos.discovery.server-addr=localhost:8848 +# spring.cloud.nacos.discovery.namespace=discovery + +# Ribbon config +ribbon.ServerListRefreshInterval=5000 +ribbon.ConnectTimeout=60000 +ribbon.ReadTimeout=60000 +ribbon.maxAutoRetries=3 +ribbon.maxAutoRetriesNextServer=3 +ribbon.okToRetryOnAllOperations=true + +# Apollo config for rule +app.id=discovery +apollo.meta=http://106.54.227.205:8080 +# apollo.namespace=application + +# Nacos config for rule +nacos.server-addr=localhost:8848 +# nacos.access-key= +# nacos.secret-key= +# nacos.username= +# nacos.password= +# nacos.namespace=application +# nacos.cluster-name= +# nacos.context-path= +# nacos.config-long-poll-timeout= +# nacos.config-retry-time= +# nacos.max-retry= +# nacos.endpoint= +# nacos.endpoint-port= +# nacos.is-use-endpoint-parsing-rule= +# nacos.is-use-cloud-namespace-parsing= +# nacos.encode= +# nacos.naming-load-cache-at-start= +# nacos.naming-client-beat-thread-count= +# nacos.naming-polling-thread-count= +# nacos.naming-request-domain-max-retry-count= +# nacos.naming-push-empty-protection= +# nacos.ram-role-name= +# nacos.timout= + +# Redis config for rule +spring.redis.host=localhost +spring.redis.port=6379 +spring.redis.password= +spring.redis.database=0 + +# Zookeeper config for rule +zookeeper.connect-string=localhost:2181 +zookeeper.retry-count=3 +zookeeper.sleep-time=3000 + +# Consul config for rule +consul.host=localhost +consul.port=8500 +consul.timeout=1 +consul.token= + +# Etcd config for rule +etcd.server.addr=http://localhost:2379 +etcd.username= +etcd.password= + +# Management config +# 该项只对Consul有效,而且必须配置在bootstrap.properties里,配置在application.properties无效 +# management.health.consul.enabled=true +management.endpoints.web.exposure.include=* +management.endpoints.jmx.exposure.include=* +management.endpoint.health.show-details=ALWAYS + +# Spring boot admin config +spring.boot.admin.client.instance.prefer-ip=true +spring.boot.admin.client.url=http://localhost:9728 + +# Plugin core config +# 随机权重算法。缺失则默认为MapWeightRandom +# spring.application.weight.random.type=MapWeightRandom +# 规则文件的格式,支持xml和json。缺失则默认为xml +# spring.application.config.format=xml +# spring.application.config.format=json +# 本地规则文件的路径,支持两种方式:classpath:rule.xml(rule.json) - 规则文件放在resources目录下,便于打包进jar;file:rule.xml(rule.json) - 规则文件放在工程根目录下,放置在外部便于修改。缺失则默认为不装载本地规则 +# spring.application.config.path=classpath:rule.xml +# spring.application.config.path=classpath:rule.json +# 为微服务归类的Key,一般通过group字段来归类,例如eureka.instance.metadataMap.group=xxx-group或者eureka.instance.metadataMap.application=xxx-application。缺失则默认为group +# spring.application.group.key=group +# spring.application.group.key=application +# 业务系统希望大多数时候Spring、SpringBoot或者SpringCloud的基本配置、调优参数(非业务系统配置参数),不配置在业务端,集成到基础框架里。但特殊情况下,业务系统有时候也希望能把基础框架里配置的参数给覆盖掉,用他们自己的配置 +# 对于此类型的配置需求,可以配置在下面的配置文件里。该文件一般放在resource目录下。缺失则默认为spring-application-default.properties +# spring.application.default.properties.path=spring-application-default.properties +# 负载均衡下,消费端尝试获取对应提供端服务实例列表为空的时候,通过日志方式通知。缺失则默认为false +# spring.application.no.servers.notify.enabled=false +# 由于Nacos注册中心会自动把服务名处理成GROUP@@SERVICE_ID的格式,导致根据服务名去获取元数据的时候会找不到。通过如下开关开启是否要过滤掉GROUP前缀。缺失则默认为true +# spring.application.nacos.service.id.filter.enabled=true +# 启动和关闭在服务启动的时候参数订阅事件发送。缺失则默认为true +# spring.application.parameter.event.onstart.enabled=true + +# Plugin strategy config +# 开启和关闭Ribbon默认的ZoneAvoidanceRule负载均衡策略。一旦关闭,则使用RoundRobin简单轮询负载均衡策略。缺失则默认为true +# spring.application.strategy.zone.avoidance.rule.enabled=true +# 路由策略过滤器的执行顺序(Order)。缺失则默认为0 +# spring.application.strategy.zuul.route.filter.order=0 +# 当外界传值Header的时候,网关也设置并传递同名的Header,需要决定哪个Header传递到后边的服务去。如果下面开关为true,以网关设置为优先,否则以外界传值为优先。缺失则默认为true +spring.application.strategy.zuul.header.priority=false +# 当以网关设置为优先的时候,网关未配置Header,而外界配置了Header,仍旧忽略外界的Header。缺失则默认为true +# spring.application.strategy.zuul.original.header.ignored=true +# 开启和关闭网关订阅配置中心的动态路由策略。缺失则默认为false +spring.application.strategy.zuul.dynamic.route.enabled=true +# 启动和关闭网关上核心策略Header传递,缺失则默认为true。当全局订阅启动时,可以关闭核心策略Header传递,这样可以节省传递数据的大小,一定程度上可以提升性能 +# 核心策略Header指n-d-开头的Header(不包括n-d-env,因为环境路由隔离,必须传递该Header),不包括n-d-service开头的Header +# spring.application.strategy.zuul.core.header.transmission.enabled=true + +# 启动和关闭监控,一旦关闭,调用链和日志输出都将关闭。缺失则默认为false +spring.application.strategy.monitor.enabled=true +# 启动和关闭告警,一旦关闭,蓝绿灰度上下文输出都将关闭。缺失则默认为false +spring.application.strategy.alarm.enabled=true +# 启动和关闭日志输出。缺失则默认为false +spring.application.strategy.logger.enabled=true +# 日志输出中,是否显示MDC前面的Key。缺失则默认为true +# spring.application.strategy.logger.mdc.key.shown=true +# 启动和关闭Debug日志打印,注意:每调用一次都会打印一次,会对性能有所影响,建议压测环境和生产环境关闭。缺失则默认为false +spring.application.strategy.logger.debug.enabled=true +# 启动和关闭调用链输出。缺失则默认为false +spring.application.strategy.tracer.enabled=true +# 启动和关闭调用链的蓝绿灰度信息以独立的Span节点输出,如果关闭,则蓝绿灰度信息输出到原生的Span节点中(SkyWalking不支持原生模式)。缺失则默认为true +# spring.application.strategy.tracer.separate.span.enabled=true +# 启动和关闭调用链的蓝绿灰度规则策略信息输出。缺失则默认为true +# spring.application.strategy.tracer.rule.output.enabled=true +# 启动和关闭调用链的异常信息是否以详细格式输出。缺失则默认为false +# spring.application.strategy.tracer.exception.detail.output.enabled=false +# 显示在调用链界面上蓝绿灰度Span的名称,建议改成具有公司特色的框架产品名称。缺失则默认为NEPXION +# spring.application.strategy.tracer.span.value=NEPXION +# 显示在调用链界面上蓝绿灰度Span Tag的插件名称,建议改成具有公司特色的框架产品的描述。缺失则默认为Nepxion Discovery +# spring.application.strategy.tracer.span.tag.plugin.value=Nepxion Discovery +# 启动和关闭Sentinel调用链上规则在Span上的输出。缺失则默认为true +# spring.application.strategy.tracer.sentinel.rule.output.enabled=true +# 启动和关闭Sentinel调用链上方法入参在Span上的输出。缺失则默认为false +# spring.application.strategy.tracer.sentinel.args.output.enabled=false + +# 启动和关闭Sentinel Metric通过次数统计输出功能。缺失则默认为true +# spring.application.strategy.metric.sentinel.pass.qps.output.enabled=true +# 启动和关闭Sentinel Metric阻塞次数统计输出功能。缺失则默认为true +# spring.application.strategy.metric.sentinel.block.qps.output.enabled=true +# 启动和关闭Sentinel Metric成功次数统计输出功能。缺失则默认为true +# spring.application.strategy.metric.sentinel.success.qps.output.enabled=true +# 启动和关闭Sentinel Metric异常次数统计输出功能。缺失则默认为true +# spring.application.strategy.metric.sentinel.exception.qps.output.enabled=true + +# 启动和关闭Sentinel限流降级熔断权限等原生功能的数据来源扩展。缺失则默认为false +# spring.application.strategy.sentinel.datasource.enabled=true +# 流控规则文件路径。缺失则默认为classpath:sentinel-flow.json +# spring.application.strategy.sentinel.flow.path=classpath:sentinel-flow.json +# 降级规则文件路径。缺失则默认为classpath:sentinel-degrade.json +# spring.application.strategy.sentinel.degrade.path=classpath:sentinel-degrade.json +# 授权规则文件路径。缺失则默认为classpath:sentinel-authority.json +# spring.application.strategy.sentinel.authority.path=classpath:sentinel-authority.json +# 系统规则文件路径。缺失则默认为classpath:sentinel-system.json +# spring.application.strategy.sentinel.system.path=classpath:sentinel-system.json +# 热点参数流控规则文件路径。缺失则默认为classpath:sentinel-param-flow.json +# spring.application.strategy.sentinel.param.flow.path=classpath:sentinel-param-flow.json + +# 启动和关闭消费端的服务隔离(基于Group是否相同的策略)。缺失则默认为false +spring.application.strategy.consumer.isolation.enabled=true + +# 版本故障转移,即无法找到相应版本的服务实例,路由到老的稳定版本的实例。其作用是防止蓝绿灰度版本发布人为设置错误,或者对应的版本实例发生灾难性的全部下线,导致流量有损 +# 在开启版本故障转移的开关前提下,故障转移有三种策略: +# 1. 如果“version-failover”值已配置,指定版本的故障转移,即找不到实例的时候,直接路由到该版本实例 +# 2. 如果“version-failover”值未配置 +# 2.1 开启“version.failover.stable.enabled”开关,版本列表排序策略的(取最老的稳定版本的实例)故障转移,即找不到实例的时候,直接路由到最老的稳定版本的实例 +# 2.2 关闭“version.failover.stable.enabled”开关,负载均衡策略的故障转移,即找不到实例的时候,执行负载均衡策略 +# 启动和关闭版本故障转移。缺失则默认为false +# spring.application.strategy.version.failover.enabled=true +# 开启和关闭版本列表排序策略下取稳定版本的版本故障转移。缺失则默认为false +# spring.application.strategy.version.failover.stable.enabled=true + +# 版本偏好,即非蓝绿灰度发布场景下,路由到老的稳定版本的实例。其作用是防止多个网关上并行实施蓝绿灰度版本发布产生混乱,对处于非蓝绿灰度状态的服务,调用它的时候,只取它的老的稳定版本的实例;蓝绿灰度状态的服务,还是根据传递的Header版本号进行匹配 +# 在开启版本偏好的开关前提下,偏好有两种策略: +# 1. 如果“version-prefer”值已配置,指定版本的偏好,即不管存在多少版本,直接路由到该版本实例 +# 2. 如果“version-prefer”值未配置,版本列表排序策略的(取最老的稳定版本的实例)偏好,即不管存在多少版本,直接路由到最老的稳定版本的实例 +# 启动和关闭版本偏好。缺失则默认为false +# spring.application.strategy.version.prefer.enabled=true + +# 区域调试转移,即当未对服务指定访问区域的时候,转移到事先指定的区域 +# 使用场景示例: +# 开发环境(个人电脑环境)在测试环境(线上环境)进行联调 +# 访问路径为A服务 -> B服务 -> C服务,A服务和B服务在开发环境上,C服务在测试环境上 +# 调用时候,在B服务上进行如下两个配置,并在最前端传入的Header(n-d-region)指定为B的开发环境区域(用来保证A服务和B服务只在开发环境调用),而B服务会自动转移调用到测试环境上的C服务实例,但不会转移到其它个人电脑的C服务实例 +# 该功能的意义,个人电脑环境可以接入到测试环境联调,当多套个人环境接入时候,可以保护不同的个人环境间不会彼此调用 +# 通过“region-transfer”值进行区域转移值配置,如果缺失,则报错 +# 启动和关闭区域调试转移。缺失则默认为false +# spring.application.strategy.region.transfer.enabled=true + +# 在开启区域故障转移的开关前提下,故障转移有两种策略: +# 1. 如果“region-failover”值已配置,指定区域的故障转移,即找不到实例的时候,直接路由到该区域实例 +# 2. 如果“region-failover”值未配置,负载均衡策略的故障转移,即找不到实例的时候,执行负载均衡策略 +# 启动和关闭区域故障转移。缺失则默认为false +# spring.application.strategy.region.failover.enabled=true + +# 启动和关闭环境故障转移。缺失则默认为false +# 如果“env-failover”值未配置,则默认为common +# spring.application.strategy.environment.failover.enabled=true + +# 启动和关闭可用区亲和性,即同一个可用区的服务才能调用,同一个可用区的条件是调用端实例和提供端实例的元数据Metadata的zone配置值必须相等。缺失则默认为false +# spring.application.strategy.zone.affinity.enabled=true + +# 在开启可用区故障转移的开关前提下,故障转移有两种策略: +# 1. 如果“zone-failover”值已配置,指定可用区的故障转移,即找不到实例的时候,直接路由到该可用区实例 +# 2. 如果“zone-failover”值未配置,负载均衡策略的故障转移,即找不到实例的时候,执行负载均衡策略 +# 启动和关闭可用区故障转移。缺失则默认为false +# spring.application.strategy.zone.failover.enabled=true + +# 在开启IP地址和端口故障转移的开关前提下,故障转移有两种策略: +# 1. 如果“address-failover”值已配置,指定IP地址或者端口的故障转移,即找不到实例的时候,直接路由到该IP地址或者端口实例 +# 2. 如果“address-failover”值未配置,负载均衡策略的故障转移,即找不到实例的时候,执行负载均衡策略 +# 启动和关闭IP地址和端口故障转移。缺失则默认为false +# spring.application.strategy.address.failover.enabled=true + +# 版本号排序类型。缺失则默认为version +# 版本故障转移或者版本偏好启动时,需要寻址旧的稳定版本 +# 1. 当排序类型为version时,适用于版本号采用时间戳或者数字递增的方式。处理逻辑为将排序后版本号列表的第一个值作为旧的稳定版本 +# 2. 当排序类型为time时,不限于版本号的格式。处理逻辑为将根据服务实例全局唯一ID的时间戳前缀进行排序,把上线时间最早的服务实例的版本号作为旧的稳定版本 +# spring.application.strategy.version.sort.type=version +# spring.application.strategy.version.sort.type=time + +# 启动和关闭自动扫描目录,当扫描目录未人工配置的时候,可以通过自动扫描方式决定扫描目录。缺失则默认为true +# spring.application.strategy.auto.scan.packages.enabled=true +# 启动和关闭嵌套扫描,嵌套扫描指扫描非本工程下外部包的目录,可以支持多层嵌套。缺失则默认为false +# spring.application.strategy.auto.scan.recursion.enabled=false + +# 开启和关闭使用服务名前缀来作为服务组名。缺失则默认为false +# spring.application.group.generator.enabled=true +# 服务名前缀的截断长度,必须大于0 +# spring.application.group.generator.length=15 +# 服务名前缀的截断标志。当截断长度配置了,则取截断长度方式,否则取截断标志方式 +# spring.application.group.generator.character=- + +# 开启和关闭使用Git信息中的字段单个或者多个组合来作为服务版本号。缺失则默认为false +# spring.application.git.generator.enabled=true +# 插件git-commit-id-plugin产生git信息文件的输出路径,支持properties和json两种格式,支持classpath:xxx和file:xxx两种路径,这些需要和插件里的配置保持一致。缺失则默认为classpath:git.properties +# spring.application.git.generator.path=classpath:git.properties +# spring.application.git.generator.path=classpath:git.json +# 使用Git信息中的字段单个或者多个组合来作为服务版本号。缺失则默认为{git.commit.time}-{git.total.commit.count} +# 日期 + Git提交次数的版本号格式 +# spring.application.git.version.key={git.commit.time}-{git.total.commit.count} +# POM版本号格式 +# spring.application.git.version.key={git.build.version} + +# 下面配置只适用于网关里直接进行Feign、RestTemplate或者WebClient调用场景 +# 启动和关闭路由策略的时候,对REST方式的调用拦截。缺失则默认为true +spring.application.strategy.rest.intercept.enabled=true +# 启动和关闭Header传递的Debug日志打印,注意:每调用一次都会打印一次,会对性能有所影响,建议压测环境和生产环境关闭。缺失则默认为false +spring.application.strategy.rest.intercept.debug.enabled=true +# 启动和关闭Feign上核心策略Header传递,缺失则默认为true。当全局订阅启动时,可以关闭核心策略Header传递,这样可以节省传递数据的大小,一定程度上可以提升性能 +# 核心策略Header指n-d-开头的Header(不包括n-d-env,因为环境路由隔离,必须传递该Header),不包括n-d-service开头的Header +# spring.application.strategy.feign.core.header.transmission.enabled=true +# 启动和关闭RestTemplate上核心策略Header传递,缺失则默认为true。当全局订阅启动时,可以关闭核心策略Header传递,这样可以节省传递数据的大小,一定程度上可以提升性能 +# 核心策略Header指n-d-开头的Header(不包括n-d-env,因为环境路由隔离,必须传递该Header),不包括n-d-service开头的Header +# spring.application.strategy.rest.template.core.header.transmission.enabled=true +# 启动和关闭WebClient上核心策略Header传递,缺失则默认为true。当全局订阅启动时,可以关闭核心策略Header传递,这样可以节省传递数据的大小,一定程度上可以提升性能 +# 核心策略Header指n-d-开头的Header(不包括n-d-env,因为环境路由隔离,必须传递该Header),不包括n-d-service开头的Header +# spring.application.strategy.web.client.core.header.transmission.enabled=true +# 路由策略的时候,对REST方式调用拦截的时候(支持Feign、RestTemplate或者WebClient调用),希望把来自外部自定义的Header参数(用于框架内置上下文Header,例如:trace-id, span-id等)传递到服务里,那么配置如下值。如果多个用“;”分隔,不允许出现空格 +spring.application.strategy.context.request.headers=trace-id;span-id +# 路由策略的时候,对REST方式调用拦截的时候(支持Feign、RestTemplate或者WebClient调用),希望把来自外部自定义的Header参数(用于业务系统自定义Header,例如:mobile)传递到服务里,那么配置如下值。如果多个用“;”分隔,不允许出现空格 +spring.application.strategy.business.request.headers=user;mobile;location + +# 开启和关闭Hystrix线程隔离模式做服务隔离时,对线程切换上下文传递的功能。缺失则默认为false +# Hystrix线程隔离模式做服务隔离时,必须把spring.application.strategy.hystrix.threadlocal.supported设置为true,同时要引入discovery-plugin-strategy-starter-hystrix包,否则线程切换时会发生ThreadLocal上下文对象丢失 +# spring.application.strategy.hystrix.threadlocal.supported=true + +# 启动和关闭服务相关操作端点。缺失则默认为true +# spring.application.admin.service.endpoint.enabled=true +# 启动和关闭配置相关操作端点。缺失则默认为true +# spring.application.admin.config.endpoint.enabled=true +# 启动和关闭版本相关操作端点。缺失则默认为true +# spring.application.admin.version.endpoint.enabled=true +# 启动和关闭侦测相关操作端点。缺失则默认为true +# spring.application.admin.inspector.endpoint.enabled=true +# 启动和关闭路由相关操作端点。缺失则默认为true +# spring.application.admin.router.endpoint.enabled=true +# 启动和关闭策略相关操作端点。缺失则默认为true +# spring.application.admin.strategy.endpoint.enabled=true +# 启动和关闭Sentinel相关操作端点。缺失则默认为true +# spring.application.admin.sentinel.endpoint.enabled=true +# 启动和关闭Git相关操作端点。缺失则默认为true +# spring.application.admin.git.endpoint.enabled=true +# 启动和关闭Spring Cloud Gateway相关操作端点。缺失则默认为true +# spring.application.admin.gateway.endpoint.enabled=true +# 启动和关闭Zuul相关操作端点。缺失则默认为true +# spring.application.admin.zuul.endpoint.enabled=true +# 启动和关闭策略操作端点的验证SPEL表达式方法。缺失则默认为true +# 该端点方法使用Spring StandardEvaluationContext类,StandardEvaluationContext支持全部的Spel语法且功能齐全,但GitHub Security报告其存在一定的注入风险,推荐使用SimpleEvaluationContext,而SimpleEvaluationContext并不能满足当前框架的需求 +# 如果未使用验证SPEL表达式方法,可以通过下面开关关闭在方法在策略端点上的暴露,规避风险 +# spring.application.admin.strategy.endpoint.validate-expression.enabled=true + +# 启动和关闭Swagger。缺失则默认为true +# swagger.enabled=true +# 业务服务Swagger Docket组名 +# swagger.service.group=Your group +# 业务服务Swagger扫描目录 +# swagger.service.packages=your-package1;your-package2 +# 业务服务Swagger描述 +# swagger.service.description=Your service Restful APIs +# 业务服务Swagger版本 +# swagger.service.version=1.0.0 +# 业务服务Swagger License名称 +# swagger.service.license.name=Apache License 2.0 +# 业务服务Swagger License链接 +# swagger.service.license.url=http://www.apache.org/licenses/LICENSE-2.0 +# 业务服务Swagger联系人名称 +# swagger.service.contact.name=Nepxion +# 业务服务Swagger联系人网址 +# swagger.service.contact.url=https://github.com/Nepxion/Discovery +# 业务服务Swagger联系人邮件 +# swagger.service.contact.email=1394997@qq.com +# 业务服务Swagger服务条件网址 +# swagger.service.termsOfService.url=http://nepxion.com/discovery + +# Zuul config +zuul.host.max-per-route-connections=1000 +zuul.host.max-total-connections=1000 +zuul.semaphore.max-semaphores=5000 + +# zuul.ribbon-isolation-strategy=THREAD + +# zuul.prefix=/api + +# 开启和关闭自动路由。缺失则默认开启自动路由 +zuul.ignoredServices=* + +# 手工配置路由。自动路由和手工动态路由允许混合使用 +zuul.routes.route0.path=/discovery-springcloud-example-a/** +zuul.routes.route0.serviceId=discovery-springcloud-example-a +zuul.routes.route1.path=/x/** +zuul.routes.route1.serviceId=discovery-springcloud-example-a +zuul.routes.route2.path=/y/** +zuul.routes.route2.serviceId=discovery-springcloud-example-a \ No newline at end of file diff --git a/discovery-springcloud-examples/discovery-springcloud-example-zuul/src/main/resources/dynamic-route-complete.json b/discovery-springcloud-examples/discovery-springcloud-example-zuul/src/main/resources/dynamic-route-complete.json new file mode 100644 index 0000000000..12d6843047 --- /dev/null +++ b/discovery-springcloud-examples/discovery-springcloud-example-zuul/src/main/resources/dynamic-route-complete.json @@ -0,0 +1,32 @@ +[ + { + "id": "route0", + "serviceId": "discovery-springcloud-example-a", + "path": "/discovery-springcloud-example-a/**", + "url": null, + "stripPrefix": true, + "retryable": null, + "sensitiveHeaders": [], + "customSensitiveHeaders": false + }, + { + "id": "route1", + "serviceId": "discovery-springcloud-example-a", + "path": "/x/**", + "url": null, + "stripPrefix": true, + "retryable": null, + "sensitiveHeaders": [], + "customSensitiveHeaders": false + }, + { + "id": "route2", + "serviceId": "discovery-springcloud-example-a", + "path": "/y/**", + "url": null, + "stripPrefix": true, + "retryable": null, + "sensitiveHeaders": [], + "customSensitiveHeaders": false + } +] \ No newline at end of file diff --git a/discovery-springcloud-examples/discovery-springcloud-example-zuul/src/main/resources/dynamic-route-simple.json b/discovery-springcloud-examples/discovery-springcloud-example-zuul/src/main/resources/dynamic-route-simple.json new file mode 100644 index 0000000000..ddc0cbdc92 --- /dev/null +++ b/discovery-springcloud-examples/discovery-springcloud-example-zuul/src/main/resources/dynamic-route-simple.json @@ -0,0 +1,17 @@ +[ + { + "id": "route0", + "serviceId": "discovery-springcloud-example-a", + "path": "/discovery-springcloud-example-a/**" + }, + { + "id": "route1", + "serviceId": "discovery-springcloud-example-a", + "path": "/x/**" + }, + { + "id": "route2", + "serviceId": "discovery-springcloud-example-a", + "path": "/y/**" + } +] \ No newline at end of file diff --git a/discovery-springcloud-examples/discovery-springcloud-example-zuul/src/main/resources/logback.xml b/discovery-springcloud-examples/discovery-springcloud-example-zuul/src/main/resources/logback.xml new file mode 100644 index 0000000000..c37b63f8e2 --- /dev/null +++ b/discovery-springcloud-examples/discovery-springcloud-example-zuul/src/main/resources/logback.xml @@ -0,0 +1,50 @@ + + + + + + + %d{yyyy-MM-dd HH:mm:ss.SSS} %5p ${PID:- } --- [%15.15t] %-40.40logger{39} : %msg%n + + UTF-8 + + + log/discovery-%d{yyyy-MM-dd}.%i.log + 50MB + + + INFO + + + true + + + + 0 + 512 + + + + + + + + + %d{yyyy-MM-dd HH:mm:ss.SSS} %levelColor(%5p) %magenta(${PID:- }) --- [%15.15t] %cyan(%-40.40logger{39}) : %msg%n + + + + INFO + + + + + + + + + + + + + \ No newline at end of file diff --git a/discovery-springcloud-example-zuul/src/main/resources/rule.json b/discovery-springcloud-examples/discovery-springcloud-example-zuul/src/main/resources/rule.json similarity index 100% rename from discovery-springcloud-example-zuul/src/main/resources/rule.json rename to discovery-springcloud-examples/discovery-springcloud-example-zuul/src/main/resources/rule.json diff --git a/discovery-springcloud-example-zuul/src/main/resources/rule.xml b/discovery-springcloud-examples/discovery-springcloud-example-zuul/src/main/resources/rule.xml similarity index 100% rename from discovery-springcloud-example-zuul/src/main/resources/rule.xml rename to discovery-springcloud-examples/discovery-springcloud-example-zuul/src/main/resources/rule.xml diff --git a/discovery-springcloud-examples/pom.xml b/discovery-springcloud-examples/pom.xml new file mode 100644 index 0000000000..1ce4877492 --- /dev/null +++ b/discovery-springcloud-examples/pom.xml @@ -0,0 +1,41 @@ + + + discovery-springcloud-examples + Nepxion Discovery Spring Cloud Examples + pom + 4.0.0 + Nepxion Discovery is a solution for Spring Cloud with blue green, gray, weight, limitation, circuit breaker, degrade, isolation, monitor, tracing, dye, failover, async agent + http://www.nepxion.com + + + com.nepxion + discovery + 6.23.0 + + + + discovery-springcloud-example-admin + discovery-springcloud-example-console + discovery-springcloud-example-eureka + discovery-springcloud-example-service + discovery-springcloud-example-zuul + discovery-springcloud-example-gateway + + + + 2.3.1 + + + + + + de.codecentric + spring-boot-admin-dependencies + ${spring.boot.admin.version} + pom + import + + + + \ No newline at end of file diff --git a/discovery-springcloud-postman/Nepxion.postman_collection.json b/discovery-springcloud-postman/Nepxion.postman_collection.json deleted file mode 100644 index fb6fb11643..0000000000 --- a/discovery-springcloud-postman/Nepxion.postman_collection.json +++ /dev/null @@ -1,726 +0,0 @@ -{ - "info": { - "_postman_id": "3aa0b5a1-940e-40e8-8f9c-ccaa4de8a084", - "name": "Nepxion", - "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json" - }, - "item": [ - { - "name": "Discovery服务接口", - "item": [ - { - "name": "查看本地和更新的规则配置信息", - "request": { - "method": "GET", - "header": [], - "url": { - "raw": "http://localhost:1100/config/view", - "protocol": "http", - "host": [ - "localhost" - ], - "port": "1100", - "path": [ - "config", - "view" - ] - } - }, - "response": [] - }, - { - "name": "查看服务的本地版本和动态版本", - "request": { - "method": "GET", - "header": [], - "url": { - "raw": "http://localhost:1100/version/view", - "protocol": "http", - "host": [ - "localhost" - ], - "port": "1100", - "path": [ - "version", - "view" - ] - } - }, - "response": [] - }, - { - "name": "获取全路径的路由信息树", - "request": { - "method": "POST", - "header": [], - "body": { - "mode": "raw", - "raw": "discovery-springcloud-example-b;discovery-springcloud-example-c" - }, - "url": { - "raw": "http://localhost:1100/router/routes/", - "protocol": "http", - "host": [ - "localhost" - ], - "port": "1100", - "path": [ - "router", - "routes", - "" - ] - } - }, - "response": [] - }, - { - "name": "服务调用示例", - "request": { - "method": "POST", - "header": [], - "body": { - "mode": "raw", - "raw": "Start" - }, - "url": { - "raw": "http://localhost:1100/invoke", - "protocol": "http", - "host": [ - "localhost" - ], - "port": "1100", - "path": [ - "invoke" - ] - } - }, - "response": [] - } - ], - "event": [ - { - "listen": "prerequest", - "script": { - "id": "9c473e26-3065-49ef-bb64-718d1f8917ec", - "type": "text/javascript", - "exec": [ - "" - ] - } - }, - { - "listen": "test", - "script": { - "id": "a7fbb188-ca44-423d-b345-85a27a88eaef", - "type": "text/javascript", - "exec": [ - "" - ] - } - } - ] - }, - { - "name": "Discovery控制台接口", - "item": [ - { - "name": "批量同步推送更新规则配置信息", - "request": { - "method": "POST", - "header": [], - "body": { - "mode": "raw", - "raw": "\r\n\r\n \r\n \r\n \r\n \r\n \r\n" - }, - "url": { - "raw": "http://localhost:2222/console/config/update-sync/discovery-springcloud-example-b", - "protocol": "http", - "host": [ - "localhost" - ], - "port": "2222", - "path": [ - "console", - "config", - "update-sync", - "discovery-springcloud-example-b" - ] - } - }, - "response": [] - }, - { - "name": "批量同步清除更新的规则配置信息", - "request": { - "method": "POST", - "header": [], - "body": { - "mode": "raw", - "raw": "" - }, - "url": { - "raw": "http://localhost:2222/console/config/clear-sync/discovery-springcloud-example-b", - "protocol": "http", - "host": [ - "localhost" - ], - "port": "2222", - "path": [ - "console", - "config", - "clear-sync", - "discovery-springcloud-example-b" - ] - } - }, - "response": [] - }, - { - "name": "批量同步更新服务的动态版本", - "request": { - "method": "POST", - "header": [], - "body": { - "mode": "raw", - "raw": "1.1" - }, - "url": { - "raw": "http://localhost:2222/console/version/update-sync/discovery-springcloud-example-zuul", - "protocol": "http", - "host": [ - "localhost" - ], - "port": "2222", - "path": [ - "console", - "version", - "update-sync", - "discovery-springcloud-example-zuul" - ] - } - }, - "response": [] - }, - { - "name": "批量同步清除服务的动态版本", - "request": { - "method": "POST", - "header": [], - "body": { - "mode": "raw", - "raw": "" - }, - "url": { - "raw": "http://localhost:2222/console/version/clear-sync/discovery-springcloud-example-zuul", - "protocol": "http", - "host": [ - "localhost" - ], - "port": "2222", - "path": [ - "console", - "version", - "clear-sync", - "discovery-springcloud-example-zuul" - ] - } - }, - "response": [] - }, - { - "name": "推送更新规则配置信息到远程配置中心", - "request": { - "method": "POST", - "header": [], - "body": { - "mode": "raw", - "raw": "\r\n\r\n \r\n \r\n \r\n \r\n \r\n" - }, - "url": { - "raw": "http://localhost:2222/console/remote-config/update/example-service-group/discovery-springcloud-example-b", - "protocol": "http", - "host": [ - "localhost" - ], - "port": "2222", - "path": [ - "console", - "remote-config", - "update", - "example-service-group", - "discovery-springcloud-example-b" - ] - } - }, - "response": [] - }, - { - "name": "清除规则配置信息到远程配置中心", - "request": { - "method": "POST", - "header": [], - "body": { - "mode": "raw", - "raw": "" - }, - "url": { - "raw": "http://localhost:2222/console/remote-config/clear/example-service-group/discovery-springcloud-example-b", - "protocol": "http", - "host": [ - "localhost" - ], - "port": "2222", - "path": [ - "console", - "remote-config", - "clear", - "example-service-group", - "discovery-springcloud-example-b" - ] - } - }, - "response": [] - }, - { - "name": "查看远程配置中心的规则配置信息", - "request": { - "method": "GET", - "header": [], - "url": { - "raw": "http://localhost:2222/console/remote-config/view/example-service-group/discovery-springcloud-example-b", - "protocol": "http", - "host": [ - "localhost" - ], - "port": "2222", - "path": [ - "console", - "remote-config", - "view", - "example-service-group", - "discovery-springcloud-example-b" - ] - } - }, - "response": [] - } - ] - }, - { - "name": "Discovery网关接口", - "item": [ - { - "name": "Zuul网关获取全路径的路由信息树", - "request": { - "method": "POST", - "header": [], - "body": { - "mode": "raw", - "raw": "discovery-springcloud-example-a;discovery-springcloud-example-b;discovery-springcloud-example-c" - }, - "url": { - "raw": "http://localhost:1400/router/routes/", - "protocol": "http", - "host": [ - "localhost" - ], - "port": "1400", - "path": [ - "router", - "routes", - "" - ] - } - }, - "response": [] - }, - { - "name": "Gateway网关获取全路径的路由信息树", - "request": { - "method": "POST", - "header": [], - "body": { - "mode": "raw", - "raw": "discovery-springcloud-example-a;discovery-springcloud-example-b;discovery-springcloud-example-c" - }, - "url": { - "raw": "http://localhost:1500/router/routes/", - "protocol": "http", - "host": [ - "localhost" - ], - "port": "1500", - "path": [ - "router", - "routes", - "" - ] - } - }, - "response": [] - }, - { - "name": "Zuul网关调用示例", - "request": { - "method": "POST", - "header": [ - { - "key": "n-d-version", - "value": "{\"discovery-springcloud-example-a\":\"1.0\", \"discovery-springcloud-example-b\":\"1.0\", \"discovery-springcloud-example-c\":\"1.0;1.2\"}", - "disabled": true - }, - { - "key": "n-d-region", - "value": "{\"discovery-springcloud-example-a\":\"qa;dev\", \"discovery-springcloud-example-b\":\"dev\", \"discovery-springcloud-example-c\":\"qa\"}", - "disabled": true - }, - { - "key": "n-d-address", - "value": "{\"discovery-springcloud-example-a\":\"192.168.43.101:1100\", \"discovery-springcloud-example-b\":\"192.168.43.101:1201\", \"discovery-springcloud-example-c\":\"192.168.43.101:1300\"}", - "type": "text", - "disabled": true - }, - { - "key": "n-d-version-weight", - "value": "{\"discovery-springcloud-example-a\":\"1.0=90;1.1=10\", \"discovery-springcloud-example-b\":\"1.0=90;1.1=10\", \"discovery-springcloud-example-c\":\"1.0=90;1.1=10\"}", - "type": "text", - "disabled": true - }, - { - "key": "n-d-region-weight", - "value": "dev=85;qa=15", - "type": "text", - "disabled": true - }, - { - "key": "mobile", - "value": "138", - "type": "text", - "disabled": true - }, - { - "key": "user", - "value": "lisi", - "type": "text", - "disabled": true - }, - { - "key": "token", - "value": "ab", - "type": "text", - "disabled": true - } - ], - "body": { - "mode": "raw", - "raw": "ab" - }, - "url": { - "raw": "http://localhost:1400/discovery-springcloud-example-a/invoke", - "protocol": "http", - "host": [ - "localhost" - ], - "port": "1400", - "path": [ - "discovery-springcloud-example-a", - "invoke" - ] - } - }, - "response": [] - }, - { - "name": "Gateway网关调用示例", - "request": { - "method": "POST", - "header": [ - { - "key": "n-d-version", - "value": "{\"discovery-springcloud-example-a\":\"1.0\", \"discovery-springcloud-example-b\":\"1.0\", \"discovery-springcloud-example-c\":\"1.0;1.2\"}", - "disabled": true - }, - { - "key": "n-d-region", - "value": "{\"discovery-springcloud-example-a\":\"qa;dev\", \"discovery-springcloud-example-b\":\"dev\", \"discovery-springcloud-example-c\":\"qa\"}", - "disabled": true - }, - { - "key": "n-d-address", - "value": "{\"discovery-springcloud-example-a\":\"192.168.43.101:1100\", \"discovery-springcloud-example-b\":\"192.168.43.101:1201\", \"discovery-springcloud-example-c\":\"192.168.43.101:1300\"}", - "type": "text", - "disabled": true - }, - { - "key": "n-d-version-weight", - "value": "{\"discovery-springcloud-example-a\":\"1.0=90;1.1=10\", \"discovery-springcloud-example-b\":\"1.0=90;1.1=10\", \"discovery-springcloud-example-c\":\"1.0=90;1.1=10\"}", - "type": "text", - "disabled": true - }, - { - "key": "n-d-region-weight", - "value": "dev=85;qa=15", - "type": "text", - "disabled": true - }, - { - "key": "mobile", - "value": "133", - "type": "text", - "disabled": true - }, - { - "key": "user", - "value": "zhangsan", - "type": "text", - "disabled": true - }, - { - "key": "token", - "value": "ab", - "type": "text", - "disabled": true - } - ], - "body": { - "mode": "raw", - "raw": "ab" - }, - "url": { - "raw": "http://localhost:1500/discovery-springcloud-example-a/invoke", - "protocol": "http", - "host": [ - "localhost" - ], - "port": "1500", - "path": [ - "discovery-springcloud-example-a", - "invoke" - ] - } - }, - "response": [] - } - ] - }, - { - "name": "Discovery极简示例接口", - "item": [ - { - "name": "Zuul网关调用示例", - "request": { - "method": "GET", - "header": [ - { - "key": "n-d-version", - "value": "{\"discovery-gray-service-a\":\"1.0\", \"discovery-gray-service-b\":\"1.0\"}", - "type": "text", - "disabled": true - }, - { - "key": "n-d-region", - "value": "qa", - "type": "text", - "disabled": true - }, - { - "key": "n-d-version-weight", - "value": "{\"discovery-gray-service-a\":\"1.0=90;1.1=10\", \"discovery-gray-service-b\":\"1.0=90;1.1=10\"}", - "type": "text", - "disabled": true - }, - { - "key": "n-d-region-weight", - "value": "dev=99;qa=1", - "type": "text", - "disabled": true - }, - { - "key": "mobile", - "value": "138", - "type": "text", - "disabled": true - }, - { - "key": "user", - "value": "lisi", - "type": "text", - "disabled": true - }, - { - "key": "a", - "value": "1", - "type": "text", - "disabled": true - }, - { - "key": "b", - "value": "2", - "type": "text", - "disabled": true - } - ], - "url": { - "raw": "http://localhost:5002/discovery-gray-service-a/invoke/zuul", - "protocol": "http", - "host": [ - "localhost" - ], - "port": "5002", - "path": [ - "discovery-gray-service-a", - "invoke", - "zuul" - ] - } - }, - "response": [] - }, - { - "name": "Gateway网关调用示例", - "request": { - "method": "GET", - "header": [ - { - "key": "n-d-version", - "value": "{\"discovery-gray-service-a\":\"1.0\", \"discovery-gray-service-b\":\"1.0\"}", - "type": "text", - "disabled": true - }, - { - "key": "n-d-region", - "value": "qa", - "type": "text", - "disabled": true - }, - { - "key": "n-d-version-weight", - "value": "{\"discovery-gray-service-a\":\"1.0=90;1.1=10\", \"discovery-gray-service-b\":\"1.0=90;1.1=10\"}", - "type": "text", - "disabled": true - }, - { - "key": "n-d-region-weight", - "value": "dev=99;qa=1", - "type": "text", - "disabled": true - }, - { - "key": "mobile", - "value": "133", - "type": "text", - "disabled": true - }, - { - "key": "user", - "value": "zhangsan", - "type": "text", - "disabled": true - }, - { - "key": "a", - "value": "1", - "type": "text", - "disabled": true - }, - { - "key": "b", - "value": "2", - "type": "text", - "disabled": true - } - ], - "url": { - "raw": "http://localhost:5001/discovery-gray-service-a/invoke/gateway", - "protocol": "http", - "host": [ - "localhost" - ], - "port": "5001", - "path": [ - "discovery-gray-service-a", - "invoke", - "gateway" - ] - } - }, - "response": [] - } - ] - }, - { - "name": "Nacos服务接口", - "item": [ - { - "name": "获取服务实例", - "request": { - "method": "GET", - "header": [], - "url": { - "raw": "http://127.0.0.1:8848/nacos/v1/ns/instances?serviceName=discovery-springcloud-example-c", - "protocol": "http", - "host": [ - "127", - "0", - "0", - "1" - ], - "port": "8848", - "path": [ - "nacos", - "v1", - "ns", - "instances" - ], - "query": [ - { - "key": "serviceName", - "value": "discovery-springcloud-example-c" - } - ] - } - }, - "response": [] - } - ] - }, - { - "name": "Permission服务接口", - "item": [ - { - "name": "权限验证调用", - "request": { - "method": "GET", - "header": [ - { - "key": "token", - "value": "abcd12345" - }, - { - "key": "user-id", - "value": "lisi" - }, - { - "key": "user-type", - "value": "LDAP" - } - ], - "url": { - "raw": "http://localhost:1212/doC/abc", - "protocol": "http", - "host": [ - "localhost" - ], - "port": "1212", - "path": [ - "doC", - "abc" - ] - } - }, - "response": [] - } - ] - } - ] -} \ No newline at end of file diff --git a/install.bat b/install.bat new file mode 100644 index 0000000000..5d08e5bfbc --- /dev/null +++ b/install.bat @@ -0,0 +1,20 @@ +@echo on +@echo ============================================================= +@echo $ $ +@echo $ Nepxion Discovery $ +@echo $ $ +@echo $ $ +@echo $ $ +@echo $ Nepxion Studio All Right Reserved $ +@echo $ Copyright (C) 2017-2050 $ +@echo $ $ +@echo ============================================================= +@echo. +@echo off + +@title Nepxion Discovery +@color 0a + +call mvn clean install -DskipTests + +pause \ No newline at end of file diff --git a/pmd.xml b/pmd.xml new file mode 100644 index 0000000000..e49f95e2a1 --- /dev/null +++ b/pmd.xml @@ -0,0 +1,99 @@ + + + + Exclude noisy rules. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/pom.xml b/pom.xml index 2ac31724ce..d53e62e9dd 100644 --- a/pom.xml +++ b/pom.xml @@ -6,64 +6,46 @@ Nepxion Discovery pom 4.0.0 - 5.2.0-SNAPSHOT - Nepxion Discovery is an enhancement for Spring Cloud Discovery + 6.23.0 + Nepxion Discovery is a solution for Spring Cloud with blue green, gray, weight, limitation, circuit breaker, degrade, isolation, monitor, tracing, dye, failover, async agent http://www.nepxion.com - discovery-common - discovery-common-apollo - discovery-common-nacos - discovery-common-redis + discovery-commons discovery-plugin-framework - discovery-plugin-framework-eureka - discovery-plugin-framework-consul - discovery-plugin-framework-zookeeper - discovery-plugin-framework-nacos + discovery-plugin-register-center discovery-plugin-config-center - discovery-plugin-config-center-starter-apollo - discovery-plugin-config-center-starter-nacos - discovery-plugin-config-center-starter-redis discovery-plugin-admin-center - discovery-plugin-starter-eureka - discovery-plugin-starter-consul - discovery-plugin-starter-zookeeper - discovery-plugin-starter-nacos discovery-plugin-strategy - discovery-plugin-strategy-starter-service - discovery-plugin-strategy-starter-zuul - discovery-plugin-strategy-starter-gateway - discovery-plugin-strategy-starter-hystrix + discovery-plugin-test discovery-console - discovery-console-starter-apollo - discovery-console-starter-nacos - discovery-console-starter-redis - discovery-console-desktop - discovery-springcloud-example-admin - discovery-springcloud-example-console - discovery-springcloud-example-eureka - discovery-springcloud-example-service - discovery-springcloud-example-zuul - discovery-springcloud-example-gateway + discovery-springcloud-examples - 2.0.11 - 2.0.7 + 2.0.15 + 2.0.9 1.0.2 + 1.3.2 3.6 4.1 2.5 - 1.6.1 - 1.4.0 - 1.0.0 - 27.0-jre - 2.7.0 - 2.7.0 - Greenwich.SR2 - 0.9.0.RELEASE - 2.1.6.RELEASE - 3.3.7 + 31.1-jre + 2.9.3 + 2.1.4 + 1.5.21 + 2.9.2 + 1.9.2 + 4.3.0 + 1.4.5 + 0.5.11 + 1.24.0 + 0.33.0 + 8.14.0 + 1.0.11 + Hoxton.SR12 + 2.2.10 + 2.3.12.RELEASE 1.8 UTF-8 @@ -96,37 +78,67 @@ ${project.groupId} - discovery-plugin-framework + discovery-common-zookeeper ${project.version} ${project.groupId} - discovery-plugin-framework-eureka + discovery-common-consul ${project.version} ${project.groupId} - discovery-plugin-framework-consul + discovery-common-etcd ${project.version} ${project.groupId} - discovery-plugin-framework-zookeeper + discovery-plugin-framework-starter ${project.version} ${project.groupId} - discovery-plugin-framework-nacos + discovery-plugin-framework-starter-parser ${project.version} ${project.groupId} - discovery-plugin-config-center + discovery-plugin-register-center-starter + ${project.version} + + + + ${project.groupId} + discovery-plugin-register-center-starter-eureka + ${project.version} + + + + ${project.groupId} + discovery-plugin-register-center-starter-consul + ${project.version} + + + + ${project.groupId} + discovery-plugin-register-center-starter-zookeeper + ${project.version} + + + + ${project.groupId} + discovery-plugin-register-center-starter-nacos + ${project.version} + + + + ${project.groupId} + discovery-plugin-config-center-starter ${project.version} @@ -150,37 +162,37 @@ ${project.groupId} - discovery-plugin-admin-center + discovery-plugin-config-center-starter-zookeeper ${project.version} ${project.groupId} - discovery-plugin-starter-eureka + discovery-plugin-config-center-starter-consul ${project.version} ${project.groupId} - discovery-plugin-starter-consul + discovery-plugin-config-center-starter-etcd ${project.version} ${project.groupId} - discovery-plugin-starter-zookeeper + discovery-plugin-admin-center-starter ${project.version} ${project.groupId} - discovery-plugin-starter-nacos + discovery-plugin-admin-center-starter-swagger ${project.version} ${project.groupId} - discovery-plugin-strategy + discovery-plugin-strategy-starter ${project.version} @@ -210,7 +222,73 @@ ${project.groupId} - discovery-console + discovery-plugin-strategy-starter-opentelemetry + ${project.version} + + + + ${project.groupId} + discovery-plugin-strategy-starter-opentracing + ${project.version} + + + + ${project.groupId} + discovery-plugin-strategy-starter-skywalking + ${project.version} + + + + ${project.groupId} + discovery-plugin-strategy-starter-sentinel-datasource + ${project.version} + + + + ${project.groupId} + discovery-plugin-strategy-starter-sentinel-limiter + ${project.version} + + + + ${project.groupId} + discovery-plugin-strategy-starter-sentinel-monitor + ${project.version} + + + + ${project.groupId} + discovery-plugin-strategy-starter-sentinel-opentelemetry + ${project.version} + + + + ${project.groupId} + discovery-plugin-strategy-starter-sentinel-opentracing + ${project.version} + + + + ${project.groupId} + discovery-plugin-strategy-starter-sentinel-skywalking + ${project.version} + + + + ${project.groupId} + discovery-plugin-strategy-starter-sentinel-micrometer + ${project.version} + + + + ${project.groupId} + discovery-plugin-test-starter-automation + ${project.version} + + + + ${project.groupId} + discovery-console-starter ${project.version} @@ -232,6 +310,24 @@ ${project.version} + + ${project.groupId} + discovery-console-starter-zookeeper + ${project.version} + + + + ${project.groupId} + discovery-console-starter-consul + ${project.version} + + + + ${project.groupId} + discovery-console-starter-etcd + ${project.version} + + ${project.groupId} eventbus-aop-starter @@ -250,6 +346,12 @@ ${banner.version} + + javax.annotation + javax.annotation-api + ${javax.annotation.version} + + org.apache.commons commons-lang3 @@ -281,11 +383,35 @@ - dom4j + org.dom4j dom4j ${dom4j.version} + + io.swagger + swagger-annotations + ${swagger.version} + + + + io.swagger + swagger-models + ${swagger.version} + + + + io.springfox + springfox-swagger2 + ${springfox.swagger.version} + + + + io.springfox + springfox-swagger-ui + ${springfox.swagger.version} + + com.ctrip.framework.apollo apollo-client @@ -299,21 +425,33 @@ - com.alibaba.nacos - nacos-client - ${nacos.client.version} + org.apache.curator + curator-framework + ${zookeeper.curator.version} - io.springfox - springfox-swagger2 - ${swagger.version} + org.apache.curator + curator-recipes + ${zookeeper.curator.version} - io.springfox - springfox-swagger-ui - ${swagger.version} + com.ecwid.consul + consul-api + ${consul.version} + + + + io.etcd + jetcd-core + ${jetcd.version} + + + + com.alibaba.spring + spring-context-support + ${alibaba.spring.version} @@ -325,7 +463,7 @@ - org.springframework.cloud + com.alibaba.cloud spring-cloud-alibaba-dependencies ${spring.cloud.alibaba.version} pom @@ -342,27 +480,6 @@ - - - com.lmax - disruptor - ${disruptor.version} - provided - - - - org.apache.logging.log4j - log4j-1.2-api - provided - - - - org.apache.logging.log4j - log4j-slf4j-impl - provided - - - diff --git a/version.bat b/version.bat index 7eb16433d9..d9e5a3bb5f 100644 --- a/version.bat +++ b/version.bat @@ -15,6 +15,5 @@ @title Nepxion Discovery @color 0a -call mvn versions:set -DnewVersion=5.2.0-SNAPSHOT - +call mvn versions:set -DgenerateBackupPoms=false -DnewVersion=6.23.0 pause \ No newline at end of file