java阿里云短信对接

技术栈:

  1. Spring boot 2.x
  2. 阿里云短信sdk
  3. java版本1.8

注意事项:

  1. 本文内的“**.**”需要自己替换为自己的路径。
  2. 常量内的“**”需要自己定义自己内容。
  3. redis存储时间默认600秒。
  4. 阿里短信模版CODE,需要从阿里云控制台获取。
  5. 阿里云短信签名,用域名审核最快。

|号段|编码|阿里-模版CODE|说明|
|:---- |
|120XX|120**| SMS_150******|身份验证验证码
|120XX|120**| SMS_150******|登录确认验证码
|120XX|120**| SMS_150******|登录异常验证码
|120XX|120**| SMS_150******|用户注册验证码
|120XX|120**| SMS_150******|修改密码验证码
|120XX|120**| SMS_150******|信息变更验证码

1、pom.xml文件:


		<dependency>
			<groupId>com.aliyun</groupId>
			<artifactId>aliyun-java-sdk-core</artifactId>
			<version>4.0.6</version>
		</dependency>
		<dependency>
			<groupId>com.aliyun</groupId>
			<artifactId>aliyun-java-sdk-dysmsapi</artifactId>
			<version>1.1.0</version>
		</dependency>

这两个必加,项目内部调用的时候会自己加载已经封装好的类、以及要调用的方法。

2、DysmsController文件:

package com.**.**.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.**.**.constants.BaseConstants;
import com.**.**.entity.Test;
import com.**.**.enums.ResultEnum;
import com.**.**.result.Result;
import com.**.**.service.IDysmsService;
import com.**.**.util.ResultUtils;
import com.**.**.util.TimeUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.regex.Pattern;


/**
 * 短信业务
 */
@Api(value = "短信业务",description = "短信业务")
@ApiResponses(value = {@ApiResponse(code = 200, message = "success",response = Test.class)})
@RequestMapping(value = "/1.1/sms",method = {RequestMethod.GET, RequestMethod.POST})
@RestController
public class DysmsController {

    private Logger log = LoggerFactory.getLogger(DysmsController.class);

    @Autowired
    private IDysmsService dysmsService;

