SpringBoot集成redis,redis操作工具类以及测试,fastjson序列化

前言

redis作为一个高性能的缓存服务器,支持多种数据格式的存取,使用范围十分广泛,在web后台缓存界中有不可动摇的地位。
redis的优势就是,单节点能支持超大的并发量(数万乃至数十万),性能强劲。通常的用法就是将数据库中的热点数据,存放到redis中,减少数据库的压力,增强系统的稳定性。且支持各种集群模式,所以将redis操作好,相当于系统多了好几条命。

操作起来

1 docker安装redis

这里我使用docker安装一个redis,非常方便快捷。没用过的朋友可以下载redis的windows版或者linux版本,双击运行起来。

  • docker环境下执行以下命令,拉取redis的镜像(也可以在https://hub.docker.com/_/redis?tab=tags中搜索指定版本的镜像,进行安装)
docker pull redis:latest

拉取redis镜像

  • 通过该镜像启动一个redis容器
docker run -p 6379:6379 --name redis -d redis:latest redis-server --appendonly yes

docker启动redis成功

  • 查看redis容器的详细信息(分配的ip地址)
docker inspect redis

docker查看redis容器信息

  • 使用redis-client工具测试一下
    redisclient测试

2 springboot集成redis

2.1 引入redis的依赖
<!-- redis支持 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- fastjson支持 -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.40</version>
</dependency>
  • 引入fastjson,作为redis的序列化和反序列化机制
2.2 修改application.xml
#redis配置
redis:
  database: 0
  host: 172.17.0.2
  port: 6379
  password:
  jedis:
    pool:
      max-active: 8 #最大连接数
      max-wait: 6000 #最大阻塞等待时间
      max-idle: 8 #最大空闲连接
      min-idle: 0 #最小空闲连接
      timeout: 500
2.3 创建一个fastjson序列化器
package com.zyu.boot.demo.utils.redis;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.ParserConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
import org.springframework.util.Assert;

import java.nio.charset.Charset;

/**
 * FastJson序列化方式
 * @author zyufocus
 *
 * @param <T>
 */
public class FastJson2JsonRedisSerializer<T> implements RedisSerializer<T> {
	private ObjectMapper objectMapper = new ObjectMapper();
    public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
 
    private Class<T> clazz;
 
    static {
        ParserConfig.getGlobalInstance().setAutoTypeSupport(true);
        ParserConfig.getGlobalInstance().addAccept("com.zyu");
    }
 
    public FastJson2JsonRedisSerializer(Class<T> clazz) {
        super();
        this.clazz = clazz;
    }
 
    public byte[] serialize(T t) throws SerializationException {
        if (t == null) {
            return new byte[0];
        }
        return JSON.toJSONString(t, SerializerFeature.WriteClassName).getBytes(DEFAULT_CHARSET);
    }
 
    public T deserialize(byte[] bytes) throws SerializationException {
        if (bytes == null || bytes.length <= 0) {
            return null;
        }
        String str = new String(bytes, DEFAULT_CHARSET);
 
        return JSON.parseObject(str, clazz);
    }
 
    public void setObjectMapper(ObjectMapper objectMapper) {
        Assert.notNull(objectMapper, "'objectMapper' must not be null");
        this.objectMapper = objectMapper;
    }
 
    protected JavaType getJavaType(Class<?> clazz) {
        return TypeFactory.defaultInstance().constructType(clazz);
    }
}
2.4 redis的配置类
package com.zyu.boot.demo.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zyu.boot.demo.utils.redis.FastJson2JsonRedisSerializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * Redis配置类,注入spring容器
 * 
 * @author zyufocus
 *
 */
@Configuration
@Order(4)
public class RedisConfig {

	@Bean
	public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
		RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>();
		redisTemplate.setConnectionFactory(factory);
		FastJson2JsonRedisSerializer<Object> fastJson2JsonRedisSerializer = new FastJson2JsonRedisSerializer<>(Object.class);
		ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        fastJson2JsonRedisSerializer.setObjectMapper(objectMapper);
        
		StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
		redisTemplate.setKeySerializer(stringRedisSerializer);// 设置key采用String的序列化方式
		redisTemplate.setHashKeySerializer(stringRedisSerializer);// 设置hash的key也采用String的序列化方式
		redisTemplate.setValueSerializer(fastJson2JsonRedisSerializer); // 设置value采用的fastjson的序列化方式
		redisTemplate.setHashValueSerializer(fastJson2JsonRedisSerializer);// 设置hash的value采用的fastjson的序列化方式
		redisTemplate.setDefaultSerializer(fastJson2JsonRedisSerializer);// 设置其他默认的序列化方式为fastjson
		redisTemplate.afterPropertiesSet();

		return redisTemplate;
	}
}

