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分页查询效率很高,对于不需要持久化的数据可以使用此方案。

相关推荐
李广坤8 小时前
MySQL 大表字段变更实践(改名 + 改类型 + 改长度)
数据库
爱可生开源社区1 天前
2026 年,优秀的 DBA 需要具备哪些素质?
数据库·人工智能·dba
随逸1772 天前
《从零搭建NestJS项目》
数据库·typescript
加号32 天前
windows系统下mysql多源数据库同步部署
数据库·windows·mysql
シ風箏2 天前
MySQL【部署 04】Docker部署 MySQL8.0.32 版本(网盘镜像及启动命令分享)
数据库·mysql·docker
李慕婉学姐2 天前
Springboot智慧社区系统设计与开发6n99s526(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。
数据库·spring boot·后端
百锦再2 天前
Django实现接口token检测的实现方案
数据库·python·django·sqlite·flask·fastapi·pip
tryCbest2 天前
数据库SQL学习
数据库·sql
jnrjian2 天前
ORA-01017 查找机器名 用户名 以及library cache lock 参数含义
数据库·oracle
十月南城2 天前
数据湖技术对比——Iceberg、Hudi、Delta的表格格式与维护策略
大数据·数据库·数据仓库·hive·hadoop·spark