    /**
     * 短信发送
     * @param phone
     * @param smsType
     * @param response
     * @param request
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "短信发送", notes = "短信发送")
    @RequestMapping(value = "/sendSms")
    public Result sendSms(@RequestParam(value = "phone", required = false) String phone,
                          @RequestParam(value = "smsType", required = false) String smsType,
                                  HttpServletResponse response,
                                  HttpServletRequest request) throws Exception{
        if(phone.isEmpty() || smsType.isEmpty() || "".equals(phone) || "".equals(smsType)){
            return ResultUtils.response(ResultEnum.ROULETTEP_NOT);
        }

        //发送短信类型
        boolean partnerStatusFlag = Arrays.asList(BaseConstants.SMS_TYPE_ARRAY).contains(smsType);
        if(!partnerStatusFlag){
            return ResultUtils.response(ResultEnum.SMS_TYPE_ERROR_INFO);
        }

        //手机号检验
        if(!Pattern.matches(BaseConstants.PHONE_REGEX_MOBILE,phone)){
            return ResultUtils.response(ResultEnum.PHONE_ERROR_INFO);
        }

        boolean result = dysmsService.sendSms(phone, smsType);

        if(result) {
            return ResultUtils.response(result);
        }else{
            return ResultUtils.response(ResultEnum.ERROR);
        }
    }


    /**
     * 验证短信验证码接口
     * @param phone
     * @param smsType
     * @param verifyCode
     * @param response
     * @param request
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "验证短信验证码接口", notes = "验证短信验证码接口")
    @RequestMapping(value = "/verifySendSms")
    public Result verifySendSms(@RequestParam(value = "phone", required = false) String phone,
                                @RequestParam(value = "smsType", required = false) String smsType,
                                @RequestParam(value = "verifyCode", required = false) String verifyCode,
                                  HttpServletResponse response,
                                  HttpServletRequest request) throws Exception{

        if(phone.isEmpty() || smsType.isEmpty() || "".equals(phone) || "".equals(smsType)){
            return ResultUtils.response(ResultEnum.ROULETTEP_NOT);
        }

        //发送短信类型
        boolean partnerStatusFlag = Arrays.asList(BaseConstants.SMS_TYPE_ARRAY).contains(smsType);
        if(!partnerStatusFlag){
            return ResultUtils.response(ResultEnum.SMS_TYPE_ERROR_INFO);
        }

        //手机号检验
        if(!Pattern.matches(BaseConstants.PHONE_REGEX_MOBILE,phone)){
            return ResultUtils.response(ResultEnum.PHONE_ERROR_INFO);
        }

        boolean result = dysmsService.verifySendSms(phone, smsType, verifyCode);

        if(result) {
            return ResultUtils.response(result);
        }else{
            return ResultUtils.response(ResultEnum.ERROR);
        }
    }

    /**
     * 短信查询API
     * @param phone
     * @param smsBizId
     * @param sendDate
     * @param pages
     * @param rows
     * @param response
     * @param request
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "短信查询API", notes = "短信查询API")
    @RequestMapping(value = "/querySendDetails")
    public Result querySendDetails(@RequestParam(value = "phone", required = false) String phone,
                                   @RequestParam(value = "smsBizId", required = false) String smsBizId,
                                   @RequestParam(value = "sendDate", required = false) String sendDate,
                                   @RequestParam(value = "pages", required = false, defaultValue = "1") Integer pages,
                                   @RequestParam(value = "rows", required = false, defaultValue = "10") Integer rows,
                                  HttpServletResponse response,
                                  HttpServletRequest request) throws Exception{

        if(phone.isEmpty() || sendDate.isEmpty() || "".equals(phone) || "".equals(sendDate)){
            return ResultUtils.response(ResultEnum.ROULETTEP_NOT);
        }

        //验证时间是否在30天内
        if(!TimeUtils.isValidDate(sendDate)){
            return ResultUtils.response(ResultEnum.SMS_SEND_DATE_ERROR_INFO);
        }

        //手机号检验
        if(!Pattern.matches(BaseConstants.PHONE_REGEX_MOBILE,phone)){
            return ResultUtils.response(ResultEnum.PHONE_ERROR_INFO);
        }

        Object result = dysmsService.sendDetails(phone, smsBizId, sendDate, pages, rows);

        if(result != null) {
            return ResultUtils.response(result);
        }else{
            return ResultUtils.response(ResultEnum.ERROR);
        }
    }


    /**
     * 短信批量发送API
     * @param phone
     * @param smsType
     * @param signName
     * @param smsUpExtendCode
     * @param response
     * @param request
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "短信批量发送API", notes = "短信批量发送API")
    @RequestMapping(value = "/sendBatchSms")
    public Result sendBatchSms(@RequestParam(value = "phone", required = false) String phone,
                               @RequestParam(value = "smsType", required = false) String smsType,
                               @RequestParam(value = "signName", required = false) String signName,
                               @RequestParam(value = "smsUpExtendCode", required = false) String smsUpExtendCode,
                                  HttpServletResponse response,
                                  HttpServletRequest request) throws Exception{

        if(phone.isEmpty() || smsType.isEmpty() || "".equals(smsType) || "".equals(phone)){
            return ResultUtils.response(ResultEnum.ROULETTEP_NOT);
        }

        //发送短信类型
        boolean partnerStatusFlag = Arrays.asList(BaseConstants.SMS_TYPE_ARRAY).contains(smsType);
        if(!partnerStatusFlag){
            return ResultUtils.response(ResultEnum.SMS_TYPE_ERROR_INFO);
        }

        //手机号 循环检验
        JSONArray phone_encode = JSON.parseArray(phone);
        if (phone_encode.size() <= 0 || phone_encode.size() > 100) {
            return ResultUtils.response(ResultEnum.SMS_SEND_BATCH_NUMBER_ERROR_INFO);
        }

        for (int i = 0;i < phone_encode.size(); i++){
            if(!Pattern.matches(BaseConstants.PHONE_REGEX_MOBILE,phone_encode.get(i).toString())){
                return ResultUtils.response(ResultEnum.PHONE_ERROR_INFO);
            }
        }

        boolean result = dysmsService.sendBatchSms(phone, signName, smsType, smsUpExtendCode);

        if(result) {
            return ResultUtils.response(result);
        }else{
            return ResultUtils.response(ResultEnum.ERROR);
        }
    }


}

3、IDysmsService文件

package com.**.**.service;

public interface IDysmsService {

    /**
     * 短信发送API
     * @param phone
     * @param smsType
     * @return
     */
    public boolean sendSms(String phone, String smsType);

    /**
     * 验证短信验证码接口
     * @param phone
     * @param smsType
     * @param verifyCode
     * @return
     */
    public boolean verifySendSms(String phone, String smsType, String verifyCode);

    /**
     * 短信查询API
     * @param phone
     * @param smsBizId
     * @param sendDate
     * @param pages
     * @param rows
     * @return
     */
    public Object sendDetails(String phone,String smsBizId,String sendDate,Integer pages,Integer rows);

    /**
     * 短信批量发送API
     * @param phone
     * @param signName
     * @param smsType
     * @param smsUpExtendCode
     * @return
     */
    public boolean sendBatchSms(String phone,String signName,String smsType,String smsUpExtendCode);

}

4、IDysmsServiceImpl 文件-service层实现类

