栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

【微服务集成阿里SMS短信服务发送短信】

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【微服务集成阿里SMS短信服务发送短信】

发送短信项目中很多地方都在使用,所以集成一个单独的服务,如果某个服务需要发送短信只需要依赖短信服务即可。 1、开通阿里SMS短信,创建模板 (省略) 2、创建短信服务 common-server-sms 2.1 添加依赖


        
            com.aliyun
            aliyun-java-sdk-core
            RELEASE
        
        
            com.aliyun
            aliyun-java-sdk-dysmsapi
            RELEASE
        
        
            org.springframework.boot
            spring-boot-autoconfigure
        
        
            org.springframework.boot
            spring-boot-configuration-processor
            true
        
    
    common-server-sms
2.2 创建配置文件并添加短信配置
ruyi:
  sms:
    aliyun:
      app-id: xxxxxxxxxxx
      app-secret: xxxxxxx
      sign-name: 自己设置的短信签名
      #模板
      templates: 
         #验证码模板
        VALID_CODE: SMS_234234343(自己设置的)
2.3 创建配置类 读取sms配置
@Data
@ConfigurationProperties(prefix = "thg.sms.aliyun")
public class AliSmsProperties {

	final static String DEFAULT_PRODUCT="Dysmsapi";

	
	final static String DEFAULT_DOMAIN="dysmsapi.aliyuncs.com";
	
	final static String DEFAULT_REGION ="cn-hangzhou";
	
	private String product=DEFAULT_PRODUCT;
	
	private String domain=DEFAULT_DOMAIN;
	
	private String regionId= DEFAULT_REGION;
	
	private String appId;
	
	private String appSecret;
	
	private String signName;

	
	private Map templates=new HashMap<>();
}
2.4 创建发送短信响应类
@Data
public class SmsResponse {

    
    private Boolean send;
    
    private String  msg;

    public SmsResponse(Boolean send, String msg) {
        this.send = send;
        this.msg = msg;
    }

    public SmsResponse(String msg) {
        this.send=Boolean.FALSE;
        this.msg = msg;
    }

    public SmsResponse() {
        this.send=Boolean.TRUE;
    }
}
2.5 创建短信模板类
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class NoticeData implements Serializable{
	
	
	private static final long serialVersionUID = -6624808649341355670L;

	
	private String type;
	
	
	private Map params;

	
	
}
2.6封装发送手机号和通知消息
@Data
@AllArgsConstructor
@NoArgsConstructor
public class NoticeInfo implements Serializable{

    
	private static final long serialVersionUID = 1L;

	
    private NoticeData noticeData;

    
    private Collection phones;
}
2.7 创建短信发送器接口
public interface baseSmsSender {
	
	default SmsResponse send(NoticeData data, String mobile) {
		Assert.notNull(mobile,"mobile must be not null");
		return send(data, Arrays.asList(mobile));
	}

	
	default SmsResponse send(NoticeData data, String... mobile) {
		if(mobile == null) {
			return new SmsResponse("手机号为空");
		}
		return send(data, Arrays.asList(mobile));
	}

	SmsResponse send(NoticeData data,Collection mobiles);

}
2.8 创建短信发送器
@Slf4j
public class AliSmsSender implements baseSmsSender {

    private IAcsClient acsClient;

    private AliSmsProperties smsProperties;

    private static final String OK = "OK";

    public AliSmsSender(AliSmsProperties smsProperties) {
        this.smsProperties = smsProperties;
        initClient();
    }

    private void initClient() {
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");
        IClientProfile profile = DefaultProfile.getProfile(smsProperties.getRegionId(), smsProperties.getAppId(), smsProperties.getAppSecret());
        DefaultProfile.addEndpoint(smsProperties.getRegionId(), smsProperties.getProduct(), smsProperties.getDomain());
        acsClient = new DefaultAcsClient(profile);
    }

    private SendSmsResponse sendSms(NoticeData data, Collection mobile) {
        SendSmsResponse sendSmsResponse = new SendSmsResponse();
        SendSmsRequest request = buildSmsRequest(data, mobile);
        try {
            sendSmsResponse = acsClient.getAcsResponse(request);
            if (OK.equals(sendSmsResponse.getCode())) {
                log.info("mobile={},data={},result={},send sms success", CollectionUtil.join(mobile, ","),JSONUtil.toJsonStr(data), sendSmsResponse.getMessage());
            }else{
                log.warn("mobile={},data={},result={},send sms failed", CollectionUtil.join(mobile, ","),JSONUtil.toJsonStr(data), sendSmsResponse.getMessage());
            }
        } catch (ClientException e) {
            log.error("send sms failed:mobile={},data:{},result={},exception={}",CollectionUtil.join(mobile, ","),JSONUtil.toJsonStr(data),sendSmsResponse.getMessage(), e.getErrMsg());
            throw new BizException("短信发送失败!");
        }
        return sendSmsResponse;

    }

    private SendSmsRequest buildSmsRequest(NoticeData data, Collection mobile) {
        SendSmsRequest request = new SendSmsRequest();
        request.setSignName(smsProperties.getSignName());
        request.setTemplateCode(smsProperties.getTemplates().get(data.getType()));
        Map params = data.getParams();
        if (params != null && params.size() > 0) {
            request.setTemplateParam(JSONUtil.toJsonStr(params));
        }
        request.setPhoneNumbers(CollectionUtil.join(mobile, ","));
        return request;
    }

    @Override
    public SmsResponse send(NoticeData data, Collection mobiles) {
      SendSmsResponse smsResponse=  sendSms(data, mobiles);
      if(OK.equals(smsResponse.getCode())) return new SmsResponse();
      else return new SmsResponse(smsResponse.getMessage());
    }
}
2.9 创建短信配置类
@Configuration
@EnableConfigurationProperties(AliSmsProperties.class)
public class AutoAliSmsConfiguration {

    private final AliSmsProperties smsProperties;

    public AutoAliSmsConfiguration(AliSmsProperties smsProperties) {
        this.smsProperties = smsProperties;
    }

    
    @Bean
    @ConditionalOnMissingBean(AliSmsProperties.class)
    public AliSmsSender aliSmsSender() {
        return new AliSmsSender(smsProperties);
    }
}

注意:需要创建spring.factories 自动装配AutoAliSmsConfiguration类
在 resource文件夹创建meta-INF文件夹 创建文件spring.factories加入配置

spring.factories:

org.springframework.boot.autoconfigure.EnableAutoConfiguration=
cn.ruyi.aliyun.AutoAliSmsConfiguration

配置路径内容如下:

这里就集成完毕了。 3、使用 3.1 依赖common-server-sms服务

比如我在用户模块需要使用短信服务,那我只在用户服务依赖短信服务common-server-sms

 		
            cn.wyj
            common-server-sms
            1.0-SNAPSHOT
        
3.2 发送短信
private   final AliSmsSender aliSmsSender;(用的构造注入,也可以直接自己喜欢的注入方式)

 @GetMapping(value = "/send")
 public SmsResponse sendSms() {
        Map content = new HashMap<>(16);
        content.put("code", String.valueOf(RandomUtil.randomInt(100000, 999999)));
      return aliSmsSender.send(new NoticeData(SmsConstants.CODE_KEY, content), "153****6968");
    }

注意:NoticeData 对象里面的参数需要一一对应,type是模板类型,params是短信内容 测试 使用postman访问接口 /send

成功

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/703626.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号