springboot redis工具类 (含完整的单元测试+简单集成)

ps

刚开始的时候,我打算从网上搜一个redis工具类,以供我在项目中redis开发的使用,我尝试了以下的关键字

1.redis工具类
2.springboot redis工具类
3.springredis工具类
4.redis集成

发现文章中并没有我完整想要的,于是我根据我想要的,开始一步步拆分收集,和自己写单元测试(连测试+改进用了6h),于是有了这篇博客
我想要的有以下几点

1.sprongboot集成redis
2.redis使用工具类,与具体方法使用方式

文章大纲

1.sprongboot集成redis(工具类环境,如果搭建可以跳过)

2.redis工具类,与单元测试

1.sprongboot集成redis(工具类环境,如果搭建可以跳过)

1.1增加maven依赖

		<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>

2.增加redis配置

##=====================redis ========
# Redis数据库索引(默认为0)
spring.redis.database=0  
# Redis服务器地址
spring.redis.host=localhost
# Redis服务器连接端口
spring.redis.port=6379  
# Redis服务器连接密码(默认为空)
spring.redis.password=
# 连接池最大连接数(使用负值表示没有限制) 默认 8
spring.redis.lettuce.pool.max-active=8
# 连接池最大阻塞等待时间(使用负值表示没有限制) 默认 -1
spring.redis.lettuce.pool.max-wait=-1
# 连接池中的最大空闲连接 默认 8
spring.redis.lettuce.pool.max-idle=8
# 连接池中的最小空闲连接 默认 0
spring.redis.lettuce.pool.min-idle=0

2.redis工具类,与单元测试

工具类代码,从网上找到个人认为一个最好的

package com.fanfan.utils.redis;

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

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 lombok.extern.slf4j.Slf4j;

/**
 * 
 * @author 王赛超 基于spring和redis的redisTemplate工具类 针对所有的hash 都是以h开头的方法 针对所有的Set 都是以s开头的方法 不含通用方法 针对所有的List 都是以l开头的方法
 */
@Component
@Slf4j
public class RedisUtil {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    // =============================common============================
    /**
     * 指定缓存失效时间
     * 
     * @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) {
            log.error(key, e);
            return false;
        }
    }

    /**
     * 根据key 获取过期时间
     * 
     * @param key
     *            键 不能为null
     * @return 时间(秒) 返回0代表为永久有效
     */
    public long getExpire(String key) {
        return redisTemplate.getExpire(key, TimeUnit.SECONDS);
    }

    /**
     * 判断key是否存在
     * 
     * @param key
     *            键
     * @return true 存在 false不存在
     */
    public boolean hasKey(String key) {
        try {
            return redisTemplate.hasKey(key);
        } catch (Exception e) {
            log.error(key, e);
            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 true成功 false失败
     */
    public boolean set(String key, Object value) {
        try {
            redisTemplate.opsForValue().set(key, value);
            return true;
        } catch (Exception e) {
            log.error(key, e);
            return false;
        }

    }

    /**
     * 普通缓存放入并设置时间
     * 
     * @param key
     *            键
     * @param value
     *            值
     * @param time
     *            时间(秒) time要大于0 如果time小于等于0 将设置无限期
     * @return true成功 false 失败
     */
    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) {
            log.error(key, e);
            return false;
        }
    }

    /**
     * 递增 适用场景: https://blog.csdn.net/y_y_y_k_k_k_k/article/details/79218254 高并发生成订单号,秒杀类的业务逻辑等。。
     * 
     * @param key
     *            键
     * @param by
     *            要增加几(大于0)
     * @return
     */
    public long incr(String key, long delta) {
        if (delta < 0) {
            throw new RuntimeException("递增因子必须大于0");
        }
        return redisTemplate.opsForValue().increment(key, delta);
    }

    /**
     * 递减
     * 
     * @param key
     *            键
     * @param by
     *            要减少几(小于0)
     * @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
     *            键 不能为null
     * @param item
     *            项 不能为null
     * @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 true 成功 false 失败
     */
    public boolean hmset(String key, Map<String, Object> map) {
        try {
            redisTemplate.opsForHash().putAll(key, map);
            return true;
        } catch (Exception e) {
            log.error(key, e);
            return false;
        }
    }

    /**
     * HashSet 并设置时间
     * 
     * @param key
     *            键
     * @param map
     *            对应多个键值
     * @param time
     *            时间(秒)
     * @return true成功 false失败
     */
    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) {
            log.error(key, e);
            return false;
        }
    }

    /**
     * 向一张hash表中放入数据,如果不存在将创建
     * 
     * @param key
     *            键
     * @param item
     *            项
     * @param value
     *            值
     * @return true 成功 false失败
     */
    public boolean hset(String key, String item, Object value) {
        try {
            redisTemplate.opsForHash().put(key, item, value);
            return true;
        } catch (Exception e) {
            log.error(key, e);
            return false;
        }
    }

    /**
     * 向一张hash表中放入数据,如果不存在将创建
     * 
     * @param key
     *            键
     * @param item
     *            项
     * @param value
     *            值
     * @param time
     *            时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间
     * @return true 成功 false失败
     */
    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) {
            log.error(key, e);
            return false;
        }
    }

    /**
     * 删除hash表中的值
     * 
     * @param key
     *            键 不能为null
     * @param item
     *            项 可以使多个 不能为null
     */
    public void hdel(String key, Object... item) {
        redisTemplate.opsForHash().delete(key, item);
    }

    /**
     * 判断hash表中是否有该项的值
     * 
     * @param key
     *            键 不能为null
     * @param item
     *            项 不能为null
     * @return true 存在 false不存在
     */
    public boolean hHasKey(String key, String item) {
        return redisTemplate.opsForHash().hasKey(key, item);
    }

    /**
     * hash递增 如果不存在,就会创建一个 并把新增后的值返回
     * 
     * @param key
     *            键
     * @param item
     *            项
     * @param by
     *            要增加几(大于0)
     * @return
     */
    public double hincr(String key, String item, double by) {
        return redisTemplate.opsForHash().increment(key, item, by);
    }

    /**
     * hash递减
     * 
     * @param key
     *            键
     * @param item
     *            项
     * @param by
     *            要减少记(小于0)
     * @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) {
            log.error(key, e);
            return null;
        }
    }

    /**
     * 根据value从一个set中查询,是否存在
     * 
     * @param key
     *            键
     * @param value
     *            值
     * @return true 存在 false不存在
     */
    public boolean sHasKey(String key, Object value) {
        try {
            return redisTemplate.opsForSet().isMember(key, value);
        } catch (Exception e) {
            log.error(key, e);
            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) {
            log.error(key, e);
            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) {
            log.error(key, e);
            return 0;
        }
    }

    /**
     * 获取set缓存的长度
     * 
     * @param key
     *            键
     * @return
     */
    public long sGetSetSize(String key) {
        try {
            return redisTemplate.opsForSet().size(key);
        } catch (Exception e) {
            log.error(key, e);
            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) {
            log.error(key, e);
            return 0;
        }
    }

    // ============================zset=============================
    /**
     * 根据key获取Set中的所有值
     * 
     * @param key
     *            键
     * @return
     */
    public Set<Object> zSGet(String key) {
        try {
            return redisTemplate.opsForSet().members(key);
        } catch (Exception e) {
            log.error(key, e);
            return null;
        }
    }

    /**
     * 根据value从一个set中查询,是否存在
     * 
     * @param key
     *            键
     * @param value
     *            值
     * @return true 存在 false不存在
     */
    public boolean zSHasKey(String key, Object value) {
        try {
            return redisTemplate.opsForSet().isMember(key, value);
        } catch (Exception e) {
            log.error(key, e);
            return false;
        }
    }

    public Boolean zSSet(String key, Object value, double score) {
        try {
            return redisTemplate.opsForZSet().add(key, value, 2);
        } catch (Exception e) {
            log.error(key, e);
            return false;
        }
    }

    /**
     * 将set数据放入缓存
     * 
     * @param key
     *            键
     * @param time
     *            时间(秒)
     * @param values
     *            值 可以是多个
     * @return 成功个数
     */
    public long zSSetAndTime(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) {
            log.error(key, e);
            return 0;
        }
    }

    /**
     * 获取set缓存的长度
     * 
     * @param key
     *            键
     * @return
     */
    public long zSGetSetSize(String key) {
        try {
            return redisTemplate.opsForSet().size(key);
        } catch (Exception e) {
            log.error(key, e);
            return 0;
        }
    }

    /**
     * 移除值为value的
     * 
     * @param key
     *            键
     * @param values
     *            值 可以是多个
     * @return 移除的个数
     */
    public long zSetRemove(String key, Object... values) {
        try {
            Long count = redisTemplate.opsForSet().remove(key, values);
            return count;
        } catch (Exception e) {
            log.error(key, e);
            return 0;
        }
    }
    // ===============================list=================================

    /**
     * 获取list缓存的内容
     * 
     * @取出来的元素 总数 end-start+1
     * 
     * @param key
     *            键
     * @param start
     *            开始 0 是第一个元素
     * @param end
     *            结束 -1代表所有值
     * @return
     */
    public List<Object> lGet(String key, long start, long end) {
        try {
            return redisTemplate.opsForList().range(key, start, end);
        } catch (Exception e) {
            log.error(key, e);
            return null;
        }
    }

    /**
     * 获取list缓存的长度
     * 
     * @param key
     *            键
     * @return
     */
    public long lGetListSize(String key) {
        try {
            return redisTemplate.opsForList().size(key);
        } catch (Exception e) {
            log.error(key, e);
            return 0;
        }
    }

    /**
     * 通过索引 获取list中的值
     * 
     * @param key
     *            键
     * @param index
     *            索引 index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推
     * @return
     */
    public Object lGetIndex(String key, long index) {
        try {
            return redisTemplate.opsForList().index(key, index);
        } catch (Exception e) {
            log.error(key, e);
            return null;
        }
    }

    /**
     * 将list放入缓存
     * 
     * @param key
     *            键
     * @param value
     *            值
     * @param time
     *            时间(秒)
     * @return
     */
    public boolean lSet(String key, Object value) {
        try {
            redisTemplate.opsForList().rightPush(key, value);
            return true;
        } catch (Exception e) {
            log.error(key, e);
            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) {
            log.error(key, e);
            return false;
        }
    }

    /**
     * 将list放入缓存
     * 
     * @param key
     *            键
     * @param value
     *            值
     * @param time
     *            时间(秒)
     * @return
     */
    public boolean lSet(String key, List<Object> value) {
        try {
            redisTemplate.opsForList().rightPushAll(key, value);
            return true;
        } catch (Exception e) {
            log.error(key, e);
            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) {
            log.error(key, e);
            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) {
            log.error(key, e);
            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) {
            log.error(key, e);
            return 0;
        }
    }

}