2.5 redis操作的工具类
package com.zyu.boot.demo.utils.redis;

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

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


/**
 * 
 * 基于spring和redis的redisTemplate工具类 
 * 针对所有的hash 都是以h开头的方法 
 * 针对所有的Set 都是以s开头的方法
 * 针对所有的List 都是以l开头的方法
 */
@Component
public class RedisUtils {

	@Autowired
	private RedisTemplate<String, Object> redisTemplate;

	public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) {
		this.redisTemplate = 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) {
			e.printStackTrace();
			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) {
			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 true成功 false失败
	 */
	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  时间(秒) 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) {
			e.printStackTrace();
			return false;
		}
	}

	/**
	 * 递增
	 * 
	 * @param key 键
	 * @param delta  要增加几(大于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 delta  要减少几(小于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) {
			e.printStackTrace();
			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) {
			e.printStackTrace();
			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) {
			e.printStackTrace();
			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) {
			e.printStackTrace();
			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) {
			e.printStackTrace();
			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) {
			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;
		}
	}

	/**
	 * 查询集合中是否有该元素
	 * @param key
	 * @param value
	 * @return
	 */
	public boolean sIsMember(String key, Object value){
		try{
			return redisTemplate.opsForSet().isMember(key, value);
		}catch (Exception e){
			e.printStackTrace();;
			return false;
		}
	}

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

	/**
	 * 获取list缓存的内容
	 * 
	 * @param key   键
	 * @param start 开始
	 * @param end   结束 0 到 -1代表所有值
	 * @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 索引 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) {
			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;
		}
	}

	public boolean leftPushIfPresent(String key,Object value){
		Long aLong = redisTemplate.opsForList().leftPushIfPresent(key, value);
		return true;

	}

	/**
	 * 根据索引修改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;
		}
	}

	//Zset 根据 socre 排序   不重复 每个元素附加一个 socre  double类型的属性(double 可以重复)

	/**
	 * 添加 ZSet 元素
	 * @param key
	 * @param value
	 * @param score
	 */
	public boolean add(String key,Object value,double score){
		return redisTemplate.opsForZSet().add(key, value, score);
	}

	/**
	 * 批量添加 Zset <br>
	 *         Set<TypedTuple<Object>> tuples = new HashSet<>();<br>
	 *         TypedTuple<Object> objectTypedTuple1 = new DefaultTypedTuple<Object>("zset-5",9.6);<br>
	 *         tuples.add(objectTypedTuple1);
	 * @param key
	 * @param tuples
	 * @return
	 */
	public Long batchAddZset(String key,Set<ZSetOperations.TypedTuple<Object>> tuples){
		return redisTemplate.opsForZSet().add(key, tuples);
	}

	/**
	 * Zset 删除一个或多个元素
	 * @param key
	 * @param values
	 * @return
	 */
	public Long removeZset(String key,Object ...values){
		return redisTemplate.opsForZSet().remove(key, values);
	}

	/**
	 * 对指定的 zset 的 value 值 , socre 属性做增减操作
	 * @param key
	 * @param value
	 * @param score
	 * @return
	 */
	public Double incrementScore(String key,Object value,double score){
		return redisTemplate.opsForZSet().incrementScore(key, value, score);
	}

	/**
	 * 获取 key 中指定 value 的排名(从0开始,从小到大排序)
	 * @param key
	 * @param value
	 * @return
	 */
	public Long rank(String key,Object value){
		return redisTemplate.opsForZSet().rank(key, value);
	}

	/**
	 * 获取 key 中指定 value 的排名(从0开始,从大到小排序)
	 * @param key
	 * @param value
	 * @return
	 */
	public Long reverseRank(String key,Object value){
		return redisTemplate.opsForZSet().reverseRank(key, value);
	}

	/**
	 * 获取索引区间内的排序结果集合(从0开始,从小到大,带上分数)
	 * @param key
	 * @param start
	 * @param end
	 * @return
	 */
	public Set<ZSetOperations.TypedTuple<Object>> rangeWithScores(String key, long start, long end){
		return redisTemplate.opsForZSet().rangeWithScores(key, start, end);
	}

	/**
	 * 获取索引区间内的排序结果集合(从0开始,从小到大,只有列名)
	 * @param key
	 * @param start
	 * @param end
	 * @return
	 */
	public Set<Object> range(String key, long start, long end){
		return redisTemplate.opsForZSet().range(key, start, end);
	}

	/**
	 * 获取分数范围内的 [min,max] 的排序结果集合 (从小到大,只有列名)
	 * @param key
	 * @param min
	 * @param max
	 * @return
	 */
	public Set<Object> rangeByScore(String key, double min, double max){
		return redisTemplate.opsForZSet().rangeByScore(key, min, max);
	}

	/**
	 * 获取分数范围内的 [min,max] 的排序结果集合 (从小到大,集合带分数)
	 * @param key
	 * @param min
	 * @param max
	 * @return
	 */
	public Set<ZSetOperations.TypedTuple<Object>> rangeByScoreWithScores(String key, double min, double max){
		return redisTemplate.opsForZSet().rangeByScoreWithScores(key, min, max);
	}

	/**
	 * 返回 分数范围内 指定 count 数量的元素集合, 并且从 offset 下标开始(从小到大,不带分数的集合)
	 * @param key
	 * @param min
	 * @param max
	 * @param offset 从指定下标开始
	 * @param count 输出指定元素数量
	 * @return
	 */
	public Set<Object> rangeByScore(String key, double min, double max,long offset,long count){
		return redisTemplate.opsForZSet().rangeByScore(key, min, max, offset, count);
	}

	/**
	 * 返回 分数范围内 指定 count 数量的元素集合, 并且从 offset 下标开始(从小到大,带分数的集合)
	 * @param key
	 * @param min
	 * @param max
	 * @param offset 从指定下标开始
	 * @param count 输出指定元素数量
	 * @return
	 */
	public Set<ZSetOperations.TypedTuple<Object>> rangeByScoreWithScores(String key, double min, double max, long offset, long count){
		return redisTemplate.opsForZSet().rangeByScoreWithScores(key, min, max, offset, count);
	}

	/**
	 * 获取索引区间内的排序结果集合(从0开始,从大到小,只有列名)
	 * @param key
	 * @param start
	 * @param end
	 * @return
	 */
	public Set<Object> reverseRange(String key,long start,long end){
		return redisTemplate.opsForZSet().reverseRange(key, start, end);
	}

	/**
	 * 获取索引区间内的排序结果集合(从0开始,从大到小,带上分数)
	 * @param key
	 * @param start
	 * @param end
	 * @return
	 */
	public Set<ZSetOperations.TypedTuple<Object>> reverseRangeWithScores(String key, long start, long end){
		return redisTemplate.opsForZSet().reverseRangeWithScores(key, start, end);
	}

	/**
	 * 获取分数范围内的 [min,max] 的排序结果集合 (从大到小,集合不带分数)
	 * @param key
	 * @param min
	 * @param max
	 * @return
	 */
	public Set<Object> reverseRangeByScore(String key,double min,double max){
		return redisTemplate.opsForZSet().reverseRangeByScore(key, min, max);
	}

	/**
	 * 获取分数范围内的 [min,max] 的排序结果集合 (从大到小,集合带分数)
	 * @param key
	 * @param min
	 * @param max
	 * @return
	 */
	public Set<ZSetOperations.TypedTuple<Object>> reverseRangeByScoreWithScores(String key, double min, double max){
		return redisTemplate.opsForZSet().reverseRangeByScoreWithScores(key, min, max);
	}

	/**
	 * 返回 分数范围内 指定 count 数量的元素集合, 并且从 offset 下标开始(从大到小,不带分数的集合)
	 * @param key
	 * @param min
	 * @param max
	 * @param offset 从指定下标开始
	 * @param count 输出指定元素数量
	 * @return
	 */
	public Set<Object> reverseRangeByScore(String key,double min,double max,long offset,long count){
		return redisTemplate.opsForZSet().reverseRangeByScore(key, min, max, offset, count);
	}

	/**
	 * 返回 分数范围内 指定 count 数量的元素集合, 并且从 offset 下标开始(从大到小,带分数的集合)
	 * @param key
	 * @param min
	 * @param max
	 * @param offset 从指定下标开始
	 * @param count 输出指定元素数量
	 * @return
	 */
	public Set<ZSetOperations.TypedTuple<Object>> reverseRangeByScoreWithScores(String key, double min, double max, long offset, long count){
		return redisTemplate.opsForZSet().reverseRangeByScoreWithScores(key, min, max, offset, count);
	}

	/**
	 * 返回指定分数区间 [min,max] 的元素个数
	 * @param key
	 * @param min
	 * @param max
	 * @return
	 */
	public long countZSet(String key,double min,double max){
		return redisTemplate.opsForZSet().count(key, min, max);
	}

	/**
	 * 返回 zset 集合数量
	 * @param key
	 * @return
	 */
	public long sizeZset(String key){
		return redisTemplate.opsForZSet().size(key);
	}

	/**
	 * 获取指定成员的 score 值
	 * @param key
	 * @param value
	 * @return
	 */
	public Double score(String key,Object value){
		return redisTemplate.opsForZSet().score(key, value);
	}

	/**
	 * 删除指定索引位置的成员,其中成员分数按( 从小到大 )
	 * @param key
	 * @param start
	 * @param end
	 * @return
	 */
	public Long removeRange(String key,long start ,long end){
		return redisTemplate.opsForZSet().removeRange(key, start, end);
	}

	/**
	 * 删除指定 分数范围 内的成员 [main,max],其中成员分数按( 从小到大 )
	 * @param key
	 * @param min
	 * @param max
	 * @return
	 */
	public Long removeRangeByScore(String key,double min ,double max){
		return redisTemplate.opsForZSet().removeRangeByScore(key, min, max);
	}

	/**
	 *  key 和 other 两个集合的并集,保存在 destKey 集合中, 列名相同的 score 相加
	 * @param key
	 * @param otherKey
	 * @param destKey
	 * @return
	 */
	public Long unionAndStoreZset(String key,String otherKey,String destKey){
		return redisTemplate.opsForZSet().unionAndStore(key, otherKey, destKey);
	}

	/**
	 *  key 和 otherKeys 多个集合的并集,保存在 destKey 集合中, 列名相同的 score 相加
	 * @param key
	 * @param otherKeys
	 * @param destKey
	 * @return
	 */
	public Long unionAndStoreZset(String key,Collection<String> otherKeys,String destKey){
		return redisTemplate.opsForZSet().unionAndStore(key, otherKeys, destKey);
	}

	/**
	 *  key 和 otherKey 两个集合的交集,保存在 destKey 集合中
	 * @param key
	 * @param otherKey
	 * @param destKey
	 * @return
	 */
	public Long intersectAndStore(String key,String otherKey,String destKey){
		return redisTemplate.opsForZSet().intersectAndStore(key, otherKey, destKey);
	}

	/**
	 *  key 和 otherKeys 多个集合的交集,保存在 destKey 集合中
	 * @param key
	 * @param otherKeys
	 * @param destKey
	 * @return
	 */
	public Long intersectAndStore(String key, Collection<String> otherKeys, String destKey){
		return redisTemplate.opsForZSet().intersectAndStore(key, otherKeys, destKey);
	}
}

