1
0
mirror of https://gitee.com/mirrors/Spring-Cloud-Alibaba.git synced 2021-06-26 13:25:11 +08:00

Merge pull request #398 from fangjian0423/master

Refactor something about SMS & Sentinel
This commit is contained in:
format 2019-03-05 19:27:26 +08:00 committed by GitHub
commit 3b3c60fbc7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
18 changed files with 461 additions and 239 deletions

View File

@ -272,6 +272,7 @@ Sentinel Endpoint 里暴露的信息非常有用。包括当前应用的所有
|`spring.cloud.sentinel.transport.client-ip`|客户端IP|
|`spring.cloud.sentinel.filter.order`|Servlet Filter的加载顺序。Starter内部会构造这个filter|Integer.MIN_VALUE
|`spring.cloud.sentinel.filter.url-patterns`|数据类型是数组。表示Servlet Filter的url pattern集合|/*
|`spring.cloud.sentinel.filter.enabled`|Enable to instance CommonFilter|true
|`spring.cloud.sentinel.metric.charset`|metric文件字符集|UTF-8
|`spring.cloud.sentinel.metric.file-single-size`|Sentinel metric 单个文件的大小|
|`spring.cloud.sentinel.metric.file-total-count`|Sentinel metric 总文件数量|

View File

@ -10,17 +10,10 @@ Spring Cloud Alibaba 已经发布了 0.2.2.BUILD-SNAPSHOT 版本,需要首先
----
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Finchley.SR2</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<version>0.2.2.BUILD-SNAPSHOT</version>
<version>0.2.0.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
@ -55,7 +48,7 @@ access-key 和 secret-key 是阿里云账号的 AK/SK需要首先注册阿里
==== 引入 SMS API
Spring Cloud Alicloud SMS 中的 SMS API 基于阿里云官方 SMS SDK 提供,具备单个短信发送、多个短信批量发送、短信查询、短信消息(`短信回执消息``上行短信消息`) 类行操作API。
Spring Cloud Alicloud SMS 中的 SMS API 基于阿里云官方 SMS SDK 提供,具备单个短信发送、多个短信批量发送、短信查询、短信消息(短信回执消息 和 上行短信消息) 类行操作API。
一个简单的使用 SMS API 发送短信的应用如下。
@ -67,13 +60,7 @@ public class SmsApplication {
@Autowired
private ISmsService smsService;
/**
* 短信发送 Example
* @param code
* @return
*/
@RequestMapping("/batch-sms-send.do")
public SendBatchSmsResponse batchsendCheckCode(
@RequestParam(name = "code") String code) {
@ -99,7 +86,6 @@ public class SmsApplication {
}
public static void main(String[] args) throws URISyntaxException {
SpringApplication.run(SmsApplication.class, args);
}
@ -119,15 +105,10 @@ Spring Cloud Alicloud SMS 封装的 API 接口为了降低学习的成本,尽
* 批量短信发送
参考以下的 Example ,来快速开发一个具有批量短信发送的功能。在 Controller 中或者新建一个 Controler 新增如下代码:
参考以下的 Example ,来快速开发一个具有批量短信发送的功能。在 Controller 中或者新建一个 Controller 新增如下代码:
[source,java]
----
/**
* 批量短信发送 Example
* @param code
* @return
*/
@RequestMapping("/batch-sms-send.do")
public SendBatchSmsResponse batchsendCheckCode(
@RequestParam(name = "code") String code) {
@ -165,16 +146,10 @@ NOTE: 这里设置请求的 MethodType 为 GET和官网给出的例子还有
* 短信查询
参考以下的 Example ,可以快速开发根据某个指定的号码查询短信历史发送状态。在 Controller 中或者新建一个 Controler 新增如下代码:
参考以下的 Example ,可以快速开发根据某个指定的号码查询短信历史发送状态。在 Controller 中或者新建一个 Controller 新增如下代码:
[source,java]
----
/**
*
* 短信查询 Example
* @param telephone
* @return
*/
@RequestMapping("/query.do")
public QuerySendDetailsResponse querySendDetailsResponse(
@RequestParam(name = "tel") String telephone) {
@ -241,7 +216,7 @@ public class SmsReportMessageListener
* 上行短信消息
通过订阅SmsUp上行短信消息可以获知终端用户回复短信的内容。这些工作也已经被 Spring Cloud AliCloud SMS 封装好了。你只需要完成以下两步即可。
通过订阅 SmsUp 上行短信消息,可以获知终端用户回复短信的内容。这些工作也已经被 Spring Cloud AliCloud SMS 封装好了。你只需要完成以下两步即可。
1、 在 `application.properties` 配置文件中(也可以是 application.yaml)配置 SmsReport 的队列名称。

View File

@ -271,6 +271,7 @@ The following table shows all the configurations of Spring Cloud Alibaba Sentine
|`spring.cloud.sentinel.transport.client-ip`|Client IP|
|`spring.cloud.sentinel.filter.order`|Loading order of Servlet Filter. The filter will be constructed in the Starter|Integer.MIN_VALUE
|`spring.cloud.sentinel.filter.url-patterns`|Data type is array. Refers to the collection of Servlet Filter ULR patterns|/*
|`spring.cloud.sentinel.filter.enabled`|Enable to instance CommonFilter|true
|`spring.cloud.sentinel.metric.charset`|metric file character set|UTF-8
|`spring.cloud.sentinel.metric.fileSingleSize`|Sentinel metric single file size|
|`spring.cloud.sentinel.metric.fileTotalCount`|Sentinel metric total file number|

View File

@ -0,0 +1,226 @@
== Spring Cloud Alibaba Cloud SMS
SMSShort Message Serviceis a messaging service that covers the globe, Alibaba SMS provides convenient, efficient, and intelligent communication capabilities that help businesses quickly contact their customers.
Spring Cloud AliCloud SMS provide an easier-to-use API for quick access to Alibaba Cloud's SMS service based on Spring Cloud Alibaba SMS.
=== 如何引入 Spring Cloud AliCloud SMS
Weve released Spring Cloud Alibaba version 0.2.0. You will need to add dependency management POM first.
[source,xml]
----
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<version>0.2.0.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
----
Next we need to introduce Spring Cloud Alibaba Cloud SMS Starter.
[source,xml]
----
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-alicloud-sms</artifactId>
</dependency>
----
=== How to use SMS API
==== Configure SMS
Before you start to use Spring Cloud Alibaba Cloud SMS, please add the following configurations in application.properties.
[source,properties]
----
spring.cloud.alicloud.access-key=AK
spring.cloud.alicloud.secret-key=SK
----
access-key and secret-key is the AK/SK of your Alibaba Cloud account. If you dont have one, please register an account first, and log on to https://usercenter.console.aliyun.com/#/manage/ak[Alibaba Cloud AK/SK Management] to get your AccessKey ID and Access Key Secret . If you havent create the AccessKeys, click “Create AccessKey” to create one.
==== Introduce SMS API
The SMS API in Spring Cloud Alicloud SMS is based on Alibaba Cloud SMS SDK. It has a single SMS sending, multiple SMS bulk sending, SMS query, SMS message (SMS receipt message and Upstream SMS message) class operation API.
The following is a simple example of how to use SMS api to send short message:
[source,java]
----
@SpringBootApplication
public class SmsApplication {
@Autowired
private ISmsService smsService;
@RequestMapping("/batch-sms-send.do")
public SendBatchSmsResponse batchsendCheckCode(
@RequestParam(name = "code") String code) {
SendSmsRequest request = new SendSmsRequest();
// Required:the mobile number
request.setPhoneNumbers("152******");
// Required:SMS-SignName-could be found in sms console
request.setSignName("******");
// Required:Template-could be found in sms console
request.setTemplateCode("******");
// Required:The param of sms template.For exmaple, if the template is "Hello,your verification code is ${code}". The param should be like following value
request.setTemplateParam("{\"code\":\"" + code + "\"}");
SendSmsResponse sendSmsResponse ;
try {
sendSmsResponse = smsService.sendSmsRequest(request);
}
catch (ClientException e) {
e.printStackTrace();
sendSmsResponse = new SendSmsResponse();
}
return sendSmsResponse ;
}
public static void main(String[] args) throws URISyntaxException {
SpringApplication.run(SmsApplication.class, args);
}
}
----
Before you send your messages, please https://account.aliyun.com/register/register.htm?spm=5176.8142029.388261.26.e9396d3eaYK2sG&oauth_callback=https%3A%2F%2Fwww.aliyun.com%2F[Register an Alibaba Cloud Account]. If you already have one, please https://dysms.console.aliyun.com/dysms.htm?spm=5176.8195934.1283918..18924183bHPct2&accounttraceid=c8cb4243-3080-4eb1-96b0-1f2316584269#/[Turn on SMS Service].
For more information about SMS , please refer to the SMS official https://help.aliyun.com/document_detail/55284.html?spm=a2c4g.11186623.6.568.715e4f30ZiVkbI[SMS] (SendSms)---JAVA] docs .
NOTE: Due to an issue with the earlier SMS sdk version, if the text message fails to be sent, please delete the line of code that contains the explicit MethodType as POST. If you still have problems, please contact us as soon as possible.
=== The Advanced Features of SMS Api
In order to reduce the cost of learning, the API interface of the Spring Cloud Alicloud SMS package is kept as consistent as the API and Example provided by the official website.
* Batch SMS sending
Refer to the following example to quickly develop a feature with bulk SMS sending. Add the following code in the Controller or create a new Controller:
[source,java]
----
@RequestMapping("/batch-sms-send.do")
public SendBatchSmsResponse batchsendCheckCode(
@RequestParam(name = "code") String code) {
SendBatchSmsRequest request = new SendBatchSmsRequest();
request.setMethod(MethodType.GET);
request.setPhoneNumberJson("[\"177********\",\"130********\"]");
request.setSignNameJson("[\"*******\",\"*******\"]");
request.setTemplateCode("******");
request.setTemplateParamJson(
"[{\"code\":\"" + code + "\"},{\"code\":\"" + code + "\"}]");
SendBatchSmsResponse sendSmsResponse ;
try {
sendSmsResponse = smsService
.sendSmsBatchRequest(request);
return sendSmsResponse;
}
catch (ClientException e) {
e.printStackTrace();
sendSmsResponse = new SendBatchSmsResponse();
}
return sendSmsResponse ;
}
----
NOTE: The MethodType of the request is set to GET, which is somewhat different from the example given by the official website. This is because the inconsistent version of the dependent Alibaba Cloud POP API version causes incompatibility issues, set to GET.
More parameter descriptions can be https://help.aliyun.com/document_detail/66041.html?spm=a2c4g.11186623.6.571.631315e8AauJhP[reference here]
* SMS Query
Refer to the following example to quickly develop a history of sending SMS messages based on a specified number. Add the following code in the Controller or create a new Controller:
[source,java]
----
@RequestMapping("/query.do")
public QuerySendDetailsResponse querySendDetailsResponse(
@RequestParam(name = "tel") String telephone) {
QuerySendDetailsRequest request = new QuerySendDetailsRequest();
request.setPhoneNumber(telephone);
request.setSendDate("20190103");
request.setPageSize(10L);
request.setCurrentPage(1L);
try {
QuerySendDetailsResponse response = smsService.querySendDetails(request);
return response;
}
catch (ClientException e) {
e.printStackTrace();
}
return new QuerySendDetailsResponse();
}
----
More parameter descriptions can be found at https://help.aliyun.com/document_detail/55289.html?spm=a2c4g.11186623.6.569.4f852c78mugEfx[reference here]
* SMS receipt message
By subscribing to the SmsReport SMS status report, you can know the status of each SMS message and whether it knows the status and related information of the terminal user. These efforts have been encapsulated internally by Spring Cloud AliCloud SMS. You only need to complete the following two steps.
1、Configure the queue name for SmsReport in the `application.properties` configuration file (which can also be application.yaml).
.application.properties
----
spring.cloud.alicloud.sms.report-queue-name=Alicom-Queue-********-SmsReport
----
2、Implement the SmsReportMessageListener interface and initialize a Spring Bean.
[source,java]
----
@Component
public class SmsReportMessageListener
implements org.springframework.cloud.alicloud.sms.SmsReportMessageListener {
@Override
public boolean dealMessage(Message message) {
//do something
System.err.println(this.getClass().getName() + "; " + message.toString());
return true;
}
}
----
More message body format for Message can be https://help.aliyun.com/document_detail/55496.html?spm=a2c4g.11186623.6.570.7f792c78rOiWXO[reference here].
* Upstream SMS message
By subscribing to the SmsUp upstream SMS message, you can know the content of the end user replying to the SMS. These efforts have also been packaged by Spring Cloud AliCloud SMS. You only need to complete the following two steps.
1、Configure the queue name for SmsReport in the `application.properties` configuration file (which can also be application.yaml).
.application.properties
----
spring.cloud.alicloud.sms.up-queue-name=Alicom-Queue-********-SmsUp
----
2、Implement the SmsUpMessageListener interface and initialize a Spring Bean.
[source,java]
----
@Component
public class SmsUpMessageListener
implements org.springframework.cloud.alicloud.sms.SmsUpMessageListener {
@Override
public boolean dealMessage(Message message) {
//do something
System.err.println(this.getClass().getName() + "; " + message.toString());
return true;
}
}
----
More message body format for Message can be https://help.aliyun.com/document_detail/55496.html?spm=a2c4g.11186623.6.570.7f792c78rOiWXO[reference here].

View File

@ -3,47 +3,22 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>alibaba.com</groupId>
<artifactId>sms-example</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>sms-example</name>
<description>Demo project for Spring Boot</description>
<description>Example demonstrating how to use alicloud sms</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.6.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
<artifactId>spring-cloud-alibaba-examples</artifactId>
<groupId>org.springframework.cloud</groupId>
<version>0.2.2.BUILD-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<spring-cloud.version>Finchley.SR2</spring-cloud.version>
<spring-cloud-alibaba-alicloud.version>0.2.2.BUILD-SNAPSHOT</spring-cloud-alibaba-alicloud.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<version>${spring-cloud-alibaba-alicloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<!--Spring Boot -->
@ -59,11 +34,6 @@
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-alicloud-sms</artifactId>
</dependency>
<dependency>
<groupId>alibaba.com</groupId>
<artifactId>env-extension</artifactId>
<version>0.2.2.BUILD-SNAPSHOT</version>
</dependency>
</dependencies>
<build>
@ -72,6 +42,14 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-deploy-plugin</artifactId>
<version>${maven-deploy-plugin.version}</version>
<configuration>
<skip>true</skip>
</configuration>
</plugin>
</plugins>
</build>

View File

@ -15,7 +15,6 @@
*/
package org.springframework.cloud.alibaba.cloud.example;
import org.springframework.alicloud.env.extension.ImportExtraConfig;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@ -23,7 +22,6 @@ import org.springframework.boot.autoconfigure.SpringBootApplication;
*
*/
@SpringBootApplication
@ImportExtraConfig(name = "/Users/toava/sms.properties")
public class SmsApplication {
public static void main(String[] args) throws Exception{

View File

@ -1,4 +1,9 @@
spring.application.name=sca-sms-example
server.port=9051
# config management
# config sms
spring.cloud.alicloud.access-key=*****
spring.cloud.alicloud.secret-key=******
spring.cloud.alicloud.sms.report-queue-name=*****
spring.cloud.alicloud.sms.up-queue-name=*****
#config endpoint
management.endpoints.web.exposure.include=*

View File

@ -16,6 +16,17 @@
package org.springframework.cloud.alibaba.sentinel.zuul;
import static org.springframework.cloud.alibaba.sentinel.zuul.SentinelZuulAutoConfiguration.PREFIX;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.alibaba.sentinel.zuul.handler.FallBackProviderHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import com.alibaba.csp.sentinel.adapter.zuul.fallback.DefaultRequestOriginParser;
import com.alibaba.csp.sentinel.adapter.zuul.fallback.DefaultUrlCleaner;
import com.alibaba.csp.sentinel.adapter.zuul.fallback.RequestOriginParser;
@ -25,17 +36,8 @@ import com.alibaba.csp.sentinel.adapter.zuul.filters.SentinelPostFilter;
import com.alibaba.csp.sentinel.adapter.zuul.filters.SentinelPreFilter;
import com.alibaba.csp.sentinel.adapter.zuul.properties.SentinelZuulProperties;
import com.alibaba.csp.sentinel.util.StringUtil;
import com.netflix.zuul.ZuulFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.alibaba.sentinel.zuul.listener.FallBackProviderListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import static org.springframework.cloud.alibaba.sentinel.zuul.SentinelZuulAutoConfiguration.PREFIX;
import com.netflix.zuul.ZuulFilter;
/**
* Sentinel Spring Cloud Zuul AutoConfiguration
@ -43,68 +45,70 @@ import static org.springframework.cloud.alibaba.sentinel.zuul.SentinelZuulAutoCo
* @author tiger
*/
@Configuration
@ConditionalOnProperty(prefix = PREFIX, name = "enabled", havingValue = "true")
@ConditionalOnProperty(prefix = PREFIX, name = "enabled", havingValue = "true", matchIfMissing = true)
public class SentinelZuulAutoConfiguration {
@Autowired
private Environment environment;
@Autowired
private Environment environment;
public static final String PREFIX = "spring.cloud.alibaba.sentinel.zuul";
public static final String PREFIX = "spring.cloud.sentinel.zuul";
@Bean
public SentinelZuulProperties sentinelZuulProperties() {
SentinelZuulProperties properties = new SentinelZuulProperties();
String enabledStr = environment.getProperty(PREFIX + "." + "enabled");
String preOrderStr = environment.getProperty(PREFIX + "." + "order.pre");
String postOrderStr = environment.getProperty(PREFIX + "." + "order.post");
String errorOrderStr = environment.getProperty(PREFIX + "." + "order.error");
if (StringUtil.isNotEmpty(enabledStr)) {
Boolean enabled = Boolean.valueOf(enabledStr);
properties.setEnabled(enabled);
}
if (StringUtil.isNotEmpty(preOrderStr)) {
properties.getOrder().setPre(Integer.parseInt(preOrderStr));
}
if (StringUtil.isNotEmpty(postOrderStr)) {
properties.getOrder().setPost(Integer.parseInt(postOrderStr));
}
if (StringUtil.isNotEmpty(errorOrderStr)) {
properties.getOrder().setError(Integer.parseInt(errorOrderStr));
}
return properties;
}
@Bean
public SentinelZuulProperties sentinelZuulProperties() {
SentinelZuulProperties properties = new SentinelZuulProperties();
String enabledStr = environment.getProperty(PREFIX + "." + "enabled");
String preOrderStr = environment.getProperty(PREFIX + "." + "order.pre");
String postOrderStr = environment.getProperty(PREFIX + "." + "order.post");
String errorOrderStr = environment.getProperty(PREFIX + "." + "order.error");
if (StringUtil.isNotEmpty(enabledStr)) {
Boolean enabled = Boolean.valueOf(enabledStr);
properties.setEnabled(enabled);
}
if (StringUtil.isNotEmpty(preOrderStr)) {
properties.getOrder().setPre(Integer.parseInt(preOrderStr));
}
if (StringUtil.isNotEmpty(postOrderStr)) {
properties.getOrder().setPost(Integer.parseInt(postOrderStr));
}
if (StringUtil.isNotEmpty(errorOrderStr)) {
properties.getOrder().setError(Integer.parseInt(errorOrderStr));
}
return properties;
}
@Bean
@ConditionalOnMissingBean(UrlCleaner.class)
public UrlCleaner urlCleaner(){
return new DefaultUrlCleaner();
}
@Bean
@ConditionalOnMissingBean(UrlCleaner.class)
public UrlCleaner urlCleaner() {
return new DefaultUrlCleaner();
}
@Bean
@ConditionalOnMissingBean(RequestOriginParser.class)
public RequestOriginParser requestOriginParser(){
return new DefaultRequestOriginParser();
}
@Bean
@ConditionalOnMissingBean(RequestOriginParser.class)
public RequestOriginParser requestOriginParser() {
return new DefaultRequestOriginParser();
}
@Bean
public ZuulFilter preFilter(SentinelZuulProperties sentinelZuulProperties,UrlCleaner urlCleaner,
RequestOriginParser requestOriginParser) {
return new SentinelPreFilter(sentinelZuulProperties,urlCleaner,requestOriginParser);
}
@Bean
public ZuulFilter preFilter(SentinelZuulProperties sentinelZuulProperties,
UrlCleaner urlCleaner, RequestOriginParser requestOriginParser) {
return new SentinelPreFilter(sentinelZuulProperties, urlCleaner,
requestOriginParser);
}
@Bean
public ZuulFilter postFilter(SentinelZuulProperties sentinelZuulProperties) {
return new SentinelPostFilter(sentinelZuulProperties);
}
@Bean
public ZuulFilter postFilter(SentinelZuulProperties sentinelZuulProperties) {
return new SentinelPostFilter(sentinelZuulProperties);
}
@Bean
public ZuulFilter errorFilter(SentinelZuulProperties sentinelZuulProperties) {
return new SentinelErrorFilter(sentinelZuulProperties);
}
@Bean
public ZuulFilter errorFilter(SentinelZuulProperties sentinelZuulProperties) {
return new SentinelErrorFilter(sentinelZuulProperties);
}
@Bean
public FallBackProviderListener fallBackProviderListener(DefaultListableBeanFactory beanFactory) {
return new FallBackProviderListener(beanFactory);
}
@Bean
public FallBackProviderHandler fallBackProviderListener(
DefaultListableBeanFactory beanFactory) {
return new FallBackProviderHandler(beanFactory);
}
}

View File

@ -0,0 +1,45 @@
package org.springframework.cloud.alibaba.sentinel.zuul.handler;
import java.util.Map;
import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import com.alibaba.csp.sentinel.adapter.zuul.fallback.DefaultBlockFallbackProvider;
import com.alibaba.csp.sentinel.adapter.zuul.fallback.ZuulBlockFallbackManager;
import com.alibaba.csp.sentinel.adapter.zuul.fallback.ZuulBlockFallbackProvider;
/**
* @author tiger
*/
public class FallBackProviderHandler implements SmartInitializingSingleton {
private static final Logger logger = LoggerFactory
.getLogger(FallBackProviderHandler.class);
private final DefaultListableBeanFactory beanFactory;
public FallBackProviderHandler(DefaultListableBeanFactory beanFactory) {
this.beanFactory = beanFactory;
}
@Override
public void afterSingletonsInstantiated() {
Map<String, ZuulBlockFallbackProvider> providerMap = beanFactory
.getBeansOfType(ZuulBlockFallbackProvider.class);
if (MapUtils.isNotEmpty(providerMap)) {
providerMap.forEach((k, v) -> {
logger.info("[Sentinel Zuul] Register provider name:{}, instance: {}", k,
v);
ZuulBlockFallbackManager.registerProvider(v);
});
}
else {
logger.info("[Sentinel Zuul] Register default fallback provider. ");
ZuulBlockFallbackManager.registerProvider(new DefaultBlockFallbackProvider());
}
}
}

View File

@ -1,43 +0,0 @@
package org.springframework.cloud.alibaba.sentinel.zuul.listener;
import com.alibaba.csp.sentinel.adapter.zuul.fallback.DefaultBlockFallbackProvider;
import com.alibaba.csp.sentinel.adapter.zuul.fallback.ZuulBlockFallbackManager;
import com.alibaba.csp.sentinel.adapter.zuul.fallback.ZuulBlockFallbackProvider;
import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.event.EventListener;
import java.util.Map;
/**
* @author tiger
*/
public class FallBackProviderListener implements SmartInitializingSingleton {
private static final Logger logger = LoggerFactory.getLogger(FallBackProviderListener.class);
private final DefaultListableBeanFactory beanFactory;
public FallBackProviderListener(DefaultListableBeanFactory beanFactory) {
this.beanFactory = beanFactory;
}
@Override
public void afterSingletonsInstantiated() {
Map<String, ZuulBlockFallbackProvider> providerMap = beanFactory.getBeansOfType(ZuulBlockFallbackProvider.class);
if (MapUtils.isNotEmpty(providerMap)) {
providerMap.forEach((k, v) -> {
logger.info("[Sentinel] Register provider name:{}, instance: {}", k, v);
ZuulBlockFallbackManager.registerProvider(v);
});
} else {
logger.info("[Sentinel] Register default fallback provider. ");
ZuulBlockFallbackManager.registerProvider(new DefaultBlockFallbackProvider());
}
}
}

View File

@ -16,17 +16,18 @@
package org.springframework.cloud.alibaba.sentinel;
import com.alibaba.csp.sentinel.config.SentinelConfig;
import com.alibaba.csp.sentinel.log.LogBase;
import com.alibaba.csp.sentinel.transport.config.TransportConfig;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.alibaba.sentinel.datasource.config.DataSourcePropertiesConfiguration;
import org.springframework.core.Ordered;
import org.springframework.validation.annotation.Validated;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import com.alibaba.csp.sentinel.config.SentinelConfig;
import com.alibaba.csp.sentinel.log.LogBase;
import com.alibaba.csp.sentinel.transport.config.TransportConfig;
/**
* {@link ConfigurationProperties} for Sentinel.
@ -306,6 +307,12 @@ public class SentinelProperties {
*/
private List<String> urlPatterns;
/**
* Enable to instance
* {@link com.alibaba.csp.sentinel.adapter.servlet.CommonFilter}.
*/
private boolean enabled = true;
public int getOrder() {
return this.order;
}
@ -321,6 +328,14 @@ public class SentinelProperties {
public void setUrlPatterns(List<String> urlPatterns) {
this.urlPatterns = urlPatterns;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
}
public static class Log {

View File

@ -16,7 +16,10 @@
package org.springframework.cloud.alibaba.sentinel;
import com.alibaba.csp.sentinel.adapter.servlet.CommonFilter;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.Filter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -28,9 +31,7 @@ import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.servlet.Filter;
import java.util.ArrayList;
import java.util.List;
import com.alibaba.csp.sentinel.adapter.servlet.CommonFilter;
/**
* @author xiaojing
@ -48,7 +49,8 @@ public class SentinelWebAutoConfiguration {
private SentinelProperties properties;
@Bean
public FilterRegistrationBean servletRequestListener() {
@ConditionalOnProperty(name = "spring.cloud.sentinel.filter.enabled", matchIfMissing = true)
public FilterRegistrationBean sentinelFilter() {
FilterRegistrationBean<Filter> registration = new FilterRegistrationBean<>();
SentinelProperties.Filter filterConfig = properties.getFilter();

View File

@ -16,6 +16,13 @@
package org.springframework.cloud.alibaba.sentinel.endpoint;
import java.util.HashMap;
import java.util.Map;
import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
import org.springframework.cloud.alibaba.sentinel.SentinelProperties;
import com.alibaba.csp.sentinel.adapter.servlet.config.WebServletConfig;
import com.alibaba.csp.sentinel.config.SentinelConfig;
import com.alibaba.csp.sentinel.log.LogBase;
@ -25,12 +32,7 @@ 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.alibaba.csp.sentinel.transport.config.TransportConfig;
import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
import org.springframework.cloud.alibaba.sentinel.SentinelProperties;
import java.util.HashMap;
import java.util.Map;
import com.alibaba.csp.sentinel.util.AppNameUtil;
/**
* Endpoint for Sentinel, contains ans properties and rules
@ -50,6 +52,7 @@ public class SentinelEndpoint {
final Map<String, Object> result = new HashMap<>();
if (sentinelProperties.isEnabled()) {
result.put("appName", AppNameUtil.getAppName());
result.put("logDir", LogBase.getLogBaseDir());
result.put("logUsePid", LogBase.isLogNameUsePid());
result.put("blockPage", WebServletConfig.getBlockPage());

View File

@ -39,6 +39,12 @@
"defaultValue": "Integer.MIN_VALUE",
"description": "sentinel filter chain order, will be set to FilterRegistrationBean."
},
{
"name": "spring.cloud.sentinel.filter.enabled",
"type": "java.lang.Boolean",
"defaultValue": true,
"description": "Enable to instance com.alibaba.csp.sentinel.adapter.servlet.CommonFilter."
},
{
"name": "spring.cloud.sentinel.metric.charset",
"type": "java.lang.String",

View File

@ -17,15 +17,20 @@ package org.springframework.cloud.alicloud.sms;
import java.text.ParseException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.alicloud.context.AliCloudProperties;
import org.springframework.cloud.alicloud.context.sms.SmsProperties;
import org.springframework.cloud.alicloud.sms.base.DefaultAlicomMessagePuller;
import org.springframework.cloud.alicloud.sms.endpoint.EndpointManager;
import org.springframework.cloud.alicloud.sms.endpoint.ReceiveMessageEntity;
import com.aliyuncs.dysmsapi.model.v20170525.*;
import com.aliyuncs.dysmsapi.model.v20170525.QuerySendDetailsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.QuerySendDetailsResponse;
import com.aliyuncs.dysmsapi.model.v20170525.SendBatchSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendBatchSmsResponse;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
@ -34,7 +39,7 @@ import com.aliyuncs.exceptions.ServerException;
*/
public final class SmsServiceImpl extends AbstractSmsService {
private static final Log log = LogFactory.getLog(SmsServiceImpl.class);
private static final Logger log = LoggerFactory.getLogger(SmsServiceImpl.class);
/**
* will expose user to call this method send sms message
* @param sendSmsRequest

View File

@ -15,14 +15,6 @@
*/
package org.springframework.cloud.alicloud.sms.base;
import com.aliyun.mns.client.CloudQueue;
import com.aliyun.mns.common.ClientException;
import com.aliyun.mns.common.ServiceException;
import com.aliyun.mns.model.Message;
import org.apache.commons.lang3.concurrent.BasicThreadFactory;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
@ -33,12 +25,22 @@ import java.util.concurrent.ExecutorService;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import org.apache.commons.lang3.concurrent.BasicThreadFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.aliyun.mns.client.CloudQueue;
import com.aliyun.mns.common.ClientException;
import com.aliyun.mns.common.ServiceException;
import com.aliyun.mns.model.Message;
/**
* 阿里通信官方消息默认拉取工具类
*/
public class DefaultAlicomMessagePuller {
private Log logger = LogFactory.getLog(DefaultAlicomMessagePuller.class);
private static final Logger log = LoggerFactory
.getLogger(DefaultAlicomMessagePuller.class);
private String mnsAccountEndpoint = "https://1943695596114318.mns.cn-hangzhou.aliyuncs.com/";// 阿里通信消息的endpoint,固定
private String endpointNameForPop = "cn-hangzhou";
@ -103,7 +105,7 @@ public class DefaultAlicomMessagePuller {
sPollingMap.put(queueName, false);
lockObj.notifyAll();
if (debugLogOpen) {
logger.info("PullMessageTask_WakeUp:Everyone WakeUp and Work!");
log.info("PullMessageTask_WakeUp:Everyone WakeUp and Work!");
}
}
}
@ -131,7 +133,7 @@ public class DefaultAlicomMessagePuller {
if (p != null && p) {
try {
if (debugLogOpen) {
logger.info("PullMessageTask_sleep:"
log.info("PullMessageTask_sleep:"
+ Thread.currentThread().getName()
+ " Have a nice sleep!");
}
@ -140,7 +142,7 @@ public class DefaultAlicomMessagePuller {
}
catch (InterruptedException e) {
if (debugLogOpen) {
logger.info("PullMessageTask_Interrupted!"
log.info("PullMessageTask_Interrupted!"
+ Thread.currentThread().getName()
+ " QueueName is " + queueName);
}
@ -158,7 +160,7 @@ public class DefaultAlicomMessagePuller {
if (debugLogOpen) {
SimpleDateFormat format = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
logger.info("PullMessageTask_popMessage:"
log.info("PullMessageTask_popMessage:"
+ Thread.currentThread().getName() + "-popDone at "
+ "," + format.format(new Date()) + " msgSize="
+ (popMsg == null ? 0 : popMsg.getMessageId()));
@ -171,7 +173,7 @@ public class DefaultAlicomMessagePuller {
else {
if (setPolling(queueName)) {
if (debugLogOpen) {
logger.info("PullMessageTask_setPolling:"
log.info("PullMessageTask_setPolling:"
+ Thread.currentThread().getName() + " Polling!");
}
}
@ -180,7 +182,7 @@ public class DefaultAlicomMessagePuller {
}
do {
if (debugLogOpen) {
logger.info("PullMessageTask_Keep_Polling"
log.info("PullMessageTask_Keep_Polling"
+ Thread.currentThread().getName()
+ "KEEP Polling!");
}
@ -189,7 +191,7 @@ public class DefaultAlicomMessagePuller {
}
catch (ClientException e) {
if (debugLogOpen) {
logger.info(
log.info(
"PullMessageTask_Pop_Message:ClientException Refresh accessKey"
+ e);
}
@ -200,7 +202,7 @@ public class DefaultAlicomMessagePuller {
}
catch (ServiceException e) {
if (debugLogOpen) {
logger.info(
log.info(
"PullMessageTask_Pop_Message:ServiceException Refresh accessKey"
+ e);
}
@ -211,7 +213,7 @@ public class DefaultAlicomMessagePuller {
}
catch (Exception e) {
if (debugLogOpen) {
logger.info(
log.info(
"PullMessageTask_Pop_Message:Exception Happened when polling popMessage: "
+ e);
}
@ -224,7 +226,7 @@ public class DefaultAlicomMessagePuller {
if (dealResult) {
// remember to delete message when consume message successfully.
if (debugLogOpen) {
logger.info("PullMessageTask_Deal_Message:"
log.info("PullMessageTask_Deal_Message:"
+ Thread.currentThread().getName() + "deleteMessage "
+ popMsg.getMessageId());
}
@ -232,19 +234,19 @@ public class DefaultAlicomMessagePuller {
}
}
catch (ClientException e) {
logger.error("PullMessageTask_execute_error,messageType:"
+ messageType + ",queueName:" + queueName, e);
log.error("PullMessageTask_execute_error,messageType:" + messageType
+ ",queueName:" + queueName, e);
break;
}
catch (ServiceException e) {
if (e.getErrorCode().equals("AccessDenied")) {
logger.error("PullMessageTask_execute_error,messageType:"
log.error("PullMessageTask_execute_error,messageType:"
+ messageType + ",queueName:" + queueName
+ ",please check messageType and queueName", e);
}
else {
logger.error("PullMessageTask_execute_error,messageType:"
log.error("PullMessageTask_execute_error,messageType:"
+ messageType + ",queueName:" + queueName, e);
}
break;
@ -252,30 +254,30 @@ public class DefaultAlicomMessagePuller {
}
catch (com.aliyuncs.exceptions.ClientException e) {
if (e.getErrCode().equals("InvalidAccessKeyId.NotFound")) {
logger.error("PullMessageTask_execute_error,messageType:"
log.error("PullMessageTask_execute_error,messageType:"
+ messageType + ",queueName:" + queueName
+ ",please check AccessKeyId", e);
}
if (e.getErrCode().equals("SignatureDoesNotMatch")) {
logger.error("PullMessageTask_execute_error,messageType:"
log.error("PullMessageTask_execute_error,messageType:"
+ messageType + ",queueName:" + queueName
+ ",please check AccessKeySecret", e);
}
else {
logger.error("PullMessageTask_execute_error,messageType:"
log.error("PullMessageTask_execute_error,messageType:"
+ messageType + ",queueName:" + queueName, e);
}
break;
}
catch (Exception e) {
logger.error("PullMessageTask_execute_error,messageType:"
+ messageType + ",queueName:" + queueName, e);
log.error("PullMessageTask_execute_error,messageType:" + messageType
+ ",queueName:" + queueName, e);
try {
Thread.sleep(sleepSecondWhenNoData);
}
catch (InterruptedException e1) {
logger.error("PullMessageTask_execute_error,messageType:"
log.error("PullMessageTask_execute_error,messageType:"
+ messageType + ",queueName:" + queueName, e);
}
}

View File

@ -15,6 +15,15 @@
*/
package org.springframework.cloud.alicloud.sms.base;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.TimeZone;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.aliyun.mns.client.CloudAccount;
import com.aliyun.mns.client.CloudQueue;
import com.aliyun.mns.client.MNSClient;
@ -27,21 +36,13 @@ import com.aliyuncs.http.MethodType;
import com.aliyuncs.http.ProtocolType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.TimeZone;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
* 获取接收云通信消息的临时token
*
*/
public class TokenGetterForAlicom {
private Log logger = LogFactory.getLog(TokenGetterForAlicom.class);
private static final Logger log = LoggerFactory.getLogger(TokenGetterForAlicom.class);
private String accessKeyId;
private String accessKeySecret;
private String endpointNameForPop;
@ -100,7 +101,7 @@ public class TokenGetterForAlicom {
return token;
}
else {
logger.error("getTokenFromRemote_error,messageType:" + messageType + ",code:"
log.error("getTokenFromRemote_error,messageType:" + messageType + ",code:"
+ response.getCode() + ",message:" + response.getMessage());
throw new ServerException(response.getCode(), response.getMessage());
}
@ -124,8 +125,6 @@ public class TokenGetterForAlicom {
CloudAccount account = new CloudAccount(token.getTempAccessKeyId(),
token.getTempAccessKeySecret(), mnsAccountEndpoint,
token.getToken());
// logger.warn("ak:"+token.getTempAccessKey());
// logger.warn("token:"+token.getToken());
MNSClient client = account.getMNSClient();
CloudQueue queue = client.getQueueRef(queueName);
token.setClient(client);

View File

@ -15,12 +15,12 @@
*/
package org.springframework.cloud.alicloud.sms.endpoint;
import java.util.Map;
import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
import java.util.Map;
@Endpoint(id = "sms-info")
@Endpoint(id = "sms")
public class SmsEndpoint {
@ReadOperation