当前位置:   article > 正文

SpringBoot项目中使用Redis整合阿里云短信服务_spring 阿里redis. 直连模式

spring 阿里redis. 直连模式

1、引入相关依赖

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

        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>aliyun-java-sdk-ecs</artifactId>
            <version>4.17.6</version>
		</dependency>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

2、目录结构
在这里插入图片描述
application.yml

server:
  port: 8005

spring:
  application:
    name: service-msm
  cloud:
    nacos:
      discovery:
        server-addr: 127.0.0.1:8848

  redis:
    host: 192.168.61.xxx
    port: 6379
    database: 0
    timeout: 1800000ms
    lettuce:
      pool:
        max-active: 20
        max-wait: -1ms
        max-idle: 5
        min-idle: 0
msm:
  access-key: LTAI4G8q7EsUc2i
  access-secret: 3FEJ5vhVjUWdt5
  sys-domain: dysmsapi.aliyuncs.com
  sys-version: 2017-05-25
  sys-action: SendSms
  sign-name: 坤爷商城
  template-code: SMS_180355450
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30

MsmConfig

@Component
@ConfigurationProperties(prefix = "msm")
@Data
public class MsmConfig {

    private String regionId;

    private String accessKey;

    private String accessSecret;

    private String sysDomain;

    private String sysVersion;

    private String sysAction;

    private String signName;

    private String templateCode;

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

MsmController

@RestController
@RequestMapping("/msm")
public class MsmController {

    @Autowired
    private MsmService msmService;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @GetMapping("sendMessage/{phone}")
    public ResponseResult sendMessage(@PathVariable("phone") String phone) {
        if (StringUtils.isBlank(phone)) {
            return ResponseResult.error().message("请输入手机号码");
        }

        //1.从redis中获取验证码,如果获取到直接返回
        String code = redisTemplate.opsForValue().get(phone);
        if(StringUtils.isNotBlank(code)){
            return ResponseResult.success();
        }

        //2.从redis中获取不到,进行阿里云发送
        //生成随机值
        code = RandomUtil.getSixBitRandom();
        Map<String, Object> params = new HashMap<>();
        params.put("code",code);

        //调用service发送短信的方法
        boolean isSend = msmService.sendMessage(params,phone);
        if(isSend){
            //短信发送成功,将验证码保存到redis
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
            return ResponseResult.success().message("短信发送成功");
        }else {
            return ResponseResult.error().message("短信发送失败");
        }
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38

MsmServiceImpl

@Service
public class MsmServiceImpl implements MsmService {

    @Autowired
    private MsmConfig msmConfig;


    @Override
    public boolean sendMessage(Map<String,Object> params ,String phone) {

        //初始化个人信息
        DefaultProfile profile = DefaultProfile.getProfile("default", msmConfig.getAccessKey(), msmConfig.getAccessSecret());

        IAcsClient client = new DefaultAcsClient(profile);

        //设置相关固定的参数
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain(msmConfig.getSysDomain());
        request.setSysVersion(msmConfig.getSysVersion());
        request.setSysAction(msmConfig.getSysAction());

        //设置发送相关的参数
//        request.putQueryParameter("RegionId", msmConfig.getRegionId());
        request.putQueryParameter("PhoneNumbers", phone);  //手机号
        request.putQueryParameter("SignName", msmConfig.getSignName()); //签名
        request.putQueryParameter("TemplateCode", msmConfig.getTemplateCode());//模版CODE
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(params));  //验证码数据,要转换成json格式
        try {
            //最终发送
            CommonResponse response = client.getCommonResponse(request);
            boolean success = response.getHttpResponse().isSuccess();
            return success;
        } catch (ClientException e) {
            e.printStackTrace();
            return false;
        }
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39

最后附上生成随机验证码的工具类RandomUtil

public class RandomUtil {

	private static final Random random = new Random();

	private static final DecimalFormat fourdf = new DecimalFormat("0000");

	private static final DecimalFormat sixdf = new DecimalFormat("000000");

	public static String getFourBitRandom() {
		return fourdf.format(random.nextInt(10000));
	}

	public static String getSixBitRandom() {
		return sixdf.format(random.nextInt(1000000));
	}

	/**
	 * 给定数组,抽取n个数据
	 * @param list
	 * @param n
	 * @return
	 */
	public static ArrayList getRandom(List list, int n) {

		Random random = new Random();

		HashMap<Object, Object> hashMap = new HashMap<Object, Object>();

		// 生成随机数字并存入HashMap
		for (int i = 0; i < list.size(); i++) {

			int number = random.nextInt(100) + 1;

			hashMap.put(number, i);
		}

		// 从HashMap导入数组
		Object[] robjs = hashMap.values().toArray();

		ArrayList r = new ArrayList();

		// 遍历数组并打印数据
		for (int i = 0; i < n; i++) {
			r.add(list.get((int) robjs[i]));
			System.out.print(list.get((int) robjs[i]) + "\t");
		}
		System.out.print("\n");
		return r;
	}
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50

欢迎关注公众号Java技术大本营,会不定期分享BAT面试资料等福利。

在这里插入图片描述


声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/你好赵伟/article/detail/201293
推荐阅读
相关标签
  

闽ICP备14008679号