redis6_Jedis+springBoot集成

写在前面

个人博客网址:https://jiong952.github.io/
个人github网址:https://github.com/jiong952

准备工作

导入依赖

<dependency>
  <groupId>redis.clients</groupId>
  <artifactId>jedis</artifactId>
  <version>3.2.0</version>
</dependency>

开放服务器端口

firewall-cmd --query-port=6379/tcp 【查询redis端口是否打开】

firewall-cmd --permanent --add-port=6379/tcp 【打开6379端口】

firewall-cmd --reload 【刷新 打开后一定要刷新】

在cmd中测试开放 telnet 192.168.200.130 6379

在idea中测试连通

public class Demo01 {
    public static void main(String[] args) {
        Jedis jedis = new Jedis("192.168.137.3",6379);
        String pong = jedis.ping();
        System.out.println("连接成功:"+pong);
        jedis.close();
    }
}

测试相关数据类型

Key

jedis.set("k1", "v1");
jedis.set("k2", "v2");
jedis.set("k3", "v3");
Set<String> 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"));

String

jedis.mset("str1","v1","str2","v2","str3","v3");
System.out.println(jedis.mget("str1","str2","str3"));

//可以使用setex()方法存储可以指定过期时间的 key value

jedis.setex(“activecode”,20,“hehe”);//将activecode:hehe键值对存入redis,并且20秒后自动删除该键值对

应用:网站的激活码/验证码

List 对应JAVA的linkedlist 支持重复元素

  • lpush / rpush
  • lpop / rpop
  • lrange start end : 范围获取
jedis.lpush("list", "a", "b", "c");
List<String> list = jedis.lrange("list", 0, -1);
for (String s : list) {
    System.out.println(s);
}

set 对应java的Set 不允许重复元素

sadd增

smembers:获取所有元素

srem删

jedis.sadd("orders", "order01");
jedis.sadd("orders", "order02");
jedis.sadd("orders", "order03");
jedis.sadd("orders", "order04");
Set<String> smembers = jedis.smembers("orders");
for (String order : smembers) {
System.out.println(order);
}
jedis.srem("orders", "order02");

Hash 对应Map

  • hset
  • hget
  • hgetAll

Map<String,String> map = new HashMap<String,String>();

map.put(“telphone”,“13810169999”);

map.put(“address”,“atguigu”);

map.put(“email”,“abc@163.com”);

jedis.hmset(“hash2”,map);

可以直接放一个map进去

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

Zset(sortedset) 不允许重复元素,且元素有顺序

  • zadd 增
  • zrange 取值
jedis.zadd("mysortedset",3,"亚瑟");
jedis.zadd("mysortedset",30,"后裔");
jedis.zadd("mysortedset",55,"孙悟空");
 // sortedset 获取
Set<String> mysortedset = jedis.zrange("mysortedset", 0, -1);
System.out.println(mysortedset);

手机验证码案例

需求

img

img

  1. 生成验证码 使用Ramdom类
  2. 2分钟有效 使用setex设置120秒有效时间
  3. 每天只能发3次 加多一个countKey
if(conut == null){
    //第一次
    jedis.setex(countKey,24*60*60,"1");
}else if(Integer.parseInt(conut) <= 2){
    jedis.incr(countKey);
}else {
    System.out.println("今天发送次数已经达到3次");
    jedis.close();
    return;
}
public class VerifyCode {
    public static void main(String[] args) {
        sendCode("15014318979");
//        judgeCode("15014318979","130439");
//        System.out.println(getCode());
    }

    //发送验证码
    public static void sendCode(String phone){
        Jedis jedis = new Jedis("192.168.200.130",6379);
        String countKey = "VerifyCode"+phone+":count";
        String codeKey = "VerifyCode"+phone+":code";
        String conut = jedis.get(countKey);
        if(conut == null){
            //第一次
            jedis.setex(countKey,24*60*60,"1");
        }else if(Integer.parseInt(conut) <= 2){
            jedis.incr(countKey);
        }else {
            System.out.println("今天发送次数已经达到3次");
            jedis.close();
            return;
        }
        String code = getCode();
        jedis.setex(codeKey,120,code);
        jedis.close();
    }
    //判断验证码正确
    public static void judgeCode(String phone,String code){
        Jedis jedis = new Jedis("192.168.200.130",6379);
        String codeKey = "VerifyCode"+phone+":code";
        String rightCode = jedis.get(codeKey);
        if(code.equals(rightCode)){
            System.out.println("成功");
        }else {
            System.out.println("失败");
        }
        jedis.close();
    }
    //生成6位验证码
    public static String getCode(){
        Random random = new Random();
        StringBuilder code = new StringBuilder();
        for (int i = 0; i < 6; i++) {
            int nextInt = random.nextInt(10);
            code.append(nextInt);
        }
        return  code.toString();
    }
}

缺点:这个设置的是从发送开始数24h,而不是一天

实际可能是

String countKey = “VerifyCode”+phone+Date+“:count”;

String codeKey = “VerifyCode”+phone+Date+“:code”;

jedis连接池: JedisPool 【后面使用集成的template】

//创建JedisPool连接池对象
//调用方法 getResource()方法获取Jedis连接
//0.创建一个配置对象
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxTotal(50);
config.setMaxIdle(10);

//1.创建Jedis连接池对象
JedisPool jedisPool = new JedisPool(config,"192.168.200.130",6379);

//2.获取连接
Jedis jedis = jedisPool.getResource();
//3. 使用
jedis.set("hehe","heihei");
//4. 关闭 归还到连接池中
jedis.close();

连接池工具类

package com.utils;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class JedisPoolUtils {
    private static JedisPool jedisPool;
    static {
        //读取配置文件
        InputStream is = JedisPoolUtils.class.getClassLoader().getResourceAsStream("jedis.properties");
        Properties pro = new Properties();
        try {
            pro.load(is);
        } catch (IOException e) {
            e.printStackTrace();
        }
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxTotal(Integer.parseInt(pro.getProperty("maxTotal")));
        config.setMaxIdle(Integer.parseInt(pro.getProperty("maxIdle")));
        //初始化JedisPool
        jedisPool = new JedisPool(config,pro.getProperty("host"),Integer.parseInt(pro.getProperty("port")));
    }
    public static Jedis getJedis(){
        return jedisPool.getResource();
    }
}

jedis.properties

host=192.168.200.130
port=6379
maxTotal=50
maxIdle=10

springBoot集成redis

导入依赖

<!-- redis -->
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

<!-- spring2.X集成redis所需common-pool2-->
<dependency>
  <groupId>org.apache.commons</groupId>
  <artifactId>commons-pool2</artifactId>
</dependency>

配置redis配置

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

添加redis配置类

@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;
    }
}

测试

@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;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Jiong-952

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值