目录
前提:
关闭虚拟机中的防火墙。
systemctl stop/disable firewalld.service
在redis.conf文件中注释掉bind 127.0.0.1 ,然后 protected-mode no
修改文件方法具体见:Redis——安装及使用_朂後 哋箹萣的博客-CSDN博客
切记,修改完配置文件后一定要杀死进程,然后重新启动服务。
1.在idea中创建项目。

2.引入Jedis所需要的jar包
- <dependencies>
- <dependency>
- <groupId>redis.clientsgroupId>
- <artifactId>jedisartifactId>
- <version>3.2.0version>
- dependency>
- dependencies>
3.编写测试代码,并且运行
- public class JedisDemo1 {
-
- public static void main(String[] args) {
- //创建Jedis对象
- Jedis jedis = new Jedis("192.168.10.102",6379);
-
- //测试
- String value = jedis.ping();
- System.out.println(value);
-
- }
- }

项目需求:
输入手机号,点击发送后随机生成6位数字码,2分钟有效。
输入验证码,点击验证,返回成功或失败
每个手机号每天只能输入3次
在上面项目的基础上新创建一个类:PhoneCode,并且进行编辑。
- package com.atguigu.jedis;
-
- import redis.clients.jedis.Jedis;
-
- import java.util.Random;
-
- public class PhoneCode {
-
- public static void main(String[] args) {
- //模拟验证码的发送
- verifyCode("18406586203");
-
- // getRedisCode("18406586203","444444");
- }
-
- //1.生成6位数字验证码
- public static String getCode() {
- Random random = new Random();
- String code = "";
- for(int i=0;i<6;i++) {
- int rand = random.nextInt(10);
- code += rand;
- }
- return code;
- }
-
- //2.每个手机每天只能发送三次,验证码放到redis中,设置过期时间
- public static void verifyCode(String phone) {
- //创建Jedis对象
- Jedis jedis = new Jedis("192.168.10.102",6379);
-
- //拼接key
- //手机发送次数key
- String countKey = "verifyCode" + phone + ":count";
- //验证码key
- String codeKey = "verifyCode" + phone + ":code";
-
- //每个手机每天只能发送三次
- 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();
- }
-
- //3.验证码校验
- public static void getRedisCode(String phone,String code) {
- //从redis获取验证码
- //创建Jedis对象
- Jedis jedis = new Jedis("192.168.10.102",6379);
- String codeKey = "verifyCode" + phone + ":code";
- String redisCode = jedis.get(codeKey);
- //判断
- if(redisCode != null && redisCode.equals(code)) {
- System.out.println("成功");
- }else {
- System.out.println("失败");
- }
- jedis.close();
-
- }
-
- }
当进行模拟验证码发送时,在redis中进行查看。

把redis中存储的验证码在idea中进行验证。

当输入错误的验证码时,提示失败。

当发送一个手机号发送三次验证码后,会提示相关信息。

redis中数据存储情况。
