基于java实现redis签到功能

java实现redis签到功能

注:基于Spring boot工程,使用redis的bitmap实现简单的签到功能

@RestController
@RequestMapping("/sign")
public class Qiandao {

    private RedisTemplate redisTemplate;

    public Qiandao(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @GetMapping
    public String signed(@RequestParam String userId,
                         @RequestParam String date) {
        String key = "signed#" + userId;
        //存进去。实现BitMap签到,用这个方法。
        Boolean isSign = (Boolean) redisTemplate.execute((RedisCallback<Boolean>) 
                con ->con.setBit(key.getBytes(),Long.parseLong(date),true));//参数true代表1,false代表0
        System.out.println("是否签到:"+isSign); //返回false签到成功

        //统计
        Long number = (Long) redisTemplate.execute((RedisCallback<Long>)
                con ->con.bitCount(key.getBytes()));
        System.out.println("已经签到"+number+"次");
        return "已经签到"+number+"次";
    }

    @GetMapping("/count") //统计某用户签到当月签到次数
    public String getCount(@RequestParam String id,
                           @RequestParam String start,@RequestParam String end){
        String key = "signed#"+id;
        Long count = (Long) redisTemplate.execute((RedisCallback<Long>)
                con ->con.bitCount(key.getBytes(),Long.parseLong(start),Long.parseLong(end)));
        return "用户"+id+"签到"+count+"次";
    }
}

application.yml文件配置

spring:
  redis:
    host: localhost
    port: 6379

你可能感兴趣的:(redis实例,java,redis,spring,boot)