阿里云短信服务接口实现--5分钟快速入门

aliyun短信接口实现

1. 发送短信到redis,rabbitMQ

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


        <dependency>
            <groupId>org.springframework.amqpgroupId>
            <artifactId>spring-rabbitartifactId>
            <version>2.1.4.RELEASEversion>
        dependency>

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


<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.amqpgroupId>
<artifactId>spring‐rabbitartifactId>
<version>2.1.4.RELEASEversion>
dependency>

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

2.2 添加web.xml

<web-app>
  <display-name>Archetype Created Web Applicationdisplay-name>
  
  <context-param>
    <param-name>contextConfigLocationparam-name>
    <param-value>classpath*:applicationContext*.xmlparam-value>
  context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-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


<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.aliyungroupId>
            <artifactId>aliyun-java-sdk-coreartifactId>
            <version>4.0.3version>
        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

com.aliyun
aliyun‐java‐sdk‐core
4.0.3

*/
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.aliyungroupId>
<artifactId>aliyun‐java‐sdk‐coreartifactId>
<version>4.0.3version>
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();
		}
	}
}

你可能感兴趣的:(aliyun,login/register)