package com.**.**.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.*;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.**.**.constants.BaseConstants;
import com.**.**.service.IDysmsService;
import com.**.**..util.RedisUtils;
import com.**.**.util.TimeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class IDysmsServiceImpl implements IDysmsService {

    @Autowired
    private RedisUtils redisUtils;

    /**
     * 短信发送API
     * @param phone
     * @return
     */
    @Override
    public boolean sendSms(String phone, String smsType){
        boolean result = false;

        //初始化ascClient,暂时不支持多region(请勿修改)
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", BaseConstants.ALI_ACCESS_KEY_ID, BaseConstants.ALI_ACCESS_KEY_SECRET);

        try{
            DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", BaseConstants.ALI_SMS_PROSUCT, BaseConstants.ALI_SMS_API_URL);
            IAcsClient acsClient = new DefaultAcsClient(profile);
            //组装请求对象
            SendSmsRequest request = new SendSmsRequest();
            //使用post提交
            request.setMethod(MethodType.POST);
            //必填:待发送手机号。支持以逗号分隔的形式进行批量调用,批量上限为1000个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式;发送国际/港澳台消息时,接收号码格式为国际区号+号码,如“85200000000”
            request.setPhoneNumbers(phone);
            //必填:短信签名-可在短信控制台中找到
            request.setSignName(BaseConstants.ALI_SMS_SIGN_NAME);
            //必填:短信模板-可在短信控制台中找到,发送国际/港澳台消息时,请使用国际/港澳台短信模版
            request.setTemplateCode(smsType(smsType));
            //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
            //友情提示:如果JSON中需要带换行符,请参照标准的JSON协议对换行符的要求,比如短信内容中包含\r\n的情况在JSON中需要表示成\\r\\n,否则会导致JSON在服务端解析失败
            String codeString = String.valueOf((int)((Math.random()*8+1)*100000+Math.random()*100000));
            request.setTemplateParam("{\"code\":\"" + codeString + "\"}");
            //发送短信请求
            SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
            System.out.println("===sendSmsCode===" + sendSmsResponse.getCode() + "===sendSmsBizId===" + sendSmsResponse.getBizId());

            if(sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) {
                //存储redis
                String redisName = BaseConstants.MB_SMS_CODE_PHONE + smsType(smsType) + "_" + phone;
                redisUtils.setRedisTime(redisName, codeString, BaseConstants.ASSETCENTER_BUSNESS_FLAG);
                result = true;
            }
        }catch (ClientException e){
            System.out.println(e.getMessage());
        }

        return result;
    }

    /**
     * 验证短信验证码接口
     * @param phone
     * @param smsType
     * @param verifyCode
     * @return
     */
    @Override
    public boolean verifySendSms(String phone, String smsType, String verifyCode){
        boolean result = false;

        //查询redis
        String redisName = BaseConstants.MB_SMS_CODE_PHONE + smsType(smsType) + "_" + phone;
        String codeString = redisUtils.getRedis(redisName, BaseConstants.ASSETCENTER_BUSNESS_FLAG);
        if(codeString.equals(verifyCode)){
            result = true;
        }

        return result;
    }

    /**
     * 短信查询API
     * @param phone
     * @return
     */
    @Override
    public Object sendDetails(String phone,String smsBizId,String sendDate,Integer pages,Integer rows){
        Object result = null;
        //初始化ascClient
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", BaseConstants.ALI_ACCESS_KEY_ID, BaseConstants.ALI_ACCESS_KEY_SECRET);

        try{
            DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", BaseConstants.ALI_SMS_PROSUCT, BaseConstants.ALI_SMS_API_URL);
            IAcsClient acsClient = new DefaultAcsClient(profile);
            //组装请求对象
            QuerySendDetailsRequest request = new QuerySendDetailsRequest();
            //必填-号码
            request.setPhoneNumber(phone);
            if(smsBizId !=null && !"".equals(smsBizId) && !smsBizId.isEmpty()){
                //可选-调用发送短信接口时返回的BizId
                request.setBizId(smsBizId);
            }
            //必填-短信发送的日期 支持30天内记录查询(可查其中一天的发送数据),格式yyyyMMdd
            request.setSendDate(TimeUtils.strToStr(sendDate, 4));
            //必填-页大小
            request.setPageSize(Long.valueOf(rows));
            //必填-当前页码从1开始计数
            request.setCurrentPage(Long.valueOf(pages));
            //hint 此处可能会抛出异常,注意catch
            QuerySendDetailsResponse querySendDetailsResponse = acsClient.getAcsResponse(request);
            System.out.println("===sendDetailsTime===" + TimeUtils.strToStr(sendDate, 4));
            System.out.println("===sendDetailsCode===" + querySendDetailsResponse.getCode());
            System.out.println("===getSmsSendDetailDTOs===" + querySendDetailsResponse.getSmsSendDetailDTOs());
            //获取返回结果
            if(querySendDetailsResponse.getCode() != null && querySendDetailsResponse.getCode().equals("OK")){
                result = querySendDetailsResponse.getSmsSendDetailDTOs();
            }

        }catch (ClientException e){
            System.out.println(e.getMessage());
        }
        return result;
    }

    /**
     * 短信批量发送API
     * @param phone
     * @return
     */
    @Override
    public boolean sendBatchSms(String phone,String signName,String smsType,String smsUpExtendCode){
        boolean result = false;
        JSONArray phoneEncode = JSON.parseArray(phone);
        //初始化ascClient
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", BaseConstants.ALI_ACCESS_KEY_ID, BaseConstants.ALI_ACCESS_KEY_SECRET);

        try{
            DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", BaseConstants.ALI_SMS_PROSUCT, BaseConstants.ALI_SMS_API_URL);
            IAcsClient acsClient = new DefaultAcsClient(profile);
            //组装请求对象
            SendBatchSmsRequest request = new SendBatchSmsRequest();
            //使用post提交
            request.setMethod(MethodType.POST);
            //必填:待发送手机号。支持JSON格式的批量调用,批量上限为100个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式
            request.setPhoneNumberJson(phone);
            //必填:短信签名-支持不同的号码发送不同的短信签名
            if(signName == null || signName.isEmpty() || "".equals(signName)){
                request.setSignNameJson(signNameLength(phoneEncode.size()));
            }else{
                request.setSignNameJson(signName);
            }
            //必填:短信模板-可在短信控制台中找到
            request.setTemplateCode(smsType(smsType));
            //必填:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
            //友情提示:如果JSON中需要带换行符,请参照标准的JSON协议对换行符的要求,比如短信内容中包含\r\n的情况在JSON中需要表示成\\r\\n,否则会导致JSON在服务端解析失败
            String templateParam = setTemplateParamLength(phoneEncode.size());
            request.setTemplateParamJson(templateParam);
            if(smsUpExtendCode != null && !"".equals(smsUpExtendCode) && !smsUpExtendCode.isEmpty()){
                //可选-上行短信扩展码(扩展码字段控制在7位或以下,无特殊需求用户请忽略此字段)
                request.setSmsUpExtendCodeJson(smsUpExtendCode);
            }
            //请求失败这里会抛ClientException异常
            SendBatchSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
            System.out.println("===sendBatchSmsCode===" + sendSmsResponse.getCode());
            if(sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) {
                //redis存储
                boolean redisResult = setRedisSendBatchSms(phoneEncode,templateParam,smsType);
                System.out.println("===sendBatchSmsRedis===:" + redisResult);
                result = true;
            }
        }catch (ClientException e){
            System.out.println(e.getMessage());
        }


        return result;
    }

    /**
     * 短信验证码类型---对应关系
     * @param smsType
     * @return
     */
    private String smsType(String smsType){
        switch (smsType){
            case BaseConstants.MB_SMS_ID_CARD_CODE:
                return BaseConstants.ALI_SMS_ID_CARD_CODE;
            case BaseConstants.MB_SMS_LOGIN_YES_CODE:
                return BaseConstants.ALI_SMS_LOGIN_YES_CODE;
            case BaseConstants.MB_SMS_LOGIN_ERROR_CODE:
                return BaseConstants.ALI_SMS_LOGIN_ERROR_CODE;
            case BaseConstants.MB_SMS_USER_REGISTER_CODE:
                return BaseConstants.ALI_SMS_USER_REGISTER_CODE;
            case BaseConstants.MB_SMS_UPDATE_PASSWORD_CODE:
                return BaseConstants.ALI_SMS_UPDATE_PASSWORD_CODE;
            case BaseConstants.MB_SMS_INFO_UPDATE_CODE:
                return BaseConstants.ALI_SMS_INFO_UPDATE_CODE;
            default:
                return null;
        }
    }

    /**
     * signName数组
     * @param strLength
     * @return
     */
    private String signNameLength(Integer strLength){
        String signNameString = "";
        if(strLength > 0){
            ArrayList list = new ArrayList();
            for (int i = 0;i < strLength;i++){
                list.add(BaseConstants.ALI_SMS_SIGN_NAME);
            }
            signNameString = JSON.toJSONString(list);
        }
        return signNameString;
    }

    /**
     * code数组
     * @param strLength
     * @return
     */
    private String setTemplateParamLength(Integer strLength){
        String signNameString = "";
        if(strLength > 0){
            ArrayList list = new ArrayList();
            for (int i = 0;i < strLength;i++){
                Map map = new HashMap();
                map.put("code", String.valueOf((int)((Math.random()*8+1)*100000+Math.random()*100000)));
                list.add(map);
            }
            signNameString = JSON.toJSONString(list);
        }
        return signNameString;
    }

    /**
     * redis-存储短信批量发送API
     * @return
     */
    private boolean setRedisSendBatchSms(JSONArray phoneEncode, String templateParam, String smsType){
        boolean result = false;

        JSONArray templateParamEncode = JSON.parseArray(templateParam);
        if(phoneEncode.size() > 0 && !templateParam.isEmpty()) {
            for (int i = 0;i < phoneEncode.size();i++){
                String redisName = BaseConstants.MB_SMS_BATCH_CODE_PHONE + smsType(smsType) + "_" + phoneEncode.get(i).toString();
                redisUtils.setRedisTime(redisName, templateParamEncode.getJSONObject(i).getString("code"), BaseConstants.ASSETCENTER_BUSNESS_FLAG);
            }
            result = true;
        }
        return result;
    }

}

