Redis学习三之Jedis的简单使用和SpringBoot整合Redis

jedis使用

1、导入依赖

	<dependencies>
        <!-- https://mvnrepository.com/artifact/redis.clients/jedis -->
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>3.3.0</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.62</version>
        </dependency>
    </dependencies>
package com.zzf;

import redis.clients.jedis.Jedis;

import java.util.Set;

/*
 *
 *@author:zzf
 *@time:2021-02-05
 *
 */
public class TestPing {
    
    
    public static void main(String[] args) {
    
    
        //1、new Jedis对象
        Jedis jedis = new Jedis("127.0.0.1", 6379);
        System.out.println(jedis.ping());

        System.out.println("清空数据:"+jedis.flushDB());
        System.out.println("判断某个键是否存在:"+jedis.exists("username"));
        System.out.println("新增<'username','zzf'>的键值对:"+jedis.set("username","zzf"));
        System.out.println("新增<'password','password'>的键值对:"+jedis.set("password","password"));
        System.out.println("查看系统中所有的键:");
        Set<String> keys = jedis.keys("*");
        System.out.println(keys);

        System.out.println("删除键password:"+jedis.del("password"));
        System.out.println("判断键password是否存在:"+jedis.exists("password"));
        System.out.println("查看键username所存储的值的类型:"+jedis.type("username"));
        System.out.println("随即返回key空间的一个:"+jedis.randomKey());
        System.out.println("重命名key:"+jedis.rename("username","name"));
        System.out.println("取出改后的name:"+jedis.get("name"));
        System.out.println("按索引查询:"+jedis.select(0));
        System.out.println("删除当前选择数据库中的所有key:"+jedis.flushDB());
        System.out.println("返回当前数据库中key的数目:"+jedis.dbSize());
        System.out.println("删除所有数据库中的所有key:"+jedis.flushAll());
    }
}

SpringBoot整合redis

直接用redisTemplate

package com.zzf;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;

@SpringBootTest
class RedisSpringbootApplicationTests {
    
    

    @Autowired
    private RedisTemplate redisTemplate;

    @Test
    void contextLoads() {
    
    
        redisTemplate.opsForValue().set("mykey","第一个值");
        System.out.println(redisTemplate.opsForValue().get("mykey"));
    }

}

但这样在redis数据库中查询会出现前缀乱码
在这里插入图片描述
解决方式

添加redisConfig类,而且配置自己的序列化方式,相当于自定义redisTemplate,其实SpringBoot本身是自动帮我们在容器中生成了一个RedisTemplate和一个StringRedisTemplate。但是,这个RedisTemplate的泛型是<Object,Object>,写代码不方便,需要写好多类型转换的代码;我们需要一个泛型为<String,Object>形式的RedisTemplate。并且,这个RedisTemplate没有设置数据存在Redis时,key及value的序列化方式,所以key会有前缀乱码

package com.zzf.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisConfig {
    
    
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
    
    
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);

        //这里也可用enableDefaultTyping,但它在新版SpringBoot已过期
        //objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        objectMapper.activateDefaultTyping(
                LaissezFaireSubTypeValidator.instance,
                ObjectMapper.DefaultTyping.NON_FINAL,
                JsonTypeInfo.As.WRAPPER_ARRAY);
        jackson2JsonRedisSerializer.setObjectMapper(objectMapper);

        //key采用String的序列化方式
        template.setKeySerializer(new StringRedisSerializer());
        //hash的key也采用string的序列化方式
        template.setHashKeySerializer(new StringRedisSerializer());
        //value的序列化方式采用jackson
        template.setValueSerializer(jackson2JsonRedisSerializer);
        //hash的value序列化方式采用jackson
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        template.afterPropertiesSet();

        return template;
    }
}

实际开发,还会编写一个RedisUtil类来简化操作

package com.zzf.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;


