阿里云短信服务接口实现

aliyun短信接口实现

1. 发送短信到redis,rabbitMQ

1.1 添加工程引入依赖(介绍整合,spring,springmvc的配置在此暂略,已user模块为例)

<!--添加rabbit依赖-->
        <dependency>
            <groupId>org.springframework.amqp</groupId>
            <artifactId>spring-rabbit</artifactId>
            <version>2.1.4.RELEASE</version>
        </dependency>

1.2 向user模块的resources文件夹下添加applicationContext-rabbitmq-producer.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	   xmlns:rabbit="http://www.springframework.org/schema/rabbit"
	   xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                          http://www.springframework.org/schema/rabbit http://www.springframework.org/schema/rabbit/spring-rabbit.xsd">
	<!--连接工厂-->
	<rabbit:connection-factory id="connectionFactory" host="127.0.0.1" port="5672" username="guest" password="guest" publisher-confirms="true"/>
	<!--自动创建队列-->
	<rabbit:admin connection-factory="connectionFactory"></rabbit:admin>
	<!--创建队列-->
	<rabbit:queue name="queue.sms"></rabbit:queue>

	<rabbit:template id="rabbitTemplate" connection-factory="connectionFactory" />
</beans>

1.3 在interfaces/user/UserService接口中添加方法

    /**
     * 发送短信验证码
     * @param phone 手机号
     */
    public void sendSms(String phone);

1.4 在use模块下的service/Impl/UserServiceImpl中进行接口方法的实现


   @Autowired
   private RedisTemplate redisTemplate;

   @Autowired
   private RabbitTemplate rabbitTemplate;
   /**
    * 实现发送短信的方法
    * @param phone 手机号
    */
   @Override
   public void sendSms(String phone) {
       //1.生成6位短信验证码
       Random random = new Random();
       int code = random.nextInt(999999);
       if (code < 100000){
           code += 100000;
       }
       System.out.println("短信验证码:"+code);

       //2.将验证码保存到redis中
       redisTemplate.boundValueOps("code_"+phone).set(code+"");
       redisTemplate.boundValueOps("code_"+phone).expire(5, TimeUnit.MINUTES);//5分钟过期

       //3.将验证码发送到mq
       Map<String,String> map = new HashMap<>();
       map.put("phone",phone);
       map.put("code",code+"");

       rabbitTemplate.convertAndSend("","queue.sms", JSON.toJSONString(map));

   }

1.5 在controller层中,新建UserController

@RestController
@RequestMapping("/user")
public class UserController {
    @Reference
    private UserService userService;

    @GetMapping("/sendSms")
    public Result sendSms(String phone){
        userService.sendSms(phone);
        return new Result();
    }

}


2. 短信服务接收消息

短信发送是由单独的短信服务提供的功能,所有的短信都是先发送到消息队列,短
信服务从消息队列中提取手机号和验证码,调用短信发送接口进行发送短信。
我们这个环节实现的是将手机号和验证码从消息队列中提取出来,打印到控制台上

2.1 创建easy_service_sms工程,pom文件引入依赖

<dependency>
<groupId>org.springframework.amqp</groupId>
<artifactId>spring‐rabbit</artifactId>
<version>2.1.4.RELEASE</version>
</dependency>

以及添加一些项目依赖,在此暂略

2.2 添加web.xml

<web-app>
  <display-name>Archetype Created Web Application</display-name>
  <!-- 加载spring容器 -->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath*:applicationContext*.xml</param-value>
  </context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
</web-app>

2.3 在该服务下创建监听类,在com.easy.consumer包下

public class SmsMessageConsumer implements MessageListener {
    @Override
    public void onMessage(Message message) {

        String jsonString = new String(message.getBody());
        Map<String,String> map = JSON.parseObject(jsonString, Map.class);
        String phone = map.get("phone");//手机号
        String code = map.get("code");//验证码

        System.out.println("手机号:"+phone+"验证码:"+code);

        //调用阿里云通信。。。
        	
    }
}

2.4 在resources下创建applicationContext-rabbitmq-consumer.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	   xmlns:rabbit="http://www.springframework.org/schema/rabbit"
	   xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                          http://www.springframework.org/schema/rabbit http://www.springframework.org/schema/rabbit/spring-rabbit.xsd">
	<!--连接工厂-->
	<rabbit:connection-factory id="connectionFactory" host="127.0.0.1" port="5672" username="guest" password="guest" publisher-confirms="true"/>
	<!--队列-->
	<rabbit:queue name="queue.sms" durable="true" exclusive="false" auto-delete="false" />
	<!--消费者监听类-->
	<bean id="messageConsumer" class="com.qingcheng.consumer.SmsMessageConsumer"></bean>
	<!--设置监听容器-->
	<!--主要作用是:关联队列以及监听-->
	<rabbit:listener-container connection-factory="connectionFactory" acknowledge="auto" >
		<rabbit:listener queue-names="queue.sms" ref="messageConsumer"/>
	</rabbit:listener-container>
</beans>

3. 注册功能的实现

在User服务模块

3.1 创建接口方法

    /**
     * 用户注册侧
     * @param user 用户
     * @param smsCode 验证码
     */
    public void add(User user,String smsCode);

