目录
引入依赖:
- <dependency>
- <groupId>redis.clientsgroupId>
- <artifactId>jedisartifactId>
- <version>3.2.0version>
- dependency>

- import redis.clients.jedis.Jedis;
- public class Demo01 {
- public static void main(String[] args) {
- //创建redis对象
- Jedis jedis = new Jedis("192.168.137.3",6379);
- //ping()方法,如果连接成功则会返回一个值,否则报错
- String pong = jedis.ping();
- System.out.println("连接成功:"+pong);
- jedis.close();
- }
- }
禁用Linux的防火墙:Linux(CentOS7)里执行命令(关闭防火墙之后,一定要重启)
systemctl stop/disable firewalld.service
redis.conf中注释掉bind 127.0.0.1 ,然后 protected-mode no
如果之前设置过密码的话,要在创建对象后设置auth
jedis.auth("你的密码");一定要放在,Jedis jedis = new Jedis("");下面
- @Test
- public void demo1(){
- //创建redis对象
- Jedis jedis = new Jedis("192.168.137.3",6379);
- //添加key
- jedis.set("k1", "v1");
- jedis.set("k2", "v2");
- jedis.set("k3", "v3");
- //参数为“*”表示得到所有的key,返回一个Set集合
- Set
keys = jedis.keys("*"); - System.out.println(keys.size());
- for (String key : keys) {
- System.out.println(key);
- }
- System.out.println(jedis.exists("k1"));
- System.out.println(jedis.ttl("k1"));
- System.out.println(jedis.get("k1"));
- }
- //设置多个key-value
- jedis.mset("str1","v1","str2","v2","str3","v3");
- List
mget = jedis.mget("str1","str2","str3"); - System.out.println(mget);//输出相应的value
- jedis.lpush("mylist","lucy","mary","jack");
- List
list = jedis.lrange("mylist",0,-1);//把所有值都取出来 - for (String element : list) {
- System.out.println(element);
- }
- //注意key的名字不要和之前冲突
- jedis.sadd("orders", "order01");
- jedis.sadd("orders", "order02");
- jedis.sadd("orders", "order03");
- jedis.sadd("orders", "order04");
- Set
smembers = jedis.smembers("orders"); - for (String order : smembers) {
- System.out.println(order);
- }
- jedis.srem("orders", "order02");

- jedis.hset("hash1","userName","lisi");
- System.out.println(jedis.hget("hash1","userName"));
-
- Map
map = new HashMap(); - map.put("telphone","13810169999");
- map.put("address","atguigu");
- map.put("email","abc@163.com");
-
- jedis.hmset("hash2",map);
- List
result = jedis.hmget("hash2", "telphone","email"); - for (String element : result) {
- System.out.println(element);
- }

- jedis.zadd("zset01", 100d, "z3");
- jedis.zadd("zset01", 90d, "l4");
- jedis.zadd("zset01", 80d, "w5");
- jedis.zadd("zset01", 70d, "z6");
-
- Set
zrange = jedis.zrange("zset01", 0, -1); - for (String e : zrange) {
- System.out.println(e);
- }
要求:
1、输入手机号,点击发送后随机生成6位数字码,2分钟有效
随机生成6位数字码:Random
2分钟有效:把验证码放到redis里面,设置过期时间120秒
2、输入验证码,点击验证,返回成功或失败
验证:从redis获取验证码和输入的验证码进行比较
3、每个手机号每天只能输入3次
incr(每次发送之后+1)大于2时候,提交不能发送
- package com.zqf.jedis_redsidemo;
-
- import redis.clients.jedis.Jedis;
-
- import java.util.Random;
-
- public class PhoneCode {
- public static void main(String[] args) {
- //模拟验证码
- verifyCode("12345678974");
-
- // getRedisCode("12345678974","983534");
- }
-
- //1.生成6位数验证码
- public static String getCode(){
- Random random = new Random();
- String code = "";
- for (int i=0;i<6;i++){
- int i1 = random.nextInt(10);
- code += i1;
- }
- return code;
- }
-
-
- //2.每个手机每天只能发送三次,验证码放到redis中,设置过期时间
- public static void verifyCode(String phone){
- //连接redis
- Jedis jedis = new Jedis("192.168.2.129",6379);
- //拼接key
- //手机发送次数key
- String countKey = "VerifyCode"+phone+":count";
- //验证码key
- String codeKey = "VerifyCode"+phone+":code" ;
-
- //每个手机每天只能发送三次
- String count = jedis.get(countKey); //从redis中取出发送次数
- if (count == null){
- //没有发送次数 第一次发送
- //设置发送次数是1
- jedis.setex(countKey,24*60*60,"1"); //key,过期时间,value
- }else if (Integer.parseInt(count)<=2){
- //发送次数+1
- jedis.incr(countKey);
- }else if(Integer.parseInt(count)>2){
- System.out.println("24h内发送次数已经超过三次");
- jedis.close();
- return; //三次之后return 以下代码将不执行
- }
-
- //发送验证码到redis
- 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.2.129",6379);
- //验证码key
- String codeKey = "VerifyCode"+phone+":code" ;
- String redisCode = jedis.get(codeKey);
- //判断
- if (code.equals(redisCode)){
- System.out.println("成功");
- }else {
- System.out.println("失败");
- }
-
- }
-
-
- }