3 测试

3.1 测试redis存取string类型
@Test
public void testPutOrGetString() {
    redisUtils.set("zyu", "zyufocus");
    String value = (String) redisUtils.get("zyu");
    System.out.println("get zyu value:" + value);
    redisUtils.set("zyu", "zyufocus,update");
    System.out.println("after update get zyu value:" + (String) redisUtils.get("zyu"));
    redisUtils.del("zyu");
}

在这里插入图片描述

3.2 测试redis存取hash类型
@Test
public void testPutOrGetHash() {
    User user = userMapper.selectByAccount("zyufocus");
    HashMap<String, Object> info = new HashMap<>();
    info.put("userid", user.getUserid());
    info.put("name", user.getName());
    info.put("age", user.getAge());
    info.put("role", user.getRole());
    redisUtils.hmset("zyufocus", info);
    Map<Object, Object> zyufocus = redisUtils.hmget("zyufocus");
    System.out.println("get zyufocus info:");
    zyufocus.forEach((key, value) -> {
        System.out.println(key + "---" + value);
    });
    /**
     * 用户年龄加1
     */
    redisUtils.hincr("zyufocus", "age", 1);
    zyufocus = redisUtils.hmget("zyufocus");
    System.out.println("after update get zyufocus info:");
    zyufocus.forEach((key, value) -> {
        System.out.println(key + "---" + value);
    });
    redisUtils.del("zyufocus");
}