5、redis工具类:RedisUtils文件

package com.**.**.util;


import com.**.**.constants.BaseConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.HashMap;
import java.util.Map;

/**
 * RedisUtils  redis操作工具类
 * @author: yanjianghua
 * @date: 2018/9/13 14:35
 */
@Component("RedisUtil")
public class RedisUtils {
	@Autowired
	private JedisPool jedisPool;
	    
	/**
     * 插入或修改数据(字符串)
     * @param key,value,flag(redis分区)
     * @return
     */
    public String setRedis(String key,String value,int flag){
        Jedis jedis = null;
        String res = "fail";
        try {
            jedis = jedisPool.getResource();
        	jedis.select(flag);
        	jedis.set(key, value);
        	res = "success";
        } catch (Exception e) {
        	e.printStackTrace();
        } finally {
        	//返还到连接池
           jedis.close();
        }
        return res;
    }

    /**
     * 插入或修改数据(字符串)--10分钟有效时间
     * @param key,value,flag(redis分区)
     * @return
     */
    public String setRedisTime(String key,String value,int flag){
        Jedis jedis = null;
        String res = "fail";
        try {
            jedis = jedisPool.getResource();
            jedis.select(flag);
            jedis.set(key, value, "NX", "EX", BaseConstants.MB_SMS_CODE_TIME);
            res = "success";
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //返还到连接池
            jedis.close();
        }
        return res;
    }
    
    /**
     * getRedis 获取数据(字符串)
     * @param key,flag(redis分区)
     * @author: yanjianghua
     * @date: 2018/9/13 14:47
     */
    public String getRedis(String key,int flag){
        Jedis jedis = null;
        String result = "";
        try {
            jedis = jedisPool.getResource();
        	jedis.select(flag);
        	result = jedis.get(key);
        } catch (Exception e) {
        	e.printStackTrace();
        } finally {
        	jedis.close();
        }
        return result;
    }

