连接前注意事项:
redis采用的安全策略,默认会只准许本地访问。
修改redis.conf配置文件
将 bind 127.0.0.1 - :: 1 注释掉
将 protected-mode 设置为 no
配置云服务器安全组,打开6379 端口,重启服务器
开启防火墙的放行端口 6379
这里使用宝塔linux面板

重启redis
测试连接
配置依赖
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>4.2.3</version>
</dependency>
创建测试程序
public class JedisDemo1 {
public static void main(String[] args) {
//创建Jedis对象
Jedis jedis = new Jedis("47.94.94.137",6379);
//测试
System.out.println(jedis.ping());
}
}
//PONG 成功
用时查阅即可
要求:
1、输入手机号,点击发送后随机生成6位数字码,2分钟有效
2、输入验证码,点击验证,返回成功或失败
3、每个手机号每天只能输入3次
package pub.zgq.jedis;
import redis.clients.jedis.Jedis;
import java.util.Random;
/**
* @Author 孑然
*/
public class PhoneCode {
public static void main(String[] args) {
//模拟验证码发送
verifyCode("12345678910");
//校验验证码
//getVerityCode("12345678910","629114");
}
/**
* 验证码校验
* @param inputPhone
*/
public static void getVerityCode(String inputPhone, String code){
Jedis jedis = new Jedis("47.94.94.137",6379);
//验证码key
String codeKey = "VerityCode" + inputPhone + ":code";
//从redis中获取验证码
String redisCode = jedis.get(codeKey);
//判断
if (code.equals(redisCode)){
System.out.println("验证码成功");
}else {
System.out.println("验证码不正确");
}
jedis.close();
}
/**
* 每个手机每天只能发送三次,验证码放到redis中,设置过期时间
* @param phone 手机号
*/
public static void verifyCode(String phone){
//连接redis
Jedis jedis = new Jedis("47.94.94.137",6379);
//拼接key
//手机发送次数key
String countKey = "VerityCode" + phone + ":count";
//验证码key
String codeKey = "VerityCode" + phone + ":code";
//先判断是否发送过验证码(24小时内)
String count = jedis.get(countKey);
if (count == null){
//未发送过
//添加发送次数为1
jedis.setex(countKey, 24*60*60, "1");
}else if (Integer.parseInt(count) <= 2 ){
//发送次数+1
jedis.incr(countKey);
}else if (Integer.parseInt(count) > 2){
System.out.println("今日发送次数已达上限!");
jedis.close();
return;
}
//发送验证码到redis里
String vcode = getCode();
jedis.setex(codeKey, 120, vcode);
jedis.close();
}
/**
* 生成6位的数字验证码
* @return
*/
public static String getCode(){
Random random = new Random();
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < 6; i++) {
stringBuilder.append(random.nextInt(10));
}
return stringBuilder.toString();
}
}