凉山彝族自治州网站建设_网站建设公司_服务器部署_seo优化
2026/1/11 2:49:08 网站建设 项目流程

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

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询