- <dependency>
- <groupId>org.springframework.bootgroupId>
- <artifactId>spring-boot-starter-data-redisartifactId>
- dependency>
-
- <dependency>
- <groupId>org.apache.commonsgroupId>
- <artifactId>commons-pool2artifactId>
- <version>2.6.0version>
- dependency>
- #Redis服务器地址
- spring.redis.host=192.168.xxx.xxx
- #Redis服务器连接端口
- spring.redis.port=6379
- #Redis数据库索引(默认为0)
- spring.redis.database= 0
- #连接超时时间(毫秒)
- spring.redis.timeout=1800000
- #连接池最大连接数(使用负值表示没有限制)
- spring.redis.lettuce.pool.max-active=20
- #最大阻塞等待时间(负数表示没限制)
- spring.redis.lettuce.pool.max-wait=-1
- #连接池中的最大空闲连接
- spring.redis.lettuce.pool.max-idle=5
- #连接池中的最小空闲连接
- spring.redis.lettuce.pool.min-idle=0
- package com.zqf.jedis_redsidemo.config;
-
- import com.fasterxml.jackson.annotation.JsonAutoDetect;
- import com.fasterxml.jackson.annotation.PropertyAccessor;
- import com.fasterxml.jackson.databind.ObjectMapper;
- import org.springframework.cache.CacheManager;
- import org.springframework.cache.annotation.CachingConfigurerSupport;
- import org.springframework.cache.annotation.EnableCaching;
- import org.springframework.context.annotation.Bean;
- import org.springframework.context.annotation.Configuration;
- import org.springframework.data.redis.cache.RedisCacheConfiguration;
- import org.springframework.data.redis.cache.RedisCacheManager;
- import org.springframework.data.redis.connection.RedisConnectionFactory;
- import org.springframework.data.redis.core.RedisTemplate;
- import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
- import org.springframework.data.redis.serializer.RedisSerializationContext;
- import org.springframework.data.redis.serializer.RedisSerializer;
- import org.springframework.data.redis.serializer.StringRedisSerializer;
-
- import java.time.Duration;
-
- @EnableCaching
- @Configuration
- public class RedisConfig extends CachingConfigurerSupport {
-
- @Bean
- public RedisTemplate
redisTemplate(RedisConnectionFactory factory) { - RedisTemplate
template = new RedisTemplate<>(); - RedisSerializer
redisSerializer = new StringRedisSerializer(); - Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
- ObjectMapper om = new ObjectMapper();//Objectmapper是jackson的依赖,目的把对象写成json格式
- om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
- om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
- jackson2JsonRedisSerializer.setObjectMapper(om);
- template.setConnectionFactory(factory);
- //key序列化方式
- template.setKeySerializer(redisSerializer);
- //value序列化
- template.setValueSerializer(jackson2JsonRedisSerializer);
- //value hashmap序列化
- template.setHashValueSerializer(jackson2JsonRedisSerializer);
- return template;
- }
-
- @Bean
- public CacheManager cacheManager(RedisConnectionFactory factory) {
- RedisSerializer
redisSerializer = new StringRedisSerializer(); - Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
- //解决查询缓存转换异常的问题
- ObjectMapper om = new ObjectMapper();
- om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
- om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
- jackson2JsonRedisSerializer.setObjectMapper(om);
- // 配置序列化(解决乱码的问题),过期时间600秒
- RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
- .entryTtl(Duration.ofSeconds(600))
- .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
- .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))
- .disableCachingNullValues();
- RedisCacheManager cacheManager = RedisCacheManager.builder(factory)
- .cacheDefaults(config)
- .build();
- return cacheManager;
- }
- }
- package com.zqf.jedis_redsidemo.controller;
-
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.data.redis.core.RedisTemplate;
- import org.springframework.web.bind.annotation.GetMapping;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RestController;
-
- @RestController
- @RequestMapping("/redisTest")
- public class RedisTestController {
- @Autowired
- private RedisTemplate redisTemplate;
-
- @GetMapping
- public String testRedis() {
- //设置值到redis
- redisTemplate.opsForValue().set("name","lucy");
- //从redis获取值
- String name = (String)redisTemplate.opsForValue().get("name");
- return name;
- }
- }
