ans starter suport eureka/consule registry and add sms module
parent
b475158352
commit
ee2c696bdf
@ -0,0 +1,74 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<groupId>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>
|
||||
|
||||
<parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>2.0.6.RELEASE</version>
|
||||
<relativePath/> <!-- lookup parent from repository -->
|
||||
</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 -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-actuator</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-starter-alicloud-sms</artifactId>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
|
||||
</project>
|
@ -0,0 +1,31 @@
|
||||
/*
|
||||
* Copyright (C) 2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.cloud.alibaba.cloud.example;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
@SpringBootApplication
|
||||
public class SmsApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
SpringApplication.run(SmsApplication.class, args);
|
||||
}
|
||||
}
|
@ -0,0 +1,9 @@
|
||||
spring.application.name=sca-sms-example
|
||||
server.port=9051
|
||||
# config management
|
||||
management.endpoints.web.exposure.include=*
|
||||
#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=******
|
@ -0,0 +1,31 @@
|
||||
package org.springframework.cloud.alicloud.ans.migrate;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
|
||||
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentMap;
|
||||
|
||||
@Endpoint(id = "migrate")
|
||||
public class MigrateEndpoint {
|
||||
|
||||
private static final Log log = LogFactory.getLog(MigrateEndpoint.class);
|
||||
|
||||
public MigrateEndpoint() {
|
||||
}
|
||||
|
||||
/**
|
||||
* @return ans endpoint
|
||||
*/
|
||||
@ReadOperation
|
||||
public Map<String, ConcurrentMap<String, ServerWrapper>> invoke() {
|
||||
|
||||
Map<String, ConcurrentMap<String, ServerWrapper>> result = ServerListInvocationHandler
|
||||
.getServerRegistry();
|
||||
|
||||
log.info("migrate server list :" + result);
|
||||
return result;
|
||||
}
|
||||
}
|
@ -0,0 +1,18 @@
|
||||
package org.springframework.cloud.alicloud.ans.migrate;
|
||||
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Conditional;
|
||||
|
||||
@ConditionalOnWebApplication
|
||||
|
||||
@ConditionalOnClass(name = "org.springframework.boot.actuate.endpoint.annotation.Endpoint")
|
||||
@Conditional(MigrateOnConditionClass.class)
|
||||
public class MigrateEndpointAutoConfiguration {
|
||||
|
||||
@Bean
|
||||
public MigrateEndpoint ansEndpoint() {
|
||||
return new MigrateEndpoint();
|
||||
}
|
||||
}
|
@ -0,0 +1,49 @@
|
||||
package org.springframework.cloud.alicloud.ans.migrate;
|
||||
|
||||
import org.springframework.beans.factory.BeanClassLoaderAware;
|
||||
import org.springframework.context.annotation.Condition;
|
||||
import org.springframework.context.annotation.ConditionContext;
|
||||
import org.springframework.core.type.AnnotatedTypeMetadata;
|
||||
import org.springframework.util.ClassUtils;
|
||||
|
||||
/**
|
||||
* @author pbting
|
||||
*/
|
||||
public abstract class MigrateOnCondition implements Condition, BeanClassLoaderAware {
|
||||
|
||||
final String[] conditionOnClass = new String[] {
|
||||
"org.springframework.cloud.consul.serviceregistry.ConsulAutoServiceRegistration",
|
||||
"org.springframework.cloud.netflix.eureka.serviceregistry.EurekaAutoServiceRegistration" };
|
||||
|
||||
ClassLoader classLoader;
|
||||
|
||||
@Override
|
||||
public void setBeanClassLoader(ClassLoader classLoader) {
|
||||
this.classLoader = classLoader;
|
||||
}
|
||||
|
||||
@Override
|
||||
public abstract boolean matches(ConditionContext context,
|
||||
AnnotatedTypeMetadata metadata);
|
||||
|
||||
boolean isPresent(String className, ClassLoader classLoader) {
|
||||
if (classLoader == null) {
|
||||
classLoader = ClassUtils.getDefaultClassLoader();
|
||||
}
|
||||
|
||||
try {
|
||||
forName(className, classLoader);
|
||||
return true;
|
||||
}
|
||||
catch (Throwable var3) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
Class<?> forName(String className, ClassLoader classLoader)
|
||||
throws ClassNotFoundException {
|
||||
return classLoader != null ? classLoader.loadClass(className)
|
||||
: Class.forName(className);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,22 @@
|
||||
package org.springframework.cloud.alicloud.ans.migrate;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.springframework.context.annotation.ConditionContext;
|
||||
import org.springframework.core.type.AnnotatedTypeMetadata;
|
||||
|
||||
/**
|
||||
* @author pbting
|
||||
*/
|
||||
public class MigrateOnConditionClass extends MigrateOnCondition {
|
||||
|
||||
protected static final Log log = LogFactory.getLog(MigrateOnConditionClass.class);
|
||||
|
||||
@Override
|
||||
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
|
||||
boolean result = isPresent(conditionOnClass[0], classLoader)
|
||||
|| isPresent(conditionOnClass[1], classLoader);
|
||||
log.info("the result of MigrateOnConditionClass is :" + result);
|
||||
return result;
|
||||
}
|
||||
}
|
@ -0,0 +1,23 @@
|
||||
package org.springframework.cloud.alicloud.ans.migrate;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.springframework.context.annotation.ConditionContext;
|
||||
import org.springframework.core.type.AnnotatedTypeMetadata;
|
||||
|
||||
/**
|
||||
* @author pbting
|
||||
*/
|
||||
public class MigrateOnConditionMissingClass extends MigrateOnConditionClass {
|
||||
|
||||
protected static final Log log = LogFactory
|
||||
.getLog(MigrateOnConditionMissingClass.class);
|
||||
|
||||
@Override
|
||||
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
|
||||
boolean result = !super.matches(context, metadata);
|
||||
log.info("the result of MigrateOnConditionMissingClass is :" + result);
|
||||
return result;
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,94 @@
|
||||
package org.springframework.cloud.alicloud.ans.migrate;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentSkipListSet;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
|
||||
import org.aopalliance.aop.Advice;
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.springframework.aop.AfterReturningAdvice;
|
||||
import org.springframework.aop.framework.ProxyFactory;
|
||||
|
||||
import com.netflix.client.config.IClientConfig;
|
||||
import com.netflix.loadbalancer.ILoadBalancer;
|
||||
import com.netflix.loadbalancer.Server;
|
||||
import com.netflix.loadbalancer.ServerList;
|
||||
|
||||
/**
|
||||
* @author pbting
|
||||
*/
|
||||
final class MigrateProxyManager {
|
||||
|
||||
private final static Log log = LogFactory.getLog(MigrateProxyManager.class);
|
||||
private final static AtomicBoolean IS_PROXY = new AtomicBoolean(true);
|
||||
|
||||
private final static Set<String> SERVICES_ID = new ConcurrentSkipListSet<>();
|
||||
|
||||
private static Object springProxyFactory(Object target, ClassLoader classLoader,
|
||||
List<Advice> adviceList, Class... interfaces) {
|
||||
final ProxyFactory proxyFactory = new ProxyFactory(interfaces);
|
||||
proxyFactory.setTarget(target);
|
||||
adviceList.forEach(advice -> proxyFactory.addAdvice(advice));
|
||||
return proxyFactory.getProxy(classLoader);
|
||||
}
|
||||
|
||||
static Object newServerListProxy(Object bean, ClassLoader classLoader,
|
||||
IClientConfig clientConfig) {
|
||||
bean = springProxyFactory(bean, classLoader,
|
||||
Arrays.asList(new ServerListInvocationHandler(clientConfig)),
|
||||
new Class[] { ServerList.class });
|
||||
log.info("[service id]" + clientConfig.getClientName()
|
||||
+ " new a ServerList proxy instance for spring cloud netflix to spring cloud alibaba ");
|
||||
collectServiceId(clientConfig.getClientName());
|
||||
return bean;
|
||||
}
|
||||
|
||||
static Object newLoadBalancerProxy(Object bean, ClassLoader classLoader,
|
||||
IClientConfig clientConfig) {
|
||||
|
||||
bean = springProxyFactory(bean, classLoader,
|
||||
Arrays.asList(new AfterReturningAdvice() {
|
||||
@Override
|
||||
public void afterReturning(Object returnValue, Method method,
|
||||
Object[] args, Object target) {
|
||||
String methodName = method.getName();
|
||||
if ("chooseServer".equals(methodName)) {
|
||||
String serviceId = clientConfig.getClientName();
|
||||
Server server = (Server) returnValue;
|
||||
ServerListInvocationHandler.incrementCallService(serviceId,
|
||||
server);
|
||||
}
|
||||
}
|
||||
}), new Class[] { ILoadBalancer.class });
|
||||
log.info("[service id]" + clientConfig.getClientName()
|
||||
+ " new a ILoadBalancer proxy instance for spring cloud netflix to spring cloud alibaba ");
|
||||
return bean;
|
||||
}
|
||||
|
||||
static void migrateProxyClose() {
|
||||
IS_PROXY.set(false);
|
||||
}
|
||||
|
||||
static void migrateProxyUp() {
|
||||
IS_PROXY.set(true);
|
||||
}
|
||||
|
||||
static boolean isMigrateProxy() {
|
||||
|
||||
return IS_PROXY.get();
|
||||
}
|
||||
|
||||
static void collectServiceId(String serviceId) {
|
||||
SERVICES_ID.add(serviceId);
|
||||
}
|
||||
|
||||
static Set<String> getServicesId() {
|
||||
|
||||
return Collections.unmodifiableSet(SERVICES_ID);
|
||||
}
|
||||
}
|
@ -0,0 +1,75 @@
|
||||
package org.springframework.cloud.alicloud.ans.migrate;
|
||||
|
||||
import com.netflix.loadbalancer.ILoadBalancer;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.cloud.context.named.NamedContextFactory;
|
||||
import org.springframework.cloud.endpoint.event.RefreshEvent;
|
||||
import org.springframework.context.ApplicationListener;
|
||||
import org.springframework.core.env.Environment;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
* @author pbting
|
||||
*/
|
||||
@Component
|
||||
public class MigrateRefreshEventListener implements ApplicationListener<RefreshEvent> {
|
||||
|
||||
private final static String MIGRATE_SWITCH = "sca.migrate.ans.switch";
|
||||
|
||||
private volatile String lastScaMigrateAnsSwitchValue = "true";
|
||||
|
||||
@Autowired
|
||||
private Environment environment;
|
||||
|
||||
@Autowired
|
||||
private NamedContextFactory namedContextFactory;
|
||||
|
||||
public MigrateRefreshEventListener() {
|
||||
}
|
||||
|
||||
@PostConstruct
|
||||
public void initTimerCheck() {
|
||||
Executors.newSingleThreadScheduledExecutor().scheduleWithFixedDelay(
|
||||
() -> onApplicationEvent(null), 1, 1, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onApplicationEvent(RefreshEvent event) {
|
||||
String value = environment.getProperty(MIGRATE_SWITCH, "true");
|
||||
// check 1: check the value
|
||||
if (value.equals(lastScaMigrateAnsSwitchValue)) {
|
||||
return;
|
||||
}
|
||||
|
||||
updateLastScaMigrateAnsResetValue(value);
|
||||
|
||||
// step 1: migrate up
|
||||
if ("true".equals(value)) {
|
||||
MigrateProxyManager.migrateProxyUp();
|
||||
serviceIdContextInit();
|
||||
return;
|
||||
}
|
||||
|
||||
// step 2: migrate close
|
||||
if ("false".equals(value)) {
|
||||
MigrateProxyManager.migrateProxyClose();
|
||||
serviceIdContextInit();
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
private void serviceIdContextInit() {
|
||||
namedContextFactory.destroy();
|
||||
// initializer each spring context for service id
|
||||
MigrateProxyManager.getServicesId().forEach(serviceId -> namedContextFactory
|
||||
.getInstance(serviceId, ILoadBalancer.class));
|
||||
}
|
||||
|
||||
private synchronized void updateLastScaMigrateAnsResetValue(String value) {
|
||||
this.lastScaMigrateAnsSwitchValue = value;
|
||||
}
|
||||
}
|
@ -0,0 +1,53 @@
|
||||
package org.springframework.cloud.alicloud.ans.migrate;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.springframework.beans.BeansException;
|
||||
import org.springframework.beans.factory.BeanClassLoaderAware;
|
||||
import org.springframework.beans.factory.config.BeanPostProcessor;
|
||||
|
||||
import com.netflix.client.config.IClientConfig;
|
||||
import com.netflix.loadbalancer.ILoadBalancer;
|
||||
import com.netflix.loadbalancer.ServerList;
|
||||
|
||||
public class MigrateRibbonBeanPostProcessor
|
||||
implements BeanPostProcessor, BeanClassLoaderAware {
|
||||
|
||||
protected static final Log log = LogFactory.getLog(MigrateOnCondition.class);
|
||||
|
||||
private ClassLoader classLoader;
|
||||
private IClientConfig clientConfig;
|
||||
|
||||
public MigrateRibbonBeanPostProcessor(IClientConfig clientConfig) {
|
||||
this.clientConfig = clientConfig;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object postProcessAfterInitialization(Object bean, String beanName)
|
||||
throws BeansException {
|
||||
|
||||
// step 1 : check the bean whether proxy or not
|
||||
if (!MigrateProxyManager.isMigrateProxy()) {
|
||||
log.info("Migrate proxy is Close.");
|
||||
return bean;
|
||||
}
|
||||
|
||||
// step 2 : proxy the designated bean
|
||||
if (bean instanceof ServerList) {
|
||||
bean = MigrateProxyManager.newServerListProxy(bean, classLoader,
|
||||
clientConfig);
|
||||
}
|
||||
|
||||
if (bean instanceof ILoadBalancer) {
|
||||
bean = MigrateProxyManager.newLoadBalancerProxy(bean, classLoader,
|
||||
clientConfig);
|
||||
}
|
||||
return bean;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setBeanClassLoader(ClassLoader classLoader) {
|
||||
this.classLoader = classLoader;
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,51 @@
|
||||
package org.springframework.cloud.alicloud.ans.migrate;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.springframework.boot.web.context.WebServerInitializedEvent;
|
||||
import org.springframework.cloud.alicloud.ans.registry.AnsRegistration;
|
||||
import org.springframework.cloud.alicloud.ans.registry.AnsServiceRegistry;
|
||||
import org.springframework.cloud.alicloud.context.ans.AnsProperties;
|
||||
import org.springframework.cloud.client.serviceregistry.ServiceRegistry;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.context.event.EventListener;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
|
||||
/**
|
||||
* @author pbting
|
||||
*/
|
||||
@Component
|
||||
public class MigrateServiceRegistry {
|
||||
|
||||
private static final Log log = LogFactory.getLog(MigrateServiceRegistry.class);
|
||||
|
||||
private AtomicBoolean running = new AtomicBoolean(false);
|
||||
|
||||
private ServiceRegistry serviceRegistry;
|
||||
private AnsRegistration ansRegistration;
|
||||
|
||||
public MigrateServiceRegistry(AnsProperties ansProperties,
|
||||
ApplicationContext context) {
|
||||
this.ansRegistration = new AnsRegistration(ansProperties, context);
|
||||
this.ansRegistration.init();
|
||||
this.serviceRegistry = new AnsServiceRegistry();
|
||||
}
|
||||
|
||||
@EventListener(WebServerInitializedEvent.class)
|
||||
public void onApplicationEvent(WebServerInitializedEvent event) {
|
||||
int serverPort = event.getWebServer().getPort();
|
||||
this.ansRegistration.setPort(serverPort);
|
||||
log.info("[ Migrate ] change the port to " + serverPort);
|
||||
if (!this.running.get()) {
|
||||
long s = System.currentTimeMillis();
|
||||
log.info("[Migrate] start to registry server to ANS");
|
||||
this.serviceRegistry.register(this.ansRegistration);
|
||||
log.info("[migrate] end to registry server to ANS cost time with "
|
||||
+ (System.currentTimeMillis() - s) + " ms.");
|
||||
this.running.set(true);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,25 @@
|
||||
package org.springframework.cloud.alicloud.ans.migrate;
|
||||
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||
import org.springframework.cloud.alicloud.ans.ConditionalOnAnsEnabled;
|
||||
import org.springframework.cloud.alicloud.context.ans.AnsProperties;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Conditional;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration
|
||||
@EnableConfigurationProperties
|
||||
@Conditional(MigrateOnConditionClass.class)
|
||||
@ConditionalOnProperty(value = "spring.cloud.service-registry.auto-registration.enabled", matchIfMissing = true)
|
||||
@ConditionalOnAnsEnabled
|
||||
public class MigrationAutoconfiguration {
|
||||
|
||||
@Bean
|
||||
public MigrateServiceRegistry migrationManger(AnsProperties ansProperties,
|
||||
ApplicationContext applicationContext) {
|
||||
|
||||
return new MigrateServiceRegistry(ansProperties, applicationContext);
|
||||
}
|
||||
}
|
@ -0,0 +1,35 @@
|
||||
package org.springframework.cloud.alicloud.ans.migrate;
|
||||
|
||||
import com.netflix.loadbalancer.Server;
|
||||
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
|
||||
public class ServerWrapper {
|
||||
|
||||
private Server server;
|
||||
private AtomicLong callCount;
|
||||
|
||||
public ServerWrapper() {
|
||||
}
|
||||
|
||||
public ServerWrapper(Server server, AtomicLong callCount) {
|
||||
this.server = server;
|
||||
this.callCount = callCount;
|
||||
}
|
||||
|
||||
public Server getServer() {
|
||||
return server;
|
||||
}
|
||||
|
||||
public void setServer(Server server) {
|
||||
this.server = server;
|
||||
}
|
||||
|
||||
public AtomicLong getCallCount() {
|
||||
return callCount;
|
||||
}
|
||||
|
||||
public void setCallCount(AtomicLong callCount) {
|
||||
this.callCount = callCount;
|
||||
}
|
||||
}
|
@ -0,0 +1,20 @@
|
||||
package org.springframework.cloud.alicloud.ans.ribbon;
|
||||
|
||||
import org.springframework.cloud.alicloud.ans.migrate.MigrateRibbonBeanPostProcessor;
|
||||
import org.springframework.cloud.alicloud.ans.migrate.MigrateOnConditionClass;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Conditional;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
import com.netflix.client.config.IClientConfig;
|
||||
|
||||
@Configuration
|
||||
@Conditional(MigrateOnConditionClass.class)
|
||||
public class MigrateRibbonCofiguration {
|
||||
|
||||
@Bean
|
||||
public MigrateRibbonBeanPostProcessor migrateBeanPostProcessor(IClientConfig clientConfig) {
|
||||
|
||||
return new MigrateRibbonBeanPostProcessor(clientConfig);
|
||||
}
|
||||
}
|
@ -1,6 +1,10 @@
|
||||
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
|
||||
org.springframework.cloud.alicloud.ans.endpoint.AnsEndpointAutoConfiguration,\
|
||||
org.springframework.cloud.alicloud.ans.ribbon.RibbonAnsAutoConfiguration,\
|
||||
org.springframework.cloud.alicloud.ans.AnsAutoConfiguration
|
||||
org.springframework.cloud.alicloud.ans.AnsAutoConfiguration,\
|
||||
org.springframework.cloud.alicloud.ans.migrate.MigrateEndpointAutoConfiguration,\
|
||||
org.springframework.cloud.alicloud.ans.migrate.MigrationAutoconfiguration
|
||||
org.springframework.cloud.client.discovery.EnableDiscoveryClient=\
|
||||
org.springframework.cloud.alicloud.ans.AnsDiscoveryClientAutoConfiguration
|
||||
org.springframework.context.ApplicationListener=\
|
||||
org.springframework.cloud.alicloud.ans.migrate.MigrateRefreshEventListener
|
@ -0,0 +1,107 @@
|
||||
package org.springframework.cloud.alicloud.context.sms;
|
||||
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.cloud.alicloud.context.AliCloudProperties;
|
||||
import org.springframework.core.env.Environment;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
/**
|
||||
* @author pbting
|
||||
*/
|
||||
@ConfigurationProperties(prefix = "spring.cloud.alicloud.sms")
|
||||
public class SmsConfigProperties implements Serializable {
|
||||
|
||||
// 产品名称:云通信短信API产品,开发者无需替换
|
||||
public static final String smsProduct = "Dysmsapi";
|
||||
// 产品域名,开发者无需替换
|
||||
public static final String smsDomain = "dysmsapi.aliyuncs.com";
|
||||
|
||||
private AliCloudProperties aliCloudProperties;
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private String reportQueueName;
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private String upQueueName;
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
protected String connnectTimeout = "10000";
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
protected String readTimeout = "10000";
|
||||
|
||||
public SmsConfigProperties(AliCloudProperties aliCloudProperties) {
|
||||
this.aliCloudProperties = aliCloudProperties;
|
||||
}
|
||||
|
||||
public String getConnnectTimeout() {
|
||||
return connnectTimeout;
|
||||
}
|
||||
|
||||
public void setConnnectTimeout(String connnectTimeout) {
|
||||
this.connnectTimeout = connnectTimeout;
|
||||
}
|
||||
|
||||
public String getReadTimeout() {
|
||||
return readTimeout;
|
||||
}
|
||||
|
||||
public void setReadTimeout(String readTimeout) {
|
||||
this.readTimeout = readTimeout;
|
||||
}
|
||||
|
||||
public void overiideFromEnv(Environment environment) {
|
||||
overiideCustomFromEnv(environment);
|
||||
if (StringUtils.isEmpty(connnectTimeout)) {
|
||||
String resolveResult = environment.resolveRequiredPlaceholders(
|
||||
"${spring.cloud.alibaba.sms.connect-timeout:}");
|
||||
this.setConnnectTimeout(
|
||||
StringUtils.isEmpty(resolveResult) ? "10000" : resolveResult);
|
||||
}
|
||||
|
||||
if (StringUtils.isEmpty(readTimeout)) {
|
||||
String resolveResult = environment.resolveRequiredPlaceholders(
|
||||
"${spring.cloud.alibaba.sms.read-timeout:}");
|
||||
this.setReadTimeout(
|
||||
StringUtils.isEmpty(resolveResult) ? "10000" : resolveResult);
|
||||
}
|
||||
}
|
||||
|
||||
public void overiideCustomFromEnv(Environment environment) {
|
||||
// nothing to do
|
||||
}
|
||||
|
||||
public String getReportQueueName() {
|
||||
return reportQueueName;
|
||||
}
|
||||
|
||||
public void setReportQueueName(String reportQueueName) {
|
||||
this.reportQueueName = reportQueueName;
|
||||
}
|
||||
|
||||
public String getUpQueueName() {
|
||||
return upQueueName;
|
||||
}
|
||||
|
||||
public String getAccessKeyId() {
|
||||
return aliCloudProperties.getAccessKey();
|
||||
}
|
||||
|
||||
public String getAccessKeySecret() {
|
||||
return aliCloudProperties.getSecretKey();
|
||||
}
|
||||
|
||||
public void setUpQueueName(String upQueueName) {
|
||||
this.upQueueName = upQueueName;
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,26 @@
|
||||
package org.springframework.cloud.alicloud.context.sms;
|
||||
|
||||
import org.springframework.core.env.Environment;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
|
||||
/**
|
||||
* @author pbting
|
||||
*/
|
||||
public class SmsConfigRegistration {
|
||||
|
||||
private Environment environment;
|
||||
|
||||
private SmsConfigProperties smsConfigProperties;
|
||||
|
||||
public SmsConfigRegistration(Environment environment,
|
||||
SmsConfigProperties smsConfigProperties) {
|
||||
this.environment = environment;
|
||||
this.smsConfigProperties = smsConfigProperties;
|
||||
}
|
||||
|
||||
@PostConstruct
|
||||
public void initSmsConfigRegistration() {
|
||||
smsConfigProperties.overiideFromEnv(environment);
|
||||
}
|
||||
}
|
@ -0,0 +1,30 @@
|
||||
package org.springframework.cloud.alicloud.context.sms;
|
||||
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||
import org.springframework.cloud.alicloud.context.AliCloudProperties;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.core.env.Environment;
|
||||
|
||||
@Configuration
|
||||
@EnableConfigurationProperties
|
||||
@ConditionalOnClass(name = "com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest")
|
||||
@ConditionalOnProperty(value = "spring.cloud.alibaba.deshao.enable.sms", matchIfMissing = true)
|
||||
public class SmsContextAutoConfiguration {
|
||||
|
||||
@Bean
|
||||
public SmsConfigProperties smsConfigProperties(
|
||||
AliCloudProperties aliCloudProperties) {
|
||||
|
||||
return new SmsConfigProperties(aliCloudProperties);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public SmsConfigRegistration smsConfigRegistration(Environment environment,
|
||||
SmsConfigProperties smsConfigProperties) {
|
||||
|
||||
return new SmsConfigRegistration(environment, smsConfigProperties);
|
||||
}
|
||||
}
|
@ -0,0 +1,83 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
|
||||
<parent>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-alibaba</artifactId>
|
||||
<version>0.2.2.BUILD-SNAPSHOT</version>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-alicloud-sms</artifactId>
|
||||
<name>Spring Cloud Alibaba Cloud SMS</name>
|
||||
|
||||
<dependencies>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-alicloud-context</artifactId>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>com.aliyun</groupId>
|
||||
<artifactId>aliyun-java-sdk-core</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
|
||||
<!-- sms -->
|
||||
<dependency>
|
||||
<groupId>com.aliyun</groupId>
|
||||
<artifactId>aliyun-java-sdk-core</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.aliyun</groupId>
|
||||
<artifactId>aliyun-java-sdk-dysmsapi</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.aliyun.mns</groupId>
|
||||
<artifactId>aliyun-sdk-mns</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.aliyun</groupId>
|
||||
<artifactId>aliyun-java-sdk-dysmsapi</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-actuator</artifactId>
|
||||
<scope>provided</scope>
|
||||
<optional>true</optional>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-actuator-autoconfigure</artifactId>
|
||||
<scope>provided</scope>
|
||||
<optional>true</optional>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-configuration-processor</artifactId>
|
||||
<scope>provided</scope>
|
||||
<optional>true</optional>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>slf4j-api</artifactId>
|
||||
<scope>provided</scope>
|
||||
<optional>true</optional>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
</project>
|
@ -0,0 +1,46 @@
|
||||
/*
|
||||
* Copyright (C) 2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.cloud.alicloud.sms;
|
||||
|
||||
import com.aliyuncs.DefaultAcsClient;
|
||||
import com.aliyuncs.IAcsClient;
|
||||
import com.aliyuncs.profile.DefaultProfile;
|
||||
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author pbting
|
||||
*/
|
||||
public abstract class AbstractSmsService implements ISmsService {
|
||||
|
||||
private ConcurrentHashMap<String, IAcsClient> acsClientConcurrentHashMap = new ConcurrentHashMap<>();
|
||||
|
||||
public IAcsClient getHangZhouRegionClientProfile(String accessKeyId,
|
||||
String accessKeySecret) {
|
||||
|
||||
return acsClientConcurrentHashMap.computeIfAbsent(
|
||||
getKey("cn-hangzhou", accessKeyId, accessKeySecret),
|
||||
(iacsClient) -> new DefaultAcsClient(DefaultProfile
|
||||
.getProfile("cn-hangzhou", accessKeyId, accessKeySecret)));
|
||||
}
|
||||
|
||||
private String getKey(String regionId, String accessKeyId, String accessKeySecret) {
|
||||
|
||||
return regionId + ":" + accessKeyId + ":" + accessKeySecret;
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,105 @@
|
||||
/*
|
||||
* Copyright (C) 2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.cloud.alicloud.sms;
|
||||
|
||||
import com.aliyuncs.exceptions.ClientException;
|
||||
import com.aliyuncs.profile.DefaultProfile;
|
||||
import org.springframework.boot.context.event.ApplicationStartedEvent;
|
||||
import org.springframework.cloud.alicloud.context.sms.SmsConfigProperties;
|
||||
import org.springframework.cloud.alicloud.sms.base.MessageListener;
|
||||
import org.springframework.context.ApplicationListener;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
|
||||
/**
|
||||
* @author pbting
|
||||
*/
|
||||
@Component
|
||||
public class SmsInitializerEventListener
|
||||
implements ApplicationListener<ApplicationStartedEvent> {
|
||||
|
||||
private final AtomicBoolean isCalled = new AtomicBoolean(false);
|
||||
|
||||
private SmsConfigProperties msConfigProperties;
|
||||
|
||||
private ISmsService smsService;
|
||||
|
||||
public SmsInitializerEventListener(SmsConfigProperties msConfigProperties,
|
||||
ISmsService smsService) {
|
||||
this.msConfigProperties = msConfigProperties;
|
||||
this.smsService = smsService;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onApplicationEvent(ApplicationStartedEvent event) {
|
||||
if (!isCalled.compareAndSet(false, true)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 整个application context refreshed then do
|
||||
// 可自助调整超时时间
|
||||
System.setProperty("sun.net.client.defaultConnectTimeout",
|
||||
msConfigProperties.getConnnectTimeout());
|
||||
System.setProperty("sun.net.client.defaultReadTimeout",
|
||||
msConfigProperties.getReadTimeout());
|
||||
// 初始化acsClient,暂不支持region化
|
||||
try {
|
||||
DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou",
|
||||
SmsConfigProperties.smsProduct, SmsConfigProperties.smsDomain);
|
||||
Collection<MessageListener> messageListeners = event.getApplicationContext()
|
||||
.getBeansOfType(MessageListener.class).values();
|
||||
if (messageListeners.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (MessageListener messageListener : messageListeners) {
|
||||
if (SmsReportMessageListener.class.isInstance(messageListener)) {
|
||||
if (msConfigProperties.getReportQueueName() != null
|
||||
&& msConfigProperties.getReportQueueName().trim()
|
||||
.length() > 0) {
|
||||
smsService.startSmsReportMessageListener(
|
||||
(SmsReportMessageListener) messageListener);
|
||||
continue;
|
||||
}
|
||||
|
||||
throw new IllegalArgumentException("the SmsReport queue name for "
|
||||
+ messageListener.getClass().getCanonicalName()
|
||||
+ " must be set.");
|
||||
}
|
||||
|
||||
if (SmsUpMessageListener.class.isInstance(messageListener)) {
|
||||
|
||||
if (msConfigProperties.getUpQueueName() != null
|
||||
&& msConfigProperties.getUpQueueName().trim().length() > 0) {
|
||||
smsService.startSmsUpMessageListener(
|
||||
(SmsUpMessageListener) messageListener);
|
||||
continue;
|
||||
}
|
||||
|
||||
throw new IllegalArgumentException("the SmsUp queue name for "
|
||||
+ messageListener.getClass().getCanonicalName()
|
||||
+ " must be set.");
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (ClientException e) {
|
||||
throw new RuntimeException(
|
||||
"initialize sms profile end point cause an exception");
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,24 @@
|
||||
/*
|
||||
* Copyright (C) 2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.cloud.alicloud.sms;
|
||||
|
||||
import org.springframework.cloud.alicloud.sms.base.MessageListener;
|
||||
|
||||
/**
|
||||
* @author pbting
|
||||
*/
|
||||
public interface SmsMessageListener extends MessageListener {
|
||||
}
|
@ -0,0 +1,22 @@
|
||||
/*
|
||||
* Copyright (C) 2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.cloud.alicloud.sms;
|
||||
|
||||
/**
|
||||
* @author pbting
|
||||
*/
|
||||
public interface SmsReportMessageListener extends SmsMessageListener {
|
||||
}
|
@ -0,0 +1,22 @@
|
||||
/*
|
||||
* Copyright (C) 2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.cloud.alicloud.sms;
|
||||
|
||||
/**
|
||||
* @author pbting
|
||||
*/
|
||||
public interface SmsUpMessageListener extends SmsMessageListener {
|
||||
}
|
@ -0,0 +1,429 @@
|
||||
/*
|
||||
* Copyright (C) 2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package 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;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.ScheduledThreadPoolExecutor;
|
||||
|
||||
/**
|
||||
* 阿里通信官方消息默认拉取工具类
|
||||
*/
|
||||
public class DefaultAlicomMessagePuller {
|
||||
|
||||
private Log logger = LogFactory.getLog(DefaultAlicomMessagePuller.class);
|
||||
|
||||
private String mnsAccountEndpoint = "https://1943695596114318.mns.cn-hangzhou.aliyuncs.com/";// 阿里通信消息的endpoint,固定。
|
||||
private String endpointNameForPop = "cn-hangzhou";
|
||||
private String regionIdForPop = "cn-hangzhou";
|
||||
private String domainForPop = "dybaseapi.aliyuncs.com";
|
||||
private TokenGetterForAlicom tokenGetter;
|
||||
private MessageListener messageListener;
|
||||
private boolean isRunning = false;
|
||||
private Integer pullMsgThreadSize = 1;
|
||||
private boolean debugLogOpen = false;
|
||||
private Integer sleepSecondWhenNoData = 30;
|
||||
|
||||
public void openDebugLog(boolean debugLogOpen) {
|
||||
this.debugLogOpen = debugLogOpen;
|
||||
}
|
||||
|
||||
public Integer getSleepSecondWhenNoData() {
|
||||
return sleepSecondWhenNoData;
|
||||
}
|
||||
|
||||
public void setSleepSecondWhenNoData(Integer sleepSecondWhenNoData) {
|
||||
this.sleepSecondWhenNoData = sleepSecondWhenNoData;
|
||||
}
|
||||
|
||||
public Integer getPullMsgThreadSize() {
|
||||
return pullMsgThreadSize;
|
||||
}
|
||||
|
||||
public void setPullMsgThreadSize(Integer pullMsgThreadSize) {
|
||||
if (pullMsgThreadSize != null && pullMsgThreadSize > 1) {
|
||||
this.pullMsgThreadSize = pullMsgThreadSize;
|
||||
}
|
||||
}
|
||||
|
||||
private ExecutorService executorService;
|
||||
|
||||
public ExecutorService getExecutorService() {
|
||||
return executorService;
|
||||
}
|
||||
|
||||
public void setExecutorService(ExecutorService executorService) {
|
||||
this.executorService = executorService;
|
||||
}
|
||||
|
||||
protected static final Map<String, Object> sLockObjMap = new HashMap<String, Object>();
|
||||
protected static Map<String, Boolean> sPollingMap = new ConcurrentHashMap<String, Boolean>();
|
||||
protected Object lockObj;
|
||||
|
||||
public boolean setPolling(String queueName) {
|
||||
synchronized (lockObj) {
|
||||
Boolean ret = sPollingMap.get(queueName);
|
||||
if (ret == null || !ret) {
|
||||
sPollingMap.put(queueName, true);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public void clearPolling(String queueName) {
|
||||
synchronized (lockObj) {
|
||||
sPollingMap.put(queueName, false);
|
||||
lockObj.notifyAll();
|
||||
if (debugLogOpen) {
|
||||
logger.info("PullMessageTask_WakeUp:Everyone WakeUp and Work!");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isRunning() {
|
||||
return isRunning;
|
||||
}
|
||||
|
||||
public void setRunning(boolean running) {
|
||||
isRunning = running;
|
||||
}
|
||||
|
||||
private class PullMessageTask implements Runnable {
|
||||
private String messageType;
|
||||
private String queueName;
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
|
||||
boolean polling = false;
|
||||
while (isRunning) {
|
||||
try {
|
||||
synchronized (lockObj) {
|
||||
Boolean p = sPollingMap.get(queueName);
|
||||
if (p != null && p) {
|
||||
try {
|
||||
if (debugLogOpen) {
|
||||
logger.info("PullMessageTask_sleep:"
|
||||
+ Thread.currentThread().getName()
|
||||
+ " Have a nice sleep!");
|
||||
}
|
||||
polling = false;
|
||||
lockObj.wait();
|
||||
}
|
||||
catch (InterruptedException e) {
|
||||
if (debugLogOpen) {
|
||||
logger.info("PullMessageTask_Interrupted!"
|
||||
+ Thread.currentThread().getName()
|
||||
+ " QueueName is " + queueName);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
TokenForAlicom tokenObject = tokenGetter.getTokenByMessageType(
|
||||
messageType, queueName, mnsAccountEndpoint);
|
||||
CloudQueue queue = tokenObject.getQueue();
|
||||
Message popMsg = null;
|
||||
if (!polling) {
|
||||
popMsg = queue.popMessage();
|
||||
if (debugLogOpen) {
|
||||
SimpleDateFormat format = new SimpleDateFormat(
|
||||
"yyyy-MM-dd HH:mm:ss");
|
||||
logger.info("PullMessageTask_popMessage:"
|
||||
+ Thread.currentThread().getName() + "-popDone at "
|
||||
+ "," + format.format(new Date()) + " msgSize="
|
||||
+ (popMsg == null ? 0 : popMsg.getMessageId()));
|
||||
}
|
||||
if (popMsg == null) {
|
||||
polling = true;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
else {
|
||||
if (setPolling(queueName)) {
|
||||
if (debugLogOpen) {
|
||||
logger.info("PullMessageTask_setPolling:"
|
||||
+ Thread.currentThread().getName() + " Polling!");
|
||||
}
|
||||
}
|
||||
else {
|
||||
continue;
|
||||
}
|
||||
do {
|
||||
if (debugLogOpen) {
|
||||
logger.info("PullMessageTask_Keep_Polling"
|
||||
+ Thread.currentThread().getName()
|
||||
+ "KEEP Polling!");
|
||||
}
|
||||
try {
|
||||
popMsg = queue.popMessage(sleepSecondWhenNoData);
|
||||
}
|
||||
catch (ClientException e) {
|
||||
if (debugLogOpen) {
|
||||
logger.info(
|
||||
"PullMessageTask_Pop_Message:ClientException Refresh accessKey"
|
||||
+ e);
|
||||
}
|
||||
tokenObject = tokenGetter.getTokenByMessageType(
|
||||
messageType, queueName, mnsAccountEndpoint);
|
||||
queue = tokenObject.getQueue();
|
||||
|
||||
}
|
||||
catch (ServiceException e) {
|
||||
if (debugLogOpen) {
|
||||
logger.info(
|
||||
"PullMessageTask_Pop_Message:ServiceException Refresh accessKey"
|
||||
+ e);
|
||||
}
|
||||
tokenObject = tokenGetter.getTokenByMessageType(
|
||||
messageType, queueName, mnsAccountEndpoint);
|
||||
queue = tokenObject.getQueue();
|
||||
|
||||
}
|
||||
catch (Exception e) {
|
||||
if (debugLogOpen) {
|
||||
logger.info(
|
||||
"PullMessageTask_Pop_Message:Exception Happened when polling popMessage: "
|
||||
+ e);
|
||||
}
|
||||
}
|
||||
}
|
||||
while (popMsg == null && isRunning);
|
||||
clearPolling(queueName);
|
||||
}
|
||||
boolean dealResult = messageListener.dealMessage(popMsg);
|
||||
if (dealResult) {
|
||||
// remember to delete message when consume message successfully.
|
||||
if (debugLogOpen) {
|
||||
logger.info("PullMessageTask_Deal_Message:"
|
||||
+ Thread.currentThread().getName() + "deleteMessage "
|
||||
+ popMsg.getMessageId());
|
||||
}
|
||||
queue.deleteMessage(popMsg.getReceiptHandle());
|
||||
}
|
||||
}
|
||||
catch (ClientException e) {
|
||||
logger.error("PullMessageTask_execute_error,messageType:"
|
||||
+ messageType + ",queueName:" + queueName, e);
|
||||
break;
|
||||
|
||||
}
|
||||
catch (ServiceException e) {
|
||||
if (e.getErrorCode().equals("AccessDenied")) {
|
||||
logger.error("PullMessageTask_execute_error,messageType:"
|
||||
+ messageType + ",queueName:" + queueName
|
||||
+ ",please check messageType and queueName", e);
|
||||
}
|
||||
else {
|
||||
logger.error("PullMessageTask_execute_error,messageType:"
|
||||
+ messageType + ",queueName:" + queueName, e);
|
||||
}
|
||||
break;
|
||||
|
||||
}
|
||||
catch (com.aliyuncs.exceptions.ClientException e) {
|
||||
if (e.getErrCode().equals("InvalidAccessKeyId.NotFound")) {
|
||||
logger.error("PullMessageTask_execute_error,messageType:"
|
||||
+ messageType + ",queueName:" + queueName
|
||||
+ ",please check AccessKeyId", e);
|
||||
}
|
||||
if (e.getErrCode().equals("SignatureDoesNotMatch")) {
|
||||
logger.error("PullMessageTask_execute_error,messageType:"
|
||||
+ messageType + ",queueName:" + queueName
|
||||
+ ",please check AccessKeySecret", e);
|
||||
}
|
||||
else {
|
||||
logger.error("PullMessageTask_execute_error,messageType:"
|
||||
+ messageType + ",queueName:" + queueName, e);
|
||||
}
|
||||
break;
|
||||
|
||||
}
|
||||
catch (Exception e) {
|
||||
logger.error("PullMessageTask_execute_error,messageType:"
|
||||
+ messageType + ",queueName:" + queueName, e);
|
||||
try {
|
||||
Thread.sleep(sleepSecondWhenNoData);
|
||||
}
|
||||
catch (InterruptedException e1) {
|
||||
logger.error("PullMessageTask_execute_error,messageType:"
|
||||
+ messageType + ",queueName:" + queueName, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* @param accessKeyId accessKeyId
|
||||
* @param accessKeySecret accessKeySecret
|
||||
* @param messageType 消息类型
|
||||
* @param queueName 队列名称
|
||||
* @param messageListener 回调的listener,用户自己实现
|
||||
* @throws com.aliyuncs.exceptions.ClientException
|
||||
* @throws ParseException
|
||||
*/
|
||||
public void startReceiveMsg(String accessKeyId, String accessKeySecret,
|
||||
String messageType, String queueName, MessageListener messageListener)
|
||||
throws com.aliyuncs.exceptions.ClientException, ParseException {
|
||||
|
||||
tokenGetter = new TokenGetterForAlicom(accessKeyId, accessKeySecret,
|
||||
endpointNameForPop, regionIdForPop, domainForPop, null);
|
||||
|
||||
this.messageListener = messageListener;
|
||||
isRunning = true;
|
||||
PullMessageTask task = new PullMessageTask();
|
||||
task.messageType = messageType;
|
||||
task.queueName = queueName;
|
||||
|
||||
synchronized (sLockObjMap) {
|
||||
lockObj = sLockObjMap.get(queueName);
|
||||
if (lockObj == null) {
|
||||
lockObj = new Object();
|
||||
sLockObjMap.put(queueName, lockObj);
|
||||
}
|
||||
}
|
||||
|
||||
if (executorService == null) {
|
||||
ScheduledExecutorService scheduledExecutorService = new ScheduledThreadPoolExecutor(
|
||||
pullMsgThreadSize,
|
||||
new BasicThreadFactory.Builder()
|
||||
.namingPattern(
|
||||
"PullMessageTask-" + messageType + "-thread-pool-%d")
|
||||
.daemon(true).build());
|
||||
executorService = scheduledExecutorService;
|
||||
}
|
||||
for (int i = 0; i < pullMsgThreadSize; i++) {
|
||||
executorService.execute(task);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param accessKeyId accessKeyId
|
||||
* @param accessKeySecret accessKeySecret
|
||||
* @param messageType 消息类型
|
||||
* @param queueName 队列名称
|
||||
* @param messageListener 回调的listener,用户自己实现
|
||||
* @throws com.aliyuncs.exceptions.ClientException
|
||||
* @throws ParseException
|
||||
*/
|
||||
public void startReceiveMsgForVPC(String accessKeyId, String accessKeySecret,
|
||||
String messageType, String queueName, String regionIdForPop,
|
||||
String endpointNameForPop, String domainForPop, String mnsAccountEndpoint,
|
||||
MessageListener messageListener)
|
||||
throws com.aliyuncs.exceptions.ClientException, ParseException {
|
||||
this.mnsAccountEndpoint = mnsAccountEndpoint;
|
||||
tokenGetter = new TokenGetterForAlicom(accessKeyId, accessKeySecret,
|
||||
endpointNameForPop, regionIdForPop, domainForPop, null);
|
||||
|
||||
this.messageListener = messageListener;
|
||||
isRunning = true;
|
||||
PullMessageTask task = new PullMessageTask();
|
||||
task.messageType = messageType;
|
||||
task.queueName = queueName;
|
||||
|
||||
synchronized (sLockObjMap) {
|
||||
lockObj = sLockObjMap.get(queueName);
|
||||
if (lockObj == null) {
|
||||
lockObj = new Object();
|
||||
sLockObjMap.put(queueName, lockObj);
|
||||
}
|
||||
}
|
||||
|
||||
if (executorService == null) {
|
||||
ScheduledExecutorService scheduledExecutorService = new ScheduledThreadPoolExecutor(
|
||||
pullMsgThreadSize,
|
||||
new BasicThreadFactory.Builder()
|
||||
.namingPattern(
|
||||
"PullMessageTask-" + messageType + "-thread-pool-%d")
|
||||
.daemon(true).build());
|
||||
executorService = scheduledExecutorService;
|
||||
}
|
||||
for (int i = 0; i < pullMsgThreadSize; i++) {
|
||||
executorService.execute(task);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 虚商用户定制接收消息方法
|
||||
* @param accessKeyId accessKeyId
|
||||
* @param accessKeySecret accessKeySecret
|
||||
* @param ownerId 实际的ownerId
|
||||
* @param messageType 消息类型
|
||||
* @param queueName 队列名称
|
||||
* @param messageListener 回调listener
|
||||
* @throws com.aliyuncs.exceptions.ClientException
|
||||
* @throws ParseException
|
||||
*/
|
||||
public void startReceiveMsgForPartnerUser(String accessKeyId, String accessKeySecret,
|
||||
Long ownerId, String messageType, String queueName,
|
||||
MessageListener messageListener)
|
||||
throws com.aliyuncs.exceptions.ClientException, ParseException {
|
||||
|
||||
tokenGetter = new TokenGetterForAlicom(accessKeyId, accessKeySecret,
|
||||
endpointNameForPop, regionIdForPop, domainForPop, ownerId);
|
||||
|
||||
this.messageListener = messageListener;
|
||||
isRunning = true;
|
||||
PullMessageTask task = new PullMessageTask();
|
||||
task.messageType = messageType;
|
||||
task.queueName = queueName;
|
||||
|
||||
synchronized (sLockObjMap) {
|
||||
lockObj = sLockObjMap.get(queueName);
|
||||
if (lockObj == null) {
|
||||
lockObj = new Object();
|
||||
sLockObjMap.put(queueName, lockObj);
|
||||
}
|
||||
}
|
||||
|
||||
if (executorService == null) {
|
||||
ScheduledExecutorService scheduledExecutorService = new ScheduledThreadPoolExecutor(
|
||||
pullMsgThreadSize,
|
||||
new BasicThreadFactory.Builder()
|
||||
.namingPattern(
|
||||
"PullMessageTask-" + messageType + "-thread-pool-%d")
|
||||
.daemon(true).build());
|
||||
executorService = scheduledExecutorService;
|
||||
}
|
||||
for (int i = 0; i < pullMsgThreadSize; i++) {
|
||||
executorService.execute(task);
|
||||
}
|
||||
}
|
||||
|
||||
public void stop() {
|
||||
isRunning = false;
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,24 @@
|
||||
/*
|
||||
* Copyright (C) 2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.cloud.alicloud.sms.base;
|
||||
|
||||
import com.aliyun.mns.model.Message;
|
||||
|
||||
public interface MessageListener {
|
||||
|
||||
boolean dealMessage(Message message);
|
||||
|
||||
}
|
@ -0,0 +1,82 @@
|
||||
/*
|
||||
* Copyright (C) 2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.cloud.alicloud.sms.base;
|
||||
|
||||
import com.aliyuncs.RpcAcsRequest;
|
||||
|
||||
public class QueryTokenForMnsQueueRequest
|
||||
extends RpcAcsRequest<QueryTokenForMnsQueueResponse> {
|
||||
private String resourceOwnerAccount;
|
||||
private String messageType;
|
||||
private Long resourceOwnerId;
|
||||
private Long ownerId;
|
||||
|
||||
public QueryTokenForMnsQueueRequest() {
|
||||
super("Dybaseapi", "2017-05-25", "QueryTokenForMnsQueue");
|
||||
}
|
||||
|
||||
public String getResourceOwnerAccount() {
|
||||
return this.resourceOwnerAccount;
|
||||
}
|
||||
|
||||
public void setResourceOwnerAccount(String resourceOwnerAccount) {
|
||||
this.resourceOwnerAccount = resourceOwnerAccount;
|
||||
if (resourceOwnerAccount != null) {
|
||||
this.putQueryParameter("ResourceOwnerAccount", resourceOwnerAccount);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public String getMessageType() {
|
||||
return this.messageType;
|
||||
}
|
||||
|
||||
public void setMessageType(String messageType) {
|
||||
this.messageType = messageType;
|
||||
if (messageType != null) {
|
||||
this.putQueryParameter("MessageType", messageType);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public Long getResourceOwnerId() {
|
||||
return this.resourceOwnerId;
|
||||
}
|
||||
|
||||
public void setResourceOwnerId(Long resourceOwnerId) {
|
||||
this.resourceOwnerId = resourceOwnerId;
|
||||
if (resourceOwnerId != null) {
|
||||
this.putQueryParameter("ResourceOwnerId", resourceOwnerId.toString());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public Long getOwnerId() {
|
||||
return this.ownerId;
|
||||
}
|
||||
|
||||
public void setOwnerId(Long ownerId) {
|
||||
this.ownerId = ownerId;
|
||||
if (ownerId != null) {
|
||||
this.putQueryParameter("OwnerId", ownerId.toString());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public Class<QueryTokenForMnsQueueResponse> getResponseClass() {
|
||||
return QueryTokenForMnsQueueResponse.class;
|
||||
}
|
||||
}
|
@ -0,0 +1,117 @@
|
||||
/*
|
||||
* Copyright (C) 2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.cloud.alicloud.sms.base;
|
||||
|
||||
import com.aliyuncs.AcsResponse;
|
||||
import com.aliyuncs.transform.UnmarshallerContext;
|
||||
|
||||
public class QueryTokenForMnsQueueResponse extends AcsResponse {
|
||||
private String requestId;
|
||||
private String code;
|
||||
private String message;
|
||||
private QueryTokenForMnsQueueResponse.MessageTokenDTO messageTokenDTO;
|
||||
|
||||
public QueryTokenForMnsQueueResponse() {
|
||||
}
|
||||
|
||||
public String getRequestId() {
|
||||
return this.requestId;
|
||||
}
|
||||
|
||||
public void setRequestId(String requestId) {
|
||||
this.requestId = requestId;
|
||||
}
|
||||
|
||||
public String getCode() {
|
||||
return this.code;
|
||||
}
|
||||
|
||||
public void setCode(String code) {
|
||||
this.code = code;
|
||||
}
|
||||
|
||||
public String getMessage() {
|
||||
return this.message;
|
||||
}
|
||||
|
||||
public void setMessage(String message) {
|
||||
this.message = message;
|
||||
}
|
||||
|
||||
public QueryTokenForMnsQueueResponse.MessageTokenDTO getMessageTokenDTO() {
|
||||
return this.messageTokenDTO;
|
||||
}
|
||||
|
||||
public void setMessageTokenDTO(
|
||||
QueryTokenForMnsQueueResponse.MessageTokenDTO messageTokenDTO) {
|
||||
this.messageTokenDTO = messageTokenDTO;
|
||||
}
|
||||
|
||||
public QueryTokenForMnsQueueResponse getInstance(UnmarshallerContext context) {
|
||||
return QueryTokenForMnsQueueResponseUnmarshaller.unmarshall(this, context);
|
||||
}
|
||||
|
||||
public static class MessageTokenDTO {
|
||||
private String accessKeyId;
|
||||
private String accessKeySecret;
|
||||
private String securityToken;
|
||||
private String createTime;
|
||||
private String expireTime;
|
||||
|
||||
public MessageTokenDTO() {
|
||||
}
|
||||
|
||||
public String getAccessKeyId() {
|
||||
return this.accessKeyId;
|
||||
}
|
||||
|
||||
public void setAccessKeyId(String accessKeyId) {
|
||||
this.accessKeyId = accessKeyId;
|
||||
}
|
||||
|
||||
public String getAccessKeySecret() {
|
||||
return this.accessKeySecret;
|
||||
}
|
||||
|
||||
public void setAccessKeySecret(String accessKeySecret) {
|
||||
this.accessKeySecret = accessKeySecret;
|
||||
}
|
||||
|
||||
public String getSecurityToken() {
|
||||
return this.securityToken;
|
||||
}
|
||||
|
||||
public void setSecurityToken(String securityToken) {
|
||||
this.securityToken = securityToken;
|
||||
}
|
||||
|
||||
public String getCreateTime() {
|
||||
return this.createTime;
|
||||
}
|
||||
|
||||
public void setCreateTime(String createTime) {
|
||||
this.createTime = createTime;
|
||||
}
|
||||
|
||||
public String getExpireTime() {
|
||||
return this.expireTime;
|
||||
}
|
||||
|
||||
public void setExpireTime(String expireTime) {
|
||||
this.expireTime = expireTime;
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,48 @@
|
||||
/*
|
||||
* Copyright (C) 2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.cloud.alicloud.sms.base;
|
||||
|
||||
import com.aliyuncs.transform.UnmarshallerContext;
|
||||
|
||||
public class QueryTokenForMnsQueueResponseUnmarshaller {
|
||||
|
||||
public QueryTokenForMnsQueueResponseUnmarshaller() {
|
||||
}
|
||||
|
||||
public static QueryTokenForMnsQueueResponse unmarshall(
|
||||
QueryTokenForMnsQueueResponse queryTokenForMnsQueueResponse,
|
||||
UnmarshallerContext context) {
|
||||
queryTokenForMnsQueueResponse.setRequestId(
|
||||
context.stringValue("QueryTokenForMnsQueueResponse.RequestId"));
|
||||
queryTokenForMnsQueueResponse
|
||||
.setCode(context.stringValue("QueryTokenForMnsQueueResponse.Code"));
|
||||
queryTokenForMnsQueueResponse
|
||||
.setMessage(context.stringValue("QueryTokenForMnsQueueResponse.Message"));
|
||||
QueryTokenForMnsQueueResponse.MessageTokenDTO messageTokenDTO = new QueryTokenForMnsQueueResponse.MessageTokenDTO();
|
||||
messageTokenDTO.setAccessKeyId(context.stringValue(
|
||||
"QueryTokenForMnsQueueResponse.MessageTokenDTO.AccessKeyId"));
|
||||
messageTokenDTO.setAccessKeySecret(context.stringValue(
|
||||
"QueryTokenForMnsQueueResponse.MessageTokenDTO.AccessKeySecret"));
|
||||
messageTokenDTO.setSecurityToken(context.stringValue(
|
||||
"QueryTokenForMnsQueueResponse.MessageTokenDTO.SecurityToken"));
|
||||
messageTokenDTO.setCreateTime(context
|
||||
.stringValue("QueryTokenForMnsQueueResponse.MessageTokenDTO.CreateTime"));
|
||||
messageTokenDTO.setExpireTime(context
|
||||
.stringValue("QueryTokenForMnsQueueResponse.MessageTokenDTO.ExpireTime"));
|
||||
queryTokenForMnsQueueResponse.setMessageTokenDTO(messageTokenDTO);
|
||||
return queryTokenForMnsQueueResponse;
|
||||
}
|
||||
}
|
@ -0,0 +1,96 @@
|
||||
/*
|
||||
* Copyright (C) 2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.cloud.alicloud.sms.base;
|
||||
|
||||
import com.aliyun.mns.client.CloudQueue;
|
||||
import com.aliyun.mns.client.MNSClient;
|
||||
|
||||
/**
|
||||
* 用于接收云通信消息的临时token
|
||||
*
|
||||
*/
|
||||
public class TokenForAlicom {
|
||||
private String messageType;
|
||||
private String token;
|
||||
private Long expireTime;
|
||||
private String tempAccessKeyId;
|
||||
private String tempAccessKeySecret;
|
||||
private MNSClient client;
|
||||
private CloudQueue queue;
|
||||
|
||||
public String getMessageType() {
|
||||
return messageType;
|
||||
}
|
||||
|
||||
public void setMessageType(String messageType) {
|
||||
this.messageType = messageType;
|
||||
}
|
||||
|
||||
public String getToken() {
|
||||
return token;
|
||||
}
|
||||
|
||||
public void setToken(String token) {
|
||||
this.token = token;
|
||||
}
|
||||
|
||||
public Long getExpireTime() {
|
||||
return expireTime;
|
||||
}
|
||||
|
||||
public void setExpireTime(Long expireTime) {
|
||||
this.expireTime = expireTime;
|
||||
}
|
||||
|
||||
public String getTempAccessKeyId() {
|
||||
return tempAccessKeyId;
|
||||
}
|
||||
|
||||
public void setTempAccessKeyId(String tempAccessKeyId) {
|
||||
this.tempAccessKeyId = tempAccessKeyId;
|
||||
}
|
||||
|
||||
public String getTempAccessKeySecret() {
|
||||
return tempAccessKeySecret;
|
||||
}
|
||||
|
||||
public void setTempAccessKeySecret(String tempAccessKeySecret) {
|
||||
this.tempAccessKeySecret = tempAccessKeySecret;
|
||||
}
|
||||
|
||||
public MNSClient getClient() {
|
||||
return client;
|
||||
}
|
||||
|
||||
public void setClient(MNSClient client) {
|
||||
this.client = client;
|
||||
}
|
||||
|
||||
public CloudQueue getQueue() {
|
||||
return queue;
|
||||
}
|
||||
|
||||
public void setQueue(CloudQueue queue) {
|
||||
this.queue = queue;
|
||||
}
|
||||
|
||||
public void closeClient() {
|
||||
if (client != null) {
|
||||
this.client.close();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,49 @@
|
||||
/*
|
||||
* Copyright (C) 2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.cloud.alicloud.sms.config;
|
||||
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||
import org.springframework.cloud.alicloud.context.sms.SmsConfigProperties;
|
||||
import org.springframework.cloud.alicloud.sms.ISmsService;
|
||||
import org.springframework.cloud.alicloud.sms.SmsInitializerEventListener;
|
||||
import org.springframework.cloud.alicloud.sms.SmsServiceImpl;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
|
||||
|
||||
/**
|
||||
* @author pbting
|
||||
*/
|
||||
@Configuration
|
||||
@EnableConfigurationProperties
|
||||
@ConditionalOnClass(value = SendSmsRequest.class)
|
||||
@ConditionalOnProperty(value = "spring.cloud.alicloud.sms.enable", matchIfMissing = true)
|
||||
public class SmsAutoConfiguration {
|
||||
|
||||
@Bean
|
||||
public SmsServiceImpl smsService(SmsConfigProperties smsConfigProperties) {
|
||||
return new SmsServiceImpl(smsConfigProperties);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public SmsInitializerEventListener smsInitializePostListener(
|
||||
SmsConfigProperties msConfigProperties, ISmsService smsService) {
|
||||
return new SmsInitializerEventListener(msConfigProperties, smsService);
|
||||
}
|
||||
}
|
@ -0,0 +1,106 @@
|
||||
/*
|
||||
* Copyright (C) 2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.cloud.alicloud.sms.endpoint;
|
||||
|
||||
import com.aliyuncs.dysmsapi.model.v20170525.SendBatchSmsRequest;
|
||||
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.LinkedBlockingQueue;
|
||||
import java.util.concurrent.locks.ReentrantLock;
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
public final class EndpointManager {
|
||||
|
||||
private final static int BACKLOG_SIZE = 20;
|
||||
|
||||
private final static ReentrantLock SEND_REENTRANT_LOCK = new ReentrantLock(true);
|
||||
private final static ReentrantLock SEND_BATCH_REENTRANT_LOCK = new ReentrantLock(
|
||||
true);
|
||||
|
||||
private final static LinkedBlockingQueue<SendSmsRequest> SEND_SMS_REQUESTS = new LinkedBlockingQueue(
|
||||
BACKLOG_SIZE);
|
||||
private final static LinkedBlockingQueue<SendBatchSmsRequest> SEND_BATCH_SMS_REQUESTS = new LinkedBlockingQueue(
|
||||
BACKLOG_SIZE);
|
||||
private final static LinkedBlockingQueue<ReceiveMessageEntity> RECEIVE_MESSAGE_ENTITIES = new LinkedBlockingQueue(
|
||||
BACKLOG_SIZE);
|
||||
|
||||
public static void addSendSmsRequest(SendSmsRequest sendSmsRequest) {
|
||||
if (SEND_SMS_REQUESTS.offer(sendSmsRequest)) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
SEND_REENTRANT_LOCK.lock();
|
||||
SEND_SMS_REQUESTS.poll();
|
||||
SEND_SMS_REQUESTS.offer(sendSmsRequest);
|
||||
}
|
||||
finally {
|
||||
SEND_REENTRANT_LOCK.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
public static void addSendBatchSmsRequest(SendBatchSmsRequest sendBatchSmsRequest) {
|
||||
if (SEND_BATCH_SMS_REQUESTS.offer(sendBatchSmsRequest)) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
SEND_BATCH_REENTRANT_LOCK.lock();
|
||||
SEND_BATCH_SMS_REQUESTS.poll();
|
||||
SEND_BATCH_SMS_REQUESTS.offer(sendBatchSmsRequest);
|
||||
}
|
||||
finally {
|
||||
SEND_BATCH_REENTRANT_LOCK.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
public static void addReceiveMessageEntity(
|
||||
ReceiveMessageEntity receiveMessageEntity) {
|
||||
if (RECEIVE_MESSAGE_ENTITIES.offer(receiveMessageEntity)) {
|
||||
return;
|
||||
}
|
||||
RECEIVE_MESSAGE_ENTITIES.poll();
|
||||
RECEIVE_MESSAGE_ENTITIES.offer(receiveMessageEntity);
|
||||
}
|
||||
|
||||
public static Map<String, Object> getSmsEndpointMessage() {
|
||||
List<SendSmsRequest> sendSmsRequests = new LinkedList<>();
|
||||
List<SendBatchSmsRequest> sendBatchSmsRequests = new LinkedList<>();
|
||||
List<ReceiveMessageEntity> receiveMessageEntities = new LinkedList<>();
|
||||
try {
|
||||
SEND_REENTRANT_LOCK.lock();
|
||||
SEND_BATCH_REENTRANT_LOCK.lock();
|
||||
sendSmsRequests.addAll(SEND_SMS_REQUESTS);
|
||||
sendBatchSmsRequests.addAll(SEND_BATCH_SMS_REQUESTS);
|
||||
}
|
||||
finally {
|
||||
SEND_REENTRANT_LOCK.unlock();
|
||||
SEND_BATCH_REENTRANT_LOCK.unlock();
|
||||
}
|
||||
receiveMessageEntities.addAll(RECEIVE_MESSAGE_ENTITIES);
|
||||
|
||||
Map<String, Object> endpointMessages = new HashMap<>();
|
||||
endpointMessages.put("send-sms-request", sendSmsRequests);
|
||||
endpointMessages.put("send-batch-sms-request", sendBatchSmsRequests);
|
||||
endpointMessages.put("message-listener", receiveMessageEntities);
|
||||
|
||||
return endpointMessages;
|
||||
}
|
||||
}
|
@ -0,0 +1,60 @@
|
||||
/*
|
||||
* Copyright (C) 2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.cloud.alicloud.sms.endpoint;
|
||||
|
||||
import org.springframework.cloud.alicloud.sms.base.MessageListener;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
/**
|
||||
* @author pbting
|
||||
*/
|
||||
public class ReceiveMessageEntity implements Serializable {
|
||||
private String messageType;
|
||||
private String queueName;
|
||||
private MessageListener messageListener;
|
||||
|
||||
public ReceiveMessageEntity(String messageType, String queueName,
|
||||
MessageListener messageListener) {
|
||||
this.messageType = messageType;
|
||||
this.queueName = queueName;
|
||||
this.messageListener = messageListener;
|
||||
}
|
||||
|
||||
public String getMessageType() {
|
||||
return messageType;
|
||||
}
|
||||
|
||||
public void setMessageType(String messageType) {
|
||||
this.messageType = messageType;
|
||||
}
|
||||
|
||||
public String getQueueName() {
|
||||
return queueName;
|
||||
}
|
||||
|
||||
public void setQueueName(String queueName) {
|
||||
this.queueName = queueName;
|
||||
}
|
||||
|
||||
public MessageListener getMessageListener() {
|
||||
return messageListener;
|
||||
}
|
||||
|
||||
public void setMessageListener(MessageListener messageListener) {
|
||||
this.messageListener = messageListener;
|
||||
}
|
||||
}
|
@ -0,0 +1,31 @@
|
||||
/*
|
||||
* Copyright (C) 2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.cloud.alicloud.sms.endpoint;
|
||||
|
||||
import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
|
||||
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
@Endpoint(id = "sms-info")
|
||||
public class SmsEndpoint {
|
||||
|
||||
@ReadOperation
|
||||
public Map<String, Object> invoke() {
|
||||
|
||||
return EndpointManager.getSmsEndpointMessage();
|
||||
}
|
||||
}
|
@ -0,0 +1,31 @@
|
||||
/*
|
||||
* Copyright (C) 2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.cloud.alicloud.sms.endpoint;
|
||||
|
||||
import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
|
||||
@ConditionalOnWebApplication
|
||||
@ConditionalOnClass(Endpoint.class)
|
||||
public class SmsEndpointAutoConfiguration {
|
||||
|
||||
@Bean
|
||||
public SmsEndpoint smsEndpoint() {
|
||||
return new SmsEndpoint();
|
||||
}
|
||||
}
|
@ -0,0 +1,3 @@
|
||||
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
|
||||
org.springframework.cloud.alicloud.sms.config.SmsAutoConfiguration,\
|
||||
org.springframework.cloud.alicloud.sms.endpoint.SmsEndpointAutoConfiguration
|
@ -0,0 +1,20 @@
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<parent>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-starter-alicloud</artifactId>
|
||||
<version>0.2.2.BUILD-SNAPSHOT</version>
|
||||
</parent>
|
||||
<artifactId>spring-cloud-starter-alicloud-sms</artifactId>
|
||||
<name>Spring Cloud Starter Alibaba Cloud SMS</name>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-alicloud-sms</artifactId>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
</project>
|
Loading…
Reference in New Issue