2 、五大数据类型代码实例
package com.guor.redis;
import redis.clients.jedis.Jedis;
import java.util.List;
import java.util.Set;
public class JedisTest01 {
public static void main(String[] args) {
test05();
}
private static void test01(){
Jedis jedis = new Jedis("192.168.194.131", 6379);
String value = jedis.ping();
System.out.println(value);
// 添加
jedis.set("name","GooReey");
// 获取
String name = jedis.get("name");
System.out.println(name);
jedis.set("age","30");
jedis.set("city","dalian");
// 获取全部的 key
Set
for(String key : keys){
System.out.println(key+" --> "+jedis.get(key));
}
// 加入多个 key 和 value
jedis.mset("name1","zs","name2","ls","name3","ww");
List
System.out.println(mget);//[zs, ls]
}
//list
private static void test02(){
Jedis jedis = new Jedis("192.168.194.131", 6379);
jedis.lpush("key1","01","02","03");
List
System.out.println(values);//[03, 02, 01]
}
//set
private static void test03(){
Jedis jedis = new Jedis("192.168.194.131", 6379);
jedis.sadd("username","zs","ls","ww");
Set
System.out.println(names);//[ww, zs, ls]
}
//hash
private static void test04(){
Jedis jedis = new Jedis("192.168.194.131", 6379);
jedis.hset("users","age", "20");
String hget = jedis.hget("users","age");
System.out.println(hget);
}
//zset
private static void test05(){
Jedis jedis = new Jedis("192.168.194.131", 6379);
jedis.zadd("china",100d,"shanghai");
Set
System.out.println(names);//[shanghai]
}
}
3 、手机验证码功能代码实例
package com.guor.redis;
import redis.clients.jedis.Jedis;
import java.util.Random;
public class PhoneCode {
public static void main(String[] args) {
verifyCode("10086");//795258
getRedisCode("10086","795258");//success.
}
//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;//849130
}
//2 、每个手机每天只能发送三次,外汇跟单gendan5.com验证码放到 redis 中,设置过期时间
public static void verifyCode(String phone){
Jedis jedis = new Jedis("192.168.194.131", 6379);
// 拼接 key
// 手机发送次数 key
String countKey = "VerifyCode" + phone + ":count";
// 验证码 key
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){
// 发送次数 +1
jedis.incr(countKey);
}else if(Integer.parseInt(count)>2){
System.out.println(" 今天的发送次数已经超过三次 ");
jedis.close();
}
String vCode = getCode();
jedis.setex(codeKey,120,vCode);
jedis.close();
}
//3 、验证码校验
public static void getRedisCode(String phone, String code){
// 从 redis 中获取验证码
Jedis jedis = new Jedis("192.168.194.131", 6379);
// 验证码 key
String codeKey = "VerifyCode" + phone + ":code";
String redisCode = jedis.get(codeKey);
if(redisCode.equals(code)){
System.out.println("success.");
}else{
System.out.println("error");
}
jedis.close();
}
}