    /**
     * delRedis 删除redis
     * @author: yanjianghua
     * @date: 2018/9/13 14:47
     */
    public void delRedis(String key,int flag){
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            jedis.select(flag);
            jedis.del(key);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //返还到连接池
            jedis.close();
        }
    }

    /**
     * existsRedis 判断redis键Key是否存在
     * @author: yanjianghua
     * @date: 2018/9/13 14:47
     */
    public boolean existsRedis(String key,int flag){
        Jedis jedis = null;
        Boolean result = false;
        try {
            jedis = jedisPool.getResource();
            jedis.select(flag);
            result = jedis.exists(key);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //返还到连接池
            jedis.close();
        }
        return result;
    }

    /**
     * incrRedis 整数(incr:自增;decr:自减)
     * @author: yanjianghua
     * @date: 2018/9/13 14:47
     */
    public long incrRedis(String key,int flag,String type){
        Jedis jedis = null;
        String incr = "incr";
        String decr = "decr";
        long result = 0;
        try {
            jedis = jedisPool.getResource();
            jedis.select(flag);
            if(incr.equals(type)){
                result = jedis.incr(key);
            }else if (decr.equals(decr)) {
                result = jedis.decr(key);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //返还到连接池
            jedis.close();
        }
        return result;
    }

    /**
     * hget 获取redisHash 键名值
     * @param keyname
     * @param field
     * @param section
     * @return
     * @author: yanjianghua
     * @date: 2018/9/13 14:47
     */
    public String hgetKey(String keyname,String field,int section) {
        Jedis jedis = null;
        String res = "";
        try {
            jedis = jedisPool.getResource();
            jedis.select(section);
            res = jedis.hget(keyname, field);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //返还到连接池
            jedis.close();
        }
        return res;
    }

    /**
     * hget 获取redisHash 所有值
     * @param keyname
     * @param section
     * @return
     * @author: yanjianghua
     * @date: 2018/9/13 14:47
     */
    public Map<String, String> hgetKey(String keyname,int section) {
        Jedis jedis = null;
        Map<String, String> result = new HashMap<>(16);
        try {
            jedis = jedisPool.getResource();
            jedis.select(section);
            result = jedis.hgetAll(keyname);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //返还到连接池
            jedis.close();
        }
        return result;
    }

    /**
     * hset 设置redisHash值
     * @param key
     * @param field
     * @param value
     * @param flag
     * @return
     * @author: yanjianghua
     * @date: 2018/9/13 14:47
     */
    public long setHashRedis(String key,String field,String value,int flag){
        Jedis jedis = null;
        long result = 0;
        try {
            jedis = jedisPool.getResource();
            jedis.select(flag);
            result = jedis.hset(key, field, value);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            jedis.close();
        }
        return result;
    }


    /**
     * hset 设置redisHash值 (map集合<String, String>)
     * @param key
     * @param map   <String, String>
     * @param flag
     * @return
     * @author: yanjianghua
     * @date: 2018/9/13 14:47
     */
    public String setHashRedis(String key,Map<String, String> map,int flag){
        Jedis jedis = null;
        String result = "";
        try {
            jedis = jedisPool.getResource();
            jedis.select(flag);
            result = jedis.hmset(key, map);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            jedis.close();
        }
        return result;
    }


    /**
     * delHashRedis 删除redisHash一个或者多个键值对
     * @param key
     * @param field
     * @param flag
     * @author: yanjianghua
     * @date: 2018/9/13 15:50
     */
    public long delHashRedis(String key,String field,int flag){
        Jedis jedis = null;
        long result = 0;
        try {
            jedis = jedisPool.getResource();
            jedis.select(flag);
            result = jedis.hdel(key, field);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            jedis.close();
        }
        return result;
    }


    /**
     * setRedisNx  公共锁(不会被覆盖的)
     * @param key
     * @param value
     * @param flag
     * @author: yanjianghua
     * @date: 2018/9/13 15:02
     */
    public long setRedisNx(String key,String value,int flag){
        Jedis jedis = null;
        Long result = 0L;
        try {
            jedis = jedisPool.getResource();
            jedis.select(flag);
            result = jedis.setnx(key,value);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //返还到连接池
            jedis.close();
        }
        return result;
    }



}

6、常量类:BaseConstants文件

package com.**.**.constants;

/**
 * 常量类
 */
public class BaseConstants {
    /**
     * 短信redis的数据库 16库
     */
    public static final Integer ASSETCENTER_BUSNESS_FLAG = 16;
    /**
     * 手机号正则检验
     */
    public static final String PHONE_REGEX_MOBILE = "(134[0-8]\\d{7})" + "|(" + "((13([0-3]|[5-9]))" + "|149" + "|15([0-3]|[5-9])" + "|166" + "|17(3|[5-8])" + "|18[0-9]" + "|19[8-9]" + ")" + "\\d{8}" + ")";
    /**
     * 阿里-access_key_id
     */
    public static final String ALI_ACCESS_KEY_ID = "**********";
    /**
     * 阿里-access_key_secret
     */
    public static final String ALI_ACCESS_KEY_SECRET = "*********************";
    /**
     * 阿里短信-短信API产品名称
     */
    public static final String ALI_SMS_PROSUCT = "Dysmsapi";
    /**
     * 阿里短信-短信API产品域名
     */
    public static final String ALI_SMS_API_URL = "dysmsapi.aliyuncs.com";
    /**
     * 阿里短信-短信签名
     */
    public static final String ALI_SMS_SIGN_NAME = "**";



