redis分页查询

redis不仅可以存普通文本,还可以存入List,这里就整理了下用redis做分页查询的功能。首先定义一个redis工具类,这里只贴出了需要的方法。

复制代码
public class RedisUtils {

	private JedisPool pool;

	public RedisUtils() {
		if (pool == null) {
			JedisPoolConfig config = new JedisPoolConfig();
			config.setMaxIdle(10);
			config.setTestOnBorrow(true);
			pool = new JedisPool(config, 127.0.0.1, 6379, 100000);
		}
	}
	
	/**
	 * <p>
	 * 通过key向list尾部添加字符串
	 * </p>
	 * 
	 * @param key
	 * @param strs
	 *            可以使一个string 也可以使string数组
	 * @return 返回list的value个数
	 */
	public Long rpush(String key, String... strs) {
		Jedis jedis = null;
		Long res = null;
		try {
			jedis = pool.getResource();
			res = jedis.rpush(key, strs);
		} catch (Exception e) {
			pool.returnBrokenResource(jedis);
			e.printStackTrace();
		} finally {
			returnResource(pool, jedis);
		}
		return res;
	}

/**
	 * 获取key当前页的list
	 * @param key
	 * @param curr
	 * @param pageSize
	 * @return
	 */
	public List<String> page(String key, int curr, int pageSize){

		Jedis jedis = null;
		String res = null;
		List<String> lrange = null;
		try {
			jedis = pool.getResource();
			lrange = jedis.lrange(key, (curr - 1) * pageSize, curr * pageSize);
		} catch (Exception e) {
			pool.returnBrokenResource(jedis);
			e.printStackTrace();
		} finally {
			returnResource(pool, jedis);
		}
		return lrange;
	}

/**
	 * 获取key的总条数
	 * @param key
	 * @return
	 */
	public long count(String key){
		Jedis jedis = null;
		long total = 0L;
		try {
			jedis = pool.getResource();
			total = jedis.llen(key);
		} catch (Exception e) {
			pool.returnBrokenResource(jedis);
			e.printStackTrace();
		} finally {
			returnResource(pool, jedis);
		}
		return total;
	}
}

接下来是应用层的调用

复制代码
	//这里演示存入redis的操作
    public static void main(String[] args) {
		RedisUtils redisUtils = new RedisUtils();
		for(int i=0;i<1000;i++){
			HashMap<String, Object> map = new HashMap<>();
			map.put("key_"+i, "value_"+i);
			//存入redis
			redisUtils.rpush("key", map.toString());
		}
	}

	//这里演示读取redis数据的操作
    public static void main(String[] args) {
		RedisUtils redisUtils = new RedisUtils();
		//获取当前页的数据,1代表当前页 10代表每页条数
		List<String> list = redisUtils.page("key", 1, 10);
		//获取总条数
		long count = redisUtils.count("key");
	}

redis分页查询效率很高,对于不需要持久化的数据可以使用此方案。

相关推荐
Database_Cool_几秒前
向量检索加速首选:阿里云 Tair 内置向量能力毫秒级召回
数据库·阿里云
这不小天嘛27 分钟前
JAVA八股——redis篇
java·开发语言·redis
强健的石头39 分钟前
django文件对象是什么?
数据库·django·sqlite
ClouGence1 小时前
保障公共安全,一线治安机构实时数据应用与实践
数据库·mysql·postgresql
烟漠河洛2 小时前
线上事故复盘:Redis幂等性设计边界没覆盖跨状态请求,订单状态机直接崩了
数据库·redis·缓存
Minxinbb2 小时前
TDSQL for MySQL 服务器重启操作
数据库·mysql·dba
SelectDB2 小时前
Doris 实战:用 Colocate Join 消除 Shuffle,AB 指标计算性能提升 145 倍 🚀
数据库·性能优化·ab测试
PawSQL2 小时前
PawSQL 技术月报 | 2026年6月
数据库·sql·tdsql·pawsql·sql审核
SelectDB2 小时前
Apache Doris 在 AgentLogsBench 中领先,支撑 Agent 可观测性生产负载
运维·数据库·agent
聚美智数3 小时前
黄历查询-运势查询-国际法定节假日查询-API接口介绍
android·java·数据库