完整的单元测试

package com.fanfan.utils.redis;

import java.io.Serializable;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import lombok.Data;

/**
 * 工具栏类进行单元测试
 * 
 * @ClassName RedisUtilTest
 * @author <a href="892042158@qq.com" target="_blank">于国帅</a>
 * @date 2019年3月6日 下午5:30:07
 *
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class RedisUtilTest {
    @Autowired
    private RedisUtil redisUtil;

    @BeforeClass
    public static void setUpBeforeClass() throws Exception {
    }

    @AfterClass
    public static void tearDownAfterClass() throws Exception {
    }

    /**
     * 设置缓存过期时间
     * 
     * @Title testExpire
     * @author 于国帅
     * @date 2019年3月7日 上午8:35:24
     * @throws Exception
     *             void
     */
    @Test
    public void testExpire() throws Exception {
        redisUtil.set("aaaKey", "aaaValue");
        redisUtil.expire("aaaKey", 100);
        Assert.assertEquals(redisUtil.get("aaaKey"), "aaaValue");
        TimeUnit.SECONDS.sleep(100);
        Assert.assertNotEquals(redisUtil.get("aaaKey"), "aaaValue");

    }

    @Test
    public void testGetExpire() throws Exception {
        redisUtil.set("aaaKey", "aaaValue");
        redisUtil.expire("aaaKey", 100);
        // 设置了缓存就会及时的生效,所以缓存时间小于最初设置的时间
        Assert.assertTrue(redisUtil.getExpire("aaaKey") < 100L);
    }

    @Test
    public void testHasKey() throws Exception {
        redisUtil.set("aaaKey", "aaaValue");
        // 存在的
        Assert.assertTrue(redisUtil.hasKey("aaaKey"));
        // 不存在的
        Assert.assertFalse(redisUtil.hasKey("bbbKey"));
    }

    @Test
    public void testDel() throws Exception {
        redisUtil.set("aaaKey", "aaaValue");
        // 存在的
        Assert.assertTrue(redisUtil.hasKey("aaaKey"));
        redisUtil.del("aaaKey");
        Assert.assertFalse(redisUtil.hasKey("bbbKey"));
    }

    @Test
    public void testGet() throws Exception {
        redisUtil.set("aaaKey", "aaaValue");
        Assert.assertEquals(redisUtil.get("aaaKey"), "aaaValue");
    }

    @Test
    public void testSetStringObject() throws Exception {
        Assert.assertTrue(redisUtil.set("aaaKey", "aaaValue"));
    }

    @Test
    public void testSetStringObjectLong() throws Exception {
        Assert.assertTrue(redisUtil.set("aaaKeyLong", 100L));
    }

    @Test
    public void testSetObject() {
        // 测试对象
        TestModel testModel = new TestModel();
        testModel.setId(System.currentTimeMillis());
        testModel.setName("测试");
        redisUtil.set("testModel", testModel);
        TestModel testModel2 = (TestModel) redisUtil.get("testModel");
        System.err.println(testModel2);
        System.err.println(testModel2.getName());
        System.err.println(testModel2.getId());
    }

    @Test
    @Ignore
    public void testIncr() throws Exception {
        String key = "testIncr";
        redisUtil.incr(key, 1);
        redisUtil.expire(key, 10); // 缓存失效10s
        Assert.assertEquals(redisUtil.get(key), 1);
    }

    // 高并发下 递增 测试
    @Test
    @Ignore
    public void testIncr2() throws Exception {
        // 模拟发送短信的并发
        // 首先开启一个线程池,创建一个专门消费短信的线程
        // 一次性放入多个线程实例 ,实例 都是2秒请求一次 ,而10s内的只能允许一条。 也就是说我测试100个线程,只能10s一条
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(6, 6, 30, TimeUnit.SECONDS, new LinkedBlockingQueue<>(100));
        Thread[] threads = new Thread[100];
        for (int i = 0; i < 100; i++) {
            threads[i] = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        TimeUnit.SECONDS.sleep(2);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    //
                    String key = "testIncr2_17353620612";
                    long count = redisUtil.incr(key, 1);
                    if (count == 1L) {
                        redisUtil.expire(key, 10); // 缓存失效10s
                        System.err.println("短信发送成功===" + new Date());

                    } else {
                        System.err.println("访问次数快===" + new Date());
                    }
                }
            });
            threadPoolExecutor.submit(threads[i]);
        }

        while (threadPoolExecutor.getQueue().isEmpty()) {
            threadPoolExecutor.shutdown();
            System.err.println("所有线程执行完毕");
        }

        System.in.read();// 加入该代码,让主线程不挂掉

