Jedis

1本地安装Redis后运行

  1. 进入redis所在的根目录 ,cmd命令进入
  2. 敲入redis-server.exe redis.windows.conf
  3. redis启动程序:redis-cli.exe
    如图:
    在这里插入图片描述

2.Jedis

java客户端连接数据库的一个工具,相当于java中连接mysql数据库的JDBC

2.1Jedis使用

  1. 导入相关的依赖
   <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>3.2.0</version>
        </dependency>
  1. 连接测试
  public static void main(String[] args) {
        Jedis jedis = new Jedis("127.0.0.1", 6379);
        String value = jedis.ping();
        System.out.println(value);
    }

  1. 其他操作
 /**
     * 操作string
     */
    @Test
    public void demo1()
    {
        Jedis jedis = new Jedis("127.0.0.1", 6379);
        Set<String> keys = jedis.keys("*");
        //设置
        jedis.set("name","zhangsan");
        //获取
        String name = jedis.get("name");

        //设置多个
        jedis.mset("s1","张三","s2","李四","s3","王五");
        //获取多个
        List<String> mget = jedis.mget("s1", "s2", "s3");
        System.out.println(mget);
        System.out.println(name);

    }

    /**
     * 操作list
     */
    @Test
    public void demo2()
    {
        Jedis jedis = new Jedis("127.0.0.1", 6379);
        jedis.lpush("l","1","2","3","4");
        jedis.lpop("l");
        String l = jedis.lindex("l", 1);
        System.out.println(l);
        List<String> l1 = jedis.lrange(String.valueOf('l'), 0, -1);
        System.out.println(l1);

    }
    /**
     * 操作set
     */
    @Test
    public void demo3()
    {
        Jedis jedis = new Jedis("127.0.0.1", 6379);
        jedis.sadd("s","zhangsan");
        jedis.sadd("s","lisi");
        jedis.sadd("s","wangwu");
        Set<String> s = jedis.smembers("s");
        for(String s1:s)
        {
            System.out.println(s1);
        }
    }
    /**
     * 操作hash
     */
    @Test
    public void demo4()
    {
        Jedis jedis = new Jedis("127.0.0.1", 6379);
        jedis.hset("h","name","zhangsan");
        HashMap<String,String> hashMap=new HashMap<>();
        hashMap.put("age","18");
        hashMap.put("sex","男");
        jedis.hset("h",hashMap);
        Boolean hexists = jedis.hexists("h", "ss");
        System.out.println(hexists);
        String hget = jedis.hget("h", "name");
        System.out.println(hget);
        Map<String, String> h = jedis.hgetAll("h");
        System.out.println(h);
    }

3.Jedis实例

要求:

  1. 输入手机号,点击发送后随机生成6位数字码,2分钟内有效
  2. 输入验证码,点击验证,返回成功或失败
  3. 每个手机号每天只能输入3次
    代码实现
package com.blb.redis;

import redis.clients.jedis.Jedis;

import java.util.Random;

/**
 * @author smile
 * @date 2021/7/5 0005 17:24
 */
public class PhoneCode {
    public static void main(String[] args) {
//        verifyCode("15717841491");
        getRedisCode("15717841491","041846");

    }
    //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=new Jedis("127.0.0.1",6379);
        //拼接key
        //手机发送次数key
        String countKey=phone+"count";
        //手机验证码
        String codeKey=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
        {
            System.out.println("今天注册超过三次");
            jedis.close();
        }
        //验证码放入redis
        String code1 = getCode();
        jedis.setex(codeKey,24*60*60,code1);
        jedis.close();


    }
     //3.验证码校验
    public static void getRedisCode(String phone,String code)
    {
        Jedis jedis=new Jedis("127.0.0.1",6379);

        String codeKey=phone+"code";
        System.out.println(codeKey);
        //通过手机号得到验证码
        String redisCode = jedis.get(codeKey);
        System.out.println(redisCode);
        //进行比较
        if(code.equals(redisCode))
        {
            System.out.println("成功");
        }
        else
            System.out.println("失败");
        jedis.close();
    }

}

4.springboot整合redis

4.1导入依赖

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
        </dependency>

4.2 在application.properties配置参数

#Redis服务器地址
spring.redis.host=127.0.0.1
#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

4.3写配置类

package com.blb.springredis.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;

/**
 * @author smile
 * @date 2021/7/5 0005 21:06
 */
@EnableCaching
@Configuration
public class RedisConfig extends CachingConfigurerSupport {

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        RedisSerializer<String> 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);
        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<String> 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;
    }
}

4.4测试

package com.blb.springredis.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author smile
 * @date 2021/7/5 0005 21:09
 */
@Controller
public class RedisController {

    @Autowired
    private RedisTemplate redisTemplate;
    @RequestMapping("/one")
    @ResponseBody
    public String one()
        {
             redisTemplate.opsForValue().set("name","lisi");
            String name =(String) redisTemplate.opsForValue().get("name");
            return name;
        }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值