Commit f0958551 authored by m1991's avatar m1991

各种工具类

parent 627c6c38
package cn.wisenergy.common.utils;
/***
* 系统中保存的一些常量
*/
/**
* Created by m1991 on 2021/2/28 22:50
*/
public class Constants {
//通用常量
public static class Common{
//否
public final static Integer NOT = 0;
//是
public final static Integer YES = 1;
//女
public final static Integer SEX_WOMEN = 0;
//男
public final static Integer SEX_MAN = 1;
//数据精度
public final static Integer DECIMAL_DIGITS = 2;
}
//访问来源
public static class SourceType{
//访问来源-APP
public final static Integer APP = 0;
//访问来源-PC
public final static Integer PC = 1;
}
//连接符
public static class Connnector{
//逗号
public final static String COMMA_ = ",";
//下划线
public final static String UNDERLINE = "_";
//冒号
public final static String COLON=":";
}
//时长
public static class Duration{
//一秒
public final static Integer SECOND_INT = 1;
//一分钟
public final static Integer MINUTE_INT = SECOND_INT * 60;
//半小时
public final static Integer HALF_HOUR_INT = MINUTE_INT * 30;
}
//正则的一些常量
public static class RegConstant{
//手机号正则
public static String PHONE_REGSTR = "^[1][0-9]{10}$";
//密码正则
public static String PASSWORD_REGSTR = "^([A-Z]|[a-z]|[0-9]|[_]){6,10}$";
}
//SMS相关常量
public static class Sms{
public static class TemplateCode{
public static String LOGIN_OR_REGISTER="SMS_197895260";
}
public static class CodeType{
public static Integer LOGIN_OR_REGISTER=0;
public static Integer PASS_UPDATE=1;
public static Integer ORDER_NOTICE=2;
}
}
//RedisKey相关的常量
public static class RedisKey{
public static String PROJECT_PRIFIX="xts";
public static String SMS_PRIFIX="sms";
public static String TOKEN_PRIFIX="token";
}
}
package cn.wisenergy.common.utils;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.*;
import org.springframework.stereotype.Component;
import java.util.concurrent.TimeUnit;
/**
* Redis工具类
*
*/
@Component
public class RedisUtil {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
@Autowired
private ValueOperations<String, String> valueOperations;
@Autowired
private HashOperations<String, String, Object> hashOperations;
@Autowired
private ListOperations<String, Object> listOperations;
@Autowired
private SetOperations<String, Object> setOperations;
@Autowired
private ZSetOperations<String, Object> zSetOperations;
/** 不设置过期时长 */
public final static long NOT_EXPIRE = -1;
public void set(String key, Object value){
set(key, value);
}
public void set(String key, Object value, long expire){
valueOperations.set(key, toJson(value), expire, TimeUnit.SECONDS);
}
public void set(String key, Object value, long expire, TimeUnit var5){
valueOperations.set(key, toJson(value), expire, var5);
}
public <T> T get(String key, Class<T> clazz, long expire) {
String value = valueOperations.get(key);
if(expire != NOT_EXPIRE){
redisTemplate.expire(key, expire, TimeUnit.SECONDS);
}
return value == null ? null : fromJson(value, clazz);
}
public <T> T get(String key, Class<T> clazz) {
return get(key, clazz, NOT_EXPIRE);
}
public String get(String key, long expire) {
String value = valueOperations.get(key);
if(expire != NOT_EXPIRE){
redisTemplate.expire(key, expire, TimeUnit.SECONDS);
}
return value;
}
public String get(String key) {
return get(key, NOT_EXPIRE);
}
public Boolean delete(String key) {
return redisTemplate.delete(key);
}
/**
* Object转成JSON数据
*/
private String toJson(Object object){
if(object instanceof Integer || object instanceof Long || object instanceof Float ||
object instanceof Double || object instanceof Boolean || object instanceof String){
return String.valueOf(object);
}
return JSON.toJSONString(object);
}
/**
* JSON数据,转成Object
*/
private <T> T fromJson(String json, Class<T> clazz){
return JSON.parseObject(json, clazz);
}
}
package cn.wisenergy.common.utils;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.data.redis.core.BoundListOperations;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
/**
* redis工具 类
*/
@Component
@EnableCaching
public class RedisUtils {
static Logger log = LoggerFactory.getLogger(RedisUtils.class);
@Autowired
private StringRedisTemplate redisTemplate;
/**
* 存储key-value
* @param key
* @param value
* @throws Exception
*/
public void putValue(String key, String value) {
try {
ValueOperations<String, String> valueOps = redisTemplate.opsForValue();
valueOps.set(key, value);
log.info("[REDIS] put k-v key=%s, value=%s", key, value);
} catch (Exception e) {
log.error("[REDIS-ERROR] put k-v key=%s, value=%s", key, value);
}
}
/**
* 存储key-value
*
* @param key
* @param value
* @param timeout 单位为毫秒
* @throws Exception
*/
public void putValue(String key, String value, long timeout) {
try {
ValueOperations<String, String> valueOps = redisTemplate.opsForValue();
valueOps.set(key, value, timeout, TimeUnit.SECONDS);
log.info("[REDIS] put k-v key=%s, value=%s, timeout=%s", key, value, timeout);
} catch (Exception e) {
log.info("[REDIS--ERROR] put k-v key=%s, value=%s, timeout=%s", key, value, timeout);
}
}
/**
* 批量存储key-value
*
* @param values
* @throws Exception
*/
public void putValue(Map<String, String> values) {
try {
ValueOperations<String, String> valueOps = redisTemplate.opsForValue();
valueOps.multiSet(values);
log.info("[REDIS] put map Map=%s", values);
} catch (Exception e) {
log.error("[REDIS--ERROR] put map Map=%s", values);
}
}
/**
* 获取value
*
* @param key
* @return 不存在时,返回null
* @throws Exception
*/
public String getValue(String key) {
String result = null;
try {
ValueOperations<String, String> valueOps = redisTemplate.opsForValue();
result = valueOps.get(key);
log.info("[REDIS] Get k-v key={}, value={}", key, result);
} catch (Exception e) {
log.error("[REDIS--ERROR]-->getValue(String key)错误:{}", e);
}
return result;
}
/**
* 批量获取值
*
* @param keys
* @return
* @throws Exception
*/
public Map<String, String> multiGetValue(List<String> keys) {
Map<String, String> results = null;
try {
ValueOperations<String, String> valueOps = redisTemplate.opsForValue();
List<String> values = valueOps.multiGet(keys);
results = new HashMap<>();
if (values != null && !keys.isEmpty()) {
for (int i = 0; i < keys.size(); i++) {
String fieldName = keys.get(i);
String fieldValue = values.get(i);
// 如果对应的字段为null,则不需要放入
if (!StringUtil.isBlank(fieldValue)) {
results.put(fieldName, fieldValue);
}
}
}
log.info("[REDIS] Get Map map=%s", results);
} catch (Exception e) {
log.error("[REDIS--ERROR] Get Map map=%s", results);
}
return results;
}
/**
* 批量删除key
*
* @param keys
* @throws Exception
*/
public void delete(Collection<String> keys) {
try {
redisTemplate.delete(keys);
log.info("[REDIS] Delete keys=%s", keys);
} catch (Exception e) {
log.error("[REDIS] Delete keys=%s", keys);
}
}
/**
* 删除key
*
* @param key
* @throws Exception
*/
public void delete(String key) {
try {
redisTemplate.delete(key);
log.info("[REDIS] Delete key=%s", key);
} catch (Exception e) {
log.error("[REDIS] Delete key=%s", key);
}
}
/**
* 更新hash里面的属性字段
*
* @param key 键
* @param hashKey 属性名称
* @param value 属性值
* @throws Exception
*/
public void putHash(String key, String hashKey, String value) {
try {
HashOperations<String, String, String> hashOps = redisTemplate.opsForHash();
hashOps.put(key, hashKey, value);
log.info("[REDIS] Put hash key=%s,hashKey=%s,value=%s", key, hashKey, value);
} catch (Exception e) {
log.error("[REDIS] Put hash key=%s,hashKey=%s,value=%s", key, hashKey, value);
}
}
/**
* 批量更新hash里面的属性字段
*
* @param key
* @param hashProperties 属性集合
* @throws Exception
*/
public void putHash(String key, Map<String, String> hashProperties) {
try {
HashOperations<String, String, String> hashOps = redisTemplate.opsForHash();
hashOps.putAll(key, hashProperties);
log.info("[REDIS] Put hash key=%s,hashKey-value=%s", key, hashProperties);
} catch (Exception e) {
log.error("[REDIS] Put hash key=%s,hashKey-value=%s", key, hashProperties);
}
}
/**
* 获取hash的字段值
*
* @param key
* @param hashKey
* @throws Exception
*/
public String getHash(String key, String hashKey) {
String result = null;
try {
HashOperations<String, String, String> hashOps = redisTemplate.opsForHash();
result = hashOps.get(key, hashKey);
log.info("[REDIS] Get hash key=%s,hashKey=%s,value=%s", key, hashKey, result);
return StringUtil.isBlank(result) ? null : result;
} catch (Exception e) {
log.error("[REDIS] Get hash key=%s,hashKey=%s,value=%s", key, hashKey, result);
}
return result;
}
/**
* 批量获取hash的字段值
*
* @param key
* @param hashKeys
* @return filed的Map集合, filedName-filedValue
* @throws Exception
*/
public Map<String, String> multiGetHash(String key, List<String> hashKeys) {
HashMap<String, String> results = null;
try {
HashOperations<String, String, String> hashOps = redisTemplate.opsForHash();
List<String> values = hashOps.multiGet(key, hashKeys);
results = new HashMap<String, String>();
if (values != null && !values.isEmpty()) {
for (int i = 0; i < hashKeys.size(); i++) {
String fieldName = hashKeys.get(i);
String fieldValue = values.get(i);
// 如果对应的字段为null,则不需要放入
if (!StringUtil.isBlank(fieldValue)) {
results.put(fieldName, fieldValue);
}
}
}
log.info("[REDIS] Get hash key=%s,hashKey-value=%s", key, results);
} catch (Exception e) {
log.error("[REDIS] Get hash key=%s,hashKey-value=%s", key, results);
}
return results;
}
/**
* 获取结果
*
* @param key
* @return
* @throws Exception
*/
public Map<String, String> getHashValues(String key) {
Map<String, String> results = null;
try {
HashOperations<String, String, String> hashOps = redisTemplate.opsForHash();
results = hashOps.entries(key);
log.info("[REDIS] Get hash key=%s,hashKey-value=%s", key, results);
} catch (Exception e) {
log.error("[REDIS] Get hash key=%s,hashKey-value=%s", key, results);
}
return results;
}
/**
* 从hash表里面删除对应的值
*
* @param key
* @param hashKey
* @throws Exception
*/
public void deleteHash(String key, String hashKey) {
try {
HashOperations<String, String, String> hashOps = redisTemplate.opsForHash();
hashOps.delete(key, hashKey);
log.info("[REDIS] Delete hash key=%s, hashKey=%s", key, hashKey);
} catch (Exception e) {
log.error("[REDIS] Delete hash key=%s, hashKey=%s", key, hashKey);
}
}
/**
* 为key设置超时时间
*
* @param key
* @param timeout
*/
public void expire(String key, long timeout) {
try {
boolean expore = redisTemplate.expire(key, timeout, TimeUnit.SECONDS);
if (expore) {
log.info("[REDIS] Expire success key=%s, timeout=%s", key, timeout);
} else {
log.info("[REDIS] Expire fail key=%s, timeout=%s", key, timeout);
}
} catch (Exception e) {
log.error("[REDIS] Expire fail key=%s, timeout=%s", key, timeout);
}
}
/**
* 进行递增
*
* @param key
* @param delta
* @param timeout
* @return
* @throws Exception
*/
public long incrementDelta(String key, long delta, long timeout) {
long result = -1L;
try {
ValueOperations<String, String> valueOps = redisTemplate.opsForValue();
result = valueOps.increment(key, delta);
redisTemplate.expire(key, timeout, TimeUnit.SECONDS);
log.info("[REDIS] increment key=%s, result=%s, timeout=%s", key, result, timeout);
} catch (Exception e) {
log.error("[REDIS] increment key=%s, result=%s, timeout=%s", key, result, timeout);
}
return result;
}
/**
* 进行递增
*
* @param key
* @param delta
* @return
* @throws Exception
*/
public long incrementDelta(String key, long delta) {
long result = -1L;
try {
ValueOperations<String, String> valueOps = redisTemplate.opsForValue();
result = valueOps.increment(key, delta);
log.info("[REDIS] increment key=%s, result=%s", key, result);
} catch (Exception e) {
log.error("[REDIS] increment key=%s, result=%s", key, result);
}
return result;
}
/**
* 从左推送到list中
*/
public void leftPush(String key, String value) {
try {
BoundListOperations<String, String> stringStringBoundListOperations = redisTemplate.boundListOps(key);
stringStringBoundListOperations.leftPush(value);
log.info("[REDIS] leftPush list key=%s,value=%s", key, value);
} catch (Exception e) {
log.error("[REDIS] leftPush list key=%s,value=%s", key, value);
}
}
/**
* 从list右边弹出
*/
public String rightPop(String key) {
String result = null;
try {
BoundListOperations<String, String> stringStringBoundListOperations = redisTemplate.boundListOps(key);
result = stringStringBoundListOperations.rightPop();
log.info("[REDIS] rightPop list key=%s,result=%s", key, result);
} catch (Exception e) {
log.error("[REDIS] rightPop list key=%s,result=%s", key, result);
}
return result;
}
public Object get(String key) {
return key == null ? null : redisTemplate.opsForValue().get(key);
}
/**
* 普通缓存放入
*
* @param key 键
* @param value 值
* @return true成功 false失败
*/
public boolean set(String key, Object value) {
try {
redisTemplate.opsForValue().set(key, value.toString());
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 普通缓存放入并设置时间
*
* @param key 键
* @param value 值
* @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期
* @return true成功 false 失败
*/
public boolean set(String key, Object value, long time) {
try {
if (time > 0) {
redisTemplate.opsForValue().set(key, value.toString(), time, TimeUnit.SECONDS);
} else {
set(key, value);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public <T> T getJson(String key, Class<T> entityClass) {
try {
String value = getValue(key);
if (StringUtil.isBlank(value)) {
return null;
}
return JSON.parseObject(value, entityClass);
} catch (Exception e) {
log.error("从redis获取json对象失败:%s,异常信息为: %s", key, ExceptionUtils.getStackTrace(e));
}
return null;
}
public boolean setJson(String key, Object value, long time) {
try {
if (time > 0) {
putValue(key, JSON.toJSONString(value), time);
} else {
putValue(key, JSON.toJSONString(value));
}
return true;
} catch (Exception e) {
log.error("往redis放入json对象失败:%s,异常信息为: %s", key, ExceptionUtils.getStackTrace(e));
return false;
}
}
public <T> List<T> getJsonList(String key, Class<T> entityClass) {
try {
String value = getValue(key);
if (StringUtil.isBlank(value)) {
return null;
}
return JSON.parseArray(value, entityClass);
} catch (Exception e) {
log.error("从redis获取json对象失败:%s", key, ExceptionUtils.getStackTrace(e));
}
return null;
}
}
\ No newline at end of file
package cn.wisenergy.common.utils;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
@Component("springUtils")
@Lazy(false)
public final class SpringUtils implements ApplicationContextAware,
DisposableBean {
/**
* applicationContext
*/
private static ApplicationContext applicationContext;
/**
* 不可实例化
*/
private SpringUtils() {
}
public void setApplicationContext(ApplicationContext applicationContext) {
SpringUtils.applicationContext = applicationContext;
}
public void destroy() throws Exception {
applicationContext = null;
}
/**
* 获取applicationContext
*
* @return applicationContext
*/
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
/**
* 获取实例
*
* @param name
* Bean名称
* @return 实例
*/
@SuppressWarnings("deprecation")
public static Object getBean(String name) {
Assert.hasText(name);
return applicationContext.getBean(name);
}
/**
* 获取实例
*
* @param name
* Bean名称
* @param type
* Bean类型
* @return 实例
*/
@SuppressWarnings("deprecation")
public static <T> T getBean(String name, Class<T> type) {
Assert.hasText(name);
Assert.notNull(type);
return applicationContext.getBean(name, type);
}
}
......@@ -10,10 +10,25 @@ import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import java.util.*;
/**
* 字符串工具类
*/
public class StringUtil {
@Component("springUtils")
@Lazy(false)
public final class StringUtil implements ApplicationContextAware,
DisposableBean {
/**
* String转为Integer
......@@ -562,4 +577,194 @@ public class StringUtil {
}
return result;
}
/**
* applicationContext
*/
private static ApplicationContext applicationContext;
// public static void setApplicationContext(ApplicationContext applicationContext) {
// StringUtil.applicationContext = applicationContext;
// }
/**
* 不可实例化
*/
private StringUtil() { }
// public void setApplicationContext(ApplicationContext applicationContext) {
// SpringUtils.applicationContext = applicationContext;
// }
public void destroy() throws Exception {
applicationContext = null;
}
/**
* 获取applicationContext
*
* @return applicationContext
*/
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
/**
* 获取实例
*
* @param name
* Bean名称
* @return 实例
*/
@SuppressWarnings("deprecation")
public static Object getBean(String name) {
Assert.hasText(name);
return applicationContext.getBean(name);
}
/**
* 获取实例
*
* @param name
* Bean名称
* @param type
* Bean类型
* @return 实例
*/
@SuppressWarnings("deprecation")
public static <T> T getBean(String name, Class<T> type) {
Assert.hasText(name);
Assert.notNull(type);
return applicationContext.getBean(name, type);
}
/**
* 根据传入的字符串和切割方式返回一个Long的集合
* @param s
* @param cut
* @return
*/
public static Set<Long> string2LongSet(String s, String cut) {
if(StringUtils.isBlank(s) ){
return null;
}
if(StringUtils.isBlank(cut)){
cut = Constants.Connnector.COMMA_;
}
String s_temp = s.trim();
String[] arr = s_temp.split(cut);
Set<Long> list = new HashSet<Long>();
if(arr==null || arr.length<=0){
return null;
}
for(String l : arr){
if(!StringUtils.isBlank(l)){
try {
list.add(Long.parseLong(l));
} catch (NumberFormatException e) {
e.printStackTrace();
continue;
}
}
}
return list;
}
/**
* 根据传入的字符串和切割方式返回一个object的集合
* @param s
* @param cut
* @return
* @author:
* @date:
*/
public static List<String> string2StringList(String s, String cut) {
if(StringUtils.isBlank(s)){
return null;
}
if(StringUtils.isBlank(cut)){
cut = Constants.Connnector.COMMA_;
}
String s_temp = s.trim();
String[] arr = s_temp.split(cut);
List<String> list = new ArrayList<String>();
if(arr==null || arr.length<=0){
return null;
}
for(String l : arr){
if(!StringUtils.isBlank(l)){
list.add(l);
}
}
return list;
}
/**
* 根据出入的参数创建一个key
* @return 如果参数为空,那么返回null
*/
public static String formatKeys(String ... args){
if (args != null && args.length > 0){
StringBuilder key = new StringBuilder();
for (String s: args){
key.append(s).append(Constants.Connnector.UNDERLINE);
}
return key.toString();
}
return null;
}
/**
* 根据出入的参数创建一个Redis key,自动拼接前缀
* @return 如果参数为空,那么返回null
*/
public static String formatKeyWithPrefix(String ... args){
if (args != null && args.length > 0){
StringBuffer key=new StringBuffer("");
for (String s: args){
key.append(s).append(Constants.Connnector.COLON);
}
return key.toString();
}
return null;
}
/**
* Description: 创建一个简单的map对象
* @param key
* @param value
* @return
* @Author
* @since
*/
public static Map<String,Object> createSimpleMap(String key, Object value){
Map<String,Object> conditions = null;
if(key !=null && !key.equals("")){
conditions = new HashMap<String,Object>();
conditions.put(key, value);
}
return conditions;
}
/***
* 判断字符串是否为空
* @param temp
* @return
*/
public static boolean isBlank(String temp){
return StringUtils.isBlank(temp);
}
/**
* 返回一个没有中划线的32位字符串
* @return
*/
public static String createToken(){
return UUID.randomUUID().toString().replace("-","");
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
StringUtil.applicationContext = applicationContext;
}
}
package cn.wisenergy.mapper;
import cn.wisenergy.model.app.SmsLog;
import org.apache.ibatis.annotations.Param;
import java.util.List;
import java.util.Map;
public interface SmsLogMapper {
public SmsLog getSmsLogById(@Param(value = "id") Long id);
public List<SmsLog> getSmsLogListByMap(Map<String, Object> param);
public Integer getSmsLogCountByMap(Map<String, Object> param);
public Integer insertSmsLog(SmsLog smsLog);
public Integer updateSmsLog(SmsLog smsLog);
public Integer deleteSmsLogById(@Param(value = "id") Long id);
public Integer batchDeleteSmsLog(Map<String, List<String>> params);
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.wisenergy.mapper.SmsLogMapper">
<select id="getSmsLogById" resultType="cn.wisenergy.model.app.SmsLog">
select
id as id,
codeType as codeType,
phone as phone,
message as message,
failInfo as failInfo,
status as status,
createdUserId as createdUserId,
updatedUserId as updatedUserId,
creatdTime as creatdTime,
updatedTime as updatedTime,
isDelete as isDelete
from sms_log
<trim prefix="where" prefixOverrides="and | or">
<if test="id != null">
and id=#{id}
</if>
</trim>
</select>
<select id="getSmsLogListByMap" resultType="cn.wisenergy.model.app.SmsLog" parameterType="java.util.Map">
select
id as id,
codeType as codeType,
phone as phone,
message as message,
failInfo as failInfo,
status as status,
createdUserId as createdUserId,
updatedUserId as updatedUserId,
creatdTime as creatdTime,
updatedTime as updatedTime,
isDelete as isDelete
from sms_log
<trim prefix="where" prefixOverrides="and | or">
<if test="id != null">
and id=#{id}
</if>
<if test="codeType != null">
and codeType=#{codeType}
</if>
<if test="phone != null and phone!=''">
and phone=#{phone}
</if>
<if test="message != null and message!=''">
and message=#{message}
</if>
<if test="failInfo != null and failInfo!=''">
and failInfo=#{failInfo}
</if>
<if test="status != null">
and status=#{status}
</if>
<if test="createdUserId != null">
and createdUserId=#{createdUserId}
</if>
<if test="updatedUserId != null">
and updatedUserId=#{updatedUserId}
</if>
<if test="null!=creatdTime">
and creatdTime=#{creatdTime}
</if>
<if test="null!=updatedTime">
and updatedTime=#{updatedTime}
</if>
<if test="isDelete != null">
and isDelete=#{isDelete}
</if>
</trim>
<if test="beginPos != null and pageSize != null ">
limit #{beginPos},#{pageSize}
</if>
</select>
<select id="getSmsLogCountByMap" resultType="Integer" parameterType="java.util.Map">
select count(*) from sms_log
<trim prefix="where" prefixOverrides="and | or">
<if test="id != null">
and id=#{id}
</if>
<if test="codeType != null">
and codeType=#{codeType}
</if>
<if test="phone != null and phone!=''">
and phone=#{phone}
</if>
<if test="message != null and message!=''">
and message=#{message}
</if>
<if test="failInfo != null and failInfo!=''">
and failInfo=#{failInfo}
</if>
<if test="status != null">
and status=#{status}
</if>
<if test="createdUserId != null">
and createdUserId=#{createdUserId}
</if>
<if test="updatedUserId != null">
and updatedUserId=#{updatedUserId}
</if>
<if test="null!=creatdTime">
and creatdTime=#{creatdTime}
</if>
<if test="null!=updatedTime">
and updatedTime=#{updatedTime}
</if>
<if test="isDelete != null">
and isDelete=#{isDelete}
</if>
</trim>
</select>
<insert id="insertSmsLog" parameterType="cn.wisenergy.model.app.SmsLog">
insert into sms_log(
codeType,
phone,
message,
failInfo,
status,
createdUserId,
updatedUserId,
creatdTime,
updatedTime,
isDelete)
values(
#{codeType},
#{phone},
#{message},
#{failInfo},
#{status},
#{createdUserId},
#{updatedUserId},
#{creatdTime},
#{updatedTime},
#{isDelete})
</insert>
<update id="updateSmsLog" parameterType="cn.wisenergy.model.app.SmsLog">
update sms_log
<trim prefix="set" suffixOverrides="," suffix="where id=#{id}">
<if test="codeType != null">
codeType=#{codeType},
</if>
<if test="phone != null and phone!=''">
phone=#{phone},
</if>
<if test="message != null and message!=''">
message=#{message},
</if>
<if test="failInfo != null and failInfo!=''">
failInfo=#{failInfo},
</if>
<if test="status != null">
status=#{status},
</if>
<if test="createdUserId != null">
createdUserId=#{createdUserId},
</if>
<if test="updatedUserId != null">
updatedUserId=#{updatedUserId},
</if>
<if test="creatdTime != null">
creatdTime=#{creatdTime},
</if>
<if test="updatedTime != null">
updatedTime=#{updatedTime},
</if>
<if test="isDelete != null">
isDelete=#{isDelete}
</if>
</trim>
</update>
<delete id="deleteSmsLogById" parameterType="String">
delete from sms_log where id = #{id}
</delete>
<delete id="batchDeleteSmsLog" parameterType="java.util.Map">
delete from sms_log where id in (
<foreach collection="ids" item="id" separator=",">
#{id}
</foreach>
)
</delete>
</mapper>
\ No newline at end of file
package cn.wisenergy.model.app;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
/**
* 分页类
* Created by m1991 on 2021/2/28 23:06
*/
public class Page<T> implements Serializable {
private static final long serialVersionUID = 5294589632707269745L;
//默认页大小
private static int DEFAULT_PAGE_SIZE = 20;
private static int DEFAULT_PAGE_NO = 1;
//当前页码
private int pageNo;
/**
* 每页的记录数
*/
private int pageSize = DEFAULT_PAGE_SIZE;
/**
* 总记录数
*/
private Integer total;
/**
* 总页数
*/
private int pages;
/**
* 数据
*/
private List<T> list;
//开始位置
private Integer beginPos;
public Page(List<T> list) {
this.list = list;
}
public Page(int pageNo, int pageSize, Integer total) {
pageNo = (pageNo==0 )? DEFAULT_PAGE_NO : pageNo;
pageSize = (pageSize==0 )?DEFAULT_PAGE_SIZE : pageSize;
this.beginPos=(pageNo-1)*pageSize;
this.pageNo = pageNo;
this.pageSize = pageSize;
this.total = total;
}
public Page(List<T> list, int pageNo, int pageSize, int total) {
this.list = list;
this.pageNo = pageNo;
this.setPageSize(pageSize);
this.setTotal(total);
}
public Page() {
new Page<T>(new ArrayList<T>(), 0, 0, 0);
}
public void setPage(int pageNo, int pageSize,Integer total) {
this.pageNo = pageNo;
this.pageSize = pageSize;
this.total = total;
}
public static long getSerialVersionUID() {
return serialVersionUID;
}
public static int getDefaultPageSize() {
return DEFAULT_PAGE_SIZE;
}
public static void setDefaultPageSize(int defaultPageSize) {
DEFAULT_PAGE_SIZE = defaultPageSize;
}
public int getPageNo() {
return pageNo;
}
public void setPageNo(int pageNo) {
this.pageNo = pageNo;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public long getTotal() {
return total;
}
public void setTotal(Integer total) {
this.total = total;
}
public List<T> getList() {
return list;
}
public void setList(List<T> list) {
this.list = list;
}
public int getPages() {
return pages;
}
public void setPages(int pages) {
this.pages = pages;
}
public Integer getBeginPos() {
return beginPos;
}
public void setBeginPos(Integer beginPos) {
this.beginPos = beginPos;
}
}
package cn.wisenergy.model.app;
import java.io.Serializable;
import java.util.Date;
import java.math.BigDecimal;
/***
* 短信记录
*/
public class SmsLog implements Serializable {
//
private Long id;
//短信类型(0:注册、登录验证码,1:修改密码,2:订单状态通知信息)
private Integer codeType;
//接收短信手机号
private String phone;
//短信内容
private String message;
//失败原因
private String failInfo;
//状态(1:成功2:失败)
private Integer status;
//创建人
private Long createdUserId;
//修改人
private Long updatedUserId;
//创建时间
private Date creatdTime;
//修改时间
private Date updatedTime;
//是否删除(0:否,1:是)
private Integer isDelete;
//get set 方法
public void setId (Long id){
this.id=id;
}
public Long getId(){
return this.id;
}
public void setCodeType (Integer codeType){
this.codeType=codeType;
}
public Integer getCodeType(){
return this.codeType;
}
public void setPhone (String phone){
this.phone=phone;
}
public String getPhone(){
return this.phone;
}
public void setMessage (String message){
this.message=message;
}
public String getMessage(){
return this.message;
}
public void setFailInfo (String failInfo){
this.failInfo=failInfo;
}
public String getFailInfo(){
return this.failInfo;
}
public void setStatus (Integer status){
this.status=status;
}
public Integer getStatus(){
return this.status;
}
public void setCreatedUserId (Long createdUserId){
this.createdUserId=createdUserId;
}
public Long getCreatedUserId(){
return this.createdUserId;
}
public void setUpdatedUserId (Long updatedUserId){
this.updatedUserId=updatedUserId;
}
public Long getUpdatedUserId(){
return this.updatedUserId;
}
public void setCreatdTime (Date creatdTime){
this.creatdTime=creatdTime;
}
public Date getCreatdTime(){
return this.creatdTime;
}
public void setUpdatedTime (Date updatedTime){
this.updatedTime=updatedTime;
}
public Date getUpdatedTime(){
return this.updatedTime;
}
public void setIsDelete (Integer isDelete){
this.isDelete=isDelete;
}
public Integer getIsDelete(){
return this.isDelete;
}
}
package cn.wisenergy.service.app;
/**
*
* 短信功能业务层接口
*
* Created by m1991 on 2021/2/28 22:53
*/
public interface SmsLogService {
/**
* 发送短信
* @param phone
* @param codeType
* @param uId
*/
void sendMessage(String phone, Integer codeType, Long uId);
}
package cn.wisenergy.service.app.impl;
import cn.wisenergy.mapper.SmsLogMapper;
import cn.wisenergy.model.app.SmsLog;
import cn.wisenergy.service.app.SmsLogService;
import cn.wisenergy.model.app.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.ArrayList;
import java.util.HashMap;
@Service
public class SmsLogServiceImpl implements SmsLogService {
@Autowired
private SmsLogMapper smsLogMapper;
public SmsLog getSmsLogById(Long id){
return smsLogMapper.getSmsLogById(id);
}
public List<SmsLog> getSmsLogListByMap(Map<String,Object> param){
return smsLogMapper.getSmsLogListByMap(param);
}
public Integer getSmsLogCountByMap(Map<String,Object> param){
return smsLogMapper.getSmsLogCountByMap(param);
}
public Integer qdtxAddSmsLog(SmsLog smsLog){
smsLog.setCreatdTime(new Date());
return smsLogMapper.insertSmsLog(smsLog);
}
public Integer qdtxModifySmsLog(SmsLog smsLog){
smsLog.setUpdatedTime(new Date());
return smsLogMapper.updateSmsLog(smsLog);
}
public Integer qdtxDeleteSmsLogById(Long id){
return smsLogMapper.deleteSmsLogById(id);
}
public Integer qdtxBatchDeleteSmsLog(String ids){
Map<String,List<String>> param=new HashMap<String,List<String>>();
String[] paramArrays=ids.split(",");
List<String> idList=new ArrayList<String>();
for (String temp:paramArrays){
idList.add(temp);
}
param.put("ids",idList);
return smsLogMapper.batchDeleteSmsLog(param);
}
public Page<SmsLog> querySmsLogPageByMap(Map<String,Object> param,Integer pageNo,Integer pageSize){
Integer total = smsLogMapper.getSmsLogCountByMap(param);
Page page = new Page(pageNo, pageSize, total);
param.put("beginPos", page.getBeginPos());
param.put("pageSize", page.getPageSize());
List<SmsLog> smsLogList = smsLogMapper.getSmsLogListByMap(param);
page.setList(smsLogList);
return page;
}
@Override
public void sendMessage(String phone, Integer codeType, Long uId) {
}
}
......@@ -28,6 +28,28 @@
<artifactId>shiro-spring</artifactId>
<version>1.4.0</version>
</dependency>
<!-- thymeleaf模板 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-core</artifactId>
<version>4.4.0</version>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-dysmsapi</artifactId>
<version>1.0.0</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
</dependencies>
<!-- MAVEN构建 -->
......
......@@ -12,6 +12,7 @@ import springfox.documentation.swagger2.annotations.EnableSwagger2;
* 配置netty启动
*/
@EnableCaching
//@SpringBootApplication(scanBasePackages = “com.mall”)
@SpringBootApplication(exclude = {MultipartAutoConfiguration.class})
@MapperScan(
basePackages = "cn.wisenergy.mapper")
......
package cn.wisenergy.web.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import java.nio.charset.Charset;
import java.util.List;
/**
* 配置全局编码格式 utf-8
* Created by m1991 on 2021/3/1 4:15
*/
@Configuration
public class GlobalConversConfiguration extends WebMvcConfigurationSupport {
@Bean
public HttpMessageConverter<String> responseBodyConverter() {
StringHttpMessageConverter converter = new StringHttpMessageConverter(
Charset.forName("UTF-8"));
return converter;
}
@Override
public void configureMessageConverters(
List<HttpMessageConverter<?>> converters) {
super.configureMessageConverters(converters);
converters.add(responseBodyConverter());
}
@Override
public void configureContentNegotiation(
ContentNegotiationConfigurer configurer) {
configurer.favorPathExtension(false);
}
}
package cn.wisenergy.web.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "sms")
public class SmsConfig {
private String accessKeyId;
private String secret;
private String regionId;
private String domain;
private String version;
private String action;
private String signName;
public String getAccessKeyId() {
return accessKeyId;
}
public void setAccessKeyId(String accessKeyId) {
this.accessKeyId = accessKeyId;
}
public String getSecret() {
return secret;
}
public void setSecret(String secret) {
this.secret = secret;
}
public String getRegionId() {
return regionId;
}
public void setRegionId(String regionId) {
this.regionId = regionId;
}
public String getDomain() {
return domain;
}
public void setDomain(String domain) {
this.domain = domain;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getAction() {
return action;
}
public void setAction(String action) {
this.action = action;
}
public String getSignName() {
return signName;
}
public void setSignName(String signName) {
this.signName = signName;
}
}
package cn.wisenergy.web.sms;
/**
*
* 通用异常的处理
*/
public class BaseException extends Exception {
private static final long serialVersionUID = 1L;
public BaseException() {}
/**
* 一个返回状态枚举的构造函数
* @param resultEnum
*/
public BaseException(ResultEnum resultEnum) {
super(resultEnum.getMsg());
this.resultEnum = resultEnum;
this.errorCode = resultEnum.getCode();
this.errorMessage = resultEnum.getMsg();
}
// 返回信息枚举
private ResultEnum resultEnum;
// 错误码
private String errorCode;
// 错误信息
private String errorMessage;
public static long getSerialVersionUID() {
return serialVersionUID;
}
public ResultEnum getResultEnum() {
return resultEnum;
}
public void setResultEnum(ResultEnum resultEnum) {
this.resultEnum = resultEnum;
}
public String getErrorCode() {
return errorCode;
}
public void setErrorCode(String errorCode) {
this.errorCode = errorCode;
}
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
}
package cn.wisenergy.web.sms;
/***
* 系统中保存的一些常量
*/
/**
* Created by m1991 on 2021/2/28 22:50
*/
public class Constants {
//通用常量
public static class Common{
//否
public final static Integer NOT = 0;
//是
public final static Integer YES = 1;
//女
public final static Integer SEX_WOMEN = 0;
//男
public final static Integer SEX_MAN = 1;
//数据精度
public final static Integer DECIMAL_DIGITS = 2;
}
//访问来源
public static class SourceType{
//访问来源-APP
public final static Integer APP = 0;
//访问来源-PC
public final static Integer PC = 1;
}
//连接符
public static class Connnector{
//逗号
public final static String COMMA_ = ",";
//下划线
public final static String UNDERLINE = "_";
//冒号
public final static String COLON=":";
}
//时长
public static class Duration{
//一秒
public final static Integer SECOND_INT = 1;
//一分钟
public final static Integer MINUTE_INT = SECOND_INT * 60;
//半小时
public final static Integer HALF_HOUR_INT = MINUTE_INT * 30;
}
//正则的一些常量
public static class RegConstant{
//手机号正则
public static String PHONE_REGSTR = "^[1][0-9]{10}$";
//密码正则
public static String PASSWORD_REGSTR = "^([A-Z]|[a-z]|[0-9]|[_]){6,10}$";
}
//SMS相关常量
public static class Sms{
public static class TemplateCode{
public static String LOGIN_OR_REGISTER="SMS_197895260";
}
public static class CodeType{
public static Integer LOGIN_OR_REGISTER=0;
public static Integer PASS_UPDATE=1;
public static Integer ORDER_NOTICE=2;
}
}
//RedisKey相关的常量
public static class RedisKey{
public static String PROJECT_PRIFIX="xts";
public static String SMS_PRIFIX="sms";
public static String TOKEN_PRIFIX="token";
}
}
package cn.wisenergy.web.sms;
import java.math.BigDecimal;
/**
* @Description 数字相关工具类
* @Date 2019-08-22 17:08
* @Author est team
* Version 1.0
**/
public class MathUtils {
/**
* 返回一个4位随机数
* @return
*/
public static String random(){
int random = (int) ((Math.random() * 9 + 1) * 1000);
return random + "";
}
/**
* 格式化BigDecimal,返回保留相应的小数
* @param decimal
* @param num
* @return
*/
public static BigDecimal formatDecimal(BigDecimal decimal, int num){
BigDecimal result = decimal.setScale(num,BigDecimal.ROUND_HALF_UP);
return result;
}
/**
* 格式化BigDecimal,默认保留两位小数
* @param decimal
* @return
*/
public static BigDecimal formatDecimal(BigDecimal decimal){
BigDecimal result = formatDecimal(decimal, Constants.Common.DECIMAL_DIGITS);
return result;
}
}
package cn.wisenergy.web.sms;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
/**
* 分页类
* Created by m1991 on 2021/2/28 23:06
*/
public class Page<T> implements Serializable {
private static final long serialVersionUID = 5294589632707269745L;
//默认页大小
private static int DEFAULT_PAGE_SIZE = 20;
private static int DEFAULT_PAGE_NO = 1;
//当前页码
private int pageNo;
/**
* 每页的记录数
*/
private int pageSize = DEFAULT_PAGE_SIZE;
/**
* 总记录数
*/
private Integer total;
/**
* 总页数
*/
private int pages;
/**
* 数据
*/
private List<T> list;
//开始位置
private Integer beginPos;
public Page(List<T> list) {
this.list = list;
}
public Page(int pageNo, int pageSize,Integer total) {
pageNo = (pageNo==0 )? DEFAULT_PAGE_NO : pageNo;
pageSize = (pageSize==0 )?DEFAULT_PAGE_SIZE : pageSize;
this.beginPos=(pageNo-1)*pageSize;
this.pageNo = pageNo;
this.pageSize = pageSize;
this.total = total;
}
public Page(List<T> list, int pageNo, int pageSize, int total) {
this.list = list;
this.pageNo = pageNo;
this.setPageSize(pageSize);
this.setTotal(total);
}
public Page() {
new Page<T>(new ArrayList<T>(), 0, 0, 0);
}
public void setPage(int pageNo, int pageSize,Integer total) {
this.pageNo = pageNo;
this.pageSize = pageSize;
this.total = total;
}
public static long getSerialVersionUID() {
return serialVersionUID;
}
public static int getDefaultPageSize() {
return DEFAULT_PAGE_SIZE;
}
public static void setDefaultPageSize(int defaultPageSize) {
DEFAULT_PAGE_SIZE = defaultPageSize;
}
public int getPageNo() {
return pageNo;
}
public void setPageNo(int pageNo) {
this.pageNo = pageNo;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public long getTotal() {
return total;
}
public void setTotal(Integer total) {
this.total = total;
}
public List<T> getList() {
return list;
}
public void setList(List<T> list) {
this.list = list;
}
public int getPages() {
return pages;
}
public void setPages(int pages) {
this.pages = pages;
}
public Integer getBeginPos() {
return beginPos;
}
public void setBeginPos(Integer beginPos) {
this.beginPos = beginPos;
}
}
package cn.wisenergy.web.sms;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
/**
* Title:向浏览器输出一个json
* Description: 类的功能详细描述
* @Author est team
* @version 1.0
* @since 2017年5月23日
*/
public class ResponseOutput {
static Logger log = LoggerFactory.getLogger(ResponseOutput.class);
/**
* 根据枚举对象将数据写会前端
* @param response
* @param resultEnum
*/
public static void outputJson(HttpServletResponse response, ResultEnum resultEnum) {
outputJson(response, ResultUtils.returnResult(resultEnum));
}
/**
* 根据返回对象将数据写会前端
* @param response
* @param result
*/
public static void outputJson(HttpServletResponse response, Result result) {
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json; charset=utf-8");
PrintWriter out = null;
try {
out = response.getWriter();
out.append(JSONObject.toJSON(result).toString());
} catch (IOException e) {
log.error("ResponseOut-->error:{}", e.getMessage());
} finally {
if (out != null) {
out.close();
}
}
}
}
\ No newline at end of file
package cn.wisenergy.web.sms;
import java.io.Serializable;
/**
* 返回信息包装类
* Created by m1991 on 2021/2/28 23:08
*/
public class Result<T> implements Serializable{
public String code;
public String msg;
private T data;
/**
* 无参构造
*/
public Result() {}
/**
* 根据code,msg创建一个Resutl
* @param code
* @param msg
*/
public Result(String code, String msg) {
this.code = code;
this.msg = msg;
}
/**
* 根据code,msg,data创建一个Resutl
* @param code
* @param msg
* @param data
*/
public Result(String code, String msg, T data) {
this.code = code;
this.msg = msg;
this.data = data;
}
/**
* 根据枚举创建一个Result
* @param resultEnum
*/
public Result(ResultEnum resultEnum) {
this.code = resultEnum.getCode();
this.msg = resultEnum.getMsg();
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
}
package cn.wisenergy.web.sms;
/**
* 出参错误码列表
* 尽管是后台信息,文案受制于中前台要求,暴露给用户
* 接手者请推动前端的后台包装,目前谨慎修改
*
* Created by m1991 on 2021/2/28 23:10
*/
public enum ResultEnum {
SUCCESS("0", "成功"),
FAIL("1", "失败"),
COMMON_EXCEPTION("5", "系统异常"),
FAIL_PARAM("1001", "请求参数错误"),
FAIL_LOGIN("1002", "登录失败"),
FAIL_VERIFY("1003", "验证码错误"),
FAIL_ACCOUNT_EXIST("1004", "账号已存在"),
FAIL_ACCOUNT_NOT_EXIST("1005", "账号不存在"),
FAIL_TIMESTAMP_NOT_NULL("1006", "时间戳不能为空"),
FAIL_VISIT_SOURCE_NOT_NULL("1007", "访问来源不能为空"),
PHONE_ERROR("1008","手机号码格式不正确"),
CODETYPE_ERROR("1009","手机号码格式不正确"),
CODESEND_ERROR("1010","请相隔60S后再发送"),
FILE_NOT_LOGIN("2001", "未登录"),
FILE_NOT_HAVE_PERMISSION("2002", "没有权限"),
FAIL_ACCOUNT_LOCK("2003", "账号已被锁定"),
FAIL_NOT_FIND_PAGE("3001", "找不到页面"),
FAIL_TIMEOUT("3002", "请求超时"),
FAIL_HAVE_DELETED("3003", "已被删除"),
FAIL_HAVE_NOT_EXIST("3005", "数据不存在");
String code;
String msg;
ResultEnum(String code, String msg) {
this.code = code;
this.msg = msg;
}
public String getCode() {
return code;
}
public String getMsg() {
return msg;
}
public static ResultEnum getByCode(String code) {
if (code == null) {
return COMMON_EXCEPTION;
}
for (ResultEnum outputEnum : ResultEnum.values()) {
if (code.equals(outputEnum.code)) {
return outputEnum;
}
}
return COMMON_EXCEPTION;
}
}
package cn.wisenergy.web.sms;
/**
* 用于返回Result的工具类
* Created by m1991 on 2021/2/28 23:03
*/
public class ResultUtils {
/**
* 统一返回成功的Result
*/
public static Result returnSuccess() {
Result Result = new Result(ResultEnum.SUCCESS);
return Result;
}
/**
* 统一返回成功的Result 带数据
*/
public static Result returnSuccess(String msg, Object data) {
Result Result = new Result(ResultEnum.SUCCESS.getCode(), msg, data);
return Result;
}
/**
* 统一返回成功的Result 不带数据
*/
public static Result returnSuccess(String msg) {
Result Result = new Result(ResultEnum.SUCCESS.getCode(), msg);
return Result;
}
/**
* 统一返回成功的Result 带数据 没有消息
*/
public static Result returnDataSuccess(Object data) {
Result Result = new Result(ResultEnum.SUCCESS);
Result.setData(data);
return Result;
}
/**
* 返回一个失败的Result
* @return
*/
public static Result returnFail() {
Result Result = new Result(ResultEnum.FAIL);
return Result;
}
/**
* 返回一个失败的Result
*
* @param msg
* @param code
* @return
*/
public static Result returnFail(String msg, String code) {
Result Result = new Result(code, msg);
return Result;
}
/**
* 返回 一个失败的Result,code统一为 “1”,msg自定义
*
* @param msg
* @return
*/
public static Result returnFail(String msg) {
Result Result = new Result(ResultEnum.FAIL.getCode(), msg);
return Result;
}
/**
* 根据枚举创建一个Result
*
* @param resultEnum
* @return
*/
public static Result returnResult(ResultEnum resultEnum) {
Result Result = new Result(resultEnum);
return Result;
}
}
package cn.wisenergy.web.sms;
import cn.wisenergy.common.utils.RedisUtils;
import cn.wisenergy.common.utils.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RequestMapping("/api/sms")
@RestController
public class SmsController {
@Autowired
private SmsUtils smsUtils;
@Autowired
private RedisUtils redisUtils;
@RequestMapping("/verifyCode")
public Result verifyCode(String phone,Integer codeType) throws Exception {
//判断phone和codeType是否符合输入类型
if(!phone.matches(Constants.RegConstant.PHONE_REGSTR)){
throw new BaseException(ResultEnum.PHONE_ERROR);
}
if(codeType!=Constants.Sms.CodeType.LOGIN_OR_REGISTER && codeType!=Constants.Sms.CodeType.PASS_UPDATE && codeType!=Constants.Sms.CodeType.ORDER_NOTICE){
throw new BaseException(ResultEnum.CODETYPE_ERROR);
}
String key= StringUtil.formatKeyWithPrefix(Constants.RedisKey.PROJECT_PRIFIX,Constants.RedisKey.SMS_PRIFIX,phone,codeType+"");
//判断是否超过60S
String oldCode=redisUtils.getValue(key);
if(!StringUtils.isBlank(oldCode)){
throw new BaseException(ResultEnum.CODESEND_ERROR);
}
//生成随机数
String code= MathUtils.random();
//保存至Redis
redisUtils.set(key,code,Constants.Duration.MINUTE_INT);
boolean flag=smsUtils.sendMessage(phone,Constants.Sms.TemplateCode.LOGIN_OR_REGISTER,code);
return flag? ResultUtils.returnSuccess():ResultUtils.returnFail();
}
}
\ No newline at end of file
package cn.wisenergy.web.sms;
import java.util.Date;
/**
* 短信记录
* Created by m1991 on 2021/2/28 22:56
*/
public class SmsLog {
//
private Long id;
//短信类型(0:注册、登录验证码,1:修改密码,2:订单状态通知信息)
private Integer codeType;
//接收短信手机号
private String phone;
//短信内容
private String message;
//失败原因
private String failInfo;
//状态(1:成功2:失败)
private Integer status;
//创建人
private Long createdUserId;
//修改人
private Long updatedUserId;
//创建时间
private Date creatdTime;
//修改时间
private Date updatedTime;
//是否删除(0:否,1:是)
private Integer isDelete;
//get set 方法
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Integer getCodeType() {
return codeType;
}
public void setCodeType(Integer codeType) {
this.codeType = codeType;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getFailInfo() {
return failInfo;
}
public void setFailInfo(String failInfo) {
this.failInfo = failInfo;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public Long getCreatedUserId() {
return createdUserId;
}
public void setCreatedUserId(Long createdUserId) {
this.createdUserId = createdUserId;
}
public Long getUpdatedUserId() {
return updatedUserId;
}
public void setUpdatedUserId(Long updatedUserId) {
this.updatedUserId = updatedUserId;
}
public Date getCreatdTime() {
return creatdTime;
}
public void setCreatdTime(Date creatdTime) {
this.creatdTime = creatdTime;
}
public Date getUpdatedTime() {
return updatedTime;
}
public void setUpdatedTime(Date updatedTime) {
this.updatedTime = updatedTime;
}
public Integer getIsDelete() {
return isDelete;
}
public void setIsDelete(Integer isDelete) {
this.isDelete = isDelete;
}
}
package cn.wisenergy.web.sms;
import cn.wisenergy.common.utils.StringUtil;
import cn.wisenergy.web.config.SmsConfig;
import com.alibaba.fastjson.JSONObject;
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;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/***
* 短信发送工具类
*/
@Component
public class SmsUtils {
@Autowired
private SmsConfig smsConfig;
/***
* 发送短信的方法
* @param
* @return
*/
public boolean sendMessage(String phone,String templateCode,String code) {
//构造一个acs的clinet
DefaultProfile profile = DefaultProfile.getProfile(smsConfig.getRegionId(), smsConfig.getAccessKeyId(), smsConfig.getSecret());
IAcsClient client = new DefaultAcsClient(profile);
//构造请求的request
CommonRequest request = new CommonRequest();
//设置了一堆参数
request.setSysMethod(MethodType.POST);
request.setSysDomain(smsConfig.getDomain());
request.setSysVersion(smsConfig.getVersion());
request.setSysAction(smsConfig.getAction());
request.putQueryParameter("RegionId", smsConfig.getRegionId());
request.putQueryParameter("PhoneNumbers", phone);
request.putQueryParameter("SignName", smsConfig.getSignName());
request.putQueryParameter("TemplateCode", templateCode);
request.putQueryParameter("TemplateParam", JSONObject.toJSONString(StringUtil.createSimpleMap("code",code)));
try {
//发送请求,接收响应
CommonResponse response = client.getCommonResponse(request);
System.out.println(response.getData());
String status= (String) JSONObject.parseObject(response.getData()).get("Code");
return "OK".equals(status);
} catch (ServerException e) {
e.printStackTrace();
} catch (ClientException e) {
e.printStackTrace();
}
return false;
}
}
package cn.wisenergy.web.sms;
//import cn.est.config.UserConfig;
//import cn.est.constants.ResultEnum;
//import cn.est.dto.Result;
//import cn.est.po.Brand;
//import cn.est.service.BrandService;
//import cn.est.utils.ResultUtils;
//import cn.est.utils.SmsUtils;
//import cn.est.utils.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class TestController {
// @Autowired
// private BrandService brandService;
@Autowired
private SmsUtils smsUtils;
//
// @Autowired
// private UserConfig useronfig;
@RequestMapping("/index")
@ResponseBody
public String index() {
return "Hello Wolrd";
}
// @RequestMapping("/query")
// @ResponseBody
// public List<Brand> queryBrandList(){
// Map<String,Object> param=new HashMap<String, Object>();
// return brandService.getBrandListByMap(param);
// }
// @RequestMapping("/testResult")
// @ResponseBody
// public Result testResult(){
// Map<String,Object> map= StringUtil.createSimpleMap("name","zzshang");
// Result result1= ResultUtils.returnSuccess("成功",map);
// Result result2=ResultUtils.returnFail(ResultEnum.FAIL_HAVE_DELETED.getCode(),ResultEnum.FAIL_HAVE_DELETED.getMsg());
// return result2;
// }
@RequestMapping("/testSms")
@ResponseBody
public Result testException()throws Exception{
// System.out.println(useronfig.getUserName()+"---"+useronfig.getSex());
return smsUtils.sendMessage("18518666833","SMS_212170059","2111")?ResultUtils.returnSuccess():ResultUtils.returnFail();
}
}
package cn.wisenergy.web.sms;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* 本类提供了对URL所指向的内容的加载操作
* @author hduser
*
*/
public class UrlUtils {
/**
* 获取url网址返回的数据内容
* @param urlStr
* @return
*/
public static String loadURL(String urlStr){
try{
URL url = new URL(urlStr);
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
String responseStr = ConvertToString(inputStream);
return responseStr;
}catch(IOException e){
e.printStackTrace();
return null;
}
}
private static String ConvertToString(InputStream inputStream){
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuilder result = new StringBuilder();
String line = null;
try {
while((line = bufferedReader.readLine()) != null){
result.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try{
inputStreamReader.close();
inputStream.close();
bufferedReader.close();
}catch(IOException e){
e.printStackTrace();
}
}
return result.toString();
}
}
package cn.wisenergy.web.sms.interceptor;
import cn.wisenergy.web.sms.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 统一异常处理
*/
@Component
public class ExceptionInterceptor extends HandlerInterceptorAdapter {
Logger log = LoggerFactory.getLogger(ExceptionInterceptor.class);
/**
* 异常处理
* @param request
* @param response
* @param handler
* @param ex
* @throws java.io.IOException
*/
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
Result result = null;
log.info(request.getRequestURI() + ">>>>>>");
log.info(request.getRequestURL() + ">>>>>>");
//拦截异常信息
if (ex != null) {
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=utf-8");
try {
String moduleMessage = ex.toString();
log.info("统一异常信息:{}", moduleMessage);
if (ex instanceof BaseException) {
BaseException se = (BaseException) ex;
result = ResultUtils.returnFail(se.getErrorMessage(), se.getErrorCode());
} else {
result = ResultUtils.returnResult(ResultEnum.FAIL);
}
} catch (Exception e) {
if (!(ex instanceof BaseException)) {
log.error("未知错误:{}", ex);
result = ResultUtils.returnResult(ResultEnum.COMMON_EXCEPTION);
}
}
ResponseOutput.outputJson(response, result);
}
}
}
package cn.wisenergy.web.sms.interceptor;
import cn.wisenergy.common.utils.RedisUtils;
import cn.wisenergy.common.utils.StringUtil;
import cn.wisenergy.web.sms.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
/**
* 前端拦截器
*/
@Component
public class LoginInterceptor extends HandlerInterceptorAdapter {
Logger log = LoggerFactory.getLogger(LoginInterceptor.class);
/**
* 直接放行的接口
*/
public static String[] EXCLUDE_URI = new String[]{"/pay/alipay/notify", "/pay/alipay/return", "/user/wechat/callback"};
/**
* 需要登录才可以访问的接口
*/
public static String[] VERIFY_URI = new String[]{"/evaluate/assess", "/order/maintain/", "/pay/aliPay", "/user/logout"};
@Autowired
private RedisUtils redisUtils;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object obj) throws Exception {
boolean flag = false;
String loginUser = null;
String key = null;
Map<String, String> params = new HashMap<>();
Enumeration<String> names = request.getHeaderNames();
while (names.hasMoreElements()) {
String name = names.nextElement();
String value = request.getHeader(name);
params.put(name, value);
}
// 获取访问url
String url = request.getRequestURL().toString();
// 判断是否直接放行
for (String s : EXCLUDE_URI) {
if (url.contains(s)) {
return true;
}
}
// if (StringUtil.isBlank(params.get("timestamp"))) {
// log.error("时间戳不能为空");
// ResponseOutput.outputJson(response, ResultEnum.FAIL_TIMESTAMP_NOT_NULL);
// return false;
// } else if (StringUtil.isBlank(params.get("source-type"))) {
// log.error("访问来源不能为空");
// ResponseOutput.outputJson(response, ResultEnum.FAIL_VISIT_SOURCE_NOT_NULL);
// return false;
// }
for (String s : VERIFY_URI) {
if (url.contains(s)) {
flag = true;
break;
}
}
// 判断,如果是需要拦截的方法
if (flag) {
String token = request.getHeader("token");
key = StringUtil.formatKeyWithPrefix(token);
// 获取登录用户
loginUser = redisUtils.getValue(key);
log.info("Basenterceptor-->获取到用户登录信息users:{}", loginUser);
// 验证用户登陆
if (null == loginUser) {
ResponseOutput.outputJson(response, ResultEnum.FILE_NOT_LOGIN);
return false;
}
}
// 如果用户是登录状态,登录状态续命
if(!StringUtil.isBlank(key) && !StringUtil.isBlank(loginUser)){
redisUtils.putValue(key, loginUser, Constants.Duration.HALF_HOUR_INT);
}
return true;
}
@Override
public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
throws Exception {
// TODO Auto-generated method stub
}
@Override
public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
Object arg2, ModelAndView arg3) throws Exception {
// TODO Auto-generated method stub
}
}
\ No newline at end of file
package cn.wisenergy.web.sms.interceptor;
import cn.wisenergy.web.sms.ResponseOutput;
import cn.wisenergy.web.sms.ResultEnum;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
/**
* 参数校验
*/
@Component
public class ValidateParamInterceptor extends HandlerInterceptorAdapter {
Logger log = LoggerFactory.getLogger(ValidateParamInterceptor.class);
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
response.setHeader("Content-type", "text/html;charset=UTF-8");
//获取URL
String servletPath = request.getServletPath();
//先判断空值
// Map<String, String[]> reqParams = request.getParameterMap();
Map<String, String> reqParams = new HashMap<>();
Enumeration<String> names = request.getParameterNames();
while (names.hasMoreElements()) {
String name = names.nextElement();
String value = request.getParameter(name);
reqParams.put(name, value);
}
Map<String, List<String>> notNullParams = notNullParems();
for(String key :notNullParams.keySet()){
// 如果这个接口有需要判断非空的参数
if(servletPath.equals(key)){
for (String notNullParam : notNullParams.get(key)) {
// 如果没有入参或者入参中不包括必传参数
if(reqParams == null || !reqParams.containsKey(notNullParam)
|| reqParams.get(notNullParam) == null || StringUtils.isBlank(reqParams.get(notNullParam))){
log.info("接口:{},的参数:【{}】不能为空", servletPath, notNullParam);
ResponseOutput.outputJson(response, ResultEnum.FAIL_PARAM);
return false;
}
}
}
}
return true;
}
/**
* 初始化非空接口和参数
* @return
*/
public static Map<String, List<String>> notNullParems(){
Map<String, List<String>> map = new HashMap<>();
// 评估维度
map.put("/api/evaluate/specList", Arrays.asList("modelId"));
// 估计
map.put("/api/evaluate/assess", Arrays.asList("modelId", "optionIds"));
// 维修--下单
map.put("/api/order/maintain/submit", Arrays.asList("evaluateId", "phone", "appintData", "temporalInterval", "adress"));
// 阿里支付
map.put("/api/pay/alipay", Arrays.asList("orderNo", "amount"));
// 验证码登录、注册接口
map.put("/api/sms/login/sms", Arrays.asList("phone", "sms"));
// 发送验证码接口
map.put("/api/sms/verifyCode", Arrays.asList("phone", "codeType"));
return map;
}
}
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
# 192.168.110.164 shop_app adm4HYservice$
druid:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://192.168.110.164:3306/shop_app?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&serverTimezone=GMT%2B8
url: jdbc:mysql://localhost:3306/est?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&serverTimezone=GMT%2B8
username: root
password: adm4HYservice$
password: root
initial-size: 10
max-active: 100
min-idle: 10
......@@ -44,27 +45,52 @@ spring:
# 总限制
max-request-size: 20MB
# redis:
# database: 0
# host: 192.168.110.165
# port: 6379
# password: adm4HYservice$ # 密码(默认为空)
# timeout: 6000ms # 连接超时时长(毫秒)
# jedis:
# pool:
# max-active: 1000 # 连接池最大连接数(使用负值表示没有限制)
# max-wait: -1ms # 连接池最大阻塞等待时间(使用负值表示没有限制)
# max-idle: 10 # 连接池中的最大空闲连接
# min-idle: 5 # 连接池中的最小空闲连
#redis
redis:
database: 0
host: 192.168.110.165
host: 192.168.0.105
port: 6379
password: adm4HYservice$ # 密码(默认为空)
password: 123456
#连接0库
database: 0
timeout: 6000ms # 连接超时时长(毫秒)
jedis:
pool:
max-active: 1000 # 连接池最大连接数(使用负值表示没有限制)
max-wait: -1ms # 连接池最大阻塞等待时间(使用负值表示没有限制)
max-idle: 10 # 连接池中的最大空闲连接
min-idle: 5 # 连接池中的最小空闲连
pool:
max-active: 1000 # 连接池最大连接数(使用负值表示没有限制)
max-wait: -1ms # 连接池最大阻塞等待时间(使用负值表示没有限制)
max-idle: 10 # 连接池中的最大空闲连接
min-idle: 5 # 连接池中的最小空闲连
###上传文件配置 :该配置可根据部署的系统或开发人员自定义路径,每次部署之前需要修改location
uploadFile:
resourceHandler: /upload_flowChart/** #请求 url 中的资源映射也是保存到数据库中的父级路径
#location: D:/java/test/upload_flowChart/ #自定义上传文件服务器硬盘保存路径 ,linux服务器保存路径 /home/changfa/app/wxbjgkpt/upload_flowChart
location: /opt/images/upload_flowChart/ #自定义上传文件服务器硬盘保存路径 ,linux服务器保存路径 /home/changfa/app/wxbjgkpt/upload_flowChart/
file:
upload:
path: D:/aplus
jwt:
# 加密秘钥
secret: f4e2e52034348f86b67cde581c0f9eb5
# token有效时长,单位秒
expire: 14400
sms:
accessKeyId: LTAI4G6xmYPhjrS18Bxz5Kqu
secret: l3ZuSn2XjsFZXaB3yb8O5ASRJh3DDe
regionId: cn-hangzhou
domain: dysmsapi.aliyuncs.com
version: 2017-05-25
action: SendSms
signName: 西田森生物科技
logging:
config: classpath:logback-spring.xml
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment