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

相关推荐
Mike117.2 分钟前
GBase 8c schema 和 search_path 引发的对象定位问题
数据库·sql·oracle
ITyunwei098737 分钟前
数字化转型与遗留系统:如何为老旧的IT系统“减负“并注入新活力?
运维·网络·数据库
SelectDB1 小时前
强行拍平?全表扫描? AI Agent 动态 JSON 的观测分析
数据库·人工智能·数据分析
万邦科技Lafite1 小时前
如何通过 item_search_img API 接口获取淘宝商品信息
java·前端·数据库
雨辰AI1 小时前
面试题:人大金仓事务隔离级别、MVCC 机制详解(与MySQL差异对比)
数据库·后端·mysql·面试·政务
丑八怪大丑1 小时前
SQL新特性
数据库·sql
磊 子1 小时前
cpu是如何执行程序的?
数据库·操作系统·cpu
赵渝强老师1 小时前
【赵渝强老师】金仓数据库的运行日志文件
数据库·postgresql·oracle·国产数据库
D3bugRealm2 小时前
pgvector:PostgreSQL 原生向量搜索扩展
数据库·其他·postgresql
Thanks_ks2 小时前
分布式锁:Redis 与 Redisson 的工程实践与避坑指南
java·redis·分布式锁·redisson·微服务架构·并发编程·高可用