jedis 实现 redis 统计一个用户在一段时间内的登录次数



import java.util.BitSet;


import redis.clients.jedis.Jedis;


public class SetBitTest {


public static void main(String[] args) {
// TODO Auto-generated method stub
Jedis j = null;


try {


j = new Jedis("192.****", 6379);


//setbit 参数说明
//setbit key 用户ID 1 or 0 (1表示用户登入过 0表示没有登入 默认为0)
// 2016-12-3 login operation user
j.setbit("login:2016-12-3".getBytes(), 1, "1".getBytes());
j.setbit("login:2016-12-3".getBytes(), 124431, "1".getBytes());
j.setbit("login:2016-12-3".getBytes(), 1231, "1".getBytes());
j.setbit("login:2016-12-3".getBytes(), 323121, "1".getBytes());
j.setbit("login:2016-12-3".getBytes(), 100, "1".getBytes());
//一下命令等价redis 命令 bitcount login:2016-12-3
BitSet b = BitSet.valueOf(j.get("login:2016-12-3".getBytes()));


// the number of bit value 1
int lognum3 = b.cardinality();
System.out.println("2016-12-3  login user number: " + lognum3);


// 2016-12-3 login operation user
j.setbit("login:2016-12-4".getBytes(), 1, "1".getBytes());
j.setbit("login:2016-12-4".getBytes(), 1231231, "1".getBytes());
j.setbit("login:2016-12-4".getBytes(), 334441, "1".getBytes());
BitSet b2 = BitSet.valueOf(j.get("login:2016-12-4".getBytes()));


int lognum4 = b2.cardinality();
System.out.println("2016-12-4  login user number: "
+ b2.cardinality());
            
//统计连续两天都登入的用户数
b.or(b2);
// or操作之后 同样userid的记录会重合不做记录,所以具体的数据统计看自己的需求而定
int lognumexceptsameuser = b.cardinality();
int logtotalnum = lognum3 + lognum4;
System.out
.println("2016-12-3 to 2016-12-4 login user number except same userid: "
+ lognumexceptsameuser);
System.out.println("2016-12-3 to 2016-12-4 login user number: "
+ logtotalnum);





} catch (Exception e) {


e.printStackTrace();


}


finally {


if (j != null) {


j.disconnect();


}


}
}


}

你可能感兴趣的:(大数据,架构师)