Jedis 2.1.0 API文档:
https://tool.oschina.net/apidocs/apidoc?api=jedis-2.1.0
Jedis 常用API整理:
https://blog.csdn.net/fanbaodan/article/details/89047909
Redis类似JDBC, Java操作Redis
在maven配置文件中添加依赖即可使用Jedis
1 2 3 4 5 6 7
| <dependencies> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>3.2.0</version> </dependency> </dependencies>
|
Jedis对象中两个参数, 第一个虚拟机ip地址, 第二个端口号.
如果连接失败:
- 请看第二篇redis配置文件, 需要的修改是否修改了.
- 虚拟机防火墙是否关闭了,
systemctl stop firewalld
简单示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
| package com.wakabaka;
import redis.clients.jedis.Jedis;
import java.util.List; import java.util.Set;
public class jedisDemo1 {
public static void main(String[] args) { Jedis jedis = new Jedis("192.168.31.65", 6379);
String value = jedis.ping(); System.out.println(value);
jedis.close(); demol(); }
public static void demol() { Jedis jedis = new Jedis("192.168.31.65", 6379);
jedis.set("name", "zhangsan");
String name = jedis.get("name"); System.out.println(name);
jedis.mset("k1", "v1", "k2", "v2"); List<String> mget = jedis.mget("k1", "k2"); System.out.println(mget);
jedis.close();
}
}
|
前面详细整理过的命令在Jedis都有其对应的方法.
实例:
- 输入手机号, 点击发送后生成6位数字, 2分钟有效
- 输入验证码 , 点击验证, 返回成功或失败
- 每个手机号每天只能输入三次
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
| package com.wakabaka;
import redis.clients.jedis.Jedis;
import java.util.List; import java.util.Random; import java.util.Set;
public class jedisDemo1 {
public static void main(String[] args) {
verifyCode("12362171139");
}
public static void getRedisCode(String phone, String code) { Jedis jedis = new Jedis("192.168.31.65", 6379);
String codeKey = "VerifyCode" + phone + ":code"; String redisCode = jedis.get(codeKey); if(redisCode.equals(code)) { System.out.println("成功!"); } else { System.out.println("失败!"); } jedis.close(); }
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; }
public static void verifyCode(String phone) { Jedis jedis = new Jedis("192.168.31.65", 6379);
String countKey = "VerifyCode" + phone + ":count";
String codeKey = "VerifyCode" + phone + ":code";
String count = jedis.get(countKey); if(count == null) { jedis.setex(countKey, 24*60*60, "1"); } else if(Integer.parseInt(count) <= 2) { jedis.incr(countKey); } else if(Integer.parseInt(count) > 2) { System.out.println("发送次数已达上线"); jedis.close(); }
String vcode = getCode(); jedis.setex(codeKey, 120, vcode); jedis.close(); } }
|