JAVA实现阿里云短信验证码发送

详情可参考阿里云官方文档: 开始使用 - 阿里云SDK - 阿里云

 首先进入阿里云开通短信服务  并且申请阿里云签名和模板

redis安装详见 centos redis安装及相关命令_lanan_dream的博客-CSDN博客_centos redis 安装

 1、配置类中引入redis配置:固定写法,复制即可

@EnableCaching
@Configuration
public class RedisConfig extends CachingConfigurerSupport {
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        RedisSerializer<String> redisSerializer = new StringRedisSerializer();
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        template.setConnectionFactory(factory);
        //key序列化方式
        template.setKeySerializer(redisSerializer);
        //value序列化
        template.setValueSerializer(jackson2JsonRedisSerializer);
        //value hashmap序列化
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        return template;
    }

    @Bean
    public CacheManager cacheManager(RedisConnectionFactory factory) {
        RedisSerializer<String> redisSerializer = new StringRedisSerializer();
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        //解决查询缓存转换异常的问题
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        // 配置序列化(解决乱码的问题),过期时间600秒
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofSeconds(600))
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))
                .disableCachingNullValues();
        RedisCacheManager cacheManager = RedisCacheManager.builder(factory)
                .cacheDefaults(config)
                .build();
        return cacheManager;
    }
}

 引入Maven依赖:

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

<dependency>
  <groupId>com.alibaba</groupId>
  <artifactId>fastjson</artifactId>
  <version>1.2.28</version>
</dependency>

业务逻辑层----service:

注:TemplateParam参数必须为JSON格式的字符串,可使用fastJSON的 JSONObject.toJSONString()方法将map转为JSON格式字符串

public boolean send(Map<String, Object> param, String phone) {
        if (StringUtils.isEmpty(phone)) {
            return false;
        }
        DefaultProfile profile =
                DefaultProfile.getProfile("default", "阿里云账号ID", "阿里云账号秘钥");
        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("PhoneNumbers", phone);//设置发送的手机号码
        request.putQueryParameter("SignName", "*****");//*****为阿里云申请的签名名称
        request.putQueryParameter("TemplateCode", "*****");//*****为阿里云申请的模板ID
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(param));//设置验证码 参数需要是json格式字符串

        try {
            CommonResponse response = client.getCommonResponse(request);
//            System.out.println(response.getData());
            return response.getHttpResponse().isSuccess();//是否发送成功
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

 

控制层Controller:

    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    
    //发送短信
    @GetMapping("send/{phone}")
    public R sendMsm(@PathVariable String phone) {
        String code = "";
        code = RandomUtil.getSixBitRandom();//使用工具类生成随机六位数验证码
        Map<String,Object> param = new HashMap<>();
        param.put("code",code);定义一个Map用于存储验证码
        //调用service发送短信
        boolean isSend = msmService.send(param,phone);
        if (isSend) {
            //发送成功,把验证码放到redis里面,设置有效时间5分钟
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
            return R.ok();
        }else {
            return R.error().message("短信发送失败");
        }

    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值