redis統計

7325 ワード

package com.xu.boot;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * Created by Administrator on 2017/9/4.
 */

@SpringBootApplication // same as @Configuration @EnableAutoConfiguration @ComponentScan
@RestController
public class RedisTest {

    public String key = "apiCount";
    public boolean flag = false;

    public static void main(String[] args) {
        SpringApplication.run(RedisTest.class, args);
    }

//    @Autowired
    RedisTemplate redisTemplate;

    @Autowired(required = false)
    public void setRedisTemplate(RedisTemplate redisTemplate) {
        RedisSerializer stringSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(stringSerializer);
        redisTemplate.setValueSerializer(stringSerializer);
        redisTemplate.setHashKeySerializer(stringSerializer);
        redisTemplate.setHashValueSerializer(stringSerializer);
        this.redisTemplate = redisTemplate;
    }

    @RequestMapping("/api")
    public void api() {
        if(this.flag) {
//            long count = redisTemplate.opsForValue().increment(key, 1);
//            if (count == 1) {
//                //        
//                redisTemplate.expire(key, 60, TimeUnit.SECONDS);
//            }

            redisTemplate.opsForValue().increment(key, 1);
        }
    }

    @RequestMapping("/show")
    @ResponseBody
    public String show() throws Exception{
        String str = (String) this.redisTemplate.opsForValue().get(key);
        return str;
    }

    @RequestMapping("/start")
    public String start() throws Exception {
        this.flag = true;
        return "start";
    }

    @RequestMapping("/stop")
    public String stop() throws Exception {
        this.flag = false;
        return "stop";
    }

    @RequestMapping("/reset")
    public String reset() throws Exception {
        redisTemplate.opsForValue().getAndSet(key, "0");
        return "reset";
    }
}