    /**
     * 短信redis存储~前缀
     */
    public static final String MB_SMS_CODE_PHONE = "**_SMS_";

    /**
     * 批量短信redis存储~前缀
     */
    public static final String MB_SMS_BATCH_CODE_PHONE = "**_SMS_BATCH_";
    /**
     * 短信redis存储~过期时间
     */
    public static final int MB_SMS_CODE_TIME = 600;
    /**
     * 阿里短信-身份验证验证码
     */
    public static final String ALI_SMS_ID_CARD_CODE = "SMS_150*******";

    /**
     * 阿里短信-登录确认验证码
     */
    public static final String ALI_SMS_LOGIN_YES_CODE = "SMS_150*******";

    /**
     * 阿里短信-登录异常验证码
     */
    public static final String ALI_SMS_LOGIN_ERROR_CODE = "SMS_150*******";

    /**
     * 阿里短信-用户注册验证码
     */
    public static final String ALI_SMS_USER_REGISTER_CODE = "SMS_150*******";

    /**
     * 阿里短信-修改密码验证码
     */
    public static final String ALI_SMS_UPDATE_PASSWORD_CODE = "SMS_150*******";

    /**
     * 阿里短信-信息变更验证码
     */
    public static final String ALI_SMS_INFO_UPDATE_CODE = "SMS_150*******";


    /**
     * 内部编码-阿里短信-身份验证验证码
     */
    public static final String MB_SMS_ID_CARD_CODE = "1200**";

    /**
     * 内部编码-阿里短信-登录确认验证码
     */
    public static final String MB_SMS_LOGIN_YES_CODE = "1200**";

    /**
     * 内部编码-阿里短信-登录异常验证码
     */
    public static final String MB_SMS_LOGIN_ERROR_CODE = "1200**";

    /**
     * 内部编码-阿里短信-用户注册验证码
     */
    public static final String MB_SMS_USER_REGISTER_CODE = "1200**";

    /**
     * 内部编码-阿里短信-修改密码验证码
     */
    public static final String MB_SMS_UPDATE_PASSWORD_CODE = "1200**";

    /**
     * 内部编码-阿里短信-信息变更验证码
     */
    public static final String MB_SMS_INFO_UPDATE_CODE = "1200**";

    /**
     * 阿里短信类型-内部短信类型编码
     */
    public static final String[] SMS_TYPE_ARRAY = {
            MB_SMS_ID_CARD_CODE,
            MB_SMS_LOGIN_YES_CODE,
            MB_SMS_LOGIN_ERROR_CODE,
            MB_SMS_USER_REGISTER_CODE,
            MB_SMS_UPDATE_PASSWORD_CODE,
            MB_SMS_INFO_UPDATE_CODE
    };


}

7、时间判断工具类:TimeUtils

package com.**.**.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
/**
 * Date 工具类 
 * @author Dyc
 */
public class TimeUtils {
	
	private static SimpleDateFormat sdf;
	private static SimpleDateFormat strSdf;
	private static SimpleDateFormat getSdf(int type) {
		if(type == 1){
			return sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		}else if(type == 2 || type == 0){
			return sdf = new SimpleDateFormat("yyyy-MM-dd");
		}else if(type == 3){
			return sdf = new SimpleDateFormat("yyyy-M-d HH:mm:ss");
		}else if(type == 4){
			return sdf = new SimpleDateFormat("yyyyMMdd");
		}else if(type == 5){
			return sdf = new SimpleDateFormat("yyyy-M-d");
		}else{
			return sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		}
	}

	/**
	 * 获取当前时间
	 * @return
	 */
	public static Date getCurrentDateYMDHMSFORDATE(){
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = null;
		try{
			date = new Date();
		}catch (Exception e){

		}
		return date;
	}

	public static String getCurDate(int type){
		String date = null;
		sdf = getSdf(type);
		try{
			date = sdf.format(new Date());
		}catch (Exception e){

		}
		return date;
	}

	/**
	 * 获取当前时间
	 * @return
	 */
	public static Date getCurrentDateYMDHMS(){
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = null;
		try{
			date = new Date();
		}catch (Exception e){

		}
		return date;
	}

	/**
	 * 获取当前时间 格式:YYYY-MM-dd
	 * @return
	 */
	public static java.time.LocalDate getLocalDateYMDHMS(){
		DateTimeFormatter sdf =  DateTimeFormatter.ofPattern("YYYY-MM-dd");
		LocalDate date = LocalDate.now();
		return date;
	}

	/**
	 * 获取当前时间 格式:YYYY-MM-dd HH:mm:ss
	 * @return
	 */
	public static java.time.LocalDateTime getLocalDateTimeYMDHMS(){
		DateTimeFormatter sdf =  DateTimeFormatter.ofPattern("YYYY-MM-dd HH:mm:ss");
		LocalDateTime date = LocalDateTime.now();
		return date;
	}

	/**
	 *      昨天
	 * */
	public static String getYesterdayDay() {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String nextDay = getDateWithInterval(-1);
		return nextDay;
	}

	/**
	 *     明天
	 * */
	public static String getTomorrowDay() {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String nextDay = getDateWithInterval(+1);
		return nextDay;
	}

