- Jedis所需要的jar包 ,可通过Maven的依赖引入
Commons-pool-1.6.jar
Jedis-2.1.0.jar - 使用Windows环境下Eclipse连接虚拟机中的Redis注意事项
禁用Linux的防火墙:Linux(CentOS7)里执行命令 : systemctl stop firewalld.service
redis.conf中注释掉bind 127.0.0.1 ,然后 protect-mode no。
关闭redis
redis 线程 kill不掉
重启 redis-server redis.conf - Jedis测试连通性
public class Demo01 {
public static void main(String[] args) {
Jedis jedis = new Jedis("127.0.0.1",6379);
System.out.println("connection is OK=======>:"+jedis.ping());
}
}
- 完成一个手机验证码功能
要求:
1、输入手机号,点击发送后随机生成6位数字码,2分钟有效
2、输入验证码,点击验证,返回成功或失败
3、每个手机号每天只能输入3次
import redis.clients.jedis.Jedis;
import java.util.Random;
public class ValidationTest {
public static void main(String[] args) {
checkValidation("877630","15005076571");
}
static void getValidation(String tel) {
Jedis jedis = new Jedis("192.168.0.101", 6379);
try {
String phoneNo = tel;
jedis.select(1);
String countKey = phoneNo + ":count";
String codeKey = phoneNo + ":code";
String cnt = jedis.get(countKey);
if (cnt == null) {
jedis.setex(countKey, 60 * 60 * 24, "1");
StringBuffer code = new StringBuffer();
for (int i = 0; i < 6; i++) {
code.append(new Random().nextInt(10));
}
System.out.println("code:" + code);
jedis.setex(codeKey, 60 * 2, code.toString());
} else {
if (Integer.parseInt(cnt) < 3) {
StringBuffer code = new StringBuffer();
for (int i = 0; i < 6; i++) {
code.append(new Random().nextInt(10));
}
System.out.println("code:" + code);
jedis.setex(codeKey, 60 * 2, code.toString());
jedis.incr(countKey);
} else {
System.out.println("超出3次,禁止发送");
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (jedis != null) {
jedis.close();
}
}
}
static void checkValidation(String code, String tel) {
Jedis jedis = null;
try {
jedis = new Jedis("192.168.0.101", 6379);
jedis.select(1);
String codeKey = tel + ":code";
String validation = jedis.get(codeKey);
if (validation == null) {
System.out.println("验证码未发送或者失效");
} else {
if (validation.equals(code)) {
System.out.println("验证成功");
} else {
System.out.println("验证失败");
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (jedis != null) {
jedis.close();
}
}
}
}