在这里插入图片描述

3.3 测试redis存取对象
@Test
public void testPutOrGetObject() {
    User user = userMapper.selectByAccount("zyufocus");
    redisUtils.set("zyufocus", user);
    User zyufocus = (User) redisUtils.get("zyufocus");
    System.out.println(zyufocus.toString());
    redisUtils.del("zyufocus");
}

在这里插入图片描述

3.4 测试redis存取list
@Test
public void testPutOrGetList() {
    redisUtils.lSet("list", "A");
    List<Object> list = redisUtils.lGet("list", 0, -1);
    System.out.println(list);
    redisUtils.lSet("list", Arrays.asList("B", "C", "D"));
    list = redisUtils.lGet("list", 0, -1);
    System.out.println(list);
    redisUtils.del("list");
}

在这里插入图片描述

3.5 测试redis存取set
@Test
public void testPutOrGetSet() {
  redisUtils.sSet("set", "A", "B", "C");
  Set<Object> set = redisUtils.sGet("set");
  System.out.println(set);
  System.out.println("A is member:" + redisUtils.sIsMember("set", "A"));
  System.out.println("F is member:" + redisUtils.sIsMember("set", "F"));
  redisUtils.setRemove("set", "A");
  set = redisUtils.sGet("set");
  System.out.println(set);
  redisUtils.del("set");
}

在这里插入图片描述

3.6 测试redis存取zset
@Test
public void testPutOrGetZSet() {
    redisUtils.add("zset", "A", System.currentTimeMillis());
    redisUtils.add("zset", "B", System.currentTimeMillis());
    redisUtils.add("zset", "C", System.currentTimeMillis());
    redisUtils.add("zset", "D", System.currentTimeMillis());
    Set<Object> range = redisUtils.range("zset", 0, -1);
    System.out.println(range);
    redisUtils.removeZset("zset", "A", "B");
    Set<ZSetOperations.TypedTuple<Object>> zset = redisUtils.rangeWithScores("zset", 0, -1);
    zset.forEach(objectTypedTuple -> {
        System.out.println(objectTypedTuple.getValue() + "---" + objectTypedTuple.getScore());
    });
    redisUtils.del("zset");
}

在这里插入图片描述

结束语

  • 基础的redis操作到这里就结束了,很简单是不是
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值