	/**
	 *    根据时间加个获取时间
	 * */
	public static String getDateWithInterval(int interval) {

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String returnDate = null;
		try{
			Date date = new Date();
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(date);
			calendar.add(Calendar.DAY_OF_MONTH, interval);
			date = calendar.getTime();
			returnDate = sdf.format(date);
		}catch (Exception e){
			e.printStackTrace();
		}
		return returnDate;
	}


	/**
	 * 		给日期 +1 天 , 参数格式为 : 2018-01-31
	 * */
	public static String addOneDay(String dateStr){
		try {
			SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
			Date date = f.parse(dateStr);
			Calendar c = Calendar.getInstance();
			c.setTime(date);
			c.add(Calendar.DAY_OF_MONTH, 1);//  end date +1天
			dateStr = f.format(c.getTime());
		}
		catch (Exception e){
			e.printStackTrace();
		}
		return dateStr;
	}

	/**
	 * 根据时间 String 返回  Date
	 * @param type  1 为  yyyy-MM-dd HH:mm:ss格式  2为  yyyy-MM-dd格式  3为 yyyy-M-d HH:mm:ss  4为yyyyMMdd 5为 yyyy-M-d
	 * @return
	 */
	public static Date str2Date(String dateStr,int type){
		Date date = null;
		try {
			sdf = getSdf(type);
			date = sdf.parse(dateStr);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return date;
	}

	/**
	 * 根据时间 String 返回  String
	 * @param type  1 为  yyyy-MM-dd HH:mm:ss格式  2为  yyyy-MM-dd格式  3为 yyyy-M-d HH:mm:ss  4为yyyyMMdd 5为 yyyy-M-d
	 * @return
	 */
	public static String strToStr(String dateStr,int type){
		String date = null;
		try {
			strSdf = getSdf(2);
			Date str2 = strSdf.parse(dateStr);
			sdf = getSdf(type);
			date = sdf.format(str2);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return date;
	}
	
	/**
	 * 根据时间 Date 返回  String
	 * @param type  type  1 为  yyyy-MM-dd HH:mm:ss格式  2为  yyyy-MM-dd格式  3为 yyyy-M-d HH:mm:ss 4为yyyyMMdd 5为 yyyy-M-d
	 * @return
	 */
	public static String date2Str(Date date,int type){
		sdf = getSdf(type);
		return sdf.format(date);
	}
	
	
	//----------------- 首页  足迹  时间显示格式
	/**
	 * 首页 足迹   显示的时间  
	 * @param date
	 * @return  String[]  0 :月:1 1:日:1   2:时间:24:00  
	 */
	public static String[] formatDataByLogin(Date date){
		String[] reStr = new String[4]; 
		String dateStr = date2Str(date,3);
		String[] str1 = dateStr.split(" ");
		String fistStr = str1[0];
		String lastStr = str1[1];
		//年
		reStr[0] = (fistStr.split("-"))[0];
		//月
		reStr[1] = (fistStr.split("-"))[1];
		//日
		reStr[2] = (fistStr.split("-"))[2];
		//天
		reStr[3] = lastStr.substring(0,lastStr.lastIndexOf(":"));
		
		return reStr;
	}
	
	/**
	 * 获得年
	 * @return
	 */
	public static String getYearByLogin(Date date){
		String[] str = formatDataByLogin(date);
		return str[0];
	}
	
	/**
	 * 获得月
	 * @return
	 */
	public static String getMonthByLogin(Date date){
		String[] str = formatDataByLogin(date);
		int i = Integer.parseInt(str[1]);
		return marchConversionCapital(i)+"";
	}
	
	/**
	 * 获得日
	 * @return
	 */
	public static String getDayByLogin(Date date){
		String[] str = formatDataByLogin(date);
		return str[2];
	}
	
	/**
	 * 获得时间
	 * @return
	 */
	public static String getTimeByLogin(Date date){
		String[] str = formatDataByLogin(date);
		return str[3];
	}
	
	
	/**
	 * 月份格式化后显示大写月份(一,三,九)
	 * @param march
	 * @return
	 */
	public static String marchConversionCapital(int march){
		String marchCapital=new String();
		switch(march) { 
			case 1: 
				marchCapital="一";
				break; 
			case 2: 
				marchCapital="二";
				break; 
			case 3: 
				marchCapital="三";
				break; 
			case 4: 
				marchCapital="四";
				break; 
			case 5: 
				marchCapital="五";
				break; 
			case 6: 
				marchCapital="六";
				break; 
			case 7: 
				marchCapital="七";
				break; 
			case 8: 
				marchCapital="八";
				break; 
			case 9: 
				marchCapital="九";
				break; 
			case 10: 
				marchCapital="十";
				break; 
			case 11: 
				marchCapital="十一";
				break; 
			case 12: 
				marchCapital="十二";
				break; 
			default: 
				marchCapital="一";
				break; 
			} 
			return marchCapital;
		}
	/**
	 * 计算日期相减
	 * @param oldDate 以前的日期,格式为yyyy-MM-dd
	 * @param newDate 现在的日期,格式为yyyy-MM-dd
	 * @return
	 */
	public static String dateSubtraction(String oldDate,String newDate){
		String[] a=newDate.split("-");
	    String[] b=oldDate.split("-");
	    int ya = Integer.valueOf(a[0]);
	    int ma = Integer.valueOf(a[1]);
	    int da = Integer.valueOf(a[2]);
	    int yb = Integer.valueOf(b[0]);
	    int mb = Integer.valueOf(b[1]);
	    int db = Integer.valueOf(b[2]);
	    int d,m,y;
	    if(da-db>=0){
	    	d=da-db;
	    	if(ma-mb>=0){
	    		m=ma-mb;
	    		y=ya-yb;
	    	}else {
				ya=ya-1;
				m=ma-mb+12;
				y=ya-yb;
			}
	    }else {
			ma=ma-1;
			d=da-db+30;
			if(ma-mb>=0){
	    		m=ma-mb;
	    		y=ya-yb;
	    	}else {
				ya=ya-1;
				m=ma-mb+12;
				y=ya-yb;
			}
		}
	    String s=y+"岁"+m+"个月"+d+"天";
	    return s;
	}

	/**
	 * 根据   2010-02-05获得宝贝多大了   	根据身份日期判断
	 * @param birthday
	 * @return
	 */
	public static int getAge(String birthday) {
		String[] bStr = birthday.split("-");
		String curDate = date2Str(new Date(),2);
		String[] cStr = curDate.split("-");
		int ageY = Integer.parseInt(cStr[0]) - Integer.parseInt(bStr[0]);
		if((Integer.parseInt(bStr[1])-Integer.parseInt(cStr[1])) < 0){
			ageY-=1;
		}else if(Integer.parseInt(bStr[1]) == Integer.parseInt(cStr[1]) && (Integer.parseInt(bStr[2])-Integer.parseInt(cStr[2])) < 0 ){
			ageY-=1;
		}
		return ageY;
	}
	
	/**
	 * 通过当前日期,获得该月的所有天数时间
	 * @param date
	 * @return
	 */
	public static List<Date> getAllTheDateOftheMonth(Date date) {
		List<Date> list = new ArrayList<Date>();
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		cal.set(Calendar.DATE, 1);

		int month = cal.get(Calendar.MONTH);
		while (cal.get(Calendar.MONTH) == month) {
			list.add(cal.getTime());
			cal.add(Calendar.DATE, 1);
		}
		return list;
	}
	/**
	 * yyyy-MM-dd日期格式 加减日期
	 * @param m 要被减的时间
	 * @param m 被加减的天数
	 * @param type  type  1 为  yyyy-MM-dd HH:mm:ss格式  2为  yyyy-MM-dd格式  3为 yyyy-M-d HH:mm:ss 4为yyyyMMdd 5为 yyyy-M-d
	 */
	public static String dayCount(Date date,int m,int type) {
			sdf = getSdf(type);
			Calendar cal=Calendar.getInstance();
			cal.setTime(date);
			//减1天
			cal.add(Calendar.DATE, m);
			return sdf.format(cal.getTime());
	}
	/**
	 * yyyy-MM-dd日期格式 加减日期
	 * @param m 要被减的时间
	 * @param m 被加减的天数
	 * @param type  type  1 为  yyyy-MM-dd HH:mm:ss格式  2为  yyyy-MM-dd格式  3为 yyyy-M-d HH:mm:ss 4为yyyyMMdd 5为 yyyy-M-d
	 */
	public static Date dayCountOfYear(Date date,int m,int type) {
			sdf = getSdf(type);
			Calendar cal=Calendar.getInstance();
			cal.setTime(date);
			//减1天
			cal.add(Calendar.YEAR, m);
			return cal.getTime();
	}


	/**
	 * 		处理分页
	 * */

	public static List subInfosWithPageRows(String page,String rows, List infos){

		int from = (Integer.valueOf(page) - 1) * Integer.valueOf(rows);
		int toIndex =  Integer.valueOf(page) * Integer.valueOf(rows);
		from = from > infos.size() ? infos.size() : from;
		toIndex = toIndex > infos.size() ? infos.size() : toIndex;
		infos = infos.subList(from, toIndex);

		return infos;
	}

	/**
	 * 获取当天零点时间
	 * @return
	 */
	public static Date getCurrentDateZero(){
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(new Date());
		calendar.set(Calendar.HOUR, 0);
		calendar.set(Calendar.MINUTE, 0);
		calendar.set(Calendar.SECOND, 0);
		return calendar.getTime();
	}

	/**
	 * 验证字符串时间,是否在30天内
	 * @param str
	 * @return
	 */
	public static boolean isValidDate(String str) {
		boolean convertSuccess=true;
		//时间格式定义
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		//获取当前时间日期--nowDate
		String nowDate = format.format(new Date());
		//获取30天前的时间日期--minDate
		Calendar calc = Calendar.getInstance();
		calc.add(Calendar.DAY_OF_MONTH, -30);
		String minDate = format.format(calc.getTime());
		try {
			//设置lenient为false. 否则SimpleDateFormat会比较宽松地验证日期,比如2007/02/29会被接受,并转换成2007/03/01
			format.setLenient(false);
			//获取字符串转换后的时间--strDate
			String strDate = format.format(format.parse(str));
			//判断传的STR时间,是否在当前时间之前,且在30天日期之后-----测试的时候打印输出结果
			if (nowDate.compareTo(strDate) >= 0 && strDate.compareTo(minDate) >= 0){
				convertSuccess = true;
			}else{
				convertSuccess = false;
			}
		} catch (ParseException e) {
			convertSuccess=false;
		}
		return convertSuccess;
	}
}

 


版权声明:本文为yjh44780791原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。