import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Component
public class RedisUtil {
    
    
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 指定缓存失效时间
     *
     * @param key
     * @param time
     * @return
     */
    public boolean expire(String key, long time) {
    
    
        try {
    
    
            if (time > 0) {
    
    
                redisTemplate.expire(key, time, TimeUnit.SECONDS);
            }
            return true;
        } catch (Exception e) {
    
    
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 根据key获取过期时间
     *
     * @param key
     * @return
     */
    public long getExpire(String key) {
    
    
        return redisTemplate.getExpire(key, TimeUnit.SECONDS);
    }

    /**
     * 判断key是否存在
     *
     * @param key
     * @return
     */
    public boolean hasKey(String key) {
    
    
        try {
    
    
            return redisTemplate.hasKey(key);
        } catch (Exception e) {
    
    
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 删除缓存
     *
     * @param key
     */
    @SuppressWarnings("unchecked")
    public void del(String... key) {
    
    
        if (key != null && key.length > 0) {
    
    
            if (key.length == 1) {
    
    
                redisTemplate.delete(key[0]);
            } else {
    
    
                redisTemplate.delete(CollectionUtils.arrayToList(key));
            }
        }
    }

    //====================String=========================

    /**
     * 普通缓存获取
     *
     * @param key
     * @return
     */
    public Object get(String key) {
    
    
        return key == null ? null : redisTemplate.opsForValue().get(key);
    }

    /**
     * 普通缓存放入
     *
     * @param key
     * @param value
     * @return
     */
    public boolean set(String key, Object value) {
    
    
        try {
    
    
            redisTemplate.opsForValue().set(key, value);
            return true;
        } catch (Exception e) {
    
    
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 普通缓存放入并设置时间
     *
     * @param key
     * @param value
     * @param time
     * @return
     */
    public boolean set(String key, Object value, long time) {
    
    
        try {
    
    
            if (time > 0) {
    
    
                redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
            } else {
    
    
                set(key, value);
            }
            return true;
        } catch (Exception e) {
    
    
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 递增
     *
     * @param key
     * @param delta
     * @return
     */
    public long incr(String key, long delta) {
    
    
        if (delta < 0) {
    
    
            throw new RuntimeException("递增参数必须大于0");
        }
        return redisTemplate.opsForValue().increment(key, delta);
    }

    /**
     * 递减
     *
     * @param key
     * @param delta
     * @return
     */
    public long decr(String key, long delta) {
    
    
        if (delta < 0) {
    
    
            throw new RuntimeException("递减参数必须大于0");
        }
        return redisTemplate.opsForValue().increment(key, -delta);
    }

    //==================Map==========================

    /**
     * HashGet
     *
     * @param key
     * @param item
     * @return
     */
    public Object hget(String key, String item) {
    
    
        return redisTemplate.opsForHash().get(key, item);
    }

    /**
     * 获取hashKey对应的所有键值
     *
     * @param key
     * @return
     */
    public Map<Object, Object> hmget(String key) {
    
    
        return redisTemplate.opsForHash().entries(key);
    }

    /**
     * HashSet
     *
     * @param key
     * @param map
     * @return
     */
    public boolean hmset(String key, Map<String, Object> map) {
    
    
        try {
    
    
            redisTemplate.opsForHash().putAll(key, map);
            return true;
        } catch (Exception e) {
    
    
            e.printStackTrace();
            return false;
        }
    }

    /**
     * HashSet并设置时间
     *
     * @param key
     * @param map
     * @param time
     * @return
     */
    public boolean hmset(String key, Map<String, Object> map, long time) {
    
    
        try {
    
    

            redisTemplate.opsForHash().putAll(key, map);

            if (time > 0) {
    
    

                expire(key, time);

            }

            return true;

        } catch (Exception e) {
    
    

            e.printStackTrace();

            return false;

        }
    }


    /**
     * 向一张hash表里放入数据,如果不存在将创建
     *
     * @param key
     * @param item
     * @param value
     * @return
     */
    public boolean hset(String key, String item, Object value) {
    
    
        try {
    
    

            redisTemplate.opsForHash().put(key, item, value);

            return true;

        } catch (Exception e) {
    
    

            e.printStackTrace();

            return false;

        }
    }

    /**
     * 向一张hash表中放入数据并设置时间,如果不存在将创建
     *
     * @param key
     * @param item
     * @param value
     * @param time
     * @return
     */
    public boolean hset(String key, String item, Object value, long time) {
    
    

        try {
    
    

            redisTemplate.opsForHash().put(key, item, value);

            if (time > 0) {
    
    

                expire(key, time);

            }

            return true;

        } catch (Exception e) {
    
    

            e.printStackTrace();

            return false;

        }

    }

    /**
     * 删除hash表中的值
     *
     * @param key
     * @param item
     */
    public void hdel(String key, Object... item) {
    
    

        redisTemplate.opsForHash().delete(key, item);

    }

    /**
     * 判断hash表中是否有该项的值
     *
     * @param key
     * @param item
     * @return
     */
    public boolean hHasKey(String key, String item) {
    
    

        return redisTemplate.opsForHash().hasKey(key, item);

    }

    /**
     * hash递增,如果不存在,就会创建一个,并把新增后的值返回
     *
     * @param key
     * @param item
     * @param by
     * @return
     */
    public double hincr(String key, String item, double by) {
    
    

        return redisTemplate.opsForHash().increment(key, item, by);

    }

    /**
     * hash递减
     *
     * @param key
     * @param item
     * @param by
     * @return
     */
    public double hdecr(String key, String item, double by) {
    
    

        return redisTemplate.opsForHash().increment(key, item, -by);

    }

    //===============set=============

    /**
     * 根据key获取Set中的所有值
     *
     * @param key
     * @return
     */
    public Set<Object> sGet(String key) {
    
    
        try {
    
    
            return redisTemplate.opsForSet().members(key);
        } catch (Exception e) {
    
    
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 根据value从一个set中查询,是否存在
     *
     * @param key
     * @param value
     * @return
     */
    public boolean sHasKey(String key, Object value) {
    
    

        try {
    
    

            return redisTemplate.opsForSet().isMember(key, value);

        } catch (Exception e) {
    
    

            e.printStackTrace();

            return false;

        }

    }

    /**
     * 将数据放入set缓存
     *
     * @param key
     * @param values
     * @return
     */
    public long sSet(String key, Object... values) {
    
    

        try {
    
    

            return redisTemplate.opsForSet().add(key, values);

        } catch (Exception e) {
    
    

            e.printStackTrace();

            return 0;

        }

    }

    /**
     * 将数据放入set缓存并设置时间
     *
     * @param key
     * @param time
     * @param values
     * @return
     */
    public long sSetAndTime(String key, long time, Object... values) {
    
    

        try {
    
    

            Long count = redisTemplate.opsForSet().add(key, values);

            if (time > 0)

                expire(key, time);

            return count;

        } catch (Exception e) {
    
    

            e.printStackTrace();

            return 0;

        }

    }

    /**
     * 获取set缓存的长度
     *
     * @param key
     * @return
     */
    public long sGetSetSize(String key) {
    
    

        try {
    
    

            return redisTemplate.opsForSet().size(key);

        } catch (Exception e) {
    
    

            e.printStackTrace();

            return 0;

        }

    }

    /**
     * 移除值为value的数据
     *
     * @param key
     * @param values
     * @return
     */
    public long setRemove(String key, Object... values) {
    
    

        try {
    
    

            Long count = redisTemplate.opsForSet().remove(key, values);

            return count;

        } catch (Exception e) {
    
    

            e.printStackTrace();

            return 0;

        }

    }

    //=================list===============

    /**
     * 获取list缓存的内容
     *
     * @param key
     * @param start
     * @param end
     * @return
     */
    public List<Object> lGet(String key, long start, long end) {
    
    
        try {
    
    
            return redisTemplate.opsForList().range(key, start, end);
        } catch (Exception e) {
    
    
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获取list缓存的长度
     *
     * @param key
     * @return
     */
    public long lGetListSize(String key) {
    
    

        try {
    
    

            return redisTemplate.opsForList().size(key);

        } catch (Exception e) {
    
    

            e.printStackTrace();

            return 0;

        }

    }

    /**
     * 通过下标索引获取list中的值
     *
     * @param key
     * @param index
     * @return
     */
    public Object lGetIndex(String key, long index) {
    
    

        try {
    
    

            return redisTemplate.opsForList().index(key, index);

        } catch (Exception e) {
    
    

            e.printStackTrace();

            return null;

        }

    }

    /**
     * 将list放入缓存
     *
     * @param key
     * @param value
     * @return
     */
    public boolean lSet(String key, Object value) {
    
    

        try {
    
    

            redisTemplate.opsForList().rightPush(key, value);

            return true;

        } catch (Exception e) {
    
    

            e.printStackTrace();

            return false;

        }

    }

    /**
     * 将list放入缓存并设置时间
     *
     * @param key
     * @param value
     * @param time
     * @return
     */
    public boolean lSet(String key, Object value, long time) {
    
    

        try {
    
    

            redisTemplate.opsForList().rightPush(key, value);

            if (time > 0)

                expire(key, time);

            return true;

        } catch (Exception e) {
    
    

            e.printStackTrace();

            return false;

        }

    }

    /**
     * 将list放入缓存(多个值)
     *
     * @param key
     * @param value
     * @return
     */
    public boolean lSet(String key, List<Object> value) {
    
    

        try {
    
    

            redisTemplate.opsForList().rightPushAll(key, value);

            return true;

        } catch (Exception e) {
    
    

            e.printStackTrace();

            return false;

        }

    }

    /**
     * 将list放入缓存(多个值)并设置时间
     *
     * @param key
     * @param value
     * @param time
     * @return
     */
    public boolean lSet(String key, List<Object> value, long time) {
    
    

        try {
    
    

            redisTemplate.opsForList().rightPushAll(key, value);

            if (time > 0)

                expire(key, time);

            return true;

        } catch (Exception e) {
    
    

            e.printStackTrace();

            return false;

        }

    }

    /**
     * 根据索引修改list中的某条数据
     *
     * @param key
     * @param index
     * @param value
     * @return
     */
    public boolean lUpdateIndex(String key, long index, Object value) {
    
    

        try {
    
    

            redisTemplate.opsForList().set(key, index, value);

            return true;

        } catch (Exception e) {
    
    

            e.printStackTrace();

            return false;

        }

    }

    /**
     * 移除N个值为value的数据
     *
     * @param key
     * @param count
     * @param value
     * @return
     */
    public long lRemove(String key, long count, Object value) {
    
    

        try {
    
    

            Long remove = redisTemplate.opsForList().remove(key, count, value);

            return remove;

        } catch (Exception e) {
    
    

            e.printStackTrace();

            return 0;

        }

    }
}

测试

@Autowired
    private RedisUtil redisUtil;

    @Test
    void testRedisUtil() {
    
    
        User user = new User("赵志峰", 19);
        redisUtil.set("user", user);
        System.out.println(redisUtil.get("user"));

    }

参考

https://www.bilibili.com/video/BV1S54y1R7SB

猜你喜欢

转载自blog.csdn.net/qq_43610675/article/details/113687053