//        // 启动线程
//        for (int i = 0; i < 100; i++) {
//            threads[i].start();
//        }
    }

    long count = 0L;

    // 高并发下 错误的测试 递增 测试
    @Test
    @Ignore
    public void testIncr3() throws Exception {
        // 模拟发送短信的并发

        // 首先开启一个线程池,创建一个专门消费短信的线程
        // 一次性放入多个线程实例 ,实例 都是2秒请求一次 ,而10s内的只能允许一条。 也就是说我测试100个线程,只能10s一条
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(6, 6, 30, TimeUnit.SECONDS, new LinkedBlockingQueue<>(100));
        Thread[] threads = new Thread[100];
        for (int i = 0; i < 100; i++) {
            threads[i] = new Thread(new Runnable() {
                @Override
                public void run() {
//                    try {
//                        TimeUnit.SECONDS.sleep(2);
//                    } catch (InterruptedException e) {
//                        e.printStackTrace();
//                    }
//                    pool-3-thread-1count===1
//                   pool-3-thread-5count===1
                    String key = "testIncr2_17353620612";
                    count = count + 1;
                    System.err.println(Thread.currentThread().getName() + "count===" + count);
                    // 督导的count
                    // if (count == 1L) {
//                        count = count - 1;
//                        System.err.println("短信发送成功===" + new Date());
//                    } else {
//                        System.err.println("访问次数快===" + new Date());
//                    }
                }
            });
            threadPoolExecutor.submit(threads[i]);
        }

        while (threadPoolExecutor.getQueue().isEmpty()) {
            threadPoolExecutor.shutdown();
            System.err.println("所有线程执行完毕");
        }

//        System.in.read();// 加入该代码,让主线程不挂掉
    }

    @Test
    @Ignore
    public void testDecr() throws Exception {
        String key = "Decr_17353620612";
        redisUtil.decr(key, 1);
        redisUtil.expire(key, 10); // 缓存失效10s
        Assert.assertEquals(redisUtil.get(key), 1);
    }

    @Test
    public void testHget() throws Exception {
        redisUtil.hset("testHget", "testHget", "testHget");
        Assert.assertEquals("testHget", redisUtil.hget("testHget", "testHget"));

    }

    @Test
    public void testHmget() throws Exception {
        redisUtil.hset("testHmget", "testHmget1", "testHmget1");
        redisUtil.hset("testHmget", "testHmget2", "testHmget2");
        Map<Object, Object> map = redisUtil.hmget("testHmget");
        if (MapUtils.isNotEmpty(map)) {
            for (Entry<Object, Object> e : map.entrySet()) {
                System.err.println(e.getKey() + "===" + e.getValue());
            }
        }
    }

    @Test
    public void testHsetStringStringObject() throws Exception {
        redisUtil.hset("map", "testHsetStringStringObject", "testHsetStringStringObject");

    }

    // 测试放在hash 里面的对象
    @Test
    public void testHsetObject() {
        // 测试对象
        TestModel testModel = new TestModel();
        testModel.setId(System.currentTimeMillis());
        testModel.setName("测试");
        redisUtil.hset("hash", "testModel", testModel);
        TestModel testModel2 = (TestModel) redisUtil.hget("hash", "testModel");
        System.err.println(testModel2);
        System.err.println(testModel2.getName());
        System.err.println(testModel2.getId());
    }

    // 太奇妙了 放进去Long 取出来会根据大小变为相应的数据类型
    @Test
    public void testHsetStringStringObjectLong() throws Exception {
        redisUtil.hset("testHsetStringStringObjectLong", "int", 100); // java.lang.Integer 读取来是inter
        System.err.println(redisUtil.hget("testHsetStringStringObjectLong", "int").getClass().getTypeName());
//        Assert.assertEquals(redisUtil.hget("map", "testHsetStringStringObject"), 100L);
        redisUtil.hset("testHsetStringStringObjectLong", "long", System.currentTimeMillis()); // java.lang.Integer 读取来是inter
        System.err.println(redisUtil.hget("testHsetStringStringObjectLong", "long").getClass().getTypeName());

    }

    @Test
    public void testHdel() throws Exception {
        redisUtil.hset("testHdel", "int", 100);
        Assert.assertEquals(redisUtil.hget("testHdel", "int"), 100);
        redisUtil.hdel("testHdel", "int");
        Assert.assertEquals(redisUtil.hget("testHdel", "int"), null);

    }

    @Test
    public void testHHasKey() throws Exception {
        redisUtil.hset("testHHasKey", "int", 100);
        Assert.assertTrue(redisUtil.hHasKey("testHHasKey", "int"));

    }

    @Test
    public void testHincr() throws Exception {
        System.err.println(redisUtil.hincr("testHincr", "testHincr", 1));

    }

    @Test
    public void testHdecr() throws Exception {
        System.err.println(redisUtil.hincr("testHincr", "testHincr", 1));
    }

    @Test
    public void testSGet() throws Exception {
        redisUtil.sSet("testSGet", "testSGet1");
        redisUtil.sSet("testSGet", "testSGet2");
        System.err.println(StringUtils.join(redisUtil.sGet("testSGet"), ","));
    }

    @Test
    public void testSHasKey() throws Exception {
        redisUtil.sSet("testSHasKey", "testSHasKey");
        Assert.assertTrue(redisUtil.sHasKey("testSHasKey", "testSHasKey"));

    }

    @Test
    public void testSSet() throws Exception {
        redisUtil.sSet("testSSet", "testSSet");

    }

    @Test
    public void testSSetAndTime() throws Exception {
        redisUtil.sSetAndTime("testSSetAndTime", 20, "testSSetAndTime1");
        redisUtil.sSetAndTime("testSSetAndTime", 5, "testSSetAndTime2");
        System.err.println(StringUtils.join(redisUtil.sGet("testSSetAndTime"), ","));
        TimeUnit.SECONDS.sleep(5);
        System.err.println(StringUtils.join(redisUtil.sGet("testSSetAndTime"), ","));
        TimeUnit.SECONDS.sleep(20);
        System.err.println(StringUtils.join(redisUtil.sGet("testSSetAndTime"), ","));

    }

    @Test
    public void testSGetSetSize() throws Exception {
        redisUtil.sSetAndTime("testSGetSetSize", 20, "testSGetSetSize1");
        redisUtil.sSetAndTime("testSGetSetSize", 5, "testSGetSetSize");
        Assert.assertEquals(redisUtil.sGetSetSize("testSGetSetSize"), 2);
    }

    @Test
    public void testSetRemove() throws Exception {
        redisUtil.sSetAndTime("testSetRemove", 20, "testSetRemove1");
        redisUtil.sSetAndTime("testSetRemove", 5, "testSetRemove");
        Assert.assertEquals(redisUtil.sGetSetSize("testSetRemove"), 2);
        redisUtil.setRemove("testSetRemove", "testSetRemove");
        Assert.assertEquals(redisUtil.sGetSetSize("testSetRemove"), 1);

    }

    @Test
    public void testLGet() throws Exception {
        redisUtil.lSet("testLGet", "testLGet0", 10); // 10秒过期
        redisUtil.lSet("testLGet", "testLGet1", 10);
        // 查询三个元素 2-0+1
        List<Object> list = redisUtil.lGet("testLGet", 0, 2);
        System.err.println("list===" + list);
        // 查询两个
        List<Object> list2 = redisUtil.lGet("testLGet", 0, 1);
        System.err.println("list2===" + list2);
        // 查询全部
        List<Object> list3 = redisUtil.lGet("testLGet", 0, -1);
        System.err.println("list3===" + list3);

    }

    @Test
    public void testLGetListSize() throws Exception {
        // 看看重复元素会怎么处理
        long size = 0;
        redisUtil.lSet("testLGetListSize", "testLGetListSize0", 10); // 10秒过期
        size = redisUtil.lGetListSize("testLGetListSize");
        System.err.println(size);
        redisUtil.lSet("testLGetListSize", "testLGetListSize0", 10);
        size = redisUtil.lGetListSize("testLGetListSize");
        System.err.println(size);
    }

    //
    @Test
    public void testLGetIndex() throws Exception {
        redisUtil.lSet("testLGetIndex", "testLGetIndex0", 10); // 10秒过期
        redisUtil.lSet("testLGetIndex", "testLGetIndex1", 10);
        Object obj = redisUtil.lGetIndex("testLGetIndex", 0);
        Assert.assertEquals(obj, "testLGetIndex0");
    }

    @Test
    public void testLSetStringObject() throws Exception {
        redisUtil.lSet("testLSetStringObject", "testLSetStringObject0");
        redisUtil.lSet("testLSetStringObject", "testLSetStringObject1");
        redisUtil.lSet("testLSetStringObject", "testLSetStringObject2");
    }

    @Test
    public void testLSetStringObjectLong() throws Exception {

    }

    @Test
    public void testLUpdateIndex() throws Exception {
        redisUtil.lSet("testLUpdateIndex", "testLUpdateIndex0");
        redisUtil.lSet("testLUpdateIndex", "testLUpdateIndex1");
        redisUtil.lSet("testLUpdateIndex", "testLUpdateIndex2");
        Object obj = redisUtil.lUpdateIndex("testLUpdateIndex", 0, "更新的");
        Assert.assertEquals("更新的", obj);
    }

    @Test
    public void testLRemove() throws Exception {
        redisUtil.lSet("testLRemove", "testLRemove0");
        redisUtil.lSet("testLRemove", "testLRemove1");
        redisUtil.lSet("testLRemove", "testLRemove2");
        Object obj = redisUtil.lRemove("testLRemove", 1, "testLRemove2");
    }
}

@Data
class TestModel implements Serializable {
    /**
     * @Fields serialVersionUID : (用一句话描述这个变量表示什么)
     */
    private static final long serialVersionUID = 1L;
    private Long id;
    private String name;
}

参考

博客
SpringBoot整合Redis及Redis工具类撰写
https://www.cnblogs.com/zeng1994/p/03303c805731afc9aa9c60dbbd32a323.html
redis整合spring(redisTemplate工具类)
https://blog.csdn.net/qq_34021712/article/details/75949706

  • 8
    点赞
  • 58
    收藏
    觉得还不错? 一键收藏
  • 7
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值