redis sortedset实现推送

添加推送id

@Test
    public void c() throws InterruptedException {
        int i = 0;
        while (true) {
            int sum = (int) Math.round(Math.random() * 100000);
            int random = (int) Math.round(Math.random() * 10);
            i += random;
            double timestamp = System.currentTimeMillis();
            timestamp += 100 * i;
            redisTemplate.opsForZSet().add("zSetValue", sum, timestamp);
            System.out.println("插入了id:" + sum + " " + new Date(new BigDecimal(timestamp).longValue()));
            Thread.sleep(200);
        }
    }

add(key,value,score) redis sortedset会根据score进行排序

获取推送id

@Test
    public void d() throws InterruptedException {
        while (true) {
            long size = redisTemplate.opsForZSet().size("zSetValue");
            if (size > 10) {
                Set zSetValue = redisTemplate.opsForZSet().range("zSetValue", 0, 20);
                //System.out.println("通过range(K key, long start, long end)方法获取指定区间的元素:" + zSetValue);
                long timestamp = System.currentTimeMillis();
                long timestamp1 = System.currentTimeMillis() - 1000 * 5;
                if (CollectionUtils.isEmpty(zSetValue)) {
                    Thread.sleep(300);
                } else {
                    for (Iterator iterator = zSetValue.iterator(); iterator.hasNext(); ) {
                        Object i = iterator.next();
                        double time = redisTemplate.opsForZSet().score("zSetValue", i);
                        if (time >= timestamp1 && time < timestamp) {
                            System.out.println("时间为:" + new Date(new BigDecimal(time).longValue()) + "获取到推送id:" + i);
                            redisTemplate.opsForZSet().remove("zSetValue", i);
                        } else if (time > timestamp) {
                            break;
                        } else if (time < timestamp1) {
                            redisTemplate.opsForZSet().remove("zSetValue", i);
                        }
                    }
                }
            }
        }
    }

score(key,value)获取score数值

实际可以使用定时器去获取,如果在分布式环境在处理逻辑(删除key的时候)进行统一记录,如果被处理了就不做处理。

你可能感兴趣的:(redis sortedset实现推送)