3.2 在com.easy.service.impl.UserServiceImpl类中实现该方法

    /**
     *完成用户的注册功能
     * @param user 用户
     * @param smsCode 验证码
     */
    @Override
    public void add(User user, String smsCode) {
        //1.校验
        String sysCode = (String) redisTemplate.boundValueOps("code_" + user.getPhone()).get();//提取系统验证码
        if (sysCode == null){
            throw new RuntimeException("验证码未发送或已过期");
        }
        if (!sysCode.equals(smsCode)){
            throw new RuntimeException( "验证码不正确");
        }
        if (user.getUsername() == null){
            user.setUsername(user.getPhone());//把手机号作为用户名
        }
        //校验用户名是否注册
        User searchUser = new User();
        searchUser.setUsername(user.getUsername());
        if (userMapper.selectCount(searchUser) >0 ){
            throw new RuntimeException("该手机号已被注册");
        }

        //2.数据的添加
        user.setCreated(new Date());//用户创建时间
        user.setUpdated(new Date());//用户修改时间
        user.setPoints(0);//积分数
        user.setStatus("1");//状态
        user.setIsEmailCheck("0");//邮箱验证
        user.setIsMobileCheck("1");//手机验证

        userMapper.insert(user);

    }

user-- controller层进行代码的编写

    @PostMapping("/save")
    public Result save(@RequestBody User user, String smsCode){
        //密码加密
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String newpassword = encoder.encode(user.getPassword());
        user.setPassword(newpassword);
        userService.add(user,smsCode);
        return new Result();
    }

4. 实现阿里云通信

4.1 快速入门

1)创建工程引入依赖

 <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>aliyun-java-sdk-core</artifactId>
            <version>4.0.3</version>
        </dependency>

2)创建测试类,以下代码从官网获取

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
/*
pom.xml
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun‐java‐sdk‐core</artifactId>
<version>4.0.3</version>
</dependency>
*/
public class CommonRpc {
	public static void main(String[] args) {
			DefaultProfile profile = DefaultProfile.getProfile("cn‐hangzhou",
			"*******", "********");
			IAcsClient client = new DefaultAcsClient(profile);
			CommonRequest request = new CommonRequest();
			//request.setProtocol(ProtocolType.HTTPS);
			request.setMethod(MethodType.POST);
			request.setDomain("dysmsapi.aliyuncs.com");
			request.setVersion("2017‐05‐25");
			request.setAction("SendSms");
			request.putQueryParameter("RegionId", "cn‐hangzhou");
			request.putQueryParameter("PhoneNumbers", "111********");
			request.putQueryParameter("SignName", "testSing");
			request.putQueryParameter("TemplateCode", "SMS_111111111");
			request.putQueryParameter("TemplateParam", "
			{\"code\":\"123123\"}");
		try {
			CommonResponse response = client.getCommonResponse(request);
			System.out.println(response.getData());
		} catch (ServerException e) {
			e.printStackTrace();
		} catch (ClientException e) {
			e.printStackTrace();
		}
	}
}

4.2 向sms服务中集成阿里云短信功能

1)短信服务pom.xml引入阿里云sdk依赖

<
dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun‐java‐sdk‐core</artifactId>
<version>4.0.3</version>
</dependency>

2)添加配置文件sms.properties

accessKeyId=******
accessKeySecret=*******
smsCode=SMS_111111111
param={"code":"[value]"}

3)添加配置文件applicationContext-sms.xml

<context:component‐scan base‐package="com.qingcheng"></context:component‐
scan>

4)创建短信工具类SmsUtil

@Component
public class SmsUtil {
	@Value("${accessKeyId}")
	private String accessKeyId;
	@Value("${accessKeySecret}")
	private String accessKeySecret;
	public CommonResponse sendSms(String phone,String smsCode,String
	param){
		DefaultProfile profile = DefaultProfile.getProfile("cn‐hangzhou",
		accessKeyId, accessKeySecret);
		IAcsClient client = new DefaultAcsClient(profile);
		CommonRequest request = new CommonRequest();
		//request.setProtocol(ProtocolType.HTTPS);
		request.setMethod(MethodType.POST);
		request.setDomain("dysmsapi.aliyuncs.com");
		request.setVersion("2017‐05‐25");
		request.setAction("SendSms");
		request.putQueryParameter("RegionId", "cn‐hangzhou");
		request.putQueryParameter("PhoneNumbers", phone);
		request.putQueryParameter("SignName", "singTest");
		request.putQueryParameter("TemplateCode", smsCode);
		request.putQueryParameter("TemplateParam", param);
	try {
		CommonResponse response = client.getCommonResponse(request);
		System.out.println(response.getData());
		return response;
	} catch (ServerException e) {
		e.printStackTrace();
	return null;
	} catch (ClientException e) {
		e.printStackTrace();
		return null;
		}
	}
}

5)修改消息监听类,完成短信发送

public class SmsMessageConsumer implements MessageListener {
@Autowired
private SmsUtil smsUtil;
@Value("${smsCode}")
private String smsCode;//短信模板编号
@Value("${param}")
private String param;//短信参数	
public void onMessage(Message message) {
		String jsonString = new String(message.getBody());
		Map<String,String> map = JSON.parseObject(jsonString, Map.class);
		String phone = map.get("phone");
		String code=map.get("code");
		System.out.println("手机号:"+phone+"验证码:"+code);
		String param= templateParam_smscode.replace("[value]",code);
	try {
		//调用阿里云进行短信发送
		SendSmsResponse smsResponse = smsUtil.sendSms(phone, smsCode,param);
	} catch (ClientException e) {
		e.printStackTrace();
		}
	}
}
  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值