<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-devtoolsartifactId>
<scope>runtimescope>
<optional>trueoptional>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<optional>trueoptional>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-testartifactId>
<scope>testscope>
<exclusions>
<exclusion>
<groupId>org.junit.vintagegroupId>
<artifactId>junit-vintage-engineartifactId>
exclusion>
exclusions>
dependency>
<dependency>
<groupId>com.aliyungroupId>
<artifactId>aliyun-java-sdk-coreartifactId>
<version>4.0.6version>
dependency>
<dependency>
<groupId>com.aliyungroupId>
<artifactId>aliyun-java-sdk-dysmsapiartifactId>
<version>1.1.0version>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-data-redisartifactId>
dependency>
<dependency>
<groupId>redis.clientsgroupId>
<artifactId>jedisartifactId>
dependency>
<dependency>
<groupId>org.apache.commonsgroupId>
<artifactId>commons-pool2artifactId>
<version>2.5.0version>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>fastjsonartifactId>
<version>1.2.47version>
dependency>
# redis配置
spring:
redis:
# Redis数据库索引(默认为0)
database: 0
# Redis服务器地址
host: 127.0.0.1
# Redis服务器连接端口
port: 6379
# Redis服务器连接密码(默认为空)
password: #自己设置的密码
jedis:
pool:
# 连接池最大连接数(使用负值表示没有限制)
max-active: 20
# 连接池最大阻塞等待时间(使用负值表示没有限制)
max-wait: -1
# 连接池中的最大空闲连接
max-idle: 10
# 连接池中的最小空闲连接
min-idle: 0
# 连接超时时间(毫秒)
timeout: 1000
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
// /**
// * springboot1.x用这个来管理缓存
// * 选择redis作为默认缓存工具
// * @param redisTemplate
// * @return
// */
// @Bean
// public CacheManager cacheManager(RedisTemplate redisTemplate) {
// RedisCacheManager rcm = new RedisCacheManager(redisTemplate);
// return rcm;
// }
/**
* Logger
*/
private static final Logger lg = LoggerFactory.getLogger(RedisConfiguration.class);
@Autowired
private JedisConnectionFactory jedisConnectionFactory;
@Bean
@Override
public KeyGenerator keyGenerator() {
// 设置自动key的生成规则,配置spring boot的注解,进行方法级别的缓存
// 使用:进行分割,可以很多显示出层级关系
// 这里其实就是new了一个KeyGenerator对象,只是这是lambda表达式的写法,我感觉很好用,大家感兴趣可以去了解下
return (target, method, params) -> {
StringBuilder sb = new StringBuilder();
sb.append(target.getClass().getName());
sb.append(":");
sb.append(method.getName());
for (Object obj : params) {
sb.append(":" + String.valueOf(obj));
}
String rsToUse = String.valueOf(sb);
lg.info("自动生成Redis Key -> [{}]", rsToUse);
return rsToUse;
};
}
@Bean
@Override
public CacheManager cacheManager() {
// 初始化缓存管理器,在这里我们可以缓存的整体过期时间什么的,我这里默认没有配置
lg.info("初始化 -> [{}]", "CacheManager RedisCacheManager Start");
RedisCacheManager.RedisCacheManagerBuilder builder = RedisCacheManager
.RedisCacheManagerBuilder
.fromConnectionFactory(jedisConnectionFactory);
return builder.build();
}
@Bean
public RedisTemplate<String, Object> redisTemplate(JedisConnectionFactory jedisConnectionFactory ) {
//设置序列化
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
// 配置redisTemplate
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>();
redisTemplate.setConnectionFactory(jedisConnectionFactory);
RedisSerializer stringSerializer = new StringRedisSerializer();
redisTemplate.setKeySerializer(stringSerializer); // key序列化
redisTemplate.setValueSerializer(jackson2JsonRedisSerializer); // value序列化
redisTemplate.setHashKeySerializer(stringSerializer); // Hash key序列化
redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer); // Hash value序列化
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
@Override
@Bean
public CacheErrorHandler errorHandler() {
// 异常处理,当Redis发生异常时,打印日志,但是程序正常走
lg.info("初始化 -> [{}]", "Redis CacheErrorHandler");
CacheErrorHandler cacheErrorHandler = new CacheErrorHandler() {
@Override
public void handleCacheGetError(RuntimeException e, Cache cache, Object key) {
lg.error("Redis occur handleCacheGetError:key -> [{}]", key, e);
}
@Override
public void handleCachePutError(RuntimeException e, Cache cache, Object key, Object value) {
lg.error("Redis occur handleCachePutError:key -> [{}];value -> [{}]", key, value, e);
}
@Override
public void handleCacheEvictError(RuntimeException e, Cache cache, Object key) {
lg.error("Redis occur handleCacheEvictError:key -> [{}]", key, e);
}
@Override
public void handleCacheClearError(RuntimeException e, Cache cache) {
lg.error("Redis occur handleCacheClearError:", e);
}
};
return cacheErrorHandler;
}
/**
* 此内部类就是把yml的配置数据,进行读取,创建JedisConnectionFactory和JedisPool,以供外部类初始化缓存管理器使用
* 不了解的同学可以去看@ConfigurationProperties和@Value的作用
*
*/
@ConfigurationProperties
class DataJedisProperties{
@Value("${spring.redis.host}")
private String host;
@Value("${spring.redis.password}")
private String password;
@Value("${spring.redis.port}")
private int port;
@Value("${spring.redis.timeout}")
private int timeout;
@Value("${spring.redis.jedis.pool.max-idle}")
private int maxIdle;
@Value("${spring.redis.jedis.pool.max-wait}")
private long maxWaitMillis;
@Bean
JedisConnectionFactory jedisConnectionFactory() {
lg.info("Create JedisConnectionFactory successful");
JedisConnectionFactory factory = new JedisConnectionFactory();
factory.setHostName(host);
factory.setPort(port);
factory.setTimeout(timeout);
factory.setPassword(password);
return factory;
}
@Bean
public JedisPool redisPoolFactory() {
lg.info("JedisPool init successful,host -> [{}];port -> [{}]", host, port);
JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
jedisPoolConfig.setMaxIdle(maxIdle);
jedisPoolConfig.setMaxWaitMillis(maxWaitMillis);
JedisPool jedisPool = new JedisPool(jedisPoolConfig, host, port, timeout, password);
return jedisPool;
}
}
}
/**
* 发送短信工具类
*/
public class SendSMSUtil {
/**
* 你的accessKeyId
*/
private static final String accessKeyId="";
/**
* 你的accessKeySecret
*/
private static final String accessKeySecret="";
/**
* 签名
*/
private static final String signName="";
/**
* 短信模板
*/
private static final String templateCode="";
/**
* 验证码
*/
private static int code;
/**
* @Descirption:发送手机验证码
* @param phoneNumber:需要发送的手机号码
* @return OK表示成功,失败则返回失败消息
*/
public static String sendSmsUtil(String phoneNumber){
//设置超时时间-可自行调整
System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
System.setProperty("sun.net.client.defaultReadTimeout", "10000");
// 初始化ascClient需要的几个参数
// 短信API产品名称(短信产品名固定,无需修改)
final String product = "Dysmsapi";
// 短信API产品域名(接口地址固定,无需修改)
final String domain = "dysmsapi.aliyuncs.com";
// 初始化ascClient,暂时不支持多region(请勿修改)
IClientProfile profile= DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
try {
DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
} catch (ClientException e) {
e.printStackTrace();
}
IAcsClient acsClient=new DefaultAcsClient(profile);
// 组装请求对象
SendSmsRequest request=new SendSmsRequest();
//使用post提交
request.setMethod(MethodType.POST);
// 必填:待发送手机号。支持以逗号分隔的形式进行批量调用,批量上限为1000个手机号码,批量调用相对于单条调用及时性稍有延迟,
// 验证码类型的短信推荐使用单条调用的方式;发送国际/港澳台消息时,接收号码格式为国际区号+号码,如“85200000000”
request.setPhoneNumbers(phoneNumber);
request.setSignName(signName);
// 必填:短信模板-可在短信控制台中找到,发送国际/港澳台消息时,请使用国际/港澳台短信模版
request.setTemplateCode(templateCode);
//随机生成6位验证码
code = (int) ((Math.random() * 9 + 1) * 100000);
// 可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
// 友情提示:如果JSON中需要带换行符,请参照标准的JSON协议对换行符的要求,比如短信内容中包含\r\n的情况在JSON中需要表示成\\r\\n,否则会导致JSON在服务端解析失败
request.setTemplateParam("{code:"+code+"}");
// 请求失败这里会抛ClientException异常
SendSmsResponse sendSmsResponse = null;
try {
sendSmsResponse = acsClient.getAcsResponse(request);
} catch (ClientException e) {
e.printStackTrace();
return "请求失败";
}
assert sendSmsResponse.getCode() != null;
// 发送不成功
if (sendSmsResponse.getCode() == null || !sendSmsResponse.getCode().equals("OK")) {
return sendSmsResponse.getMessage();
}
// 请求成功
return "OK";
}
public static int getCode(){
return code;
}
}
@Controller
//跨域使用
@CrossOrigin
public class SmsController {
@Autowired
StringRedisTemplate stringRedisTemplate;
/**
* 发送手机验证码
* @param phoneNumber 手机号码
* @return 1表示成功,0表示失败
*/
@RequestMapping("/sendSms")
@ResponseBody
public String SmsTest(String phoneNumber){
//发送短信
String result = SendSMSUtil.sendSmsUtil(phoneNumber);
if (result == null || !result.equals("OK")) {// 发送不成功
return "0";
}
// 获取验证码
int code = SendSMSUtil.getCode();
Map<String,Object> map=new HashMap<>();
// 将数据存入redis
map.put(phoneNumber,code+"");
//用phoneNumber来做键,可以做到唯一性
stringRedisTemplate.opsForHash().putAll(phoneNumber,map);
// 设置redis过期时间,这个时间是秒为单位的,我现在设置5分钟之内有效,过了就会自动删除
stringRedisTemplate.expire(phoneNumber, 60*5, TimeUnit.SECONDS);
return "OK";
}
/**
* 校验验证码
* @param phoneNumber
* @param checkSMSCode
* @return
*/
@RequestMapping(value = "/checkSMSCode", method = RequestMethod.POST)
@ResponseBody
public String checkSMSCode(String phoneNumber,String checkSMSCode) {
// 服务器放入的验证码
//从redis中取出以电话号码为key,验证码为value的值
Map<Object, Object> map=stringRedisTemplate.opsForHash().entries(phoneNumber);
String serverCheckCode =(String) map.get(phoneNumber);
if (serverCheckCode == null || serverCheckCode.equals("")) {
return "CodeError";
}
// 验证码不匹配
if (!checkSMSCode.equals(serverCheckCode)) {
return "CodeError";
}else {
//如果验证成功就删除验证码
stringRedisTemplate.opsForHash().delete(phoneNumber,phoneNumber);
}
return "OK";
}
}
这里还有点瑕疵,前端点击发送之后,要有倒计时,并且后端要有时间限制,比如1分钟之内不可以重复发送验证码,这都是小问题,大家可以自己去写一个判断
本文转载自:https://mp.weixin.qq.com/s/faDOoXnciWFQW-uo2MMp2A